import type { PluginContext } from 'rollup'; import typescript from 'typescript'; import type { CustomTransformers, Diagnostic, EmitAndSemanticDiagnosticsBuilderProgram, ParsedCommandLine, Program, WatchCompilerHostOfFilesAndCompilerOptions, WatchStatusReporter, WriteFileCallback } from 'typescript'; import type { CustomTransformerFactories } from '../types'; import { buildDiagnosticReporter } from './diagnostics/emit'; import type { DiagnosticsHost } from './diagnostics/host'; import type { Resolver } from './moduleResolution'; import { mergeTransformers } from './customTransformers'; const { DiagnosticCategory } = typescript; type BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram; // @see https://github.com/microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json // eslint-disable-next-line no-shadow enum DiagnosticCode { FILE_CHANGE_DETECTED = 6032, FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES = 6193, FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES = 6194 } interface CreateProgramOptions { /** Formatting host used to get some system functions and emit type errors. */ formatHost: DiagnosticsHost; /** Parsed Typescript compiler options. */ parsedOptions: ParsedCommandLine; /** Callback to save compiled files in memory. */ writeFile: WriteFileCallback; /** Callback for the Typescript status reporter. */ status: WatchStatusReporter; /** Function to resolve a module location */ resolveModule: Resolver; /** Custom TypeScript transformers */ transformers?: CustomTransformerFactories | ((program: Program) => CustomTransformers); /** * Advanced: when true, recreate custom transformer factories on each * TypeScript watch rebuild. Defaults to legacy behavior (false), which * reuses the same factories for the lifetime of the watch session. */ recreateTransformersOnRebuild?: boolean; } type DeferredResolve = ((value: boolean | PromiseLike) => void) | (() => void); interface Deferred { promise: Promise; resolve: DeferredResolve; } function createDeferred(timeout?: number): Deferred { let promise: Promise; let resolve: DeferredResolve = () => {}; if (timeout) { promise = Promise.race([ new Promise((r) => setTimeout(r, timeout, true)), new Promise((r) => (resolve = r)) ]); } else { promise = new Promise((r) => (resolve = r)); } return { promise, resolve }; } /** * Typescript watch program helper to sync Typescript watch status with Rollup hooks. */ export class WatchProgramHelper { private _startDeferred: Deferred | null = null; private _finishDeferred: Deferred | null = null; watch(timeout = 1000) { // Race watcher start promise against a timeout in case Typescript and Rollup change detection is not in sync. this._startDeferred = createDeferred(timeout); this._finishDeferred = createDeferred(); } handleStatus(diagnostic: Diagnostic) { // Fullfil deferred promises by Typescript diagnostic message codes. if (diagnostic.category === DiagnosticCategory.Message) { switch (diagnostic.code) { case DiagnosticCode.FILE_CHANGE_DETECTED: this.resolveStart(); break; case DiagnosticCode.FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES: case DiagnosticCode.FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES: this.resolveFinish(); break; default: } } } resolveStart() { if (this._startDeferred) { this._startDeferred.resolve(false); this._startDeferred = null; } } resolveFinish() { if (this._finishDeferred) { this._finishDeferred.resolve(false); this._finishDeferred = null; } } async wait() { if (this._startDeferred) { const timeout = await this._startDeferred.promise; // If there is no file change detected by Typescript skip deferred promises. if (timeout) { this._startDeferred = null; this._finishDeferred = null; } await this._finishDeferred?.promise; } } } /** * Create a language service host to use with the Typescript compiler & type checking APIs. * Typescript hosts are used to represent the user's system, * with an API for reading files, checking directories and case sensitivity etc. * @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API */ function createWatchHost( ts: typeof typescript, context: PluginContext, { formatHost, parsedOptions, writeFile, status, resolveModule, transformers, recreateTransformersOnRebuild }: CreateProgramOptions ): WatchCompilerHostOfFilesAndCompilerOptions { const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; const baseHost = ts.createWatchCompilerHost( parsedOptions.fileNames, parsedOptions.options, ts.sys, createProgram, buildDiagnosticReporter(ts, context, formatHost), status, parsedOptions.projectReferences ); let createdTransformers: CustomTransformers | undefined; return { ...baseHost, /** Override the created program so an in-memory emit is used */ afterProgramCreate(program) { // Optionally recompute custom transformers for each new builder program in watch mode // so factories capture the current Program/TypeChecker and any provided getters can // return the latest values. When disabled (default), legacy behavior reuses the // same factories across rebuilds. if (recreateTransformersOnRebuild) { createdTransformers = void 0; } const origEmit = program.emit; // eslint-disable-next-line no-param-reassign program.emit = ( targetSourceFile, _, cancellationToken, emitOnlyDtsFiles, customTransformers ) => { createdTransformers ??= typeof transformers === 'function' ? transformers(program.getProgram()) : mergeTransformers( program, transformers, customTransformers as CustomTransformerFactories ); return origEmit( targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, createdTransformers ); }; return baseHost.afterProgramCreate!(program); }, /** Add helper to deal with module resolution */ resolveModuleNames( moduleNames, containingFile, _reusedNames, redirectedReference, _optionsOnlyWithNewerTsVersions, containingSourceFile ) { return moduleNames.map((moduleName, i) => { const mode = containingSourceFile ? ts.getModeForResolutionAtIndex?.(containingSourceFile, i) : undefined; // eslint-disable-line no-undefined return resolveModule(moduleName, containingFile, redirectedReference, mode); }); } }; } export default function createWatchProgram( ts: typeof typescript, context: PluginContext, options: CreateProgramOptions ) { const host = createWatchHost(ts, context, options); // TypeScript schedules program updates through the host's timers and does not // clear a pending update when the program is closed. Track the timers the // program arms so `close()` can cancel whatever is still pending; otherwise a // file change in the last 250ms of a one-shot build fires after `buildEnd`, // recreates every file watcher on the closed program and keeps Rollup alive. const timers = new Set(); const { setTimeout: schedule, clearTimeout: cancel } = host; if (schedule && cancel) { host.setTimeout = (callback, ms, ...args) => { const timer: unknown = schedule( () => { timers.delete(timer); callback(...args); }, ms, ...args ); timers.add(timer); return timer; }; host.clearTimeout = (timer) => { timers.delete(timer); cancel(timer); }; } const program = ts.createWatchProgram(host); const { close } = program; program.close = () => { close.call(program); if (cancel) { timers.forEach((timer) => cancel(timer)); } timers.clear(); }; return program; }