• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / brighterscript / #12837

24 Jul 2024 05:52PM UTC coverage: 87.936% (+2.3%) from 85.65%
#12837

push

TwitchBronBron
0.67.4

6069 of 7376 branches covered (82.28%)

Branch coverage included in aggregate %.

8793 of 9525 relevant lines covered (92.31%)

1741.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.53
/src/ProgramBuilder.ts
1
import * as debounce from 'debounce-promise';
1✔
2
import * as path from 'path';
1✔
3
import { rokuDeploy } from 'roku-deploy';
1✔
4
import type { LogLevel as RokuDeployLogLevel } from 'roku-deploy/dist/Logger';
5
import type { BsConfig, FinalizedBsConfig } from './BsConfig';
6
import type { BscFile, BsDiagnostic, FileObj, FileResolver } from './interfaces';
7
import { Program } from './Program';
1✔
8
import { standardizePath as s, util } from './util';
1✔
9
import { Watcher } from './Watcher';
1✔
10
import { DiagnosticSeverity } from 'vscode-languageserver';
1✔
11
import { LogLevel, createLogger } from './logging';
1✔
12
import PluginInterface from './PluginInterface';
1✔
13
import * as diagnosticUtils from './diagnosticUtils';
1✔
14
import * as fsExtra from 'fs-extra';
1✔
15
import * as requireRelative from 'require-relative';
1✔
16
import { Throttler } from './Throttler';
1✔
17
import { URI } from 'vscode-uri';
1✔
18

19
/**
20
 * A runner class that handles
21
 */
22
export class ProgramBuilder {
1✔
23

24
    public constructor() {
25
        //add the default file resolver (used to load source file contents).
26
        this.addFileResolver((filePath) => {
58✔
27
            return fsExtra.readFile(filePath).then((value) => {
23✔
28
                return value.toString();
23✔
29
            });
30
        });
31
    }
32
    /**
33
     * Determines whether the console should be cleared after a run (true for cli, false for languageserver)
34
     */
35
    public allowConsoleClearing = true;
58✔
36

37
    public options: FinalizedBsConfig = util.normalizeConfig({});
58✔
38
    private isRunning = false;
58✔
39
    private watcher: Watcher | undefined;
40
    public program: Program | undefined;
41
    public logger = createLogger();
58✔
42
    public plugins: PluginInterface = new PluginInterface([], { logger: this.logger });
58✔
43
    private fileResolvers = [] as FileResolver[];
58✔
44

45
    public addFileResolver(fileResolver: FileResolver) {
46
        this.fileResolvers.push(fileResolver);
93✔
47
    }
48

49
    /**
50
     * Get the contents of the specified file as a string.
51
     * This walks backwards through the file resolvers until we get a value.
52
     * This allow the language server to provide file contents directly from memory.
53
     */
54
    public async getFileContents(srcPath: string) {
55
        srcPath = s`${srcPath}`;
23✔
56
        let reversedResolvers = [...this.fileResolvers].reverse();
23✔
57
        for (let fileResolver of reversedResolvers) {
23✔
58
            let result = await fileResolver(srcPath);
43✔
59
            if (typeof result === 'string') {
43✔
60
                return result;
23✔
61
            }
62
        }
63
        throw new Error(`Could not load file "${srcPath}"`);
×
64
    }
65

66
    /**
67
     * A list of diagnostics that are always added to the `getDiagnostics()` call.
68
     */
69
    private staticDiagnostics = [] as BsDiagnostic[];
58✔
70

71
    public addDiagnostic(srcPath: string, diagnostic: Partial<BsDiagnostic>) {
72
        if (!this.program) {
×
73
            throw new Error('Cannot call `ProgramBuilder.addDiagnostic` before `ProgramBuilder.run()`');
×
74
        }
75
        let file: BscFile | undefined = this.program.getFile(srcPath);
×
76
        if (!file) {
×
77
            file = {
×
78
                pkgPath: this.program.getPkgPath(srcPath),
79
                pathAbsolute: srcPath, //keep this for backwards-compatibility. TODO remove in v1
80
                srcPath: srcPath,
81
                getDiagnostics: () => {
82
                    return [<any>diagnostic];
×
83
                }
84
            } as BscFile;
85
        }
86
        diagnostic.file = file;
×
87
        this.staticDiagnostics.push(<any>diagnostic);
×
88
    }
89

90
    public getDiagnostics() {
91
        return [
105✔
92
            ...this.staticDiagnostics,
93
            ...(this.program?.getDiagnostics() ?? [])
630!
94
        ];
95
    }
96

97
    public async run(options: BsConfig) {
98
        this.logger.logLevel = options.logLevel;
43✔
99

100
        if (this.isRunning) {
43!
101
            throw new Error('Server is already running');
×
102
        }
103
        this.isRunning = true;
43✔
104
        try {
43✔
105
            this.options = util.normalizeAndResolveConfig(options);
43✔
106
            if (this.options.noProject) {
42!
107
                this.logger.log(`'no-project' flag is set so bsconfig.json loading is disabled'`);
×
108
            } else if (this.options.project) {
42✔
109
                this.logger.log(`Using config file: "${this.options.project}"`);
9✔
110
            } else {
111
                this.logger.log(`No bsconfig.json file found, using default options`);
33✔
112
            }
113
            this.loadRequires();
42✔
114
            this.loadPlugins();
42✔
115
        } catch (e: any) {
116
            if (e?.file && e.message && e.code) {
1!
117
                let err = e as BsDiagnostic;
1✔
118
                this.staticDiagnostics.push(err);
1✔
119
            } else {
120
                //if this is not a diagnostic, something else is wrong...
121
                throw e;
×
122
            }
123
            this.printDiagnostics();
1✔
124

125
            //we added diagnostics, so hopefully that draws attention to the underlying issues.
126
            //For now, just use a default options object so we have a functioning program
127
            this.options = util.normalizeConfig({});
1✔
128
        }
129
        this.logger.logLevel = this.options.logLevel;
43✔
130

131
        this.createProgram();
43✔
132

133
        //parse every file in the entire project
134
        await this.loadAllFilesAST();
43✔
135

136
        if (this.options.watch) {
43!
137
            this.logger.log('Starting compilation in watch mode...');
×
138
            await this.runOnce();
×
139
            this.enableWatchMode();
×
140
        } else {
141
            await this.runOnce();
43✔
142
        }
143
    }
144

145
    protected createProgram() {
146
        this.program = new Program(this.options, this.logger, this.plugins);
44✔
147

148
        this.plugins.emit('afterProgramCreate', this.program);
44✔
149

150
        return this.program;
44✔
151
    }
152

153
    protected loadPlugins() {
154
        const cwd = this.options.cwd ?? process.cwd();
42!
155
        const plugins = util.loadPlugins(
42✔
156
            cwd,
157
            this.options.plugins ?? [],
126!
158
            (pathOrModule, err) => this.logger.error(`Error when loading plugin '${pathOrModule}':`, err)
×
159
        );
160
        this.logger.log(`Loading ${this.options.plugins?.length ?? 0} plugins for cwd "${cwd}"`);
42!
161
        for (let plugin of plugins) {
42✔
162
            this.plugins.add(plugin);
×
163
        }
164

165
        this.plugins.emit('beforeProgramCreate', this);
42✔
166
    }
167

168
    /**
169
     * `require()` every options.require path
170
     */
171
    protected loadRequires() {
172
        for (const dep of this.options.require ?? []) {
42✔
173
            requireRelative(dep, this.options.cwd);
2✔
174
        }
175
    }
176

177
    private clearConsole() {
178
        if (this.allowConsoleClearing) {
41✔
179
            util.clearConsole();
6✔
180
        }
181
    }
182

183
    /**
184
     * A handle for the watch mode interval that keeps the process alive.
185
     * We need this so we can clear it if the builder is disposed
186
     */
187
    private watchInterval: NodeJS.Timer | undefined;
188

189
    public enableWatchMode() {
190
        this.watcher = new Watcher(this.options);
×
191
        if (this.watchInterval) {
×
192
            clearInterval(this.watchInterval);
×
193
        }
194
        //keep the process alive indefinitely by setting an interval that runs once every 12 days
195
        this.watchInterval = setInterval(() => { }, 1073741824);
×
196

197
        //clear the console
198
        this.clearConsole();
×
199

200
        let fileObjects = rokuDeploy.normalizeFilesArray(this.options.files ? this.options.files : []);
×
201

202
        //add each set of files to the file watcher
203
        for (let fileObject of fileObjects) {
×
204
            let src = typeof fileObject === 'string' ? fileObject : fileObject.src;
×
205
            this.watcher.watch(src);
×
206
        }
207

208
        this.logger.log('Watching for file changes...');
×
209

210
        let debouncedRunOnce = debounce(async () => {
×
211
            this.logger.log('File change detected. Starting incremental compilation...');
×
212
            await this.runOnce();
×
213
            this.logger.log(`Watching for file changes.`);
×
214
        }, 50);
215

216
        //on any file watcher event
217
        this.watcher.on('all', async (event: string, thePath: string) => { //eslint-disable-line @typescript-eslint/no-misused-promises
×
218
            if (!this.program) {
×
219
                throw new Error('Internal invariant exception: somehow file watcher ran before `ProgramBuilder.run()`');
×
220
            }
221
            thePath = s`${path.resolve(this.rootDir, thePath)}`;
×
222
            if (event === 'add' || event === 'change') {
×
223
                const fileObj = {
×
224
                    src: thePath,
225
                    dest: rokuDeploy.getDestPath(
226
                        thePath,
227
                        this.program.options.files,
228
                        //some shells will toTowerCase the drive letter, so do it to rootDir for consistency
229
                        util.driveLetterToLower(this.rootDir)
230
                    )
231
                };
232
                this.program.setFile(
×
233
                    fileObj,
234
                    await this.getFileContents(fileObj.src)
235
                );
236
            } else if (event === 'unlink') {
×
237
                this.program.removeFile(thePath);
×
238
            }
239
            //wait for change events to settle, and then execute `run`
240
            await debouncedRunOnce();
×
241
        });
242
    }
243

244
    /**
245
     * The rootDir for this program.
246
     */
247
    public get rootDir() {
248
        if (!this.program) {
8!
249
            throw new Error('Cannot access `ProgramBuilder.rootDir` until after `ProgramBuilder.run()`');
×
250
        }
251
        return this.program.options.rootDir;
8✔
252
    }
253

254
    /**
255
     * A method that is used to cancel a previous run task.
256
     * Does nothing if previous run has completed or was already canceled
257
     */
258
    private cancelLastRun = () => {
58✔
259
        return Promise.resolve();
41✔
260
    };
261

262
    /**
263
     * Run the entire process exactly one time.
264
     */
265
    private runOnce() {
266
        //clear the console
267
        this.clearConsole();
41✔
268
        let cancellationToken = { isCanceled: false };
41✔
269
        //wait for the previous run to complete
270
        let runPromise = this.cancelLastRun().then(() => {
41✔
271
            //start the new run
272
            return this._runOnce(cancellationToken);
41✔
273
        }) as any;
274

275
        //a function used to cancel this run
276
        this.cancelLastRun = () => {
41✔
277
            cancellationToken.isCanceled = true;
×
278
            return runPromise;
×
279
        };
280
        return runPromise;
41✔
281
    }
282

283
    private printDiagnostics(diagnostics?: BsDiagnostic[]) {
284
        if (this.options?.showDiagnosticsInConsole === false) {
48!
285
            return;
34✔
286
        }
287
        if (!diagnostics) {
14✔
288
            diagnostics = this.getDiagnostics();
6✔
289
        }
290

291
        //group the diagnostics by file
292
        let diagnosticsByFile = {} as Record<string, BsDiagnostic[]>;
14✔
293
        for (let diagnostic of diagnostics) {
14✔
294
            if (!diagnosticsByFile[diagnostic.file.srcPath]) {
7✔
295
                diagnosticsByFile[diagnostic.file.srcPath] = [];
6✔
296
            }
297
            diagnosticsByFile[diagnostic.file.srcPath].push(diagnostic);
7✔
298
        }
299

300
        //get printing options
301
        const options = diagnosticUtils.getPrintDiagnosticOptions(this.options);
14✔
302
        const { cwd, emitFullPaths } = options;
14✔
303

304
        let srcPaths = Object.keys(diagnosticsByFile).sort();
14✔
305
        for (let srcPath of srcPaths) {
14✔
306
            let diagnosticsForFile = diagnosticsByFile[srcPath];
6✔
307
            //sort the diagnostics in line and column order
308
            let sortedDiagnostics = diagnosticsForFile.sort((a, b) => {
6✔
309
                return (
1✔
310
                    (a.range?.start.line ?? -1) - (b.range?.start.line ?? -1) ||
14!
311
                    (a.range?.start.character ?? -1) - (b.range?.start.character ?? -1)
12!
312
                );
313
            });
314

315
            let filePath = srcPath;
6✔
316
            if (!emitFullPaths) {
6!
317
                filePath = path.relative(cwd, filePath);
6✔
318
            }
319
            //load the file text
320
            const file = this.program?.getFile(srcPath);
6!
321
            //get the file's in-memory contents if available
322
            const lines = file?.fileContents?.split(/\r?\n/g) ?? [];
6✔
323

324
            for (let diagnostic of sortedDiagnostics) {
6✔
325
                //default the severity to error if undefined
326
                let severity = typeof diagnostic.severity === 'number' ? diagnostic.severity : DiagnosticSeverity.Error;
7✔
327
                let relatedInformation = (diagnostic.relatedInformation ?? []).map(x => {
7!
328
                    let relatedInfoFilePath = URI.parse(x.location.uri).fsPath;
×
329
                    if (!emitFullPaths) {
×
330
                        relatedInfoFilePath = path.relative(cwd, relatedInfoFilePath);
×
331
                    }
332
                    return {
×
333
                        filePath: relatedInfoFilePath,
334
                        range: x.location.range,
335
                        message: x.message
336
                    };
337
                });
338
                //format output
339
                diagnosticUtils.printDiagnostic(options, severity, filePath, lines, diagnostic, relatedInformation);
7✔
340
            }
341
        }
342
    }
343

344
    /**
345
     * Run the process once, allowing cancelability.
346
     * NOTE: This should only be called by `runOnce`.
347
     */
348
    private async _runOnce(cancellationToken: { isCanceled: any }) {
349
        let wereDiagnosticsPrinted = false;
41✔
350
        try {
41✔
351
            //maybe cancel?
352
            if (cancellationToken.isCanceled === true) {
41!
353
                return -1;
×
354
            }
355
            //validate program
356
            this.validateProject();
41✔
357

358
            //maybe cancel?
359
            if (cancellationToken.isCanceled === true) {
41!
360
                return -1;
×
361
            }
362

363
            const diagnostics = this.getDiagnostics();
41✔
364
            this.printDiagnostics(diagnostics);
41✔
365
            wereDiagnosticsPrinted = true;
41✔
366
            let errorCount = diagnostics.filter(x => x.severity === DiagnosticSeverity.Error).length;
41✔
367

368
            if (errorCount > 0) {
41✔
369
                this.logger.log(`Found ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`);
1!
370
                return errorCount;
1✔
371
            }
372

373
            //create the deployment package (and transpile as well)
374
            await this.createPackageIfEnabled();
40✔
375

376
            //maybe cancel?
377
            if (cancellationToken.isCanceled === true) {
40!
378
                return -1;
×
379
            }
380

381
            //deploy the package
382
            await this.deployPackageIfEnabled();
40✔
383

384
            return 0;
40✔
385
        } catch (e) {
386
            if (wereDiagnosticsPrinted === false) {
×
387
                this.printDiagnostics();
×
388
            }
389
            throw e;
×
390
        }
391
    }
392

393
    private async createPackageIfEnabled() {
394
        if (this.options.copyToStaging || this.options.createPackage || this.options.deploy) {
40✔
395

396
            //transpile the project
397
            await this.transpile();
4✔
398

399
            //create the zip file if configured to do so
400
            if (this.options.createPackage !== false || this.options.deploy) {
4✔
401
                await this.logger.time(LogLevel.log, [`Creating package at ${this.options.outFile}`], async () => {
2✔
402
                    await rokuDeploy.zipPackage({
2✔
403
                        ...this.options,
404
                        logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
405
                        outDir: util.getOutDir(this.options),
406
                        outFile: path.basename(this.options.outFile)
407
                    });
408
                });
409
            }
410
        }
411
    }
412

413
    private transpileThrottler = new Throttler(0);
58✔
414
    /**
415
     * Transpiles the entire program into the staging folder
416
     */
417
    public async transpile() {
418
        await this.transpileThrottler.run(async () => {
4✔
419
            let options = util.cwdWork(this.options.cwd, () => {
4✔
420
                return rokuDeploy.getOptions({
4✔
421
                    ...this.options,
422
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
423
                    outDir: util.getOutDir(this.options),
424
                    outFile: path.basename(this.options.outFile)
425

426
                    //rokuDeploy's return type says all its fields can be nullable, but it sets values for all of them.
427
                }) as any as Required<ReturnType<typeof rokuDeploy.getOptions>>;
428
            });
429

430
            //get every file referenced by the files array
431
            let fileMap = await rokuDeploy.getFilePaths(options.files, options.rootDir);
4✔
432

433
            //remove files currently loaded in the program, we will transpile those instead (even if just for source maps)
434
            let filteredFileMap = [] as FileObj[];
4✔
435

436
            for (let fileEntry of fileMap) {
4✔
437
                if (this.program!.hasFile(fileEntry.src) === false) {
4✔
438
                    filteredFileMap.push(fileEntry);
2✔
439
                }
440
            }
441

442
            this.plugins.emit('beforePrepublish', this, filteredFileMap);
4✔
443

444
            await this.logger.time(LogLevel.log, ['Copying to staging directory'], async () => {
4✔
445
                //prepublish all non-program-loaded files to staging
446
                await rokuDeploy.prepublishToStaging({
4✔
447
                    ...options,
448
                    files: filteredFileMap
449
                });
450
            });
451

452
            this.plugins.emit('afterPrepublish', this, filteredFileMap);
4✔
453
            this.plugins.emit('beforePublish', this, fileMap);
4✔
454

455
            await this.logger.time(LogLevel.log, ['Transpiling'], async () => {
4✔
456
                //transpile any brighterscript files
457
                await this.program!.transpile(fileMap, options.stagingDir);
4✔
458
            });
459

460
            this.plugins.emit('afterPublish', this, fileMap);
4✔
461
        });
462
    }
463

464
    private async deployPackageIfEnabled() {
465
        //deploy the project if configured to do so
466
        if (this.options.deploy) {
40!
467
            await this.logger.time(LogLevel.log, ['Deploying package to', this.options.host], async () => {
×
468
                await rokuDeploy.publish({
×
469
                    ...this.options,
470
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
471
                    outDir: util.getOutDir(this.options),
472
                    outFile: path.basename(this.options.outFile)
473
                });
474
            });
475
        }
476
    }
477

478
    /**
479
     * Parse and load the AST for every file in the project
480
     */
481
    private async loadAllFilesAST() {
482
        await this.logger.time(LogLevel.log, ['Parsing files'], async () => {
45✔
483
            let files = await this.logger.time(LogLevel.debug, ['getFilePaths'], async () => {
45✔
484
                return util.getFilePaths(this.options);
45✔
485
            });
486
            this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);
45✔
487

488
            const typedefFiles = [] as FileObj[];
45✔
489
            const sourceFiles = [] as FileObj[];
45✔
490
            let manifestFile: FileObj | null = null;
45✔
491

492
            for (const file of files) {
45✔
493
                // source files (.brs, .bs, .xml)
494
                if (/(?<!\.d)\.(bs|brs|xml)$/i.test(file.dest)) {
30✔
495
                    sourceFiles.push(file);
23✔
496

497
                    // typedef files (.d.bs)
498
                } else if (/\.d\.bs$/i.test(file.dest)) {
7✔
499
                    typedefFiles.push(file);
2✔
500

501
                    // manifest file
502
                } else if (/^manifest$/i.test(file.dest)) {
5!
503
                    manifestFile = file;
5✔
504
                }
505
            }
506

507
            if (manifestFile) {
45✔
508
                this.program!.loadManifest(manifestFile, false);
5✔
509
            }
510

511
            const loadFile = async (fileObj) => {
45✔
512
                try {
25✔
513
                    this.program!.setFile(fileObj, await this.getFileContents(fileObj.src));
25✔
514
                } catch (e) {
515
                    this.logger.log(e); // log the error, but don't fail this process because the file might be fixable later
×
516
                }
517
            };
518
            await Promise.all(typedefFiles.map(loadFile)); // preload every type definition file, which eliminates duplicate file loading
45✔
519
            await Promise.all(sourceFiles.map(loadFile)); // parse source files
45✔
520
        });
521
    }
522

523
    /**
524
     * Remove all files from the program that are in the specified folder path
525
     * @param srcPath the path to the
526
     */
527
    public removeFilesInFolder(srcPath: string) {
528
        for (let filePath in this.program.files) {
×
529
            //if the file path starts with the parent path and the file path does not exactly match the folder path
530
            if (filePath.startsWith(srcPath) && filePath !== srcPath) {
×
531
                this.program.removeFile(filePath);
×
532
            }
533
        }
534
    }
535

536
    /**
537
     * Scan every file and resolve all variable references.
538
     * If no errors were encountered, return true. Otherwise return false.
539
     */
540
    private validateProject() {
541
        this.program.validate();
41✔
542
    }
543

544
    public dispose() {
545
        if (this.watcher) {
20!
546
            this.watcher.dispose();
×
547
        }
548
        if (this.program) {
20!
549
            this.program.dispose?.();
20!
550
        }
551
        if (this.watchInterval) {
20!
552
            clearInterval(this.watchInterval);
×
553
        }
554
    }
555
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc