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

rokucommunity / brighterscript / #13265

01 Nov 2024 05:58PM UTC coverage: 89.076% (+0.9%) from 88.214%
#13265

push

web-flow
Merge 30be955de into 7cfaaa047

7248 of 8577 branches covered (84.51%)

Branch coverage included in aggregate %.

1095 of 1214 new or added lines in 28 files covered. (90.2%)

24 existing lines in 5 files now uncovered.

9640 of 10382 relevant lines covered (92.85%)

1782.98 hits per line

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

72.35
/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 type { Logger } from './logging';
12
import { LogLevel, createLogger } from './logging';
1✔
13
import PluginInterface from './PluginInterface';
1✔
14
import * as diagnosticUtils from './diagnosticUtils';
1✔
15
import * as fsExtra from 'fs-extra';
1✔
16
import * as requireRelative from 'require-relative';
1✔
17
import { Throttler } from './Throttler';
1✔
18
import { URI } from 'vscode-uri';
1✔
19

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

25
    public constructor(
26
        options?: {
27
            logger?: Logger;
28
        }
29
    ) {
30
        this.logger = options?.logger ?? createLogger();
102✔
31
        this.plugins = new PluginInterface([], { logger: this.logger });
102✔
32

33
        //add the default file resolver (used to load source file contents).
34
        this.addFileResolver((filePath) => {
102✔
35
            return fsExtra.readFile(filePath).then((value) => {
41✔
36
                return value.toString();
41✔
37
            });
38
        });
39
    }
40
    /**
41
     * Determines whether the console should be cleared after a run (true for cli, false for languageserver)
42
     */
43
    public allowConsoleClearing = true;
102✔
44

45
    public options: FinalizedBsConfig = util.normalizeConfig({});
102✔
46
    private isRunning = false;
102✔
47
    private watcher: Watcher | undefined;
48
    public program: Program | undefined;
49
    public logger: Logger;
50
    public plugins: PluginInterface;
51
    private fileResolvers = [] as FileResolver[];
102✔
52

53
    /**
54
     * Add file resolvers that will be able to provide file contents before loading from the file system
55
     * @param fileResolvers a list of file resolvers
56
     */
57
    public addFileResolver(...fileResolvers: FileResolver[]) {
58
        this.fileResolvers.push(...fileResolvers);
102✔
59
    }
60

61
    /**
62
     * Get the contents of the specified file as a string.
63
     * This walks backwards through the file resolvers until we get a value.
64
     * This allow the language server to provide file contents directly from memory.
65
     */
66
    public async getFileContents(srcPath: string) {
67
        srcPath = s`${srcPath}`;
41✔
68
        let reversedResolvers = [...this.fileResolvers].reverse();
41✔
69
        for (let fileResolver of reversedResolvers) {
41✔
70
            let result = await fileResolver(srcPath);
46✔
71
            if (typeof result === 'string') {
46✔
72
                return result;
41✔
73
            }
74
        }
75
        throw new Error(`Could not load file "${srcPath}"`);
×
76
    }
77

78
    /**
79
     * A list of diagnostics that are always added to the `getDiagnostics()` call.
80
     */
81
    private staticDiagnostics = [] as BsDiagnostic[];
102✔
82

83
    public addDiagnostic(srcPath: string, diagnostic: Partial<BsDiagnostic>) {
84
        if (!this.program) {
1!
85
            throw new Error('Cannot call `ProgramBuilder.addDiagnostic` before `ProgramBuilder.run()`');
×
86
        }
87
        let file: BscFile | undefined = this.program.getFile(srcPath);
1✔
88
        if (!file) {
1!
89
            file = {
1✔
90
                pkgPath: path.basename(srcPath),
91
                pathAbsolute: srcPath, //keep this for backwards-compatibility. TODO remove in v1
92
                srcPath: srcPath,
93
                getDiagnostics: () => {
94
                    return [<any>diagnostic];
×
95
                }
96
            } as BscFile;
97
        }
98
        diagnostic.file = file;
1✔
99
        this.staticDiagnostics.push(<any>diagnostic);
1✔
100
    }
101

102
    public getDiagnostics() {
103
        return [
204✔
104
            ...this.staticDiagnostics,
105
            ...(this.program?.getDiagnostics() ?? [])
1,224!
106
        ];
107
    }
108

109
    public async run(options: BsConfig & { skipInitialValidation?: boolean }) {
110
        if (options?.logLevel) {
87✔
111
            this.logger.logLevel = options.logLevel;
2✔
112
        }
113

114
        if (this.isRunning) {
87!
115
            throw new Error('Server is already running');
×
116
        }
117
        this.isRunning = true;
87✔
118
        try {
87✔
119
            this.options = util.normalizeAndResolveConfig(options);
87✔
120
            if (this.options?.logLevel !== undefined) {
85!
121
                this.logger.logLevel = this.options?.logLevel;
85!
122
            }
123

124
            if (this.options.noProject) {
85!
125
                this.logger.log(`'no-project' flag is set so bsconfig.json loading is disabled'`);
×
126
            } else if (this.options.project) {
85✔
127
                this.logger.log(`Using config file: "${this.options.project}"`);
31✔
128
            } else {
129
                this.logger.log(`No bsconfig.json file found, using default options`);
54✔
130
            }
131
            this.loadRequires();
85✔
132
            this.loadPlugins();
85✔
133
        } catch (e: any) {
134
            //For now, just use a default options object so we have a functioning program
135
            this.options = util.normalizeConfig({
2✔
136
                showDiagnosticsInConsole: options?.showDiagnosticsInConsole
6!
137
            });
138

139
            if (e?.file && e.message && e.code) {
2!
140
                let err = e as BsDiagnostic;
2✔
141
                this.staticDiagnostics.push(err);
2✔
142
            } else {
143
                //if this is not a diagnostic, something else is wrong...
144
                throw e;
×
145
            }
146

147
            this.printDiagnostics();
2✔
148
        }
149
        this.logger.logLevel = this.options.logLevel;
87✔
150

151
        this.createProgram();
87✔
152

153
        //parse every file in the entire project
154
        await this.loadAllFilesAST();
87✔
155

156
        if (this.options.watch) {
87!
157
            this.logger.log('Starting compilation in watch mode...');
×
NEW
158
            await this.runOnce({
×
159
                skipValidation: options?.skipInitialValidation
×
160
            });
UNCOV
161
            this.enableWatchMode();
×
162
        } else {
163
            await this.runOnce({
87✔
164
                skipValidation: options?.skipInitialValidation
261✔
165
            });
166
        }
167
    }
168

169
    protected createProgram() {
170
        this.program = new Program(this.options, this.logger, this.plugins);
88✔
171

172
        this.plugins.emit('afterProgramCreate', this.program);
88✔
173

174
        return this.program;
88✔
175
    }
176

177
    protected loadPlugins() {
178
        const cwd = this.options.cwd ?? process.cwd();
85!
179
        const plugins = util.loadPlugins(
85✔
180
            cwd,
181
            this.options.plugins ?? [],
255!
182
            (pathOrModule, err) => this.logger.error(`Error when loading plugin '${pathOrModule}':`, err)
×
183
        );
184
        this.logger.log(`Loading ${this.options.plugins?.length ?? 0} plugins for cwd "${cwd}"`, this.options.plugins);
85!
185
        for (let plugin of plugins) {
85✔
186
            this.plugins.add(plugin);
1✔
187
        }
188

189
        this.plugins.emit('beforeProgramCreate', this);
85✔
190
    }
191

192
    /**
193
     * `require()` every options.require path
194
     */
195
    protected loadRequires() {
196
        for (const dep of this.options.require ?? []) {
85✔
197
            requireRelative(dep, this.options.cwd);
2✔
198
        }
199
    }
200

201
    private clearConsole() {
202
        if (this.allowConsoleClearing) {
84!
203
            util.clearConsole();
84✔
204
        }
205
    }
206

207
    /**
208
     * A handle for the watch mode interval that keeps the process alive.
209
     * We need this so we can clear it if the builder is disposed
210
     */
211
    private watchInterval: NodeJS.Timer | undefined;
212

213
    public enableWatchMode() {
214
        this.watcher = new Watcher(this.options);
×
215
        if (this.watchInterval) {
×
216
            clearInterval(this.watchInterval);
×
217
        }
218
        //keep the process alive indefinitely by setting an interval that runs once every 12 days
219
        this.watchInterval = setInterval(() => { }, 1073741824);
×
220

221
        //clear the console
222
        this.clearConsole();
×
223

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

226
        //add each set of files to the file watcher
227
        for (let fileObject of fileObjects) {
×
228
            let src = typeof fileObject === 'string' ? fileObject : fileObject.src;
×
229
            this.watcher.watch(src);
×
230
        }
231

232
        this.logger.log('Watching for file changes...');
×
233

234
        let debouncedRunOnce = debounce(async () => {
×
235
            this.logger.log('File change detected. Starting incremental compilation...');
×
236
            await this.runOnce();
×
237
            this.logger.log(`Watching for file changes.`);
×
238
        }, 50);
239

240
        //on any file watcher event
241
        this.watcher.on('all', async (event: string, thePath: string) => { //eslint-disable-line @typescript-eslint/no-misused-promises
×
242
            if (!this.program) {
×
243
                throw new Error('Internal invariant exception: somehow file watcher ran before `ProgramBuilder.run()`');
×
244
            }
245
            thePath = s`${path.resolve(this.rootDir, thePath)}`;
×
246
            if (event === 'add' || event === 'change') {
×
247
                const fileObj = {
×
248
                    src: thePath,
249
                    dest: rokuDeploy.getDestPath(
250
                        thePath,
251
                        this.program.options.files,
252
                        //some shells will toTowerCase the drive letter, so do it to rootDir for consistency
253
                        util.driveLetterToLower(this.rootDir)
254
                    )
255
                };
256
                this.program.setFile(
×
257
                    fileObj,
258
                    await this.getFileContents(fileObj.src)
259
                );
260
            } else if (event === 'unlink') {
×
261
                this.program.removeFile(thePath);
×
262
            }
263
            //wait for change events to settle, and then execute `run`
264
            await debouncedRunOnce();
×
265
        });
266
    }
267

268
    /**
269
     * The rootDir for this program.
270
     */
271
    public get rootDir() {
UNCOV
272
        if (!this.program) {
×
273
            throw new Error('Cannot access `ProgramBuilder.rootDir` until after `ProgramBuilder.run()`');
×
274
        }
UNCOV
275
        return this.program.options.rootDir;
×
276
    }
277

278
    /**
279
     * A method that is used to cancel a previous run task.
280
     * Does nothing if previous run has completed or was already canceled
281
     */
282
    private cancelLastRun = () => {
102✔
283
        return Promise.resolve();
84✔
284
    };
285

286
    /**
287
     * Run the entire process exactly one time.
288
     */
289
    private runOnce(options?: { skipValidation?: boolean }) {
290
        //clear the console
291
        this.clearConsole();
84✔
292
        let cancellationToken = { isCanceled: false };
84✔
293
        //wait for the previous run to complete
294
        let runPromise = this.cancelLastRun().then(() => {
84✔
295
            //start the new run
296
            return this._runOnce({
84✔
297
                cancellationToken: cancellationToken,
298
                skipValidation: options?.skipValidation
252!
299
            });
300
        }) as any;
301

302
        //a function used to cancel this run
303
        this.cancelLastRun = () => {
84✔
304
            cancellationToken.isCanceled = true;
×
305
            return runPromise;
×
306
        };
307
        return runPromise;
84✔
308
    }
309

310
    private printDiagnostics(diagnostics?: BsDiagnostic[]) {
311
        if (this.options?.showDiagnosticsInConsole === false) {
92!
312
            return;
80✔
313
        }
314
        if (!diagnostics) {
12✔
315
            diagnostics = this.getDiagnostics();
6✔
316
        }
317

318
        //group the diagnostics by file
319
        let diagnosticsByFile = {} as Record<string, BsDiagnostic[]>;
12✔
320
        for (let diagnostic of diagnostics) {
12✔
321
            if (!diagnosticsByFile[diagnostic.file.srcPath]) {
7✔
322
                diagnosticsByFile[diagnostic.file.srcPath] = [];
6✔
323
            }
324
            diagnosticsByFile[diagnostic.file.srcPath].push(diagnostic);
7✔
325
        }
326

327
        //get printing options
328
        const options = diagnosticUtils.getPrintDiagnosticOptions(this.options);
12✔
329
        const { cwd, emitFullPaths } = options;
12✔
330

331
        let srcPaths = Object.keys(diagnosticsByFile).sort();
12✔
332
        for (let srcPath of srcPaths) {
12✔
333
            let diagnosticsForFile = diagnosticsByFile[srcPath];
6✔
334
            //sort the diagnostics in line and column order
335
            let sortedDiagnostics = diagnosticsForFile.sort((a, b) => {
6✔
336
                return (
1✔
337
                    (a.range?.start.line ?? -1) - (b.range?.start.line ?? -1) ||
14!
338
                    (a.range?.start.character ?? -1) - (b.range?.start.character ?? -1)
12!
339
                );
340
            });
341

342
            let filePath = srcPath;
6✔
343
            if (!emitFullPaths) {
6!
344
                filePath = path.relative(cwd, filePath);
6✔
345
            }
346
            //load the file text
347
            const file = this.program?.getFile(srcPath);
6!
348
            //get the file's in-memory contents if available
349
            const lines = file?.fileContents?.split(/\r?\n/g) ?? [];
6✔
350

351
            for (let diagnostic of sortedDiagnostics) {
6✔
352
                //default the severity to error if undefined
353
                let severity = typeof diagnostic.severity === 'number' ? diagnostic.severity : DiagnosticSeverity.Error;
7✔
354
                let relatedInformation = (diagnostic.relatedInformation ?? []).map(x => {
7!
355
                    let relatedInfoFilePath = URI.parse(x.location.uri).fsPath;
×
356
                    if (!emitFullPaths) {
×
357
                        relatedInfoFilePath = path.relative(cwd, relatedInfoFilePath);
×
358
                    }
359
                    return {
×
360
                        filePath: relatedInfoFilePath,
361
                        range: x.location.range,
362
                        message: x.message
363
                    };
364
                });
365
                //format output
366
                diagnosticUtils.printDiagnostic(options, severity, filePath, lines, diagnostic, relatedInformation);
7✔
367
            }
368
        }
369
    }
370

371
    /**
372
     * Run the process once, allowing it to be cancelled.
373
     * NOTE: This should only be called by `runOnce`.
374
     */
375
    private async _runOnce(options: { cancellationToken: { isCanceled: any }; skipValidation: boolean }) {
376
        let wereDiagnosticsPrinted = false;
84✔
377
        try {
84✔
378
            //maybe cancel?
379
            if (options.cancellationToken.isCanceled === true) {
84!
380
                return -1;
×
381
            }
382
            //validate program
383
            if (options.skipValidation !== true) {
84✔
384
                this.validateProject();
6✔
385
            }
386

387
            //maybe cancel?
388
            if (options.cancellationToken.isCanceled === true) {
84!
389
                return -1;
×
390
            }
391

392
            const diagnostics = this.getDiagnostics();
84✔
393
            this.printDiagnostics(diagnostics);
84✔
394
            wereDiagnosticsPrinted = true;
84✔
395
            let errorCount = diagnostics.filter(x => x.severity === DiagnosticSeverity.Error).length;
84✔
396

397
            if (errorCount > 0) {
84✔
398
                this.logger.log(`Found ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`);
2!
399
                return errorCount;
2✔
400
            }
401

402
            //create the deployment package (and transpile as well)
403
            await this.createPackageIfEnabled();
82✔
404

405
            //maybe cancel?
406
            if (options.cancellationToken.isCanceled === true) {
82!
407
                return -1;
×
408
            }
409

410
            //deploy the package
411
            await this.deployPackageIfEnabled();
82✔
412

413
            return 0;
82✔
414
        } catch (e) {
415
            if (wereDiagnosticsPrinted === false) {
×
416
                this.printDiagnostics();
×
417
            }
418
            throw e;
×
419
        }
420
    }
421

422
    private async createPackageIfEnabled() {
423
        if (this.options.copyToStaging || this.options.createPackage || this.options.deploy) {
82✔
424

425
            //transpile the project
426
            await this.transpile();
4✔
427

428
            //create the zip file if configured to do so
429
            if (this.options.createPackage !== false || this.options.deploy) {
4✔
430
                await this.logger.time(LogLevel.log, [`Creating package at ${this.options.outFile}`], async () => {
2✔
431
                    await rokuDeploy.zipPackage({
2✔
432
                        ...this.options,
433
                        logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
434
                        outDir: util.getOutDir(this.options),
435
                        outFile: path.basename(this.options.outFile)
436
                    });
437
                });
438
            }
439
        }
440
    }
441

442
    private transpileThrottler = new Throttler(0);
102✔
443
    /**
444
     * Transpiles the entire program into the staging folder
445
     */
446
    public async transpile() {
447
        await this.transpileThrottler.run(async () => {
4✔
448
            let options = util.cwdWork(this.options.cwd, () => {
4✔
449
                return rokuDeploy.getOptions({
4✔
450
                    ...this.options,
451
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
452
                    outDir: util.getOutDir(this.options),
453
                    outFile: path.basename(this.options.outFile)
454

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

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

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

465
            for (let fileEntry of fileMap) {
4✔
466
                if (this.program!.hasFile(fileEntry.src) === false) {
4✔
467
                    filteredFileMap.push(fileEntry);
2✔
468
                }
469
            }
470

471
            this.plugins.emit('beforePrepublish', this, filteredFileMap);
4✔
472

473
            await this.logger.time(LogLevel.log, ['Copying to staging directory'], async () => {
4✔
474
                //prepublish all non-program-loaded files to staging
475
                await rokuDeploy.prepublishToStaging({
4✔
476
                    ...options,
477
                    files: filteredFileMap
478
                });
479
            });
480

481
            this.plugins.emit('afterPrepublish', this, filteredFileMap);
4✔
482
            this.plugins.emit('beforePublish', this, fileMap);
4✔
483

484
            await this.logger.time(LogLevel.log, ['Transpiling'], async () => {
4✔
485
                //transpile any brighterscript files
486
                await this.program!.transpile(fileMap, options.stagingDir);
4✔
487
            });
488

489
            this.plugins.emit('afterPublish', this, fileMap);
4✔
490
        });
491
    }
492

493
    private async deployPackageIfEnabled() {
494
        //deploy the project if configured to do so
495
        if (this.options.deploy) {
82!
496
            await this.logger.time(LogLevel.log, ['Deploying package to', this.options.host], async () => {
×
497
                await rokuDeploy.publish({
×
498
                    ...this.options,
499
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
500
                    outDir: util.getOutDir(this.options),
501
                    outFile: path.basename(this.options.outFile)
502
                });
503
            });
504
        }
505
    }
506

507
    /**
508
     * Parse and load the AST for every file in the project
509
     */
510
    private async loadAllFilesAST() {
511
        await this.logger.time(LogLevel.log, ['Parsing files'], async () => {
89✔
512
            let files = await this.logger.time(LogLevel.debug, ['getFilePaths'], async () => {
89✔
513
                return util.getFilePaths(this.options);
89✔
514
            });
515
            this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);
89✔
516

517
            const typedefFiles = [] as FileObj[];
89✔
518
            const sourceFiles = [] as FileObj[];
89✔
519
            let manifestFile: FileObj | null = null;
89✔
520

521
            for (const file of files) {
89✔
522
                // source files (.brs, .bs, .xml)
523
                if (/(?<!\.d)\.(bs|brs|xml)$/i.test(file.dest)) {
55✔
524
                    sourceFiles.push(file);
45✔
525

526
                    // typedef files (.d.bs)
527
                } else if (/\.d\.bs$/i.test(file.dest)) {
10✔
528
                    typedefFiles.push(file);
2✔
529

530
                    // manifest file
531
                } else if (/^manifest$/i.test(file.dest)) {
8✔
532
                    manifestFile = file;
7✔
533
                }
534
            }
535

536
            if (manifestFile) {
89✔
537
                this.program!.loadManifest(manifestFile, false);
7✔
538
            }
539

540
            const loadFile = async (fileObj) => {
89✔
541
                try {
47✔
542
                    this.program!.setFile(fileObj, await this.getFileContents(fileObj.src));
47✔
543
                } catch (e) {
544
                    this.logger.log(e); // log the error, but don't fail this process because the file might be fixable later
×
545
                }
546
            };
547
            await Promise.all(typedefFiles.map(loadFile)); // preload every type definition file, which eliminates duplicate file loading
89✔
548
            await Promise.all(sourceFiles.map(loadFile)); // parse source files
89✔
549
        });
550
    }
551

552
    /**
553
     * Remove all files from the program that are in the specified folder path
554
     * @param srcPath the path to the folder to remove
555
     */
556
    public removeFilesInFolder(srcPath: string): boolean {
NEW
557
        let removedSomeFiles = false;
×
UNCOV
558
        for (let filePath in this.program.files) {
×
559
            //if the file path starts with the parent path and the file path does not exactly match the folder path
560
            if (filePath.startsWith(srcPath) && filePath !== srcPath) {
×
561
                this.program.removeFile(filePath);
×
NEW
562
                removedSomeFiles = true;
×
563
            }
564
        }
NEW
565
        return removedSomeFiles;
×
566
    }
567

568
    /**
569
     * Scan every file and resolve all variable references.
570
     * If no errors were encountered, return true. Otherwise return false.
571
     */
572
    private validateProject() {
573
        this.program.validate();
6✔
574
    }
575

576
    public dispose() {
577
        if (this.watcher) {
96!
578
            this.watcher.dispose();
×
579
        }
580
        if (this.program) {
96!
581
            this.program.dispose?.();
96!
582
        }
583
        if (this.watchInterval) {
96!
584
            clearInterval(this.watchInterval);
×
585
        }
586
    }
587
}
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

© 2025 Coveralls, Inc