From 2e979be1e605b4e009bd5ef5562e4f98f0452fac Mon Sep 17 00:00:00 2001 From: David Michon Date: Wed, 17 May 2023 13:30:09 -0700 Subject: [PATCH 1/4] Add "useTranspilerWorker" option --- .vscode/launch.json | 18 + .../src/indexA.ts | 2 + .../src/indexB.ts | 2 + .../tsconfig-base.json | 3 + .../src/indexA.ts | 2 + .../src/indexB.ts | 2 + .../tsconfig.json | 1 + .../src/TranspilerWorker.ts | 83 ++++ .../src/TypeScriptBuilder.ts | 382 +++++++++--------- .../src/TypeScriptPlugin.ts | 7 + .../src/configureProgramForMultiEmit.ts | 181 +++++++++ .../internalTypings/TypeScriptInternals.ts | 8 + .../src/schemas/typescript.schema.json | 5 + .../heft-typescript-plugin/src/types.ts | 50 +++ 14 files changed, 554 insertions(+), 192 deletions(-) create mode 100644 heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts create mode 100644 heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts create mode 100644 heft-plugins/heft-typescript-plugin/src/types.ts diff --git a/.vscode/launch.json b/.vscode/launch.json index 6084882d779..d52370624c1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -39,6 +39,24 @@ "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" }, + { + "type": "node", + "request": "launch", + "name": "Debug Build in Selected Project (Heft)", + "cwd": "${fileDirname}", + "runtimeArgs": [ + "--nolazy", + "--inspect-brk", + "${workspaceFolder}/apps/heft/lib/start.js", + "--debug", + "build" + ], + "skipFiles": ["/**"], + "outFiles": [], + "sourceMaps": true, + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen" + }, { "name": "Attach", "type": "node", diff --git a/build-tests/heft-typescript-composite-test/src/indexA.ts b/build-tests/heft-typescript-composite-test/src/indexA.ts index 6b4db719843..4394a4bf61e 100644 --- a/build-tests/heft-typescript-composite-test/src/indexA.ts +++ b/build-tests/heft-typescript-composite-test/src/indexA.ts @@ -8,3 +8,5 @@ import(/* webpackChunkName: 'chunk' */ './chunks/ChunkClass') .catch((e) => { console.log('Error: ' + e.message); }); + +export {}; diff --git a/build-tests/heft-typescript-composite-test/src/indexB.ts b/build-tests/heft-typescript-composite-test/src/indexB.ts index 16401835981..e122ca67a73 100644 --- a/build-tests/heft-typescript-composite-test/src/indexB.ts +++ b/build-tests/heft-typescript-composite-test/src/indexB.ts @@ -1 +1,3 @@ console.log('dostuff'); + +export {}; diff --git a/build-tests/heft-typescript-composite-test/tsconfig-base.json b/build-tests/heft-typescript-composite-test/tsconfig-base.json index 2c750bee0ce..520a0cf3447 100644 --- a/build-tests/heft-typescript-composite-test/tsconfig-base.json +++ b/build-tests/heft-typescript-composite-test/tsconfig-base.json @@ -16,6 +16,9 @@ "noUnusedLocals": true, "types": ["heft-jest", "webpack-env"], + "isolatedModules": true, + "importsNotUsedAsValues": "error", + "module": "esnext", "moduleResolution": "node", "target": "es5", diff --git a/build-tests/heft-webpack4-everything-test/src/indexA.ts b/build-tests/heft-webpack4-everything-test/src/indexA.ts index 6b4db719843..4394a4bf61e 100644 --- a/build-tests/heft-webpack4-everything-test/src/indexA.ts +++ b/build-tests/heft-webpack4-everything-test/src/indexA.ts @@ -8,3 +8,5 @@ import(/* webpackChunkName: 'chunk' */ './chunks/ChunkClass') .catch((e) => { console.log('Error: ' + e.message); }); + +export {}; diff --git a/build-tests/heft-webpack4-everything-test/src/indexB.ts b/build-tests/heft-webpack4-everything-test/src/indexB.ts index 16401835981..e122ca67a73 100644 --- a/build-tests/heft-webpack4-everything-test/src/indexB.ts +++ b/build-tests/heft-webpack4-everything-test/src/indexB.ts @@ -1 +1,3 @@ console.log('dostuff'); + +export {}; diff --git a/build-tests/heft-webpack4-everything-test/tsconfig.json b/build-tests/heft-webpack4-everything-test/tsconfig.json index 8a059e84bb0..eb547d1f50d 100644 --- a/build-tests/heft-webpack4-everything-test/tsconfig.json +++ b/build-tests/heft-webpack4-everything-test/tsconfig.json @@ -16,6 +16,7 @@ "noUnusedLocals": true, "types": ["heft-jest", "webpack-env"], "incremental": true, + "isolatedModules": true, "module": "esnext", "moduleResolution": "node", diff --git a/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts new file mode 100644 index 00000000000..8f37cdfc20e --- /dev/null +++ b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts @@ -0,0 +1,83 @@ +import { parentPort, workerData } from 'node:worker_threads'; + +import * as TTypescript from 'typescript'; +import type { + ITranspilationRequestMessage, + ITranspilationResponseMessage, + ITypescriptWorkerData +} from './types'; +import type { ExtendedTypeScript } from './internalTypings/TypeScriptInternals'; +import { configureProgramForMultiEmit } from './configureProgramForMultiEmit'; + +const typedWorkerData: ITypescriptWorkerData = workerData; + +const ts: ExtendedTypeScript = require(typedWorkerData.typeScriptToolPath); + +function handleMessage(message: ITranspilationRequestMessage | false): void { + if (!message) { + process.exit(0); + } + + const { requestId, compilerOptions, moduleKindsToEmit, fileNames } = message; + + const fullySkipTypeCheck: boolean = + compilerOptions.importsNotUsedAsValues === ts.ImportsNotUsedAsValues.Error; + + for (const [option, value] of Object.entries(ts.getDefaultCompilerOptions())) { + if (compilerOptions[option] === undefined) { + compilerOptions[option] = value; + } + } + + const { target: rawTarget } = compilerOptions; + + for (const option of ts.transpileOptionValueCompilerOptions) { + compilerOptions[option.name] = option.transpileOptionValue; + } + + compilerOptions.suppressOutputPathCheck = true; + compilerOptions.skipDefaultLibCheck = true; + compilerOptions.preserveValueImports = true; + + const sourceFileByPath: Map = new Map(); + + for (const fileName of fileNames) { + const sourceText: string | undefined = ts.sys.readFile(fileName); + if (sourceText) { + const sourceFile: TTypescript.SourceFile = ts.createSourceFile(fileName, sourceText, rawTarget!); + sourceFile.hasNoDefaultLib = fullySkipTypeCheck; + sourceFileByPath.set(fileName, sourceFile); + } + } + + const newLine: string = ts.getNewLineCharacter(compilerOptions); + + const compilerHost: TTypescript.CompilerHost = { + getSourceFile: (fileName: string) => sourceFileByPath.get(fileName), + writeFile: ts.sys.writeFile, + getDefaultLibFileName: () => 'lib.d.ts', + useCaseSensitiveFileNames: () => true, + getCanonicalFileName: (fileName: string) => fileName, + getCurrentDirectory: () => '', + getNewLine: () => newLine, + fileExists: (fileName: string) => sourceFileByPath.has(fileName), + readFile: () => '', + directoryExists: () => true, + getDirectories: () => [] + }; + + const program: TTypescript.Program = ts.createProgram(fileNames, compilerOptions, compilerHost); + + configureProgramForMultiEmit(program, ts, moduleKindsToEmit, 'transpile'); + + const result: TTypescript.EmitResult = program.emit(undefined, undefined, undefined, undefined, undefined); + + const response: ITranspilationResponseMessage = { + requestId, + result + }; + + parentPort!.postMessage(response); +} + +parentPort!.on('message', handleMessage); diff --git a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts index 54fab0052d3..1fd9266279b 100644 --- a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts +++ b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts @@ -4,15 +4,14 @@ import * as crypto from 'crypto'; import * as path from 'path'; import * as semver from 'semver'; -import type * as TTypescript from 'typescript'; +import * as TTypescript from 'typescript'; import { type ITerminal, JsonFile, type IPackageJson, Path, Async, - FileError, - InternalError + FileError } from '@rushstack/node-core-library'; import type { IScopedLogger } from '@rushstack/heft'; @@ -20,24 +19,14 @@ import type { ExtendedTypeScript, IExtendedSolutionBuilder } from './internalTyp import { TypeScriptCachedFileSystem } from './fileSystem/TypeScriptCachedFileSystem'; import type { ITypeScriptConfigurationJson } from './TypeScriptPlugin'; import type { PerformanceMeasurer, PerformanceMeasurerAsync } from './Performance'; - -interface ICachedEmitModuleKind { - moduleKind: TTypescript.ModuleKind; - - outFolderPath: string; - - /** - * File extension to use instead of '.js' for emitted ECMAScript files. - * For example, '.cjs' to indicate commonjs content, or '.mjs' to indicate ECMAScript modules. - */ - jsExtensionOverride: string | undefined; - - /** - * Set to true if this is the emit kind that is specified in the tsconfig.json. - * Declarations are only emitted for the primary module kind. - */ - isPrimary: boolean; -} +import type { + ICachedEmitModuleKind, + ITranspilationRequestMessage, + ITranspilationResponseMessage, + ITypescriptWorkerData +} from './types'; +import { configureProgramForMultiEmit } from './configureProgramForMultiEmit'; +import { Worker } from 'worker_threads'; export interface ITypeScriptBuilderConfiguration extends ITypeScriptConfigurationJson { /** @@ -131,10 +120,6 @@ const OLDEST_SUPPORTED_TS_MINOR_VERSION: number = 9; const NEWEST_SUPPORTED_TS_MAJOR_VERSION: number = 5; const NEWEST_SUPPORTED_TS_MINOR_VERSION: number = 0; -// symbols for attaching hidden metadata to ts.Program instances. -const INNER_GET_COMPILER_OPTIONS_SYMBOL: unique symbol = Symbol('getCompilerOptions'); -const INNER_EMIT_SYMBOL: unique symbol = Symbol('emit'); - interface ITypeScriptTool { ts: ExtendedTypeScript; measureSync: PerformanceMeasurer; @@ -151,6 +136,10 @@ interface ITypeScriptTool { executing: boolean; + worker: Worker | undefined; + pendingTranspilePromises: Map>; + pendingTranspileResolves: Map void>; + reportDiagnostic: TTypescript.DiagnosticReporter; clearTimeout: (timeout: IPendingWork) => void; setTimeout: (timeout: (...args: T) => void, ms: number, ...args: T) => IPendingWork; @@ -175,6 +164,8 @@ export class TypeScriptBuilder { private _tool: ITypeScriptTool | undefined = undefined; + private _nextRequestId: number = 0; + private get _tsCacheFilePath(): string { if (!this.__tsCacheFilePath) { // TypeScript internally handles if the tsconfig options have changed from when the tsbuildinfo file was created. @@ -361,7 +352,12 @@ export class TypeScriptBuilder { onChangeDetected(); } return timeout; - } + }, + + worker: undefined, + + pendingTranspilePromises: new Map(), + pendingTranspileResolves: new Map() }; } @@ -371,147 +367,22 @@ export class TypeScriptBuilder { performance.enable(); if (onChangeDetected !== undefined) { - this._runWatch(this._tool); + await this._runWatchAsync(this._tool); } else if (this._useSolutionBuilder) { - this._runSolutionBuild(this._tool); + await this._runSolutionBuildAsync(this._tool); } else { await this._runBuildAsync(this._tool); } } - private _configureProgramForMultiEmit( - innerProgram: TTypescript.Program, - ts: ExtendedTypeScript - ): { changedFiles: Set } { - interface IProgramWithMultiEmit extends TTypescript.Program { - // Attach the originals to the Program instance to avoid modifying the same Program twice. - // Don't use WeakMap because this Program could theoretically get a { ... } applied to it. - [INNER_GET_COMPILER_OPTIONS_SYMBOL]?: TTypescript.Program['getCompilerOptions']; - [INNER_EMIT_SYMBOL]?: TTypescript.Program['emit']; - } - - const program: IProgramWithMultiEmit = innerProgram; - - // Check to see if this Program has already been modified. - let { [INNER_EMIT_SYMBOL]: innerEmit, [INNER_GET_COMPILER_OPTIONS_SYMBOL]: innerGetCompilerOptions } = - program; - - if (!innerGetCompilerOptions) { - program[INNER_GET_COMPILER_OPTIONS_SYMBOL] = innerGetCompilerOptions = program.getCompilerOptions; - } - - if (!innerEmit) { - program[INNER_EMIT_SYMBOL] = innerEmit = program.emit; - } - - let foundPrimary: boolean = false; - let defaultModuleKind: TTypescript.ModuleKind; - - const multiEmitMap: Map = new Map(); - for (const moduleKindToEmit of this._moduleKindsToEmit) { - const kindCompilerOptions: TTypescript.CompilerOptions = moduleKindToEmit.isPrimary - ? { - ...innerGetCompilerOptions() - } - : { - ...innerGetCompilerOptions(), - module: moduleKindToEmit.moduleKind, - outDir: moduleKindToEmit.outFolderPath, - - // Don't emit declarations for secondary module kinds - declaration: false, - declarationMap: false - }; - if (!kindCompilerOptions.outDir) { - throw new InternalError('Expected compilerOptions.outDir to be assigned'); - } - multiEmitMap.set(moduleKindToEmit, kindCompilerOptions); - - if (moduleKindToEmit.isPrimary) { - if (foundPrimary) { - throw new Error('Multiple primary module emit kinds encountered.'); - } else { - foundPrimary = true; - } - - defaultModuleKind = moduleKindToEmit.moduleKind; - } - } - - const changedFiles: Set = new Set(); - - program.emit = ( - targetSourceFile?: TTypescript.SourceFile, - writeFile?: TTypescript.WriteFileCallback, - cancellationToken?: TTypescript.CancellationToken, - emitOnlyDtsFiles?: boolean, - customTransformers?: TTypescript.CustomTransformers - ) => { - if (emitOnlyDtsFiles) { - return program[INNER_EMIT_SYMBOL]!( - targetSourceFile, - writeFile, - cancellationToken, - emitOnlyDtsFiles, - customTransformers - ); - } - - if (targetSourceFile && changedFiles) { - changedFiles.add(targetSourceFile); - } - - const originalCompilerOptions: TTypescript.CompilerOptions = - program[INNER_GET_COMPILER_OPTIONS_SYMBOL]!(); - - let defaultModuleKindResult: TTypescript.EmitResult; - const diagnostics: TTypescript.Diagnostic[] = []; - let emitSkipped: boolean = false; - try { - for (const [moduleKindToEmit, kindCompilerOptions] of multiEmitMap) { - program.getCompilerOptions = () => kindCompilerOptions; - // Need to mutate the compiler options for the `module` field specifically, because emitWorker() captures - // options in the closure and passes it to `ts.getTransformers()` - originalCompilerOptions.module = moduleKindToEmit.moduleKind; - const flavorResult: TTypescript.EmitResult = program[INNER_EMIT_SYMBOL]!( - targetSourceFile, - writeFile && wrapWriteFile(writeFile, moduleKindToEmit.jsExtensionOverride), - cancellationToken, - emitOnlyDtsFiles, - customTransformers - ); - - emitSkipped = emitSkipped || flavorResult.emitSkipped; - // Need to aggregate diagnostics because some are impacted by the target module type - for (const diagnostic of flavorResult.diagnostics) { - diagnostics.push(diagnostic); - } - - if (moduleKindToEmit.moduleKind === defaultModuleKind) { - defaultModuleKindResult = flavorResult; - } - } - - const mergedDiagnostics: readonly TTypescript.Diagnostic[] = - ts.sortAndDeduplicateDiagnostics(diagnostics); - - return { - ...defaultModuleKindResult!, - changedSourceFiles: changedFiles, - diagnostics: mergedDiagnostics, - emitSkipped - }; - } finally { - // Restore the original compiler options and module kind for future calls - program.getCompilerOptions = program[INNER_GET_COMPILER_OPTIONS_SYMBOL]!; - originalCompilerOptions.module = defaultModuleKind; - } - }; - return { changedFiles }; - } - - public _runWatch(tool: ITypeScriptTool): void { - const { ts, measureSync: measureTsPerformance, pendingOperations, rawDiagnostics } = tool; + public async _runWatchAsync(tool: ITypeScriptTool): Promise { + const { + ts, + measureSync: measureTsPerformance, + pendingOperations, + rawDiagnostics, + pendingTranspilePromises + } = tool; if (!tool.solutionBuilder && !tool.watchProgram) { //#region CONFIGURE @@ -547,13 +418,27 @@ export class TypeScriptBuilder { pendingOperations.delete(operation); operation(); } + if (pendingTranspilePromises.size) { + const emitResults: TTypescript.EmitResult[] = await Promise.all(pendingTranspilePromises.values()); + for (const { diagnostics } of emitResults) { + for (const diagnostic of diagnostics) { + rawDiagnostics.push(diagnostic); + } + } + } + // eslint-disable-next-line require-atomic-updates tool.executing = false; } this._logDiagnostics(ts, rawDiagnostics); } public async _runBuildAsync(tool: ITypeScriptTool): Promise { - const { ts, measureSync: measureTsPerformance, measureAsync: measureTsPerformanceAsync } = tool; + const { + ts, + measureSync: measureTsPerformance, + measureAsync: measureTsPerformanceAsync, + pendingTranspilePromises + } = tool; //#region CONFIGURE const { @@ -579,17 +464,26 @@ export class TypeScriptBuilder { let builderProgram: TTypescript.BuilderProgram | undefined = undefined; let innerProgram: TTypescript.Program; + const isolatedModules: boolean = + !!this._configuration.useTranspilerWorker && !!tsconfig.options.isolatedModules; + const mode: 'both' | 'declaration' = isolatedModules ? 'declaration' : 'both'; + + let fileNames: string[] | undefined; + if (tsconfig.options.incremental) { // Use ts.createEmitAndSemanticDiagnositcsBuilderProgram directly because the customizations performed by // _getCreateBuilderProgram duplicate those performed in this function for non-incremental build. + const oldProgram: TTypescript.EmitAndSemanticDiagnosticsBuilderProgram | undefined = + ts.readBuilderProgram(tsconfig.options, compilerHost); builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram( tsconfig.fileNames, tsconfig.options, compilerHost, - ts.readBuilderProgram(tsconfig.options, compilerHost), + oldProgram, ts.getConfigFileParsingDiagnostics(tsconfig), tsconfig.projectReferences ); + fileNames = getFilesToTranspileFromBuilderProgram(builderProgram); innerProgram = builderProgram.getProgram(); } else { innerProgram = ts.createProgram({ @@ -600,6 +494,7 @@ export class TypeScriptBuilder { oldProgram: undefined, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(tsconfig) }); + fileNames = getFilesToTranspileFromProgram(innerProgram); } // Prefer the builder program, since it is what gives us incremental builds @@ -608,6 +503,11 @@ export class TypeScriptBuilder { this._logReadPerformance(ts); //#endregion + if (isolatedModules) { + // Kick the transpilation worker. + this._queueTranspileInWorker(tool, genericProgram.getCompilerOptions(), fileNames); + } + //#region ANALYSIS const { duration: diagnosticsDurationMs, diagnostics: preDiagnostics } = measureTsPerformance( 'Analyze', @@ -632,7 +532,7 @@ export class TypeScriptBuilder { filesToWrite.push({ filePath, data }); }; - const { changedFiles } = this._configureProgramForMultiEmit(innerProgram, ts); + const { changedFiles } = configureProgramForMultiEmit(innerProgram, ts, this._moduleKindsToEmit, mode); const emitResult: TTypescript.EmitResult = genericProgram.emit(undefined, writeFileCallback); //#endregion @@ -657,6 +557,17 @@ export class TypeScriptBuilder { ); //#endregion + this._configuration.emitChangedFilesCallback(innerProgram, changedFiles); + + if (pendingTranspilePromises.size) { + const emitResults: TTypescript.EmitResult[] = await Promise.all(pendingTranspilePromises.values()); + for (const { diagnostics } of emitResults) { + for (const diagnostic of diagnostics) { + rawDiagnostics.push(diagnostic); + } + } + } + const { duration: writeDuration } = await writePromise; this._typescriptTerminal.writeVerboseLine(`I/O Write: ${writeDuration}ms (${filesToWrite.length} files)`); @@ -664,13 +575,14 @@ export class TypeScriptBuilder { // Reset performance counters in case any are used in the callback ts.performance.disable(); ts.performance.enable(); - this._configuration.emitChangedFilesCallback(innerProgram, changedFiles); + + await this._cleanupWorkerAsync(); } - public _runSolutionBuild(tool: ITypeScriptTool): void { + public async _runSolutionBuildAsync(tool: ITypeScriptTool): Promise { this._typescriptTerminal.writeVerboseLine(`Using solution mode`); - const { ts, measureSync, rawDiagnostics } = tool; + const { ts, measureSync, rawDiagnostics, pendingTranspilePromises } = tool; rawDiagnostics.length = 0; if (!tool.solutionBuilder) { @@ -705,7 +617,18 @@ export class TypeScriptBuilder { tool.solutionBuilder.build(); //#endregion + if (pendingTranspilePromises.size) { + const emitResults: TTypescript.EmitResult[] = await Promise.all(pendingTranspilePromises.values()); + for (const { diagnostics } of emitResults) { + for (const diagnostic of diagnostics) { + rawDiagnostics.push(diagnostic); + } + } + } + this._logDiagnostics(ts, rawDiagnostics); + + await this._cleanupWorkerAsync(); } private _logDiagnostics(ts: ExtendedTypeScript, rawDiagnostics: TTypescript.Diagnostic[]): void { @@ -1084,6 +1007,16 @@ export class TypeScriptBuilder { this._logReadPerformance(ts); + const isolatedModules: boolean = + !!this._configuration.useTranspilerWorker && !!compilerOptions!.isolatedModules; + const mode: 'both' | 'declaration' = isolatedModules ? 'declaration' : 'both'; + + if (isolatedModules) { + // Kick the transpilation worker. + const fileNamesToTranspile: string[] = getFilesToTranspileFromBuilderProgram(newProgram); + this._queueTranspileInWorker(this._tool!, compilerOptions!, fileNamesToTranspile); + } + const { emit: originalEmit } = newProgram; const emit: TTypescript.Program['emit'] = ( @@ -1097,7 +1030,12 @@ export class TypeScriptBuilder { const innerCompilerOptions: TTypescript.CompilerOptions = innerProgram.getCompilerOptions(); - const { changedFiles } = this._configureProgramForMultiEmit(innerProgram, ts); + const { changedFiles } = configureProgramForMultiEmit( + innerProgram, + ts, + this._moduleKindsToEmit, + mode + ); const result: TTypescript.EmitResult = originalEmit.call( newProgram, @@ -1293,32 +1231,92 @@ export class TypeScriptBuilder { throw new Error(`"${moduleKindName}" is not a valid module kind name.`); } } -} -const JS_EXTENSION_REGEX: RegExp = /\.js(\.map)?$/; + private _queueTranspileInWorker( + tool: ITypeScriptTool, + compilerOptions: TTypescript.CompilerOptions, + fileNames: string[] + ): void { + const { pendingTranspilePromises, pendingTranspileResolves } = tool; + let maybeWorker: Worker | undefined = tool.worker; + if (!maybeWorker) { + const workerData: ITypescriptWorkerData = { + typeScriptToolPath: this._configuration.typeScriptToolPath + }; + tool.worker = maybeWorker = new Worker(require.resolve('./TranspilerWorker.js'), { + workerData: workerData + }); -function wrapWriteFile( - baseWriteFile: TTypescript.WriteFileCallback, - jsExtensionOverride: string | undefined -): TTypescript.WriteFileCallback { - if (!jsExtensionOverride) { - return baseWriteFile; - } + maybeWorker.on('message', (response: ITranspilationResponseMessage) => { + const { requestId: resolvingRequestId, result } = response; + const resolve: ((result: TTypescript.EmitResult) => void) | undefined = + pendingTranspileResolves.get(resolvingRequestId); + if (resolve) { + resolve(result); + } else { + this._typescriptTerminal.writeErrorLine( + `Unexpected worker resolution for request with id ${resolvingRequestId}` + ); + } + }); + } - const replacementExtension: string = `${jsExtensionOverride}$1`; - return ( - fileName: string, - data: string, - writeBOM: boolean, - onError?: ((message: string) => void) | undefined, - sourceFiles?: readonly TTypescript.SourceFile[] | undefined - ) => { - return baseWriteFile( - fileName.replace(JS_EXTENSION_REGEX, replacementExtension), - data, - writeBOM, - onError, - sourceFiles + // make linter happy + const worker: Worker = maybeWorker; + + const requestId: number = ++this._nextRequestId; + const transpilePromise: Promise = new Promise( + (resolve: (result: TTypescript.EmitResult) => void, reject: (err: Error) => void) => { + pendingTranspileResolves.set(requestId, resolve); + + this._typescriptTerminal.writeLine(`Asynchronously transpiling ${compilerOptions.configFilePath}`); + const request: ITranspilationRequestMessage = { + compilerOptions, + fileNames, + moduleKindsToEmit: this._moduleKindsToEmit, + requestId + }; + + worker.postMessage(request); + } ); - }; + + pendingTranspilePromises.set(requestId, transpilePromise); + } + + private async _cleanupWorkerAsync(): Promise { + const worker: Worker | undefined = this._tool?.worker; + if (worker) { + this._typescriptTerminal.writeLine(`Waiting for worker to exit`); + await new Promise((resolve: () => void, reject: (err: Error) => void) => { + worker.on('exit', resolve); + this._tool!.worker = undefined; + worker.postMessage(false); + }); + } + } +} + +function getFilesToTranspileFromBuilderProgram(builderProgram: TTypescript.BuilderProgram): string[] { + const changedFilesSet: Set = ( + builderProgram as unknown as { getState(): { changedFilesSet: Set } } + ).getState().changedFilesSet; + const fileNames: string[] = []; + for (const fileName of changedFilesSet) { + const sourceFile: TTypescript.SourceFile | undefined = builderProgram.getSourceFile(fileName); + if (sourceFile && !sourceFile.isDeclarationFile) { + fileNames.push(fileName); + } + } + return fileNames; +} + +function getFilesToTranspileFromProgram(program: TTypescript.Program): string[] { + const fileNames: string[] = []; + for (const sourceFile of program.getSourceFiles()) { + if (!sourceFile.isDeclarationFile) { + fileNames.push(sourceFile.fileName); + } + } + return fileNames; } diff --git a/heft-plugins/heft-typescript-plugin/src/TypeScriptPlugin.ts b/heft-plugins/heft-typescript-plugin/src/TypeScriptPlugin.ts index f15a530123e..db0104f7f61 100644 --- a/heft-plugins/heft-typescript-plugin/src/TypeScriptPlugin.ts +++ b/heft-plugins/heft-typescript-plugin/src/TypeScriptPlugin.ts @@ -70,6 +70,11 @@ export interface ITypeScriptConfigurationJson { */ buildProjectReferences?: boolean; + /** + * If true, and the tsconfig has \"isolatedModules\": true, then transpilation will happen in parallel in a worker thread. + */ + useTranspilerWorker?: boolean; + /* * Specifies the tsconfig.json file that will be used for compilation. Equivalent to the "project" argument for the 'tsc' and 'tslint' command line tools. * @@ -363,6 +368,8 @@ export default class TypeScriptPlugin implements IHeftTaskPlugin { buildProjectReferences: typeScriptConfigurationJson?.buildProjectReferences, + useTranspilerWorker: typeScriptConfigurationJson?.useTranspilerWorker, + tsconfigPath: getTsconfigFilePath(heftConfiguration, typeScriptConfigurationJson), additionalModuleKindsToEmit: typeScriptConfigurationJson?.additionalModuleKindsToEmit, emitCjsExtensionForCommonJS: !!typeScriptConfigurationJson?.emitCjsExtensionForCommonJS, diff --git a/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts b/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts new file mode 100644 index 00000000000..65b2ebe45f8 --- /dev/null +++ b/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts @@ -0,0 +1,181 @@ +import type * as TTypescript from 'typescript'; +import { InternalError } from '@rushstack/node-core-library'; + +import type { ExtendedTypeScript } from './internalTypings/TypeScriptInternals'; +import type { ICachedEmitModuleKind } from './types'; + +// symbols for attaching hidden metadata to ts.Program instances. +const INNER_GET_COMPILER_OPTIONS_SYMBOL: unique symbol = Symbol('getCompilerOptions'); +const INNER_EMIT_SYMBOL: unique symbol = Symbol('emit'); + +const JS_EXTENSION_REGEX: RegExp = /\.js(\.map)?$/; + +function wrapWriteFile( + this: void, + baseWriteFile: TTypescript.WriteFileCallback, + jsExtensionOverride: string | undefined +): TTypescript.WriteFileCallback { + if (!jsExtensionOverride) { + return baseWriteFile; + } + + const replacementExtension: string = `${jsExtensionOverride}$1`; + return ( + fileName: string, + data: string, + writeBOM: boolean, + onError?: ((message: string) => void) | undefined, + sourceFiles?: readonly TTypescript.SourceFile[] | undefined + ) => { + return baseWriteFile( + fileName.replace(JS_EXTENSION_REGEX, replacementExtension), + data, + writeBOM, + onError, + sourceFiles + ); + }; +} + +export function configureProgramForMultiEmit( + this: void, + innerProgram: TTypescript.Program, + ts: ExtendedTypeScript, + moduleKindsToEmit: ICachedEmitModuleKind[], + mode: 'transpile' | 'declaration' | 'both' +): { changedFiles: Set } { + interface IProgramWithMultiEmit extends TTypescript.Program { + // Attach the originals to the Program instance to avoid modifying the same Program twice. + // Don't use WeakMap because this Program could theoretically get a { ... } applied to it. + [INNER_GET_COMPILER_OPTIONS_SYMBOL]?: TTypescript.Program['getCompilerOptions']; + [INNER_EMIT_SYMBOL]?: TTypescript.Program['emit']; + } + + const program: IProgramWithMultiEmit = innerProgram; + + // Check to see if this Program has already been modified. + let { [INNER_EMIT_SYMBOL]: innerEmit, [INNER_GET_COMPILER_OPTIONS_SYMBOL]: innerGetCompilerOptions } = + program; + + if (!innerGetCompilerOptions) { + program[INNER_GET_COMPILER_OPTIONS_SYMBOL] = innerGetCompilerOptions = program.getCompilerOptions; + } + + if (!innerEmit) { + program[INNER_EMIT_SYMBOL] = innerEmit = program.emit; + } + + let foundPrimary: boolean = false; + let defaultModuleKind: TTypescript.ModuleKind; + + const multiEmitMap: Map = new Map(); + for (const moduleKindToEmit of moduleKindsToEmit) { + const kindCompilerOptions: TTypescript.CompilerOptions = moduleKindToEmit.isPrimary + ? { + ...innerGetCompilerOptions() + } + : { + ...innerGetCompilerOptions(), + module: moduleKindToEmit.moduleKind, + outDir: moduleKindToEmit.outFolderPath, + + // Don't emit declarations for secondary module kinds + declaration: false, + declarationMap: false + }; + if (!kindCompilerOptions.outDir) { + throw new InternalError('Expected compilerOptions.outDir to be assigned'); + } + if (mode === 'transpile') { + kindCompilerOptions.declaration = false; + kindCompilerOptions.declarationMap = false; + } else if (mode === 'declaration') { + kindCompilerOptions.emitDeclarationOnly = true; + } + + if (moduleKindToEmit.isPrimary || mode !== 'declaration') { + multiEmitMap.set(moduleKindToEmit, kindCompilerOptions); + } + + if (moduleKindToEmit.isPrimary) { + if (foundPrimary) { + throw new Error('Multiple primary module emit kinds encountered.'); + } else { + foundPrimary = true; + } + + defaultModuleKind = moduleKindToEmit.moduleKind; + } + } + + const changedFiles: Set = new Set(); + + program.emit = ( + targetSourceFile?: TTypescript.SourceFile, + writeFile?: TTypescript.WriteFileCallback, + cancellationToken?: TTypescript.CancellationToken, + emitOnlyDtsFiles?: boolean, + customTransformers?: TTypescript.CustomTransformers + ) => { + if (emitOnlyDtsFiles) { + return program[INNER_EMIT_SYMBOL]!( + targetSourceFile, + writeFile, + cancellationToken, + emitOnlyDtsFiles, + customTransformers + ); + } + + if (targetSourceFile && changedFiles) { + changedFiles.add(targetSourceFile); + } + + const originalCompilerOptions: TTypescript.CompilerOptions = + program[INNER_GET_COMPILER_OPTIONS_SYMBOL]!(); + + let defaultModuleKindResult: TTypescript.EmitResult; + const diagnostics: TTypescript.Diagnostic[] = []; + let emitSkipped: boolean = false; + try { + for (const [moduleKindToEmit, kindCompilerOptions] of multiEmitMap) { + program.getCompilerOptions = () => kindCompilerOptions; + // Need to mutate the compiler options for the `module` field specifically, because emitWorker() captures + // options in the closure and passes it to `ts.getTransformers()` + originalCompilerOptions.module = moduleKindToEmit.moduleKind; + const flavorResult: TTypescript.EmitResult = program[INNER_EMIT_SYMBOL]!( + targetSourceFile, + writeFile && wrapWriteFile(writeFile, moduleKindToEmit.jsExtensionOverride), + cancellationToken, + emitOnlyDtsFiles, + customTransformers + ); + + emitSkipped = emitSkipped || flavorResult.emitSkipped; + // Need to aggregate diagnostics because some are impacted by the target module type + for (const diagnostic of flavorResult.diagnostics) { + diagnostics.push(diagnostic); + } + + if (moduleKindToEmit.moduleKind === defaultModuleKind) { + defaultModuleKindResult = flavorResult; + } + } + + const mergedDiagnostics: readonly TTypescript.Diagnostic[] = + ts.sortAndDeduplicateDiagnostics(diagnostics); + + return { + ...defaultModuleKindResult!, + changedSourceFiles: changedFiles, + diagnostics: mergedDiagnostics, + emitSkipped + }; + } finally { + // Restore the original compiler options and module kind for future calls + program.getCompilerOptions = program[INNER_GET_COMPILER_OPTIONS_SYMBOL]!; + originalCompilerOptions.module = defaultModuleKind; + } + }; + return { changedFiles }; +} diff --git a/heft-plugins/heft-typescript-plugin/src/internalTypings/TypeScriptInternals.ts b/heft-plugins/heft-typescript-plugin/src/internalTypings/TypeScriptInternals.ts index a4d78dbfbdf..5701e0f9ddb 100644 --- a/heft-plugins/heft-typescript-plugin/src/internalTypings/TypeScriptInternals.ts +++ b/heft-plugins/heft-typescript-plugin/src/internalTypings/TypeScriptInternals.ts @@ -45,6 +45,14 @@ export interface IExtendedTypeScript { getCount(measureName: string): number; }; + transpileOptionValueCompilerOptions: { + name: keyof TTypescript.CompilerOptions; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + transpileOptionValue: any; + }[]; + + getNewLineCharacter(compilerOptions: TTypescript.CompilerOptions): string; + /** * https://github.com/microsoft/TypeScript/blob/782c09d783e006a697b4ba6d1e7ec2f718ce8393/src/compiler/utilities.ts#L6540 */ diff --git a/heft-plugins/heft-typescript-plugin/src/schemas/typescript.schema.json b/heft-plugins/heft-typescript-plugin/src/schemas/typescript.schema.json index af0f3ba1097..2406afaa8e3 100644 --- a/heft-plugins/heft-typescript-plugin/src/schemas/typescript.schema.json +++ b/heft-plugins/heft-typescript-plugin/src/schemas/typescript.schema.json @@ -52,6 +52,11 @@ "type": "boolean" }, + "useTranspilerWorker": { + "description": "If true, and the tsconfig has \"isolatedModules\": true, then transpilation will happen in parallel in a worker thread.", + "type": "boolean" + }, + "project": { "description": "Specifies the tsconfig.json file that will be used for compilation. Equivalent to the \"project\" argument for the 'tsc' and 'tslint' command line tools. The default value is \"./tsconfig.json\".", "type": "string" diff --git a/heft-plugins/heft-typescript-plugin/src/types.ts b/heft-plugins/heft-typescript-plugin/src/types.ts new file mode 100644 index 00000000000..1463144b03b --- /dev/null +++ b/heft-plugins/heft-typescript-plugin/src/types.ts @@ -0,0 +1,50 @@ +import type * as TTypescript from 'typescript'; + +export interface ITypescriptWorkerData { + /** + * Path to the version of TypeScript to use. + */ + typeScriptToolPath: string; +} + +export interface ITranspilationRequestMessage { + /** + * Unique identifier for this request. + */ + requestId: number; + /** + * The tsconfig compiler options to use for the request. + */ + compilerOptions: TTypescript.CompilerOptions; + /** + * The variants to emit. + */ + moduleKindsToEmit: ICachedEmitModuleKind[]; + /** + * The set of files to build. + */ + fileNames: string[]; +} + +export interface ITranspilationResponseMessage { + requestId: number; + result: TTypescript.EmitResult; +} + +export interface ICachedEmitModuleKind { + moduleKind: TTypescript.ModuleKind; + + outFolderPath: string; + + /** + * File extension to use instead of '.js' for emitted ECMAScript files. + * For example, '.cjs' to indicate commonjs content, or '.mjs' to indicate ECMAScript modules. + */ + jsExtensionOverride: string | undefined; + + /** + * Set to true if this is the emit kind that is specified in the tsconfig.json. + * Declarations are only emitted for the primary module kind. + */ + isPrimary: boolean; +} From 3e02f93fc50a191d1cca022ea21b5a6707fe5985 Mon Sep 17 00:00:00 2001 From: David Michon Date: Thu, 18 May 2023 15:22:33 -0700 Subject: [PATCH 2/4] [heft-typescript] Add error handling, fix Windows --- .../config/typescript.json | 4 +- .../reviews/api/heft-typescript-plugin.api.md | 1 + .../src/TranspilerWorker.ts | 25 ++++++- .../src/TypeScriptBuilder.ts | 71 ++++++++++++++----- .../heft-typescript-plugin/src/types.ts | 14 +++- .../heft-typescript-plugin/tsconfig.json | 3 +- 6 files changed, 95 insertions(+), 23 deletions(-) diff --git a/build-tests/heft-webpack4-everything-test/config/typescript.json b/build-tests/heft-webpack4-everything-test/config/typescript.json index 76f0a6e9340..e672741b44e 100644 --- a/build-tests/heft-webpack4-everything-test/config/typescript.json +++ b/build-tests/heft-webpack4-everything-test/config/typescript.json @@ -55,5 +55,7 @@ // "excludeGlobs": [ // "some/path/*.css" // ] - } + }, + + "useTranspilerWorker": true } diff --git a/common/reviews/api/heft-typescript-plugin.api.md b/common/reviews/api/heft-typescript-plugin.api.md index b97ad70b765..e0671977644 100644 --- a/common/reviews/api/heft-typescript-plugin.api.md +++ b/common/reviews/api/heft-typescript-plugin.api.md @@ -59,6 +59,7 @@ export interface ITypeScriptConfigurationJson { // (undocumented) project?: string; staticAssetsToCopy?: IStaticAssetsCopyConfiguration; + useTranspilerWorker?: boolean; } // @beta (undocumented) diff --git a/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts index 8f37cdfc20e..a0f88213eb9 100644 --- a/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts +++ b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts @@ -2,8 +2,9 @@ import { parentPort, workerData } from 'node:worker_threads'; import * as TTypescript from 'typescript'; import type { + ITranspilationErrorMessage, ITranspilationRequestMessage, - ITranspilationResponseMessage, + ITranspilationSuccessMessage, ITypescriptWorkerData } from './types'; import type { ExtendedTypeScript } from './internalTypings/TypeScriptInternals'; @@ -18,6 +19,23 @@ function handleMessage(message: ITranspilationRequestMessage | false): void { process.exit(0); } + try { + const response: ITranspilationSuccessMessage = runTranspiler(message); + parentPort!.postMessage(response); + } catch (err) { + const errorResponse: ITranspilationErrorMessage = { + requestId: message.requestId, + type: 'error', + result: { + message: err.message, + ...Object.fromEntries(Object.entries(err)) + } + }; + parentPort!.postMessage(errorResponse); + } +} + +function runTranspiler(message: ITranspilationRequestMessage): ITranspilationSuccessMessage { const { requestId, compilerOptions, moduleKindsToEmit, fileNames } = message; const fullySkipTypeCheck: boolean = @@ -72,12 +90,13 @@ function handleMessage(message: ITranspilationRequestMessage | false): void { const result: TTypescript.EmitResult = program.emit(undefined, undefined, undefined, undefined, undefined); - const response: ITranspilationResponseMessage = { + const response: ITranspilationSuccessMessage = { requestId, + type: 'success', result }; - parentPort!.postMessage(response); + return response; } parentPort!.on('message', handleMessage); diff --git a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts index 1fd9266279b..6c9fa6ce566 100644 --- a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts +++ b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts @@ -114,6 +114,11 @@ interface IPendingWork { (): void; } +interface ITranspileSignal { + resolve: (result: TTypescript.EmitResult) => void; + reject: (error: Error) => void; +} + const OLDEST_SUPPORTED_TS_MAJOR_VERSION: number = 2; const OLDEST_SUPPORTED_TS_MINOR_VERSION: number = 9; @@ -137,8 +142,9 @@ interface ITypeScriptTool { executing: boolean; worker: Worker | undefined; + workerExitPromise: Promise | undefined; pendingTranspilePromises: Map>; - pendingTranspileResolves: Map void>; + pendingTranspileSignals: Map; reportDiagnostic: TTypescript.DiagnosticReporter; clearTimeout: (timeout: IPendingWork) => void; @@ -355,9 +361,10 @@ export class TypeScriptBuilder { }, worker: undefined, + workerExitPromise: undefined, pendingTranspilePromises: new Map(), - pendingTranspileResolves: new Map() + pendingTranspileSignals: new Map() }; } @@ -1237,7 +1244,7 @@ export class TypeScriptBuilder { compilerOptions: TTypescript.CompilerOptions, fileNames: string[] ): void { - const { pendingTranspilePromises, pendingTranspileResolves } = tool; + const { pendingTranspilePromises, pendingTranspileSignals } = tool; let maybeWorker: Worker | undefined = tool.worker; if (!maybeWorker) { const workerData: ITypescriptWorkerData = { @@ -1248,17 +1255,43 @@ export class TypeScriptBuilder { }); maybeWorker.on('message', (response: ITranspilationResponseMessage) => { - const { requestId: resolvingRequestId, result } = response; - const resolve: ((result: TTypescript.EmitResult) => void) | undefined = - pendingTranspileResolves.get(resolvingRequestId); - if (resolve) { - resolve(result); + const { requestId: resolvingRequestId, type, result } = response; + const signal: ITranspileSignal | undefined = pendingTranspileSignals.get(resolvingRequestId); + + if (type === 'error') { + const error: Error = Object.assign(new Error(result.message), result); + if (signal) { + signal.reject(error); + } else { + this._typescriptTerminal.writeErrorLine( + `Unexpected worker rejection for request with id ${resolvingRequestId}: ${error}` + ); + } + } else if (signal) { + signal.resolve(result); } else { this._typescriptTerminal.writeErrorLine( `Unexpected worker resolution for request with id ${resolvingRequestId}` ); } + + pendingTranspileSignals.delete(resolvingRequestId); + pendingTranspilePromises.delete(resolvingRequestId); }); + + tool.workerExitPromise = new Promise( + (resolve: (exitCode: number) => void, reject: (err: Error) => void) => { + maybeWorker!.once('exit', resolve); + + maybeWorker!.once('error', (err: Error) => { + for (const { reject: rejectTranspile } of pendingTranspileSignals.values()) { + rejectTranspile(err); + } + pendingTranspileSignals.clear(); + reject(err); + }); + } + ); } // make linter happy @@ -1267,7 +1300,7 @@ export class TypeScriptBuilder { const requestId: number = ++this._nextRequestId; const transpilePromise: Promise = new Promise( (resolve: (result: TTypescript.EmitResult) => void, reject: (err: Error) => void) => { - pendingTranspileResolves.set(requestId, resolve); + pendingTranspileSignals.set(requestId, { resolve, reject }); this._typescriptTerminal.writeLine(`Asynchronously transpiling ${compilerOptions.configFilePath}`); const request: ITranspilationRequestMessage = { @@ -1285,14 +1318,18 @@ export class TypeScriptBuilder { } private async _cleanupWorkerAsync(): Promise { - const worker: Worker | undefined = this._tool?.worker; - if (worker) { + const tool: ITypeScriptTool | undefined = this._tool; + if (!tool) { + return; + } + + const { worker, workerExitPromise } = tool; + if (worker && workerExitPromise) { + worker.postMessage(false); this._typescriptTerminal.writeLine(`Waiting for worker to exit`); - await new Promise((resolve: () => void, reject: (err: Error) => void) => { - worker.on('exit', resolve); - this._tool!.worker = undefined; - worker.postMessage(false); - }); + await workerExitPromise; + tool.worker = undefined; + tool.workerExitPromise = undefined; } } } @@ -1305,7 +1342,7 @@ function getFilesToTranspileFromBuilderProgram(builderProgram: TTypescript.Build for (const fileName of changedFilesSet) { const sourceFile: TTypescript.SourceFile | undefined = builderProgram.getSourceFile(fileName); if (sourceFile && !sourceFile.isDeclarationFile) { - fileNames.push(fileName); + fileNames.push(sourceFile.fileName); } } return fileNames; diff --git a/heft-plugins/heft-typescript-plugin/src/types.ts b/heft-plugins/heft-typescript-plugin/src/types.ts index 1463144b03b..d58f3b4a25c 100644 --- a/heft-plugins/heft-typescript-plugin/src/types.ts +++ b/heft-plugins/heft-typescript-plugin/src/types.ts @@ -26,11 +26,23 @@ export interface ITranspilationRequestMessage { fileNames: string[]; } -export interface ITranspilationResponseMessage { +export interface ITranspilationSuccessMessage { requestId: number; + type: 'success'; result: TTypescript.EmitResult; } +export interface ITranspilationErrorMessage { + requestId: number; + type: 'error'; + result: { + message: string; + [key: string]: unknown; + }; +} + +export type ITranspilationResponseMessage = ITranspilationSuccessMessage | ITranspilationErrorMessage; + export interface ICachedEmitModuleKind { moduleKind: TTypescript.ModuleKind; diff --git a/heft-plugins/heft-typescript-plugin/tsconfig.json b/heft-plugins/heft-typescript-plugin/tsconfig.json index 7512871fdbf..14f45ad644e 100644 --- a/heft-plugins/heft-typescript-plugin/tsconfig.json +++ b/heft-plugins/heft-typescript-plugin/tsconfig.json @@ -2,6 +2,7 @@ "extends": "./node_modules/@rushstack/heft-node-rig/profiles/default/tsconfig-base.json", "compilerOptions": { - "types": ["node"] + "types": ["node"], + "lib": ["ES2019"] } } From 8c155d3e2e438e44bd0e9be2316627693a2ea96c Mon Sep 17 00:00:00 2001 From: David Michon Date: Thu, 18 May 2023 15:43:27 -0700 Subject: [PATCH 3/4] (chore) Fix start command --- build-tests/heft-webpack4-everything-test/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-tests/heft-webpack4-everything-test/package.json b/build-tests/heft-webpack4-everything-test/package.json index 4edb9b07111..bd054a1895f 100644 --- a/build-tests/heft-webpack4-everything-test/package.json +++ b/build-tests/heft-webpack4-everything-test/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "build": "heft build --clean", - "start": "heft start", + "start": "heft build-watch --serve", "_phase:build": "heft run --only build -- --clean", "_phase:test": "heft run --only test -- --clean" }, From b67eb49ebd3407f6eb17644fbb3439c1ef2601fe Mon Sep 17 00:00:00 2001 From: David Michon Date: Thu, 18 May 2023 16:02:53 -0700 Subject: [PATCH 4/4] (chore) import type, add copyright headers --- heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts | 4 +++- heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts | 5 +++-- .../src/configureProgramForMultiEmit.ts | 2 ++ heft-plugins/heft-typescript-plugin/src/types.ts | 2 ++ 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts index a0f88213eb9..19984ec334a 100644 --- a/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts +++ b/heft-plugins/heft-typescript-plugin/src/TranspilerWorker.ts @@ -1,6 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. import { parentPort, workerData } from 'node:worker_threads'; -import * as TTypescript from 'typescript'; +import type * as TTypescript from 'typescript'; import type { ITranspilationErrorMessage, ITranspilationRequestMessage, diff --git a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts index 6c9fa6ce566..7dabb6ed718 100644 --- a/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts +++ b/heft-plugins/heft-typescript-plugin/src/TypeScriptBuilder.ts @@ -3,8 +3,10 @@ import * as crypto from 'crypto'; import * as path from 'path'; +import { Worker } from 'worker_threads'; + import * as semver from 'semver'; -import * as TTypescript from 'typescript'; +import type * as TTypescript from 'typescript'; import { type ITerminal, JsonFile, @@ -26,7 +28,6 @@ import type { ITypescriptWorkerData } from './types'; import { configureProgramForMultiEmit } from './configureProgramForMultiEmit'; -import { Worker } from 'worker_threads'; export interface ITypeScriptBuilderConfiguration extends ITypeScriptConfigurationJson { /** diff --git a/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts b/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts index 65b2ebe45f8..6cfbd7cfe6b 100644 --- a/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts +++ b/heft-plugins/heft-typescript-plugin/src/configureProgramForMultiEmit.ts @@ -1,3 +1,5 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. import type * as TTypescript from 'typescript'; import { InternalError } from '@rushstack/node-core-library'; diff --git a/heft-plugins/heft-typescript-plugin/src/types.ts b/heft-plugins/heft-typescript-plugin/src/types.ts index d58f3b4a25c..aea0ee72955 100644 --- a/heft-plugins/heft-typescript-plugin/src/types.ts +++ b/heft-plugins/heft-typescript-plugin/src/types.ts @@ -1,3 +1,5 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. import type * as TTypescript from 'typescript'; export interface ITypescriptWorkerData {