@analogjs/vite-plugin-angular 3.0.0-beta.47 → 3.0.0-beta.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"ngp-compile-plugin.js","names":[],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import * as compilerCli from '@angular/compiler-cli';\nimport { createRequire } from 'node:module';\nimport { resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.js';\nimport type { StylePreprocessor } from './style-preprocessor.js';\nimport { preprocessStylesheet } from './stylesheet-registry.js';\nimport { isIgnoredHmrFile } from './utils/compilation-shared.js';\nimport {\n createDepOptimizerConfig,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport { findHmrComponentUpdates } from './utils/hmr-component-updates.js';\nimport {\n LspTypeChecker,\n type FileChangeType,\n} from './utils/lsp-type-checker.js';\nimport { isRolldown } from './utils/rolldown.js';\nimport type { ComponentUpdates } from './live-reload-plugin.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\n// The unpublished NGP API is loaded at runtime. Model only the surface we use.\ninterface NgpDiagnostic {\n category: number;\n messageText: string;\n}\n\ninterface NgpFile {\n filePath: string;\n diagnostics?: NgpDiagnostic[];\n classes: {\n className?: string;\n component?: {\n templateUrl?: { resolvedPath: string };\n styleUrls?: { resolvedPath: string }[];\n stylesFromUrls?: string[];\n styles?: string[];\n };\n }[];\n}\n\ninterface NgpChunk {\n files: NgpFile[];\n}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: string } | null;\n hmrUpdateModule?: string | null;\n}\n\ninterface NgpAnalyzer {\n getFileContent(path: string): Promise<string>;\n updateFileContent(\n updates: { filePath: string; content: string }[],\n ): Promise<string[]>;\n invalidateFiles(\n updates: { filePath: string; updateType: number }[],\n ): Promise<string[]>;\n close(): void;\n}\n\ninterface NgpCompiler {\n // Parsed templates by file, cleared by NGP's own update methods\n fileCache: Map<string, unknown>;\n analyzeOptimized(): AsyncIterable<NgpChunk>;\n analyzeOptimizedDelta(): AsyncIterable<NgpChunk>;\n prepareChunk(chunk: NgpChunk): Promise<unknown>;\n processFile(\n path: string,\n content: string,\n ...args: [undefined, NgpFile, unknown] | [NgpFile, unknown]\n ): Promise<NgpResult>;\n}\n\ninterface ComponentUpdate {\n file: string;\n className: string;\n}\n\ninterface NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n enableHmr?: boolean;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: Record<string, unknown> & {\n optimize: boolean;\n enableHmr: boolean;\n },\n ) => NgpCompiler;\n buildTypeCheckingConfig(options: Record<string, unknown>): unknown;\n}\n\nfunction isFastCompileOptions(\n value: unknown,\n): value is FastCompilePluginOptions {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isAngularBuildContext(value) &&\n 'tsconfigGetter' in value &&\n typeof (value as FastCompilePluginOptions).tsconfigGetter === 'function'\n );\n}\n\n// Interim NGP build bundled with this package until @angular/ngp is published\nconst BUNDLED_NGP = new URL('../../ngp/', import.meta.url);\n\nasync function loadNgp(\n tsconfig: string,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\n let modulePath = process.env['ANALOG_NGP_COMPILER'];\n if (!modulePath) {\n try {\n modulePath = createRequire(tsconfig).resolve('@angular/ngp');\n } catch {\n if (angularFullVersion < 220200) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.\",\n );\n }\n return {\n api: await import(new URL('api.mjs', BUNDLED_NGP).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : {\n backend: 'wasm',\n wasmBinding: fileURLToPath(\n new URL('ng_analyze.cjs', BUNDLED_NGP),\n ),\n },\n };\n }\n }\n return {\n api: await import(pathToFileURL(resolve(modulePath)).href),\n analyzerOptions: nativeBinding ? { nativeBinding } : {},\n };\n}\n\nfunction transpile(\n source: string,\n filePath: string,\n map?: Parameters<typeof vite.transformWithEsbuild>[3],\n) {\n return vite.transformWithOxc\n ? vite.transformWithOxc(\n source,\n filePath,\n { lang: 'ts', sourcemap: true },\n map,\n )\n : vite.transformWithEsbuild(\n source,\n filePath,\n { loader: 'ts', sourcemap: true },\n map,\n );\n}\n\nexport function ngpCompilePlugin(\n optionsOrCtx?:\n | AngularBuildContext\n | FastCompilePluginOptions\n | AngularBuildContextOptions,\n): vite.Plugin {\n const sharedCtx = isAngularBuildContext(optionsOrCtx)\n ? optionsOrCtx\n : isFastCompileOptions(optionsOrCtx)\n ? undefined\n : createAngularBuildContext({\n jit: false,\n ...optionsOrCtx,\n compilationBackend: 'ngp',\n });\n\n const options: FastCompilePluginOptions = sharedCtx\n ? sharedCtx.options\n : (optionsOrCtx as FastCompilePluginOptions);\n\n if (options.jit || options.fastCompileMode === 'partial') {\n throw new Error(\n \"compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.\",\n );\n }\n\n let configContext: TsConfigResolutionContext | undefined;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let stylePreprocessor: StylePreprocessor | undefined;\n let watchMode = false;\n let hmr = false;\n let activeBuilds = 0;\n let analyzer: NgpAnalyzer | undefined;\n let compiler: NgpCompiler | undefined;\n let typeChecker: LspTypeChecker | undefined;\n let api: NgpApi;\n const filesByPath = new Map<string, { file: NgpFile; chunk: NgpChunk }>();\n const chunkContexts = new Map<NgpChunk, Promise<unknown>>();\n const output = new Map<string, Promise<NgpResult>>();\n const emittedMaps = new Map<string, string>();\n // Last compiled source of each file, compared on edits for HMR\n const sources = new Map<string, string>();\n // Watched files mapped to the source files that depend on them\n const dependents = new Map<string, Set<string>>();\n const hmrUpdateCode = new Map<string, string>();\n const classNames = sharedCtx\n ? sharedCtx.hmr.classNames\n : new Map<string, string>();\n const fileEmitter = (file: string, className: string) => ({\n hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`),\n });\n sharedCtx?.hmr.setFileEmitter(fileEmitter);\n\n const componentUpdates: ComponentUpdates = {\n classNames,\n fileEmitter,\n };\n let pending = Promise.resolve();\n const filter = vite.createFilter(TS_EXT_REGEX, [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ]);\n\n function resolveTsConfigPath(): string {\n if (sharedCtx) {\n return sharedCtx.resolveTsConfigPath();\n }\n const ctx = configContext ?? {\n root: resolvedConfig?.root || '.',\n isProd: isProdMode(resolvedConfig?.mode),\n isLib: !!resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n ctx.root,\n options.tsconfigGetter(),\n ctx.isProd,\n options.isTest,\n ctx.isLib,\n options.workspaceRoot,\n );\n }\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: resolveTsConfigPath,\n getSourceMap: (id: string): string | undefined =>\n emittedMaps.get(vite.normalizePath(id)),\n hasEmitted: (id: string): boolean =>\n filesByPath.has(vite.normalizePath(id)),\n output,\n ready: (): Promise<void> => pending,\n componentUpdates,\n };\n\n sharedCtx?.registerCompiler({\n name: '@analogjs/vite-plugin-angular-ngp',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n watch(file.filePath);\n const activeConfig = sharedCtx?.resolvedConfig ?? resolvedConfig;\n const activeStylePreprocessor =\n sharedCtx?.stylePreprocessor ?? stylePreprocessor;\n\n return {\n ...file,\n classes: await Promise.all(\n file.classes.map(async (metadata, classIndex) => {\n const component = metadata.component;\n if (!component) return metadata;\n if (component.templateUrl) watch(component.templateUrl.resolvedPath);\n for (const style of component.styleUrls ?? [])\n watch(style.resolvedPath);\n const preprocess = async (\n content: string,\n path: string,\n order: number,\n inline: boolean,\n ) => {\n const preprocessed = preprocessStylesheet(\n content,\n path,\n activeStylePreprocessor,\n {\n filename: path,\n containingFile: file.filePath,\n resourceFile: inline ? undefined : path,\n className: metadata.className,\n order,\n inline,\n },\n );\n const result = await vite.preprocessCSS(\n preprocessed,\n path,\n activeConfig,\n );\n result.deps?.forEach(watch);\n return result.code;\n };\n return {\n ...metadata,\n component: {\n ...component,\n styles:\n component.styles &&\n (await Promise.all(\n component.styles.map((style, index) =>\n preprocess(\n style,\n `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n index,\n true,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(\n style,\n component.styleUrls![index].resolvedPath,\n index,\n false,\n ),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>): Promise<void> {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(vite.normalizePath(filePath));\n compiler!.fileCache.delete(filePath);\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n const angularOptions = compilerCli.readConfiguration(\n resolveTsConfigPath(),\n ).options as Record<string, unknown>;\n compiler = new api.HybridCompiler(analyzer!, {\n ...angularOptions,\n optimize: true,\n enableHmr: hmr,\n tcbConfig: api.buildTypeCheckingConfig(angularOptions),\n });\n }\n const chunks = update\n ? compiler!.analyzeOptimizedDelta()\n : compiler!.analyzeOptimized();\n for await (const chunk of chunks) {\n for (const file of chunk.files) {\n const normPath = vite.normalizePath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n compiler!.fileCache.delete(file.filePath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>): Promise<void> {\n pending = pending.catch(() => {}).then(() => indexChunks(update));\n return pending;\n }\n\n function getChunkContext(chunk: NgpChunk): Promise<unknown> {\n let context = chunkContexts.get(chunk);\n if (!context) {\n context = compiler!.prepareChunk(chunk);\n chunkContexts.set(chunk, context);\n }\n return context;\n }\n\n async function checkTypes(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n ): Promise<void> {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\n );\n typeChecker.queueFile(filePath, sourceCode, tcbCode);\n if (!watchMode) return;\n const typeErrors = await typeChecker.flushQueue(true);\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n }\n\n async function processFile(\n normPath: string,\n activeCompiler: NgpCompiler,\n watch: (path: string) => void,\n ) {\n const { file: analyzed, chunk } = filesByPath.get(normPath)!;\n const [file, context, content] = await Promise.all([\n prepareResources(analyzed, (path) => {\n const key = vite.normalizePath(path);\n dependents.set(key, (dependents.get(key) ?? new Set()).add(normPath));\n watch(path);\n }),\n getChunkContext(chunk),\n analyzer!.getFileContent(analyzed.filePath),\n ]);\n sources.set(normPath, content);\n const result =\n activeCompiler.processFile.length >= 5\n ? await activeCompiler.processFile(\n file.filePath,\n content,\n undefined,\n file,\n context,\n )\n : await activeCompiler.processFile(\n file.filePath,\n content,\n file,\n context,\n );\n return { file, content, result };\n }\n\n function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n if (!filesByPath.has(normPath)) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n const { file, content, result } = await processFile(\n normPath,\n compiler!,\n watch,\n );\n const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${file.filePath}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(file.filePath, content, result.tcb?.code);\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n function componentNames(normPath: string): string[] {\n return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(\n ({ className, component }) => (component && className ? [className] : []),\n );\n }\n\n // Components to update in place, following the Angular CLI's rule\n async function findComponentUpdates(\n normPath: string,\n read: () => string | Promise<string>,\n ): Promise<ComponentUpdate[]> {\n if (!TS_EXT_REGEX.test(normPath)) {\n return [...(dependents.get(normPath) ?? [])].flatMap((file) =>\n componentNames(file).map((className) => ({ file, className })),\n );\n }\n const stale = sources.get(normPath);\n if (stale === undefined) return [];\n const matchedClassNames = findHmrComponentUpdates(\n normPath,\n stale,\n await read(),\n new Set(componentNames(normPath)),\n );\n return (matchedClassNames ?? []).map((className) => ({\n file: normPath,\n className,\n }));\n }\n\n async function emitHmrUpdate(file: string, className: string) {\n // NGP emits only the update module of the class named by `hmrUpdateTarget`,\n // and only when it doesn't reuse the file's previously processed output\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(compiler)),\n compiler,\n { hmrUpdateTarget: className, reuseProcessedFiles: false },\n );\n const { result } = await processFile(file, target, () => {});\n return (\n result.hmrUpdateModule &&\n (await transpile(result.hmrUpdateModule, file)).code\n );\n }\n\n async function sendComponentUpdates(\n updates: ComponentUpdate[],\n server: vite.ViteDevServer,\n ): Promise<boolean> {\n try {\n for (const file of new Set(updates.map((update) => update.file))) {\n await compileFile(file, () => {});\n }\n const codes = await Promise.all(\n updates.map(({ file, className }) => emitHmrUpdate(file, className)),\n );\n if (codes.some((code) => !code)) return false;\n updates.forEach(({ file, className }, index) => {\n hmrUpdateCode.set(`${file}@${className}`, codes[index]!);\n componentUpdates.classNames.set(file, className);\n server.moduleGraph\n .getModulesByFile(file)\n ?.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(\n `${filesByPath.get(file)!.file.filePath}@${className}`,\n ),\n timestamp: Date.now(),\n });\n });\n return true;\n } catch {\n // A full reload reports the compilation error\n return false;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: compilerApi,\n config(config, { command, mode }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n if (sharedCtx) {\n sharedCtx.initConfig(config, { command, mode });\n } else {\n configContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config.build?.lib,\n };\n }\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(isRolldown() ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n hmr =\n watchMode &&\n options.liveReload &&\n !options.isTest &&\n config.server.hmr !== false;\n const integrations = sharedCtx\n ? await sharedCtx.resolveConfig(config)\n : await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n stylePreprocessor = integrations.stylePreprocessor;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\n server.watcher.on('all', (event, path) => {\n const type = changeTypes[event];\n if (type) typeChecker?.notifyFileChanged(path, type);\n });\n server.httpServer?.on('close', () => {\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n });\n },\n async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const ngp = await loadNgp(tsconfig);\n api = ngp.api;\n analyzer = await api.createAnalyzer(tsconfig, {\n ...ngp.analyzerOptions,\n enableHmr: hmr,\n });\n pending = indexChunks();\n }\n await pending;\n for (const path of dependents.keys()) {\n this.addWatchFile(path);\n }\n },\n resolveId(id, importer) {\n return resolveAngularVirtualId(id, importer, {\n jit: false,\n resolvedConfig: sharedCtx?.resolvedConfig ?? resolvedConfig,\n });\n },\n async load(id) {\n return loadAngularVirtualModule(\n this,\n id,\n sharedCtx?.resolvedConfig ?? resolvedConfig,\n );\n },\n async transform(code, id) {\n const activeTransformFilter =\n sharedCtx?.transformFilter ?? transformFilter;\n if (!filter(id) || activeTransformFilter?.(code, id) === false) return;\n const filePath = vite.normalizePath(id.split('?')[0]);\n await pending;\n let result = await compileFile(filePath, (path) =>\n this.addWatchFile(path),\n );\n if (result && result.magicString.original !== code) {\n await enqueueIndex(() =>\n analyzer!.updateFileContent([{ filePath, content: code }]),\n );\n result = await compileFile(filePath, (path) => this.addWatchFile(path));\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n const source = result?.magicString.toString() ?? code;\n const map = result?.magicString.generateMap({\n source: filePath,\n includeContent: true,\n hires: true,\n });\n const transpiled = await transpile(source, filePath, map);\n if (transpiled?.map) {\n emittedMaps.set(\n filePath,\n typeof transpiled.map === 'string'\n ? transpiled.map\n : JSON.stringify(transpiled.map),\n );\n }\n return transpiled;\n },\n async handleHotUpdate(ctx) {\n if (\n sharedCtx\n ? sharedCtx.hmr.isIgnoredFile(ctx.file)\n : isIgnoredHmrFile(ctx.file)\n ) {\n return [];\n }\n const normPath = vite.normalizePath(ctx.file);\n const updates = hmr ? await findComponentUpdates(normPath, ctx.read) : [];\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([{ filePath: ctx.file, updateType: 2 }]),\n );\n if (updates.length && (await sendComponentUpdates(updates, ctx.server))) {\n return [];\n }\n hmrUpdateCode.clear();\n componentUpdates.classNames.clear();\n ctx.server.moduleGraph.invalidateAll();\n ctx.server.ws.send({ type: 'full-reload' });\n return [];\n },\n async buildEnd(error) {\n if (error || watchMode || !typeChecker) return;\n const typeErrors = await typeChecker.flushQueue();\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n },\n async closeBundle() {\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (watchMode || activeBuilds > 0) return;\n await pending.catch(() => {});\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n emittedMaps.clear();\n sources.clear();\n dependents.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2HA,SAAS,qBACP,OACmC;CACnC,OACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,sBAAsB,KAAK,KAC5B,oBAAoB,SACpB,OAAQ,MAAmC,mBAAmB;AAElE;AAGA,IAAM,cAAc,IAAA,IAAA,cAAA,KAAA,YAAA,GAAA;AAEpB,eAAe,QACb,UAC+D;CAC/D,MAAM,gBAAgB,QAAQ,IAAI;CAClC,IAAI,aAAa,QAAQ,IAAI;CAC7B,IAAI,CAAC,YACH,IAAI;EACF,aAAa,cAAc,QAAQ,CAAC,CAAC,QAAQ,cAAc;CAC7D,QAAQ;EACN,IAAI,qBAAqB,QACvB,MAAM,IAAI,MACR,sFACF;EAEF,OAAO;GACL,KAAK,MAAM,OAAO,IAAI,IAAI,WAAW,WAAW,CAAC,CAAC;GAClD,iBAAiB,gBACb,EAAE,cAAc,IAChB;IACE,SAAS;IACT,aAAa,cACX,IAAI,IAAI,kBAAkB,WAAW,CACvC;GACF;EACN;CACF;CAEF,OAAO;EACL,KAAK,MAAM,OAAO,cAAc,QAAQ,UAAU,CAAC,CAAC,CAAC;EACrD,iBAAiB,gBAAgB,EAAE,cAAc,IAAI,CAAC;CACxD;AACF;AAEA,SAAS,UACP,QACA,UACA,KACA;CACA,OAAO,KAAK,mBAC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AAO;GACpB,IAAI,SAAS,aAAa,CAAC,aAAa;GACxC,MAAM,aAAa,MAAM,YAAY,WAAW;GAChD,IAAI,WAAW,QACb,MAAM,IAAI,MAAM,WAAW,KAAK,IAAI,CAAC;EAEzC;EACA,MAAM,cAAc;GAClB,eAAe,KAAK,IAAI,GAAG,eAAe,CAAC;GAC3C,IAAI,aAAa,eAAe,GAAG;GACnC,MAAM,QAAQ,YAAY,CAAC,CAAC;GAC5B,aAAa,MAAM;GACnB,cAAc,KAAA;GACd,UAAU,MAAM;GAChB,WAAW,KAAA;GACX,WAAW,KAAA;GACX,YAAY,MAAM;GAClB,cAAc,MAAM;GACpB,OAAO,MAAM;GACb,YAAY,MAAM;GAClB,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,8BAA8B;EAChC;CACF;AACF"}
1
+ {"version":3,"file":"ngp-compile-plugin.js","names":[],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import * as compilerCli from '@angular/compiler-cli';\nimport { existsSync, promises as fsPromises, realpathSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport { glob } from 'tinyglobby';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport { ComponentScanner } from './component-scanner.js';\nimport type { FastCompileResolve } from './fast-compile-api.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.js';\nimport type {\n NgpCompileApi,\n NgpLoweredModule,\n NgpSourceFormat,\n} from './ngp-compile-api.js';\nimport type { StylePreprocessor } from './style-preprocessor.js';\nimport { preprocessStylesheet } from './stylesheet-registry.js';\nimport { isIgnoredHmrFile } from './utils/compilation-shared.js';\nimport {\n createDepOptimizerConfig,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport { findHmrComponentUpdates } from './utils/hmr-component-updates.js';\nimport {\n LspTypeChecker,\n type FileChangeType,\n type SourceLocation,\n} from './utils/lsp-type-checker.js';\nimport {\n canonicalPath,\n createNgpHostFs,\n type NgpHostFs,\n} from './utils/ngp-host-fs.js';\nimport { isRolldown } from './utils/rolldown.js';\nimport type { ComponentUpdates } from './live-reload-plugin.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\n// The unpublished NGP API is loaded at runtime. Model only the surface we use.\ninterface NgpDiagnostic {\n category: number;\n messageText: string;\n}\n\ninterface NgpFile {\n filePath: string;\n diagnostics?: NgpDiagnostic[];\n classes: {\n className?: string;\n component?: {\n templateUrl?: { resolvedPath: string };\n styleUrls?: { resolvedPath: string }[];\n stylesFromUrls?: string[];\n styles?: string[];\n };\n }[];\n}\n\ninterface NgpChunk {\n files: NgpFile[];\n removedFiles?: string[];\n}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: string } | null;\n hmrUpdateModule?: string | null;\n}\n\ninterface NgpAnalyzer {\n getFileContent(path: string): Promise<string>;\n updateFileContent(\n updates: { filePath: string; content: string }[],\n ): Promise<string[]>;\n invalidateFiles(\n updates: { filePath: string; updateType: number }[],\n ): Promise<string[]>;\n close(): void;\n}\n\ninterface NgpCompiler {\n // Parsed templates by file, cleared by NGP's own update methods\n fileCache: Map<string, unknown>;\n analyzeOptimized(): AsyncIterable<NgpChunk>;\n analyzeOptimizedDelta(): AsyncIterable<NgpChunk>;\n prepareChunk(chunk: NgpChunk): Promise<unknown>;\n processFile(\n path: string,\n content: string,\n ...args: [undefined, NgpFile, unknown] | [NgpFile, unknown]\n ): Promise<NgpResult>;\n}\n\ninterface ComponentUpdate {\n file: string;\n className: string;\n}\n\ninterface NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n enableHmr?: boolean;\n hostFs?: NgpHostFs;\n}\n\n/** NGP's `FileUpdateType`. */\nconst FILE_CREATED = 0;\nconst FILE_DELETED = 1;\nconst FILE_CHANGED = 2;\n\n/** A module of a registered source format, lowered to its program file. */\ninterface SourceModule {\n sourceFile: string;\n /** The source it was lowered from. */\n source: string;\n format: NgpSourceFormat;\n lowered: NgpLoweredModule;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: Record<string, unknown> & {\n optimize: boolean;\n enableHmr: boolean;\n },\n ) => NgpCompiler;\n buildTypeCheckingConfig(options: Record<string, unknown>): unknown;\n}\n\nfunction isFastCompileOptions(\n value: unknown,\n): value is FastCompilePluginOptions {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isAngularBuildContext(value) &&\n 'tsconfigGetter' in value &&\n typeof (value as FastCompilePluginOptions).tsconfigGetter === 'function'\n );\n}\n\n// Interim NGP build bundled with this package until @angular/ngp is published\nconst BUNDLED_NGP = new URL('../../ngp/', import.meta.url);\n\n/**\n * @param needsHostFs Whether source formats are registered, which only the\n * WebAssembly backend can read through `hostFs`.\n */\nasync function loadNgp(\n tsconfig: string,\n needsHostFs: boolean,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\n if (nativeBinding && needsHostFs) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: Source formats such as TSRX can't be compiled with a native NGP analyzer build. Unset ANALOG_NGP_NATIVE_BINDING to use NGP's default WebAssembly analyzer.\",\n );\n }\n let modulePath = process.env['ANALOG_NGP_COMPILER'];\n if (!modulePath) {\n try {\n modulePath = createRequire(tsconfig).resolve('@angular/ngp');\n } catch {\n if (angularFullVersion < 220200) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.\",\n );\n }\n return {\n api: await import(new URL('api.mjs', BUNDLED_NGP).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : {\n backend: 'wasm',\n wasmBinding: fileURLToPath(\n new URL('ng_analyze.cjs', BUNDLED_NGP),\n ),\n },\n };\n }\n }\n return {\n api: await import(pathToFileURL(resolve(modulePath)).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : needsHostFs\n ? { backend: 'wasm' }\n : {},\n };\n}\n\nfunction transpile(\n source: string,\n filePath: string,\n map?: Parameters<typeof vite.transformWithEsbuild>[3],\n) {\n return vite.transformWithOxc\n ? vite.transformWithOxc(\n source,\n filePath,\n { lang: 'ts', sourcemap: true },\n map,\n )\n : vite.transformWithEsbuild(\n source,\n filePath,\n { loader: 'ts', sourcemap: true },\n map,\n );\n}\n\nexport function ngpCompilePlugin(\n optionsOrCtx?:\n | AngularBuildContext\n | FastCompilePluginOptions\n | AngularBuildContextOptions,\n): vite.Plugin {\n const sharedCtx = isAngularBuildContext(optionsOrCtx)\n ? optionsOrCtx\n : isFastCompileOptions(optionsOrCtx)\n ? undefined\n : createAngularBuildContext({\n jit: false,\n ...optionsOrCtx,\n compilationBackend: 'ngp',\n });\n\n const options: FastCompilePluginOptions = sharedCtx\n ? sharedCtx.options\n : (optionsOrCtx as FastCompilePluginOptions);\n\n if (options.jit || options.fastCompileMode === 'partial') {\n throw new Error(\n \"compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.\",\n );\n }\n\n let configContext: TsConfigResolutionContext | undefined;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let stylePreprocessor: StylePreprocessor | undefined;\n let watchMode = false;\n let hmr = false;\n let activeBuilds = 0;\n let analyzer: NgpAnalyzer | undefined;\n let compiler: NgpCompiler | undefined;\n let typeChecker: LspTypeChecker | undefined;\n let api: NgpApi;\n const filesByPath = new Map<string, { file: NgpFile; chunk: NgpChunk }>();\n const chunkContexts = new Map<NgpChunk, Promise<unknown>>();\n const output = new Map<string, Promise<NgpResult>>();\n const emittedMaps = new Map<string, string>();\n // Last compiled source of each file, compared on edits for HMR\n const sources = new Map<string, string>();\n // Watched files mapped to the source files that depend on them\n const dependents = new Map<string, Set<string>>();\n const hmrUpdateCode = new Map<string, string>();\n const classNames = sharedCtx\n ? sharedCtx.hmr.classNames\n : new Map<string, string>();\n const fileEmitter = (file: string, className: string) => ({\n hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`),\n });\n sharedCtx?.hmr.setFileEmitter(fileEmitter);\n\n const componentUpdates: ComponentUpdates = {\n classNames,\n fileEmitter,\n };\n let pending = Promise.resolve();\n const excluded = [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ];\n const filter = vite.createFilter(TS_EXT_REGEX, excluded);\n const sourceFilter = vite.createFilter(null, excluded);\n\n // Source formats registered through `api.ngp`, the component registry their\n // lowering looks selectors up in, and their modules by program file\n // (`x.tsrx` → `x.tsrx.ts`)\n const sourceFormats: NgpSourceFormat[] = [];\n const scanner = new ComponentScanner();\n const sourceModules = new Map<string, SourceModule>();\n // Per program file: how often it was removed, which cancels a lowering in\n // progress, and the lowered code the analyzer has\n const removals = new Map<string, number>();\n const analyzed = new Map<string, string>();\n // Which modules of each format NGP compiles: its `include` under the tsconfig's directory\n const includes = new Map<NgpSourceFormat, (file: string) => boolean>();\n const moduleFormatOf = (file: string): NgpSourceFormat | undefined =>\n sourceFormats.find(\n (format) => format.test(file) && includes.get(format)?.(file),\n );\n let devServer: vite.ViteDevServer | undefined;\n // The program files a file change lowered again, for the hot update after it\n const reloweredByChange = new Map<string, string[]>();\n const programFileOf = (file: string): string | undefined => {\n const programFile = `${file}.ts`;\n return sourceModules.has(programFile) ? programFile : undefined;\n };\n const sourceFileOf = (file: string): string =>\n sourceModules.get(file)?.sourceFile ?? file;\n\n function resolveTsConfigPath(): string {\n if (sharedCtx) {\n return sharedCtx.resolveTsConfigPath();\n }\n const ctx = configContext ?? {\n root: resolvedConfig?.root || '.',\n isProd: isProdMode(resolvedConfig?.mode),\n isLib: !!resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n ctx.root,\n options.tsconfigGetter(),\n ctx.isProd,\n options.isTest,\n ctx.isLib,\n options.workspaceRoot,\n );\n }\n\n const ngp: NgpCompileApi = {\n registerSourceFormat(format) {\n if (!sourceFormats.includes(format)) {\n sourceFormats.push(format);\n scanner.registerSourceFormat(format);\n }\n },\n };\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: resolveTsConfigPath,\n getSourceMap: (id: string): string | undefined =>\n emittedMaps.get(vite.normalizePath(id)),\n hasEmitted: (id: string): boolean =>\n filesByPath.has(vite.normalizePath(id)),\n output,\n ready: (): Promise<void> => pending,\n componentUpdates,\n ngp,\n };\n\n /** Lowers a module of a source format. Returns whether its TypeScript changed. */\n async function lowerSourceModule(\n sourceFile: string,\n source: string,\n format: NgpSourceFormat,\n resolve: FastCompileResolve,\n ): Promise<boolean> {\n const programFile = `${sourceFile}.ts`;\n if (existsSync(programFile)) {\n throw new Error(\n `[@analogjs/vite-plugin-angular]: ${programFile} has the name NGP compiles ${sourceFile} as. Rename one of them.`,\n );\n }\n const removed = removals.get(programFile);\n const lowered = await format.lower(source, sourceFile, {\n scanImports: (specifiers) =>\n scanner.scanImports(specifiers, sourceFile, resolve),\n resolveSelector: (className) =>\n scanner.lookupSelector(\n className,\n sharedCtx?.componentRegistries ?? componentRegistries,\n ),\n });\n // Removed while it was lowered\n if (removals.get(programFile) !== removed) return false;\n const changed =\n sourceModules.get(programFile)?.lowered.code !== lowered.code;\n sourceModules.set(programFile, { sourceFile, source, format, lowered });\n return changed;\n }\n\n /** Lowers every module of the registered source formats under `root`. */\n async function lowerSourceModules(\n root: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n scanner.reset(root);\n sourceModules.clear();\n const sourceRoot = vite.normalizePath(realpathSync(root));\n await Promise.all(\n sourceFormats.map(async (format) => {\n includes.set(\n format,\n vite.createFilter(format.include, '**/node_modules/**', {\n resolve: sourceRoot,\n }),\n );\n const files = await glob(format.include, {\n cwd: sourceRoot,\n absolute: true,\n ignore: ['**/node_modules/**'],\n });\n await Promise.all(\n files.map(async (file) => {\n const sourceFile = canonicalPath(file);\n const source = await fsPromises.readFile(sourceFile, 'utf-8');\n await lowerSourceModule(sourceFile, source, format, resolve);\n }),\n );\n }),\n );\n // The analyzer reads them through `hostFs` when it's created\n analyzed.clear();\n for (const [programFile, { lowered }] of sourceModules) {\n analyzed.set(programFile, lowered.code);\n }\n }\n\n /**\n * Lowers the source modules a change to `file` affects again: the module\n * itself, and those that looked up selectors in it. Returns the program\n * files whose TypeScript changed.\n */\n async function relowerSourceModules(\n file: string,\n resolve: FastCompileResolve,\n ): Promise<string[]> {\n const affected = [file, ...(scanner.importersByFile.get(file) ?? [])]\n .map(programFileOf)\n .filter((programFile) => programFile !== undefined);\n scanner.invalidate(file);\n const changed = await Promise.all(\n affected.map(async (programFile) => {\n const sourceModule = sourceModules.get(programFile);\n if (!sourceModule) return [];\n const { sourceFile, format } = sourceModule;\n const source = await readSource(sourceFile);\n if (source === undefined) return [];\n const relowered = await lowerSourceModule(\n sourceFile,\n source,\n format,\n resolve,\n );\n return relowered ? [programFile] : [];\n }),\n );\n return changed.flat();\n }\n\n // Lowering and the analyzer updates that follow it, one change at a time, so\n // the modules a change lowers again reach the analyzer together\n let sourceWork: Promise<unknown> = Promise.resolve();\n function withSourceLock<T>(work: () => Promise<T>): Promise<T> {\n const run = sourceWork.catch(() => undefined).then(work);\n sourceWork = run;\n return run;\n }\n\n /** Sends the analyzer the lowered modules it doesn't have yet. */\n async function syncProgramFiles(): Promise<void> {\n const updates = [...sourceModules]\n .filter(\n ([filePath, { lowered }]) => analyzed.get(filePath) !== lowered.code,\n )\n .map(([filePath, { lowered }]) => ({ filePath, content: lowered.code }));\n if (updates.length === 0) return;\n for (const { filePath, content } of updates)\n analyzed.set(filePath, content);\n await enqueueIndex(() => analyzer!.updateFileContent(updates));\n }\n\n /** Reads a source file, or `undefined` if it was removed. */\n function readSource(file: string): Promise<string | undefined> {\n return fsPromises\n .readFile(file, 'utf-8')\n .catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n }\n\n /** Lowers a module added after the build started, if NGP compiles it. */\n async function addSourceModule(\n sourceFile: string,\n format: NgpSourceFormat,\n source: string,\n resolve: FastCompileResolve,\n ): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n await lowerSourceModule(sourceFile, source, format, resolve);\n const sourceModule = sourceModules.get(programFile);\n // Removed while it was lowered\n if (!sourceModule) return;\n // The analyzer reads it through `hostFs`\n analyzed.set(programFile, sourceModule.lowered.code);\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: programFile, updateType: FILE_CREATED },\n ]),\n );\n }\n\n /** Drops a removed module, and any lowering of it still in progress. */\n async function removeSourceModule(sourceFile: string): Promise<void> {\n const programFile = `${sourceFile}.ts`;\n removals.set(programFile, (removals.get(programFile) ?? 0) + 1);\n analyzed.delete(programFile);\n if (!sourceModules.delete(programFile)) return;\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: programFile, updateType: FILE_DELETED },\n ]),\n );\n }\n\n /**\n * Lowers a module for its transform, as fast compile does on every\n * transform, so the selectors it looks up are current. A transform that\n * started before a hot update can carry the previous code; it compiles the\n * latest lowering instead.\n */\n async function lowerForTransform(\n sourceFile: string,\n format: NgpSourceFormat,\n code: string,\n resolve: FastCompileResolve,\n ): Promise<NgpLoweredModule | undefined> {\n const programFile = `${sourceFile}.ts`;\n if (!sourceModules.has(programFile)) {\n // Requested before its `create` event, or added during `vite build --watch`\n await addSourceModule(sourceFile, format, code, resolve);\n } else if (code === (await readSource(sourceFile))) {\n await lowerSourceModule(sourceFile, code, format, resolve);\n }\n return sourceModules.get(programFile)?.lowered;\n }\n\n /** Maps a type error in a program file to the source module's location. */\n function toSourceLocation(location: SourceLocation): SourceLocation {\n const sourceModule = sourceModules.get(vite.normalizePath(location.file));\n const mapped = sourceModule?.lowered.toSourceLocation(\n location.line - 1,\n location.character - 1,\n );\n return mapped\n ? {\n file: sourceModule!.sourceFile,\n line: mapped.line + 1,\n character: mapped.column + 1,\n }\n : location;\n }\n\n sharedCtx?.registerCompiler({\n name: '@analogjs/vite-plugin-angular-ngp',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n watch(file.filePath);\n const activeConfig = sharedCtx?.resolvedConfig ?? resolvedConfig;\n const activeStylePreprocessor =\n sharedCtx?.stylePreprocessor ?? stylePreprocessor;\n\n return {\n ...file,\n classes: await Promise.all(\n file.classes.map(async (metadata, classIndex) => {\n const component = metadata.component;\n if (!component) return metadata;\n if (component.templateUrl) watch(component.templateUrl.resolvedPath);\n for (const style of component.styleUrls ?? [])\n watch(style.resolvedPath);\n const preprocess = async (\n content: string,\n path: string,\n order: number,\n inline: boolean,\n ) => {\n const preprocessed = preprocessStylesheet(\n content,\n path,\n activeStylePreprocessor,\n {\n filename: path,\n containingFile: file.filePath,\n resourceFile: inline ? undefined : path,\n className: metadata.className,\n order,\n inline,\n },\n );\n const result = await vite.preprocessCSS(\n preprocessed,\n path,\n activeConfig,\n );\n result.deps?.forEach(watch);\n return result.code;\n };\n return {\n ...metadata,\n component: {\n ...component,\n styles:\n component.styles &&\n (await Promise.all(\n component.styles.map((style, index) =>\n preprocess(\n style,\n `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n index,\n true,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(\n style,\n component.styleUrls![index].resolvedPath,\n index,\n false,\n ),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>): Promise<void> {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(vite.normalizePath(filePath));\n compiler!.fileCache.delete(filePath);\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n const angularOptions = compilerCli.readConfiguration(\n resolveTsConfigPath(),\n ).options as Record<string, unknown>;\n compiler = new api.HybridCompiler(analyzer!, {\n ...angularOptions,\n optimize: true,\n enableHmr: hmr,\n tcbConfig: api.buildTypeCheckingConfig(angularOptions),\n });\n }\n const chunks = update\n ? compiler!.analyzeOptimizedDelta()\n : compiler!.analyzeOptimized();\n for await (const chunk of chunks) {\n for (const file of chunk.files) {\n const normPath = vite.normalizePath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n compiler!.fileCache.delete(file.filePath);\n }\n for (const removed of chunk.removedFiles ?? []) {\n const normPath = vite.normalizePath(removed);\n filesByPath.delete(normPath);\n output.delete(normPath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>): Promise<void> {\n pending = pending.catch(() => {}).then(() => indexChunks(update));\n return pending;\n }\n\n function getChunkContext(chunk: NgpChunk): Promise<unknown> {\n let context = chunkContexts.get(chunk);\n if (!context) {\n context = compiler!.prepareChunk(chunk);\n chunkContexts.set(chunk, context);\n }\n return context;\n }\n\n async function checkTypes(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n ): Promise<void> {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\n {\n inMemoryFiles: () =>\n new Map(\n [...sourceModules].map(([file, { lowered }]) => [\n file,\n lowered.code,\n ]),\n ),\n mapLocation: toSourceLocation,\n },\n );\n typeChecker.queueFile(filePath, sourceCode, tcbCode);\n if (!watchMode) return;\n const typeErrors = await typeChecker.flushQueue(true);\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n }\n\n async function processFile(\n normPath: string,\n activeCompiler: NgpCompiler,\n watch: (path: string) => void,\n ) {\n const { file: analyzed, chunk } = filesByPath.get(normPath)!;\n const [file, context, content] = await Promise.all([\n prepareResources(analyzed, (path) => {\n const key = sourceFileOf(vite.normalizePath(path));\n dependents.set(key, (dependents.get(key) ?? new Set()).add(normPath));\n watch(key);\n }),\n getChunkContext(chunk),\n analyzer!.getFileContent(analyzed.filePath),\n ]);\n sources.set(normPath, content);\n const result =\n activeCompiler.processFile.length >= 5\n ? await activeCompiler.processFile(\n file.filePath,\n content,\n undefined,\n file,\n context,\n )\n : await activeCompiler.processFile(\n file.filePath,\n content,\n file,\n context,\n );\n return { file, content, result };\n }\n\n function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n if (!filesByPath.has(normPath)) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n // Analyzer updates queued before this compile land first\n await pending;\n if (!filesByPath.has(normPath)) {\n throw new Error(`${sourceFileOf(normPath)} was removed.`);\n }\n const { file, content, result } = await processFile(\n normPath,\n compiler!,\n watch,\n );\n const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${sourceFileOf(normPath)}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(file.filePath, content, result.tcb?.code);\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n function componentNames(normPath: string): string[] {\n return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(\n ({ className, component }) => (component && className ? [className] : []),\n );\n }\n\n // Components to update in place, following the Angular CLI's rule\n async function findComponentUpdates(\n normPath: string,\n read: () => string | Promise<string>,\n ): Promise<ComponentUpdate[]> {\n if (!TS_EXT_REGEX.test(normPath)) {\n return [...(dependents.get(normPath) ?? [])].flatMap((file) =>\n componentNames(file).map((className) => ({ file, className })),\n );\n }\n const stale = sources.get(normPath);\n if (stale === undefined) return [];\n const matchedClassNames = findHmrComponentUpdates(\n normPath,\n stale,\n await read(),\n new Set(componentNames(normPath)),\n );\n return (matchedClassNames ?? []).map((className) => ({\n file: normPath,\n className,\n }));\n }\n\n async function emitHmrUpdate(file: string, className: string) {\n // NGP emits only the update module of the class named by `hmrUpdateTarget`,\n // and only when it doesn't reuse the file's previously processed output\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(compiler)),\n compiler,\n { hmrUpdateTarget: className, reuseProcessedFiles: false },\n );\n const { result } = await processFile(file, target, () => {});\n return (\n result.hmrUpdateModule &&\n (await transpile(result.hmrUpdateModule, file)).code\n );\n }\n\n async function sendComponentUpdates(\n updates: ComponentUpdate[],\n server: vite.ViteDevServer,\n ): Promise<boolean> {\n try {\n for (const file of new Set(updates.map((update) => update.file))) {\n await compileFile(file, () => {});\n }\n const codes = await Promise.all(\n updates.map(({ file, className }) => emitHmrUpdate(file, className)),\n );\n if (codes.some((code) => !code)) return false;\n updates.forEach(({ file, className }, index) => {\n // Components of a source module update through the module itself\n const sourceFile = sourceModules.get(file)?.sourceFile;\n const moduleFile = sourceFile ?? file;\n hmrUpdateCode.set(`${moduleFile}@${className}`, codes[index]!);\n componentUpdates.classNames.set(moduleFile, className);\n server.moduleGraph\n .getModulesByFile(moduleFile)\n ?.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(\n `${sourceFile ?? filesByPath.get(file)!.file.filePath}@${className}`,\n ),\n timestamp: Date.now(),\n });\n });\n return true;\n } catch {\n // A full reload reports the compilation error\n return false;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: compilerApi,\n config(config, { command, mode }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n if (sharedCtx) {\n sharedCtx.initConfig(config, { command, mode });\n } else {\n configContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config.build?.lib,\n };\n }\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(isRolldown() ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n hmr =\n watchMode &&\n options.liveReload &&\n !options.isTest &&\n config.server.hmr !== false;\n const integrations = sharedCtx\n ? await sharedCtx.resolveConfig(config)\n : await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n stylePreprocessor = integrations.stylePreprocessor;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\n devServer = server;\n server.watcher.on('all', (event, path) => {\n const type = changeTypes[event];\n if (type) typeChecker?.notifyFileChanged(path, type);\n });\n server.httpServer?.on('close', () => {\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n });\n },\n // Runs on the dev server with or without HMR, and in `vite build --watch`\n async watchChange(id, { event }) {\n if (!analyzer || sourceFormats.length === 0) return;\n const file = canonicalPath(id);\n const resolve: FastCompileResolve = (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true });\n await withSourceLock(async () => {\n scanner.invalidate(file);\n const format = moduleFormatOf(file);\n if (event === 'update') {\n reloweredByChange.set(\n file,\n await relowerSourceModules(file, resolve),\n );\n } else if (event === 'delete') {\n await removeSourceModule(file);\n } else if (\n event === 'create' &&\n format &&\n !sourceModules.has(`${file}.ts`)\n ) {\n const source = await readSource(file);\n if (source !== undefined) {\n await addSourceModule(file, format, source, resolve);\n }\n }\n await syncProgramFiles();\n });\n // Modules that looked up selectors in `file` lower again when transformed\n for (const importer of scanner.importersByFile.get(file) ?? []) {\n devServer?.moduleGraph\n .getModulesByFile(importer)\n ?.forEach((mod) => devServer!.moduleGraph.invalidateModule(mod));\n }\n },\n async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const hasSourceFormats = sourceFormats.length > 0;\n const ngp = await loadNgp(tsconfig, hasSourceFormats);\n api = ngp.api;\n if (hasSourceFormats) {\n await lowerSourceModules(dirname(tsconfig), (specifier, importer) =>\n this.resolve(specifier, importer, { skipSelf: true }),\n );\n }\n analyzer = await api.createAnalyzer(tsconfig, {\n ...ngp.analyzerOptions,\n enableHmr: hmr,\n hostFs: hasSourceFormats\n ? createNgpHostFs((path) => sourceModules.get(path)?.lowered.code)\n : undefined,\n });\n pending = indexChunks();\n }\n await pending;\n for (const path of dependents.keys()) {\n this.addWatchFile(path);\n }\n },\n resolveId(id, importer) {\n return resolveAngularVirtualId(id, importer, {\n jit: false,\n resolvedConfig: sharedCtx?.resolvedConfig ?? resolvedConfig,\n });\n },\n async load(id) {\n return loadAngularVirtualModule(\n this,\n id,\n sharedCtx?.resolvedConfig ?? resolvedConfig,\n );\n },\n async transform(code, id) {\n const activeTransformFilter =\n sharedCtx?.transformFilter ?? transformFilter;\n const filePath = vite.normalizePath(id.split('?')[0]);\n const sourceFormat = scanner.sourceFormatOf(filePath);\n if (\n !(sourceFormat ? sourceFilter(id) : filter(id)) ||\n activeTransformFilter?.(code, id) === false\n ) {\n return;\n }\n await pending;\n let lowered: NgpLoweredModule | undefined;\n let compiledFile = filePath;\n if (sourceFormat) {\n const sourceFile = canonicalPath(filePath);\n const format = moduleFormatOf(sourceFile);\n if (!format) {\n this.error(\n `${filePath} is outside ${dirname(resolveTsConfigPath())}, where '${sourceFormat.name}' modules are compiled from.`,\n );\n }\n lowered = await withSourceLock(async () => {\n const result = await lowerForTransform(\n sourceFile,\n format,\n code,\n (spec, importer) =>\n this.resolve(spec, importer, { skipSelf: true }),\n );\n await syncProgramFiles();\n return result;\n });\n if (!lowered) {\n this.error(`${filePath} was removed while it was compiled.`);\n }\n if (lowered.error) {\n this.error({\n message: lowered.error.message,\n id: filePath,\n loc: lowered.error.loc && { file: filePath, ...lowered.error.loc },\n });\n }\n compiledFile = `${sourceFile}.ts`;\n // Transform the module again when a component it looked up changes\n for (const dependency of scanner.dependenciesOf(sourceFile)) {\n this.addWatchFile(dependency);\n }\n }\n const compiledCode = lowered ? lowered.code : code;\n const watch = (path: string) => this.addWatchFile(path);\n let result: NgpResult | undefined;\n try {\n result = await compileFile(compiledFile, watch);\n } catch (error) {\n // A failed compile stays cached until its file is updated, so only\n // report it if it compiled this content\n if (\n !sources.has(compiledFile) ||\n sources.get(compiledFile) === compiledCode\n ) {\n throw error;\n }\n }\n if (\n filesByPath.has(compiledFile) &&\n sources.get(compiledFile) !== compiledCode\n ) {\n if (lowered) analyzed.set(compiledFile, compiledCode);\n await enqueueIndex(() =>\n analyzer!.updateFileContent([\n { filePath: compiledFile, content: compiledCode },\n ]),\n );\n result = await compileFile(compiledFile, watch);\n } else if (!result && lowered) {\n this.error(\n `${filePath} is not part of the TypeScript program of ${resolveTsConfigPath()}. Import it, or add it to the tsconfig's \\`include\\`.`,\n );\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n let source = result?.magicString.toString() ?? code;\n if (lowered && result) {\n // Component HMR ids name the program file; the dev server knows the module\n source = source.replaceAll(\n encodeURIComponent(\n `${filesByPath.get(compiledFile)!.file.filePath}@`,\n ),\n encodeURIComponent(`${filePath}@`),\n );\n }\n const map = result?.magicString.generateMap({\n source: compiledFile,\n includeContent: true,\n hires: true,\n });\n const transpiled = await transpile(source, compiledFile, map);\n const outputMap =\n lowered && transpiled.map\n ? lowered.mapToSource(JSON.stringify(transpiled.map))\n : transpiled.map;\n if (outputMap) {\n emittedMaps.set(\n filePath,\n typeof outputMap === 'string' ? outputMap : JSON.stringify(outputMap),\n );\n }\n return {\n code: transpiled.code,\n map: outputMap as vite.Rollup.SourceMapInput,\n };\n },\n async handleHotUpdate(ctx) {\n if (\n sharedCtx\n ? sharedCtx.hmr.isIgnoredFile(ctx.file)\n : isIgnoredHmrFile(ctx.file)\n ) {\n return [];\n }\n const normPath = vite.normalizePath(ctx.file);\n const sourceFile = canonicalPath(ctx.file);\n const programFile = programFileOf(sourceFile);\n const updates = await withSourceLock(async () => {\n // Lowered again in `watchChange`, which runs first\n const relowered = reloweredByChange.get(sourceFile) ?? [];\n reloweredByChange.delete(sourceFile);\n const lowered = programFile\n ? sourceModules.get(programFile)?.lowered\n : undefined;\n // In place only for a module that lowered without errors, which no\n // other module was lowered again against\n const componentUpdates =\n hmr &&\n !lowered?.error &&\n relowered.every((file) => file === programFile)\n ? await findComponentUpdates(\n programFile ?? normPath,\n lowered ? () => lowered.code : ctx.read,\n )\n : [];\n if (!programFile) {\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([\n { filePath: ctx.file, updateType: FILE_CHANGED },\n ]),\n );\n }\n await syncProgramFiles();\n return componentUpdates;\n });\n if (updates.length && (await sendComponentUpdates(updates, ctx.server))) {\n return [];\n }\n hmrUpdateCode.clear();\n componentUpdates.classNames.clear();\n ctx.server.moduleGraph.invalidateAll();\n ctx.server.ws.send({ type: 'full-reload' });\n return [];\n },\n async buildEnd(error) {\n if (error || watchMode || !typeChecker) return;\n const typeErrors = await typeChecker.flushQueue();\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n },\n async closeBundle() {\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (watchMode || activeBuilds > 0) return;\n await pending.catch(() => {});\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n emittedMaps.clear();\n sources.clear();\n dependents.clear();\n sourceModules.clear();\n analyzed.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+HA,IAAM,eAAe;AACrB,IAA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,MAAM,IAAI,MAAM,WAAW,KAAK,IAAI,CAAC;EAEzC;EACA,MAAM,cAAc;GAClB,eAAe,KAAK,IAAI,GAAG,eAAe,CAAC;GAC3C,IAAI,aAAa,eAAe,GAAG;GACnC,MAAM,QAAQ,YAAY,CAAC,CAAC;GAC5B,aAAa,MAAM;GACnB,cAAc,KAAA;GACd,UAAU,MAAM;GAChB,WAAW,KAAA;GACX,WAAW,KAAA;GACX,YAAY,MAAM;GAClB,cAAc,MAAM;GACpB,OAAO,MAAM;GACb,YAAY,MAAM;GAClB,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,cAAc,MAAM;GACpB,SAAS,MAAM;GACf,8BAA8B;EAChC;CACF;AACF"}
@@ -29,23 +29,43 @@ interface TypeCheckerCommand {
29
29
  }
30
30
  /** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */
31
31
  export type FileChangeType = 1 | 2 | 3;
32
+ /** A reported location, with a one-based line and character. */
33
+ export interface SourceLocation {
34
+ file: string;
35
+ line: number;
36
+ character: number;
37
+ }
38
+ /** Hooks for checking files that don't exist on disk. */
39
+ export interface LspTypeCheckerHost {
40
+ /**
41
+ * The text of files that exist only in memory, by normalized path. They're
42
+ * opened before any check, so imports of them resolve.
43
+ */
44
+ inMemoryFiles(): ReadonlyMap<string, string>;
45
+ /** Maps a reported location to the source it was generated from. */
46
+ mapLocation(location: SourceLocation): SourceLocation;
47
+ }
32
48
  export declare function resolveTypeChecker(tsconfig: string, option: TypeCheckerOption): TypeCheckerCommand;
33
49
  export declare class LspTypeChecker {
50
+ private readonly host?;
34
51
  private proc;
35
52
  private seq;
36
53
  private pending;
37
54
  private versions;
38
55
  private queued;
56
+ /** The text last sent for each open in-memory file. */
57
+ private inMemoryText;
39
58
  private buffer;
40
59
  private exitError;
41
60
  readonly ready: Promise<void>;
42
- constructor(tsconfig: string, option?: TypeCheckerOption);
61
+ constructor(tsconfig: string, option?: TypeCheckerOption, host?: LspTypeCheckerHost);
43
62
  private onData;
44
63
  private send;
45
64
  private notify;
46
65
  private request;
47
66
  updateDocument(filePath: string, text: string);
48
- checkFile(filePath: string, sourceLineCount?: number, lines?: string[], tcbRanges?: TcbLineRange[]): Promise<string[]>;
67
+ checkFile(filePath: string, sourceLineCount?: number, lines?: string[], tcbRanges?: TcbLineRange[], inMemory?: boolean): Promise<string[]>;
68
+ private formatLocation;
49
69
  /** Reports a change on disk; an open copy is closed so the checker rereads the file. */
50
70
  notifyFileChanged(filePath: string, type: FileChangeType);
51
71
  queueFile(filePath: string, sourceCode: string, tcbCode?: string | null);
@@ -14,6 +14,7 @@ var IGNORED_TCB_CODES = /* @__PURE__ */ new Set([
14
14
  2695,
15
15
  7006
16
16
  ]);
17
+ var IGNORED_IN_MEMORY_CODES = /* @__PURE__ */ new Set([2742, 2883]);
17
18
  var BATCH_SIZE = 32;
18
19
  var TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\d+$/;
19
20
  var TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\d+$/;
@@ -260,15 +261,19 @@ function resolveTypeChecker(tsconfig, option) {
260
261
  };
261
262
  }
262
263
  var LspTypeChecker = class {
264
+ host;
263
265
  proc;
264
266
  seq = 1;
265
267
  pending = /* @__PURE__ */ new Map();
266
268
  versions = /* @__PURE__ */ new Map();
267
269
  queued = /* @__PURE__ */ new Map();
270
+ /** The text last sent for each open in-memory file. */
271
+ inMemoryText = /* @__PURE__ */ new Map();
268
272
  buffer = Buffer.alloc(0);
269
273
  exitError;
270
274
  ready;
271
- constructor(tsconfig, option = "tsgo") {
275
+ constructor(tsconfig, option = "tsgo", host) {
276
+ this.host = host;
272
277
  const cwd = dirname(tsconfig);
273
278
  const { command, args } = resolveTypeChecker(tsconfig, option);
274
279
  this.proc = spawn(command, args, {
@@ -373,23 +378,35 @@ var LspTypeChecker = class {
373
378
  contentChanges: [{ text }]
374
379
  });
375
380
  }
376
- async checkFile(filePath, sourceLineCount, lines, tcbRanges) {
381
+ async checkFile(filePath, sourceLineCount, lines, tcbRanges, inMemory = false) {
377
382
  const resolvedPath = resolve(filePath);
378
383
  const errors = [];
379
384
  const diag = await this.request("textDocument/diagnostic", { textDocument: { uri: pathToFileURL(resolvedPath).href } });
380
385
  for (const item of diag?.items ?? []) {
381
386
  if (item.severity !== 1) continue;
387
+ if (inMemory && IGNORED_IN_MEMORY_CODES.has(Number(item.code))) continue;
382
388
  const line = item.range.start.line;
383
389
  if (sourceLineCount !== void 0 && line >= sourceLineCount) {
384
390
  if (!IGNORED_TCB_CODES.has(Number(item.code)) && !lines?.[line]?.includes("/*D:ignore*/")) {
385
391
  const range = tcbRanges?.find((r) => line >= r.startLine && line < r.endLine);
386
392
  const location = range && lines && templateLocation(range, lines, item.range.start);
387
- errors.push(location ? `${location.file}:${location.line}:${location.character} - error TS${item.code}: ${item.message}` : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`);
393
+ errors.push(location ? `${this.formatLocation(location)} - error TS${item.code}: ${item.message}` : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`);
388
394
  }
389
- } else errors.push(`${filePath}:${line + 1}:${item.range.start.character + 1} - error TS${item.code}: ${item.message}`);
395
+ } else {
396
+ const location = {
397
+ file: filePath,
398
+ line: line + 1,
399
+ character: item.range.start.character + 1
400
+ };
401
+ errors.push(`${this.formatLocation(location)} - error TS${item.code}: ${item.message}`);
402
+ }
390
403
  }
391
404
  return errors;
392
405
  }
406
+ formatLocation(location) {
407
+ const { file, line, character } = this.host?.mapLocation(location) ?? location;
408
+ return `${file}:${line}:${character}`;
409
+ }
393
410
  /** Reports a change on disk; an open copy is closed so the checker rereads the file. */
394
411
  notifyFileChanged(filePath, type) {
395
412
  const uri = pathToFileURL(resolve(filePath)).href;
@@ -413,6 +430,18 @@ var LspTypeChecker = class {
413
430
  const entries = Array.from(this.queued.entries());
414
431
  this.queued.clear();
415
432
  await this.ready;
433
+ const toKey = (filePath) => filePath.replace(/\\/g, "/");
434
+ const inMemoryFiles = new Map([...this.host?.inMemoryFiles() ?? []].map(([filePath, text]) => [toKey(filePath), text]));
435
+ const isInMemory = (filePath) => inMemoryFiles.has(toKey(filePath));
436
+ for (const filePath of this.inMemoryText.keys()) if (!inMemoryFiles.has(filePath)) {
437
+ this.inMemoryText.delete(filePath);
438
+ const uri = pathToFileURL(resolve(filePath)).href;
439
+ if (this.versions.delete(uri)) this.notify("textDocument/didClose", { textDocument: { uri } });
440
+ }
441
+ for (const [filePath, text] of inMemoryFiles) if (this.inMemoryText.get(filePath) !== text) {
442
+ this.inMemoryText.set(filePath, text);
443
+ this.updateDocument(filePath, text);
444
+ }
416
445
  const metas = [];
417
446
  let updatesCount = 0;
418
447
  const update = async (filePath, text) => {
@@ -430,7 +459,7 @@ var LspTypeChecker = class {
430
459
  for (let i = 0; i < entries.length; i++) {
431
460
  const [filePath, { sourceCode, tcbCode }] = entries[i];
432
461
  const uri = pathToFileURL(resolve(filePath)).href;
433
- if (tcbCode && !this.versions.has(uri)) {
462
+ if (tcbCode && !this.versions.has(uri) && !isInMemory(filePath)) {
434
463
  const relocated = relocateTcb(filePath, tcbCode, hostDir, i, sharedImports);
435
464
  if (relocated !== null) {
436
465
  relocatedChunks.push({
@@ -448,7 +477,7 @@ var LspTypeChecker = class {
448
477
  }
449
478
  if (i === 0) continue;
450
479
  const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
451
- if (tcbCode || this.versions.has(uri)) await update(filePath, text);
480
+ if (tcbCode || this.versions.has(uri) || isInMemory(filePath)) await update(filePath, text);
452
481
  metas.push(meta);
453
482
  }
454
483
  const { meta: hostMeta } = inPlaceDocument(hostFilePath, hostItem.sourceCode, hostRelocated ? null : hostItem.tcbCode);
@@ -469,7 +498,7 @@ var LspTypeChecker = class {
469
498
  }
470
499
  }
471
500
  const hasHostTcb = hostTcbRanges.length > 0;
472
- if (hasHostTcb || this.versions.has(hostUri)) this.updateDocument(hostFilePath, hostLines.join("\n"));
501
+ if (hasHostTcb || this.versions.has(hostUri) || isInMemory(hostFilePath)) this.updateDocument(hostFilePath, hostLines.join("\n"));
473
502
  metas.unshift({
474
503
  filePath: hostFilePath,
475
504
  sourceLineCount: hostMeta.sourceLineCount,
@@ -479,15 +508,15 @@ var LspTypeChecker = class {
479
508
  } else for (const [filePath, { sourceCode, tcbCode }] of entries) {
480
509
  const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
481
510
  const uri = pathToFileURL(resolve(filePath)).href;
482
- if (tcbCode || watchMode || this.versions.has(uri)) await update(filePath, text);
511
+ if (tcbCode || watchMode || this.versions.has(uri) || isInMemory(filePath)) await update(filePath, text);
483
512
  metas.push(meta);
484
513
  }
485
514
  const errors = [];
486
515
  const first = metas[0];
487
- errors.push(...await this.checkFile(first.filePath, first.sourceLineCount, first.lines, first.tcbRanges));
516
+ errors.push(...await this.checkFile(first.filePath, first.sourceLineCount, first.lines, first.tcbRanges, isInMemory(first.filePath)));
488
517
  for (let i = 1; i < metas.length; i += BATCH_SIZE) {
489
518
  const slice = metas.slice(i, i + BATCH_SIZE);
490
- const batchResults = await Promise.all(slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) => this.checkFile(filePath, sourceLineCount, lines, tcbRanges)));
519
+ const batchResults = await Promise.all(slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) => this.checkFile(filePath, sourceLineCount, lines, tcbRanges, isInMemory(filePath))));
491
520
  for (const res of batchResults) errors.push(...res);
492
521
  }
493
522
  return errors;
@@ -1 +1 @@
1
- {"version":3,"file":"lsp-type-checker.js","names":[],"sources":["../../../../src/lib/utils/lsp-type-checker.ts"],"sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { dirname, relative, resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\ninterface LspDiagnostic {\n range: { start: { line: number; character: number } };\n severity?: number;\n code?: number | string;\n message: string;\n}\n\n// Same shape as NGP's `TcbTemplateSource`\nexport interface TcbTemplateSource {\n templateFile?: string;\n templateExpression?: { start: number; end: number };\n}\n\ntype TemplateSources = Record<string, TcbTemplateSource>;\n\ninterface TcbLineRange {\n startLine: number;\n endLine: number;\n filePath: string;\n sourceCode: string;\n templateSources: TemplateSources;\n}\n\ninterface FileMeta {\n filePath: string;\n sourceLineCount: number;\n lines?: string[];\n tcbRanges?: TcbLineRange[];\n}\n\n/** NGP's footer comment mapping TCB ids to the template they were generated from. */\nexport const TCB_TEMPLATE_SOURCES_PREFIX = 'ngp-tcb-template-sources:';\n\nconst IGNORED_TCB_CODES = new Set([6133, 6199, 2695, 7006]);\nconst BATCH_SIZE = 32;\n\nconst TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\\d+$/;\nconst TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\\d+$/;\nconst SPAN_COMMENT = /^(\\d+),(\\d+)$/;\n\nexport function readSpanComment(\n value: string,\n): { start: number; end: number } | null {\n const match = SPAN_COMMENT.exec(value);\n return match ? { start: Number(match[1]), end: Number(match[2]) } : null;\n}\n\nfunction walk(node: any, visit: (node: any) => void): void {\n if (Array.isArray(node)) {\n for (const child of node) walk(child, visit);\n return;\n }\n if (!node || typeof node.type !== 'string') return;\n visit(node);\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === 'object') walk(value, visit);\n }\n}\n\nfunction declaredName(stmt: any): string | undefined {\n if (stmt.type === 'VariableDeclaration')\n return stmt.declarations[0]?.id?.name;\n if (stmt.type === 'FunctionDeclaration' || stmt.type === 'TSDeclareFunction')\n return stmt.id?.name;\n return undefined;\n}\n\nfunction isTcbImport(stmt: any): boolean {\n const ns = stmt.type === 'ImportDeclaration' && stmt.specifiers[0];\n return (\n ns?.type === 'ImportNamespaceSpecifier' &&\n TCB_IMPORT_ALIAS.test(ns.local.name)\n );\n}\n\ninterface TcbParts {\n source: any[];\n imports: any[];\n blocks: any[];\n templateSources: TemplateSources;\n}\n\n// NGP places each block right after its class, so source can follow a block\nfunction splitTcb(tcbCode: string): TcbParts | null {\n if (!tcbCode.includes('/*tcb')) return null;\n const { program, comments, errors } = parseSync('tcb.ts', tcbCode);\n if (errors.length > 0) return null;\n const parts: TcbParts = {\n source: [],\n imports: [],\n blocks: [],\n templateSources: {},\n };\n const footer = comments.find((c) =>\n c.value.startsWith(TCB_TEMPLATE_SOURCES_PREFIX),\n );\n if (footer) {\n parts.templateSources = JSON.parse(\n footer.value.slice(TCB_TEMPLATE_SOURCES_PREFIX.length),\n );\n }\n for (const stmt of program.body) {\n if (TCB_LOCAL_NAME.test(declaredName(stmt) ?? '')) {\n parts.blocks.push(stmt);\n } else {\n parts.source.push(stmt);\n if (isTcbImport(stmt)) parts.imports.push(stmt);\n }\n }\n return parts.blocks.length > 0 ? parts : null;\n}\n\nfunction inPlaceDocument(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n): { text: string; meta: FileMeta } {\n const lines = sourceCode.split('\\n');\n const sourceLineCount = lines.length;\n if (!tcbCode)\n return { text: sourceCode, meta: { filePath, sourceLineCount } };\n const parts = splitTcb(tcbCode);\n const suffix = parts\n ? [...parts.imports, ...parts.blocks]\n .map((stmt) => tcbCode.slice(stmt.start, stmt.end))\n .join('\\n')\n : tcbCode;\n lines.push(...suffix.split('\\n'));\n const range: TcbLineRange = {\n startLine: sourceLineCount,\n endLine: lines.length,\n filePath,\n sourceCode,\n templateSources: parts?.templateSources ?? {},\n };\n return {\n text: lines.join('\\n'),\n meta: { filePath, sourceLineCount, lines, tcbRanges: [range] },\n };\n}\n\nfunction trailingSpan(\n text: string,\n pos: number,\n commentsByStart: Map<number, any>,\n): { start: number; end: number } | null {\n while (true) {\n while (pos < text.length && /\\s/.test(text[pos])) pos++;\n const comment = commentsByStart.get(pos);\n if (!comment) return null;\n const span = readSpanComment(comment.value);\n if (span) return span;\n pos = comment.end;\n }\n}\n\nfunction lineAndCharacter(text: string, offset: number) {\n const before = text.slice(0, offset).split('\\n');\n return {\n line: before.length,\n character: before[before.length - 1].length + 1,\n };\n}\n\n// Mirrors ngtsc: the span comment trailing the innermost node at the diagnostic\nfunction templateLocation(\n range: TcbLineRange,\n lines: string[],\n position: { line: number; character: number },\n): { file: string; line: number; character: number } | null {\n const chunk = lines.slice(range.startLine, range.endLine).join('\\n');\n let offset = position.character;\n for (let i = range.startLine; i < position.line; i++) {\n offset += lines[i].length + 1;\n }\n const { program, comments } = parseSync('tcb.ts', chunk);\n const commentsByStart = new Map(comments.map((c) => [c.start, c]));\n const ancestors: any[] = [];\n walk(program.body, (node) => {\n if (node.start <= offset && offset < node.end) ancestors.push(node);\n });\n const tcbFunction = ancestors.find(\n (node) =>\n node.type === 'FunctionDeclaration' && /_tcb\\d+$/.test(node.id?.name),\n );\n let span: { start: number; end: number } | null = null;\n for (let i = ancestors.length - 1; i >= 0 && !span; i--) {\n span = trailingSpan(chunk, ancestors[i].end, commentsByStart);\n }\n if (!tcbFunction || !span) return null;\n\n const id = /(tcb\\d+)$/.exec(tcbFunction.id.name)![1];\n const source = range.templateSources[id];\n const file = source?.templateFile ?? range.filePath;\n let content = range.sourceCode;\n if (source?.templateFile) {\n try {\n content = readFileSync(source.templateFile, 'utf-8');\n } catch {\n return null;\n }\n }\n const start = source?.templateExpression?.start ?? span.start;\n return { file, ...lineAndCharacter(content, start) };\n}\n\nfunction isBareTypeReference(type: any): boolean {\n return (\n type?.type === 'TSTypeReference' && type.typeName.type === 'Identifier'\n );\n}\n\nfunction collectExportedClasses(header: any[]): Map<string, string> {\n const exported = new Map<string, string>();\n for (const stmt of header) {\n const cls = stmt.declaration;\n if (cls?.type !== 'ClassDeclaration' || !cls.id) continue;\n if (stmt.type === 'ExportDefaultDeclaration') {\n exported.set(cls.id.name, 'default');\n } else if (stmt.type === 'ExportNamedDeclaration') {\n exported.set(cls.id.name, cls.id.name);\n }\n }\n return exported;\n}\n\nfunction hostRelativeSpecifier(absPath: string, hostDir: string): string {\n const spec = relative(hostDir, absPath).replace(/\\\\/g, '/');\n return spec.startsWith('.') ? spec : './' + spec;\n}\n\nfunction sharedAliasFor(spec: string, sharedImports: Map<string, string>) {\n let alias = sharedImports.get(spec);\n if (!alias) {\n alias = `_si${sharedImports.size}`;\n sharedImports.set(spec, alias);\n }\n return alias;\n}\n\nfunction relocateTcb(\n filePath: string,\n tcbCode: string,\n hostDir: string,\n fileIdx: number,\n sharedImports: Map<string, string>,\n): { body: string; templateSources: TemplateSources } | null {\n const parts = splitTcb(tcbCode);\n if (!parts) return null;\n\n const aliasSpecs = new Map<string, string>();\n for (const stmt of parts.imports) {\n aliasSpecs.set(stmt.specifiers[0].local.name, stmt.source.value);\n }\n\n const exportedClasses = collectExportedClasses(parts.source);\n const identifiers: any[] = [];\n const thisTypes: Array<{ node: any; exportProp: string }> = [];\n let relocatable = true;\n\n walk(parts.blocks, (node) => {\n if (node.type === 'Identifier') {\n identifiers.push(node);\n return;\n }\n // Same-file directives or pipes have no namespace import to relocate\n if (\n (node.type === 'VariableDeclarator' &&\n /^_pipe\\d+$/.test(node.id.name) &&\n isBareTypeReference(node.init?.typeAnnotation)) ||\n (node.type === 'TSFunctionType' &&\n node.params[0]?.name === 'init' &&\n isBareTypeReference(node.returnType?.typeAnnotation))\n ) {\n relocatable = false;\n return;\n }\n if (node.type !== 'FunctionDeclaration' || !/^_tcb\\d+$/.test(node.id?.name))\n return;\n const thisType = node.params[0]?.typeAnnotation?.typeAnnotation;\n if (node.params[0]?.name !== 'this' || !isBareTypeReference(thisType))\n return;\n const exportProp = exportedClasses.get(thisType.typeName.name);\n if (node.typeParameters || !exportProp) {\n relocatable = false;\n return;\n }\n thisTypes.push({ node: thisType.typeName, exportProp });\n });\n if (!relocatable) return null;\n\n const fileDir = dirname(resolve(filePath));\n const aliasMap = new Map<string, string>();\n for (const [alias, rawSpec] of aliasSpecs) {\n const spec = rawSpec.startsWith('.')\n ? hostRelativeSpecifier(resolve(fileDir, rawSpec), hostDir)\n : rawSpec;\n aliasMap.set(alias, sharedAliasFor(spec, sharedImports));\n }\n\n const ms = new MagicString(tcbCode);\n for (const node of identifiers) {\n if (TCB_LOCAL_NAME.test(node.name)) {\n ms.overwrite(node.start, node.end, `_f${fileIdx}_${node.name}`);\n } else if (aliasMap.has(node.name)) {\n ms.overwrite(node.start, node.end, aliasMap.get(node.name)!);\n }\n }\n if (thisTypes.length > 0) {\n const selfSpec = hostRelativeSpecifier(\n resolve(filePath).replace(/\\.[cm]?tsx?$/, ''),\n hostDir,\n );\n const selfAlias = sharedAliasFor(selfSpec, sharedImports);\n for (const { node, exportProp } of thisTypes) {\n ms.overwrite(node.start, node.end, `${selfAlias}.${exportProp}`);\n }\n }\n\n return {\n body: parts.blocks.map((stmt) => ms.slice(stmt.start, stmt.end)).join('\\n'),\n templateSources: parts.templateSources,\n };\n}\n\nexport type TypeCheckerOption =\n | 'tsgo'\n | 'tsrs'\n | { command: string; args?: string[] };\n\ninterface TypeCheckerCommand {\n command: string;\n args: string[];\n}\n\nconst LSP_ARGS = ['--lsp', '--stdio'];\n\n/** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */\nexport type FileChangeType = 1 | 2 | 3;\n\nfunction resolveTsgoBinary(tsconfig: string): string {\n if (process.env['TSNATIVE_BINARY_PATH'])\n return process.env['TSNATIVE_BINARY_PATH'];\n const ext = process.platform === 'win32' ? '.exe' : '';\n const candidates = [\n {\n parent: 'typescript/package.json',\n platform: `@typescript/typescript-${process.platform}-${process.arch}/package.json`,\n bin: `tsc${ext}`,\n },\n {\n parent: '@typescript/native-preview/package.json',\n platform: `@typescript/native-preview-${process.platform}-${process.arch}/package.json`,\n bin: `tsgo${ext}`,\n },\n ];\n for (const base of [tsconfig, import.meta.url]) {\n const req = createRequire(base);\n for (const candidate of candidates) {\n try {\n const parentPkg = req.resolve(candidate.parent);\n const platformPkg = createRequire(parentPkg).resolve(\n candidate.platform,\n );\n return resolve(dirname(platformPkg), 'lib', candidate.bin);\n } catch {\n // try next candidate\n }\n }\n }\n throw new Error(\n 'disableTypeChecking: false requires TypeScript 7 (typescript@^7.0.0), @typescript/native-preview, or TSNATIVE_BINARY_PATH.',\n );\n}\n\n// Run tsrs through its launcher, which selects the platform binary.\nfunction resolveTsrs(tsconfig: string): TypeCheckerCommand {\n for (const base of [tsconfig, import.meta.url]) {\n try {\n const pkg = createRequire(base).resolve('tsrs/package.json');\n return {\n command: process.execPath,\n args: [resolve(dirname(pkg), 'bin', 'tsrs'), ...LSP_ARGS],\n };\n } catch {\n // try next base\n }\n }\n throw new Error(\"typeChecker: 'tsrs' requires the tsrs package.\");\n}\n\nexport function resolveTypeChecker(\n tsconfig: string,\n option: TypeCheckerOption,\n): TypeCheckerCommand {\n if (typeof option === 'object') {\n return { command: option.command, args: option.args ?? LSP_ARGS };\n }\n if (option === 'tsrs') return resolveTsrs(tsconfig);\n return { command: resolveTsgoBinary(tsconfig), args: LSP_ARGS };\n}\n\nexport class LspTypeChecker {\n private proc: ChildProcessWithoutNullStreams;\n private seq = 1;\n private pending = new Map<\n number,\n { resolve: (value: any) => void; reject: (error: Error) => void }\n >();\n private versions = new Map<string, number>();\n private queued = new Map<\n string,\n { sourceCode: string; tcbCode?: string | null }\n >();\n private buffer = Buffer.alloc(0);\n private exitError: Error | undefined;\n readonly ready: Promise<void>;\n\n constructor(tsconfig: string, option: TypeCheckerOption = 'tsgo') {\n const cwd = dirname(tsconfig);\n const { command, args } = resolveTypeChecker(tsconfig, option);\n this.proc = spawn(command, args, {\n cwd,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n this.proc.stdout.on('data', (chunk: Buffer) => this.onData(chunk));\n const fail = (error: Error) => {\n this.exitError ??= error;\n for (const { reject } of this.pending.values()) reject(this.exitError);\n this.pending.clear();\n };\n this.proc.on('error', fail);\n this.proc.stdin.on('error', fail);\n this.proc.on('exit', (code) =>\n fail(new Error(`type checker exited with code ${code}`)),\n );\n const rootUri = pathToFileURL(cwd).href;\n this.ready = this.request('initialize', {\n processId: process.pid,\n rootUri,\n capabilities: { textDocument: { diagnostic: {} } },\n workspaceFolders: [{ uri: rootUri, name: 'root' }],\n }).then(() => this.notify('initialized', {}));\n this.ready.catch(() => {});\n }\n\n private onData(chunk: Buffer) {\n this.buffer = Buffer.concat([this.buffer, chunk]);\n while (true) {\n const headerEnd = this.buffer.indexOf('\\r\\n\\r\\n');\n if (headerEnd === -1) break;\n const match = /Content-Length: (\\d+)/i.exec(\n this.buffer.subarray(0, headerEnd).toString('utf8'),\n );\n if (!match) break;\n const bodyStart = headerEnd + 4;\n const bodyEnd = bodyStart + Number(match[1]);\n if (this.buffer.length < bodyEnd) break;\n const msg = JSON.parse(\n this.buffer.subarray(bodyStart, bodyEnd).toString('utf8'),\n );\n this.buffer = this.buffer.subarray(bodyEnd);\n if (msg.id !== undefined && msg.method !== undefined) {\n this.send({ jsonrpc: '2.0', id: msg.id, result: null });\n } else if (msg.id !== undefined && this.pending.has(msg.id)) {\n const entry = this.pending.get(msg.id)!;\n this.pending.delete(msg.id);\n if (msg.error) entry.reject(new Error(msg.error.message));\n else entry.resolve(msg.result);\n }\n }\n }\n\n private send(payload: unknown) {\n const json = JSON.stringify(payload);\n this.proc.stdin.write(\n `Content-Length: ${Buffer.byteLength(json, 'utf8')}\\r\\n\\r\\n${json}`,\n );\n }\n\n private notify(method: string, params: unknown) {\n this.send({ jsonrpc: '2.0', method, params });\n }\n\n private request(method: string, params: unknown): Promise<any> {\n if (this.exitError) return Promise.reject(this.exitError);\n const id = this.seq++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.send({ jsonrpc: '2.0', id, method, params });\n });\n }\n\n updateDocument(filePath: string, text: string) {\n const uri = pathToFileURL(resolve(filePath)).href;\n if (!this.versions.has(uri)) {\n // tsgo 7.0.0-dev.20260412 ignores didOpen text once other documents are open\n this.versions.set(uri, 1);\n this.notify('textDocument/didOpen', {\n textDocument: { uri, languageId: 'typescript', version: 1, text },\n });\n }\n const version = this.versions.get(uri)! + 1;\n this.versions.set(uri, version);\n this.notify('textDocument/didChange', {\n textDocument: { uri, version },\n contentChanges: [{ text }],\n });\n }\n\n async checkFile(\n filePath: string,\n sourceLineCount?: number,\n lines?: string[],\n tcbRanges?: TcbLineRange[],\n ): Promise<string[]> {\n const resolvedPath = resolve(filePath);\n const errors: string[] = [];\n const diag = await this.request('textDocument/diagnostic', {\n textDocument: { uri: pathToFileURL(resolvedPath).href },\n });\n for (const item of (diag?.items ?? []) as LspDiagnostic[]) {\n if (item.severity !== 1) continue;\n const line = item.range.start.line;\n if (sourceLineCount !== undefined && line >= sourceLineCount) {\n if (\n !IGNORED_TCB_CODES.has(Number(item.code)) &&\n !lines?.[line]?.includes('/*D:ignore*/')\n ) {\n const range = tcbRanges?.find(\n (r) => line >= r.startLine && line < r.endLine,\n );\n const location =\n range && lines && templateLocation(range, lines, item.range.start);\n errors.push(\n location\n ? `${location.file}:${location.line}:${location.character} - error TS${item.code}: ${item.message}`\n : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`,\n );\n }\n } else {\n errors.push(\n `${filePath}:${line + 1}:${item.range.start.character + 1} - error TS${item.code}: ${item.message}`,\n );\n }\n }\n return errors;\n }\n\n /** Reports a change on disk; an open copy is closed so the checker rereads the file. */\n notifyFileChanged(filePath: string, type: FileChangeType) {\n const uri = pathToFileURL(resolve(filePath)).href;\n const wasOpen = this.versions.delete(uri);\n this.ready.then(\n () => {\n if (wasOpen)\n this.notify('textDocument/didClose', { textDocument: { uri } });\n this.notify('workspace/didChangeWatchedFiles', {\n changes: [{ uri, type }],\n });\n },\n () => {},\n );\n }\n\n queueFile(filePath: string, sourceCode: string, tcbCode?: string | null) {\n this.queued.set(filePath, { sourceCode, tcbCode });\n }\n\n async flushQueue(watchMode = false): Promise<string[]> {\n if (this.queued.size === 0) return [];\n const entries = Array.from(this.queued.entries());\n this.queued.clear();\n await this.ready;\n\n const metas: FileMeta[] = [];\n let updatesCount = 0;\n const update = async (filePath: string, text: string) => {\n this.updateDocument(filePath, text);\n updatesCount++;\n if (updatesCount % BATCH_SIZE === 0) {\n await new Promise((r) => setTimeout(r, 5));\n }\n };\n\n if (!watchMode && entries.length > 1) {\n const [hostFilePath, hostItem] = entries[0];\n const hostDir = dirname(resolve(hostFilePath));\n const hostUri = pathToFileURL(resolve(hostFilePath)).href;\n const sharedImports = new Map<string, string>();\n const relocatedChunks: Array<{\n filePath: string;\n sourceCode: string;\n body: string;\n templateSources: TemplateSources;\n }> = [];\n let hostRelocated = false;\n\n for (let i = 0; i < entries.length; i++) {\n const [filePath, { sourceCode, tcbCode }] = entries[i];\n const uri = pathToFileURL(resolve(filePath)).href;\n if (tcbCode && !this.versions.has(uri)) {\n const relocated = relocateTcb(\n filePath,\n tcbCode,\n hostDir,\n i,\n sharedImports,\n );\n if (relocated !== null) {\n relocatedChunks.push({ filePath, sourceCode, ...relocated });\n if (i === 0) {\n hostRelocated = true;\n } else {\n metas.push({\n filePath,\n sourceLineCount: sourceCode.split('\\n').length,\n });\n }\n continue;\n }\n }\n if (i === 0) continue;\n\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n if (tcbCode || this.versions.has(uri)) await update(filePath, text);\n metas.push(meta);\n }\n\n const { meta: hostMeta } = inPlaceDocument(\n hostFilePath,\n hostItem.sourceCode,\n hostRelocated ? null : hostItem.tcbCode,\n );\n const hostLines = hostMeta.lines ?? hostItem.sourceCode.split('\\n');\n const hostTcbRanges = hostMeta.tcbRanges ?? [];\n\n if (relocatedChunks.length > 0) {\n for (const [spec, alias] of sharedImports) {\n hostLines.push(`import * as ${alias} from '${spec}';`);\n }\n for (const {\n filePath,\n sourceCode,\n body,\n templateSources,\n } of relocatedChunks) {\n const startLine = hostLines.length;\n hostLines.push(...body.split('\\n'));\n hostTcbRanges.push({\n startLine,\n endLine: hostLines.length,\n filePath,\n sourceCode,\n templateSources,\n });\n }\n }\n\n const hasHostTcb = hostTcbRanges.length > 0;\n if (hasHostTcb || this.versions.has(hostUri)) {\n this.updateDocument(hostFilePath, hostLines.join('\\n'));\n }\n metas.unshift({\n filePath: hostFilePath,\n sourceLineCount: hostMeta.sourceLineCount,\n lines: hasHostTcb ? hostLines : undefined,\n tcbRanges: hasHostTcb ? hostTcbRanges : undefined,\n });\n } else {\n for (const [filePath, { sourceCode, tcbCode }] of entries) {\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n const uri = pathToFileURL(resolve(filePath)).href;\n if (tcbCode || watchMode || this.versions.has(uri)) {\n await update(filePath, text);\n }\n metas.push(meta);\n }\n }\n\n const errors: string[] = [];\n const first = metas[0];\n errors.push(\n ...(await this.checkFile(\n first.filePath,\n first.sourceLineCount,\n first.lines,\n first.tcbRanges,\n )),\n );\n\n for (let i = 1; i < metas.length; i += BATCH_SIZE) {\n const slice = metas.slice(i, i + BATCH_SIZE);\n const batchResults = await Promise.all(\n slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) =>\n this.checkFile(filePath, sourceLineCount, lines, tcbRanges),\n ),\n );\n for (const res of batchResults) {\n errors.push(...res);\n }\n }\n return errors;\n }\n\n close() {\n this.proc.kill();\n }\n}\n"],"mappings":";;;;;;;;;AAuCA,IAAa,8BAA8B;AAE3C,IAAM,oCAAoB,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC;AAC1D,IAAM,aAAa;AAEnB,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AACvB,IAAM,eAAe;AAErB,SAAgB,gBACd,OACuC;CACvC,MAAM,QAAQ,aAAa,KAAK,KAAK;CACrC,OAAO,QAAQ;EAAE,OAAO,OAAO,MAAM,EAAE;EAAG,KAAK,OAAO,MAAM,EAAE;CAAE,IAAI;AACtE;AAEA,SAAS,KAAK,MAAW,OAAkC;CACzD,IAAI,MAAM,QAAQ,IAAI,GAAG;EACvB,KAAK,MAAM,SAAS,MAAM,KAAK,OAAO,KAAK;EAC3C;CACF;CACA,IAAI,CAAC,QAAQ,OAAO,KAAK,SAAS,UAAU;CAC5C,MAAM,IAAI;CACV,KAA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AAO,GACzC,KAAK,eAAe,cAAc,UAAU,KAAK,IAAI,CAAC;GAExD,MAAM,QAAQ;IACZ,UAAU;IACV,iBAAiB,SAAS;IAC1B,OAAO,aAAa,YAAY,KAAA;IAChC,WAAW,aAAa,gBAAgB,KAAA;GAC1C,CAAC;EACH,OACE,KAAK,MAAM,CAAC,UAAU,EAAE,YAAY,cAAc,SAAS;GACzD,MAAM,EAAE,MAAM,SAAS,gBAAgB,UAAU,YAAY,OAAO;GACpE,MAAM,MAAM,cAAc,QAAQ,QAAQ,CAAC,CAAC,CAAC;GAC7C,IAAI,WAAW,aAAa,KAAK,SAAS,IAAI,GAAG,GAC/C,MAAM,OAAO,UAAU,IAAI;GAE7B,MAAM,KAAK,IAAI;EACjB;EAGF,MAAM,SAAmB,CAAC;EAC1B,MAAM,QAAQ,MAAM;EACpB,OAAO,KACL,GAAI,MAAM,KAAK,UACb,MAAM,UACN,MAAM,iBACN,MAAM,OACN,MAAM,SACR,CACF;EAEA,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,YAAY;GACjD,MAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,UAAU;GAC3C,MAAM,eAAe,MAAM,QAAQ,IACjC,MAAM,KAAK,EAAE,UAAU,iBAAiB,OAAO,gBAC7C,KAAK,UAAU,UAAU,iBAAiB,OAAO,SAAS,CAC5D,CACF;GACA,KAAK,MAAM,OAAO,cAChB,OAAO,KAAK,GAAG,GAAG;EAEtB;EACA,OAAO;CACT;CAEA,QAAQ;EACN,KAAK,KAAK,KAAK;CACjB;AACF"}
1
+ {"version":3,"file":"lsp-type-checker.js","names":[],"sources":["../../../../src/lib/utils/lsp-type-checker.ts"],"sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { dirname, relative, resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\ninterface LspDiagnostic {\n range: { start: { line: number; character: number } };\n severity?: number;\n code?: number | string;\n message: string;\n}\n\n// Same shape as NGP's `TcbTemplateSource`\nexport interface TcbTemplateSource {\n templateFile?: string;\n templateExpression?: { start: number; end: number };\n}\n\ntype TemplateSources = Record<string, TcbTemplateSource>;\n\ninterface TcbLineRange {\n startLine: number;\n endLine: number;\n filePath: string;\n sourceCode: string;\n templateSources: TemplateSources;\n}\n\ninterface FileMeta {\n filePath: string;\n sourceLineCount: number;\n lines?: string[];\n tcbRanges?: TcbLineRange[];\n}\n\n/** NGP's footer comment mapping TCB ids to the template they were generated from. */\nexport const TCB_TEMPLATE_SOURCES_PREFIX = 'ngp-tcb-template-sources:';\n\nconst IGNORED_TCB_CODES = new Set([6133, 6199, 2695, 7006]);\n// \"The inferred type of 'x' cannot be named\": in-memory files are never emitted\nconst IGNORED_IN_MEMORY_CODES = new Set([2742, 2883]);\nconst BATCH_SIZE = 32;\n\nconst TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\\d+$/;\nconst TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\\d+$/;\nconst SPAN_COMMENT = /^(\\d+),(\\d+)$/;\n\nexport function readSpanComment(\n value: string,\n): { start: number; end: number } | null {\n const match = SPAN_COMMENT.exec(value);\n return match ? { start: Number(match[1]), end: Number(match[2]) } : null;\n}\n\nfunction walk(node: any, visit: (node: any) => void): void {\n if (Array.isArray(node)) {\n for (const child of node) walk(child, visit);\n return;\n }\n if (!node || typeof node.type !== 'string') return;\n visit(node);\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === 'object') walk(value, visit);\n }\n}\n\nfunction declaredName(stmt: any): string | undefined {\n if (stmt.type === 'VariableDeclaration')\n return stmt.declarations[0]?.id?.name;\n if (stmt.type === 'FunctionDeclaration' || stmt.type === 'TSDeclareFunction')\n return stmt.id?.name;\n return undefined;\n}\n\nfunction isTcbImport(stmt: any): boolean {\n const ns = stmt.type === 'ImportDeclaration' && stmt.specifiers[0];\n return (\n ns?.type === 'ImportNamespaceSpecifier' &&\n TCB_IMPORT_ALIAS.test(ns.local.name)\n );\n}\n\ninterface TcbParts {\n source: any[];\n imports: any[];\n blocks: any[];\n templateSources: TemplateSources;\n}\n\n// NGP places each block right after its class, so source can follow a block\nfunction splitTcb(tcbCode: string): TcbParts | null {\n if (!tcbCode.includes('/*tcb')) return null;\n const { program, comments, errors } = parseSync('tcb.ts', tcbCode);\n if (errors.length > 0) return null;\n const parts: TcbParts = {\n source: [],\n imports: [],\n blocks: [],\n templateSources: {},\n };\n const footer = comments.find((c) =>\n c.value.startsWith(TCB_TEMPLATE_SOURCES_PREFIX),\n );\n if (footer) {\n parts.templateSources = JSON.parse(\n footer.value.slice(TCB_TEMPLATE_SOURCES_PREFIX.length),\n );\n }\n for (const stmt of program.body) {\n if (TCB_LOCAL_NAME.test(declaredName(stmt) ?? '')) {\n parts.blocks.push(stmt);\n } else {\n parts.source.push(stmt);\n if (isTcbImport(stmt)) parts.imports.push(stmt);\n }\n }\n return parts.blocks.length > 0 ? parts : null;\n}\n\nfunction inPlaceDocument(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n): { text: string; meta: FileMeta } {\n const lines = sourceCode.split('\\n');\n const sourceLineCount = lines.length;\n if (!tcbCode)\n return { text: sourceCode, meta: { filePath, sourceLineCount } };\n const parts = splitTcb(tcbCode);\n const suffix = parts\n ? [...parts.imports, ...parts.blocks]\n .map((stmt) => tcbCode.slice(stmt.start, stmt.end))\n .join('\\n')\n : tcbCode;\n lines.push(...suffix.split('\\n'));\n const range: TcbLineRange = {\n startLine: sourceLineCount,\n endLine: lines.length,\n filePath,\n sourceCode,\n templateSources: parts?.templateSources ?? {},\n };\n return {\n text: lines.join('\\n'),\n meta: { filePath, sourceLineCount, lines, tcbRanges: [range] },\n };\n}\n\nfunction trailingSpan(\n text: string,\n pos: number,\n commentsByStart: Map<number, any>,\n): { start: number; end: number } | null {\n while (true) {\n while (pos < text.length && /\\s/.test(text[pos])) pos++;\n const comment = commentsByStart.get(pos);\n if (!comment) return null;\n const span = readSpanComment(comment.value);\n if (span) return span;\n pos = comment.end;\n }\n}\n\nfunction lineAndCharacter(text: string, offset: number) {\n const before = text.slice(0, offset).split('\\n');\n return {\n line: before.length,\n character: before[before.length - 1].length + 1,\n };\n}\n\n// Mirrors ngtsc: the span comment trailing the innermost node at the diagnostic\nfunction templateLocation(\n range: TcbLineRange,\n lines: string[],\n position: { line: number; character: number },\n): { file: string; line: number; character: number } | null {\n const chunk = lines.slice(range.startLine, range.endLine).join('\\n');\n let offset = position.character;\n for (let i = range.startLine; i < position.line; i++) {\n offset += lines[i].length + 1;\n }\n const { program, comments } = parseSync('tcb.ts', chunk);\n const commentsByStart = new Map(comments.map((c) => [c.start, c]));\n const ancestors: any[] = [];\n walk(program.body, (node) => {\n if (node.start <= offset && offset < node.end) ancestors.push(node);\n });\n const tcbFunction = ancestors.find(\n (node) =>\n node.type === 'FunctionDeclaration' && /_tcb\\d+$/.test(node.id?.name),\n );\n let span: { start: number; end: number } | null = null;\n for (let i = ancestors.length - 1; i >= 0 && !span; i--) {\n span = trailingSpan(chunk, ancestors[i].end, commentsByStart);\n }\n if (!tcbFunction || !span) return null;\n\n const id = /(tcb\\d+)$/.exec(tcbFunction.id.name)![1];\n const source = range.templateSources[id];\n const file = source?.templateFile ?? range.filePath;\n let content = range.sourceCode;\n if (source?.templateFile) {\n try {\n content = readFileSync(source.templateFile, 'utf-8');\n } catch {\n return null;\n }\n }\n const start = source?.templateExpression?.start ?? span.start;\n return { file, ...lineAndCharacter(content, start) };\n}\n\nfunction isBareTypeReference(type: any): boolean {\n return (\n type?.type === 'TSTypeReference' && type.typeName.type === 'Identifier'\n );\n}\n\nfunction collectExportedClasses(header: any[]): Map<string, string> {\n const exported = new Map<string, string>();\n for (const stmt of header) {\n const cls = stmt.declaration;\n if (cls?.type !== 'ClassDeclaration' || !cls.id) continue;\n if (stmt.type === 'ExportDefaultDeclaration') {\n exported.set(cls.id.name, 'default');\n } else if (stmt.type === 'ExportNamedDeclaration') {\n exported.set(cls.id.name, cls.id.name);\n }\n }\n return exported;\n}\n\nfunction hostRelativeSpecifier(absPath: string, hostDir: string): string {\n const spec = relative(hostDir, absPath).replace(/\\\\/g, '/');\n return spec.startsWith('.') ? spec : './' + spec;\n}\n\nfunction sharedAliasFor(spec: string, sharedImports: Map<string, string>) {\n let alias = sharedImports.get(spec);\n if (!alias) {\n alias = `_si${sharedImports.size}`;\n sharedImports.set(spec, alias);\n }\n return alias;\n}\n\nfunction relocateTcb(\n filePath: string,\n tcbCode: string,\n hostDir: string,\n fileIdx: number,\n sharedImports: Map<string, string>,\n): { body: string; templateSources: TemplateSources } | null {\n const parts = splitTcb(tcbCode);\n if (!parts) return null;\n\n const aliasSpecs = new Map<string, string>();\n for (const stmt of parts.imports) {\n aliasSpecs.set(stmt.specifiers[0].local.name, stmt.source.value);\n }\n\n const exportedClasses = collectExportedClasses(parts.source);\n const identifiers: any[] = [];\n const thisTypes: Array<{ node: any; exportProp: string }> = [];\n let relocatable = true;\n\n walk(parts.blocks, (node) => {\n if (node.type === 'Identifier') {\n identifiers.push(node);\n return;\n }\n // Same-file directives or pipes have no namespace import to relocate\n if (\n (node.type === 'VariableDeclarator' &&\n /^_pipe\\d+$/.test(node.id.name) &&\n isBareTypeReference(node.init?.typeAnnotation)) ||\n (node.type === 'TSFunctionType' &&\n node.params[0]?.name === 'init' &&\n isBareTypeReference(node.returnType?.typeAnnotation))\n ) {\n relocatable = false;\n return;\n }\n if (node.type !== 'FunctionDeclaration' || !/^_tcb\\d+$/.test(node.id?.name))\n return;\n const thisType = node.params[0]?.typeAnnotation?.typeAnnotation;\n if (node.params[0]?.name !== 'this' || !isBareTypeReference(thisType))\n return;\n const exportProp = exportedClasses.get(thisType.typeName.name);\n if (node.typeParameters || !exportProp) {\n relocatable = false;\n return;\n }\n thisTypes.push({ node: thisType.typeName, exportProp });\n });\n if (!relocatable) return null;\n\n const fileDir = dirname(resolve(filePath));\n const aliasMap = new Map<string, string>();\n for (const [alias, rawSpec] of aliasSpecs) {\n const spec = rawSpec.startsWith('.')\n ? hostRelativeSpecifier(resolve(fileDir, rawSpec), hostDir)\n : rawSpec;\n aliasMap.set(alias, sharedAliasFor(spec, sharedImports));\n }\n\n const ms = new MagicString(tcbCode);\n for (const node of identifiers) {\n if (TCB_LOCAL_NAME.test(node.name)) {\n ms.overwrite(node.start, node.end, `_f${fileIdx}_${node.name}`);\n } else if (aliasMap.has(node.name)) {\n ms.overwrite(node.start, node.end, aliasMap.get(node.name)!);\n }\n }\n if (thisTypes.length > 0) {\n const selfSpec = hostRelativeSpecifier(\n resolve(filePath).replace(/\\.[cm]?tsx?$/, ''),\n hostDir,\n );\n const selfAlias = sharedAliasFor(selfSpec, sharedImports);\n for (const { node, exportProp } of thisTypes) {\n ms.overwrite(node.start, node.end, `${selfAlias}.${exportProp}`);\n }\n }\n\n return {\n body: parts.blocks.map((stmt) => ms.slice(stmt.start, stmt.end)).join('\\n'),\n templateSources: parts.templateSources,\n };\n}\n\nexport type TypeCheckerOption =\n | 'tsgo'\n | 'tsrs'\n | { command: string; args?: string[] };\n\ninterface TypeCheckerCommand {\n command: string;\n args: string[];\n}\n\nconst LSP_ARGS = ['--lsp', '--stdio'];\n\n/** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */\nexport type FileChangeType = 1 | 2 | 3;\n\n/** A reported location, with a one-based line and character. */\nexport interface SourceLocation {\n file: string;\n line: number;\n character: number;\n}\n\n/** Hooks for checking files that don't exist on disk. */\nexport interface LspTypeCheckerHost {\n /**\n * The text of files that exist only in memory, by normalized path. They're\n * opened before any check, so imports of them resolve.\n */\n inMemoryFiles(): ReadonlyMap<string, string>;\n /** Maps a reported location to the source it was generated from. */\n mapLocation(location: SourceLocation): SourceLocation;\n}\n\nfunction resolveTsgoBinary(tsconfig: string): string {\n if (process.env['TSNATIVE_BINARY_PATH'])\n return process.env['TSNATIVE_BINARY_PATH'];\n const ext = process.platform === 'win32' ? '.exe' : '';\n const candidates = [\n {\n parent: 'typescript/package.json',\n platform: `@typescript/typescript-${process.platform}-${process.arch}/package.json`,\n bin: `tsc${ext}`,\n },\n {\n parent: '@typescript/native-preview/package.json',\n platform: `@typescript/native-preview-${process.platform}-${process.arch}/package.json`,\n bin: `tsgo${ext}`,\n },\n ];\n for (const base of [tsconfig, import.meta.url]) {\n const req = createRequire(base);\n for (const candidate of candidates) {\n try {\n const parentPkg = req.resolve(candidate.parent);\n const platformPkg = createRequire(parentPkg).resolve(\n candidate.platform,\n );\n return resolve(dirname(platformPkg), 'lib', candidate.bin);\n } catch {\n // try next candidate\n }\n }\n }\n throw new Error(\n 'disableTypeChecking: false requires TypeScript 7 (typescript@^7.0.0), @typescript/native-preview, or TSNATIVE_BINARY_PATH.',\n );\n}\n\n// Run tsrs through its launcher, which selects the platform binary.\nfunction resolveTsrs(tsconfig: string): TypeCheckerCommand {\n for (const base of [tsconfig, import.meta.url]) {\n try {\n const pkg = createRequire(base).resolve('tsrs/package.json');\n return {\n command: process.execPath,\n args: [resolve(dirname(pkg), 'bin', 'tsrs'), ...LSP_ARGS],\n };\n } catch {\n // try next base\n }\n }\n throw new Error(\"typeChecker: 'tsrs' requires the tsrs package.\");\n}\n\nexport function resolveTypeChecker(\n tsconfig: string,\n option: TypeCheckerOption,\n): TypeCheckerCommand {\n if (typeof option === 'object') {\n return { command: option.command, args: option.args ?? LSP_ARGS };\n }\n if (option === 'tsrs') return resolveTsrs(tsconfig);\n return { command: resolveTsgoBinary(tsconfig), args: LSP_ARGS };\n}\n\nexport class LspTypeChecker {\n private proc: ChildProcessWithoutNullStreams;\n private seq = 1;\n private pending = new Map<\n number,\n { resolve: (value: any) => void; reject: (error: Error) => void }\n >();\n private versions = new Map<string, number>();\n private queued = new Map<\n string,\n { sourceCode: string; tcbCode?: string | null }\n >();\n /** The text last sent for each open in-memory file. */\n private inMemoryText = new Map<string, string>();\n private buffer = Buffer.alloc(0);\n private exitError: Error | undefined;\n readonly ready: Promise<void>;\n\n constructor(\n tsconfig: string,\n option: TypeCheckerOption = 'tsgo',\n private readonly host?: LspTypeCheckerHost,\n ) {\n const cwd = dirname(tsconfig);\n const { command, args } = resolveTypeChecker(tsconfig, option);\n this.proc = spawn(command, args, {\n cwd,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n this.proc.stdout.on('data', (chunk: Buffer) => this.onData(chunk));\n const fail = (error: Error) => {\n this.exitError ??= error;\n for (const { reject } of this.pending.values()) reject(this.exitError);\n this.pending.clear();\n };\n this.proc.on('error', fail);\n this.proc.stdin.on('error', fail);\n this.proc.on('exit', (code) =>\n fail(new Error(`type checker exited with code ${code}`)),\n );\n const rootUri = pathToFileURL(cwd).href;\n this.ready = this.request('initialize', {\n processId: process.pid,\n rootUri,\n capabilities: { textDocument: { diagnostic: {} } },\n workspaceFolders: [{ uri: rootUri, name: 'root' }],\n }).then(() => this.notify('initialized', {}));\n this.ready.catch(() => {});\n }\n\n private onData(chunk: Buffer) {\n this.buffer = Buffer.concat([this.buffer, chunk]);\n while (true) {\n const headerEnd = this.buffer.indexOf('\\r\\n\\r\\n');\n if (headerEnd === -1) break;\n const match = /Content-Length: (\\d+)/i.exec(\n this.buffer.subarray(0, headerEnd).toString('utf8'),\n );\n if (!match) break;\n const bodyStart = headerEnd + 4;\n const bodyEnd = bodyStart + Number(match[1]);\n if (this.buffer.length < bodyEnd) break;\n const msg = JSON.parse(\n this.buffer.subarray(bodyStart, bodyEnd).toString('utf8'),\n );\n this.buffer = this.buffer.subarray(bodyEnd);\n if (msg.id !== undefined && msg.method !== undefined) {\n this.send({ jsonrpc: '2.0', id: msg.id, result: null });\n } else if (msg.id !== undefined && this.pending.has(msg.id)) {\n const entry = this.pending.get(msg.id)!;\n this.pending.delete(msg.id);\n if (msg.error) entry.reject(new Error(msg.error.message));\n else entry.resolve(msg.result);\n }\n }\n }\n\n private send(payload: unknown) {\n const json = JSON.stringify(payload);\n this.proc.stdin.write(\n `Content-Length: ${Buffer.byteLength(json, 'utf8')}\\r\\n\\r\\n${json}`,\n );\n }\n\n private notify(method: string, params: unknown) {\n this.send({ jsonrpc: '2.0', method, params });\n }\n\n private request(method: string, params: unknown): Promise<any> {\n if (this.exitError) return Promise.reject(this.exitError);\n const id = this.seq++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.send({ jsonrpc: '2.0', id, method, params });\n });\n }\n\n updateDocument(filePath: string, text: string) {\n const uri = pathToFileURL(resolve(filePath)).href;\n if (!this.versions.has(uri)) {\n // tsgo 7.0.0-dev.20260412 ignores didOpen text once other documents are open\n this.versions.set(uri, 1);\n this.notify('textDocument/didOpen', {\n textDocument: { uri, languageId: 'typescript', version: 1, text },\n });\n }\n const version = this.versions.get(uri)! + 1;\n this.versions.set(uri, version);\n this.notify('textDocument/didChange', {\n textDocument: { uri, version },\n contentChanges: [{ text }],\n });\n }\n\n async checkFile(\n filePath: string,\n sourceLineCount?: number,\n lines?: string[],\n tcbRanges?: TcbLineRange[],\n inMemory = false,\n ): Promise<string[]> {\n const resolvedPath = resolve(filePath);\n const errors: string[] = [];\n const diag = await this.request('textDocument/diagnostic', {\n textDocument: { uri: pathToFileURL(resolvedPath).href },\n });\n for (const item of (diag?.items ?? []) as LspDiagnostic[]) {\n if (item.severity !== 1) continue;\n if (inMemory && IGNORED_IN_MEMORY_CODES.has(Number(item.code))) continue;\n const line = item.range.start.line;\n if (sourceLineCount !== undefined && line >= sourceLineCount) {\n if (\n !IGNORED_TCB_CODES.has(Number(item.code)) &&\n !lines?.[line]?.includes('/*D:ignore*/')\n ) {\n const range = tcbRanges?.find(\n (r) => line >= r.startLine && line < r.endLine,\n );\n const location =\n range && lines && templateLocation(range, lines, item.range.start);\n errors.push(\n location\n ? `${this.formatLocation(location)} - error TS${item.code}: ${item.message}`\n : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`,\n );\n }\n } else {\n const location = {\n file: filePath,\n line: line + 1,\n character: item.range.start.character + 1,\n };\n errors.push(\n `${this.formatLocation(location)} - error TS${item.code}: ${item.message}`,\n );\n }\n }\n return errors;\n }\n\n private formatLocation(location: SourceLocation): string {\n const { file, line, character } =\n this.host?.mapLocation(location) ?? location;\n return `${file}:${line}:${character}`;\n }\n\n /** Reports a change on disk; an open copy is closed so the checker rereads the file. */\n notifyFileChanged(filePath: string, type: FileChangeType) {\n const uri = pathToFileURL(resolve(filePath)).href;\n const wasOpen = this.versions.delete(uri);\n this.ready.then(\n () => {\n if (wasOpen)\n this.notify('textDocument/didClose', { textDocument: { uri } });\n this.notify('workspace/didChangeWatchedFiles', {\n changes: [{ uri, type }],\n });\n },\n () => {},\n );\n }\n\n queueFile(filePath: string, sourceCode: string, tcbCode?: string | null) {\n this.queued.set(filePath, { sourceCode, tcbCode });\n }\n\n async flushQueue(watchMode = false): Promise<string[]> {\n if (this.queued.size === 0) return [];\n const entries = Array.from(this.queued.entries());\n this.queued.clear();\n await this.ready;\n\n const toKey = (filePath: string) => filePath.replace(/\\\\/g, '/');\n const inMemoryFiles = new Map(\n [...(this.host?.inMemoryFiles() ?? [])].map(([filePath, text]) => [\n toKey(filePath),\n text,\n ]),\n );\n const isInMemory = (filePath: string) => inMemoryFiles.has(toKey(filePath));\n // Keep the checker's in-memory files in step with the host's\n for (const filePath of this.inMemoryText.keys()) {\n if (!inMemoryFiles.has(filePath)) {\n this.inMemoryText.delete(filePath);\n const uri = pathToFileURL(resolve(filePath)).href;\n if (this.versions.delete(uri)) {\n this.notify('textDocument/didClose', { textDocument: { uri } });\n }\n }\n }\n for (const [filePath, text] of inMemoryFiles) {\n if (this.inMemoryText.get(filePath) !== text) {\n this.inMemoryText.set(filePath, text);\n this.updateDocument(filePath, text);\n }\n }\n\n const metas: FileMeta[] = [];\n let updatesCount = 0;\n const update = async (filePath: string, text: string) => {\n this.updateDocument(filePath, text);\n updatesCount++;\n if (updatesCount % BATCH_SIZE === 0) {\n await new Promise((r) => setTimeout(r, 5));\n }\n };\n\n if (!watchMode && entries.length > 1) {\n const [hostFilePath, hostItem] = entries[0];\n const hostDir = dirname(resolve(hostFilePath));\n const hostUri = pathToFileURL(resolve(hostFilePath)).href;\n const sharedImports = new Map<string, string>();\n const relocatedChunks: Array<{\n filePath: string;\n sourceCode: string;\n body: string;\n templateSources: TemplateSources;\n }> = [];\n let hostRelocated = false;\n\n for (let i = 0; i < entries.length; i++) {\n const [filePath, { sourceCode, tcbCode }] = entries[i];\n const uri = pathToFileURL(resolve(filePath)).href;\n if (tcbCode && !this.versions.has(uri) && !isInMemory(filePath)) {\n const relocated = relocateTcb(\n filePath,\n tcbCode,\n hostDir,\n i,\n sharedImports,\n );\n if (relocated !== null) {\n relocatedChunks.push({ filePath, sourceCode, ...relocated });\n if (i === 0) {\n hostRelocated = true;\n } else {\n metas.push({\n filePath,\n sourceLineCount: sourceCode.split('\\n').length,\n });\n }\n continue;\n }\n }\n if (i === 0) continue;\n\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n if (tcbCode || this.versions.has(uri) || isInMemory(filePath)) {\n await update(filePath, text);\n }\n metas.push(meta);\n }\n\n const { meta: hostMeta } = inPlaceDocument(\n hostFilePath,\n hostItem.sourceCode,\n hostRelocated ? null : hostItem.tcbCode,\n );\n const hostLines = hostMeta.lines ?? hostItem.sourceCode.split('\\n');\n const hostTcbRanges = hostMeta.tcbRanges ?? [];\n\n if (relocatedChunks.length > 0) {\n for (const [spec, alias] of sharedImports) {\n hostLines.push(`import * as ${alias} from '${spec}';`);\n }\n for (const {\n filePath,\n sourceCode,\n body,\n templateSources,\n } of relocatedChunks) {\n const startLine = hostLines.length;\n hostLines.push(...body.split('\\n'));\n hostTcbRanges.push({\n startLine,\n endLine: hostLines.length,\n filePath,\n sourceCode,\n templateSources,\n });\n }\n }\n\n const hasHostTcb = hostTcbRanges.length > 0;\n if (\n hasHostTcb ||\n this.versions.has(hostUri) ||\n isInMemory(hostFilePath)\n ) {\n this.updateDocument(hostFilePath, hostLines.join('\\n'));\n }\n metas.unshift({\n filePath: hostFilePath,\n sourceLineCount: hostMeta.sourceLineCount,\n lines: hasHostTcb ? hostLines : undefined,\n tcbRanges: hasHostTcb ? hostTcbRanges : undefined,\n });\n } else {\n for (const [filePath, { sourceCode, tcbCode }] of entries) {\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n const uri = pathToFileURL(resolve(filePath)).href;\n if (\n tcbCode ||\n watchMode ||\n this.versions.has(uri) ||\n isInMemory(filePath)\n ) {\n await update(filePath, text);\n }\n metas.push(meta);\n }\n }\n\n const errors: string[] = [];\n const first = metas[0];\n errors.push(\n ...(await this.checkFile(\n first.filePath,\n first.sourceLineCount,\n first.lines,\n first.tcbRanges,\n isInMemory(first.filePath),\n )),\n );\n\n for (let i = 1; i < metas.length; i += BATCH_SIZE) {\n const slice = metas.slice(i, i + BATCH_SIZE);\n const batchResults = await Promise.all(\n slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) =>\n this.checkFile(\n filePath,\n sourceLineCount,\n lines,\n tcbRanges,\n isInMemory(filePath),\n ),\n ),\n );\n for (const res of batchResults) {\n errors.push(...res);\n }\n }\n return errors;\n }\n\n close() {\n this.proc.kill();\n }\n}\n"],"mappings":";;;;;;;;;AAuCA,IAAa,8BAA8B;AAE3C,IAAM,oCAAoB,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC;AAE1D,IAAM,0CAA0B,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC;AACpD,IAAM,aAAa;AAEnB,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AACvB,IAAM,eAAe;AAErB,SAAgB,gBACd,OACuC;CACvC,MAAM,QAAQ,aAAa,KAAK,KAAK;CACrC,OAAO,QAAQ;EAAE,OAAO,OAAO,MAAM,EAAE;EAAG,KAAK,OAAO,MAAM,EAAE;CAAE,IAAI;AACtE;AAEA,SAAS,KAAK,MAAW,OAAkC;CACzD,IAAI,MAAM,QAAQ,IAAI,GAAG;EACvB,KAAK,MAAM,SAAS,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I,CAAC;GAExD,MAAM,QAAQ;IACZ,UAAU;IACV,iBAAiB,SAAS;IAC1B,OAAO,aAAa,YAAY,KAAA;IAChC,WAAW,aAAa,gBAAgB,KAAA;GAC1C,CAAC;EACH,OACE,KAAK,MAAM,CAAC,UAAU,EAAE,YAAY,cAAc,SAAS;GACzD,MAAM,EAAE,MAAM,SAAS,gBAAgB,UAAU,YAAY,OAAO;GACpE,MAAM,MAAM,cAAc,QAAQ,QAAQ,CAAC,CAAC,CAAC;GAC7C,IACE,WACA,aACA,KAAK,SAAS,IAAI,GAAG,KACrB,WAAW,QAAQ,GAEnB,MAAM,OAAO,UAAU,IAAI;GAE7B,MAAM,KAAK,IAAI;EACjB;EAGF,MAAM,SAAmB,CAAC;EAC1B,MAAM,QAAQ,MAAM;EACpB,OAAO,KACL,GAAI,MAAM,KAAK,UACb,MAAM,UACN,MAAM,iBACN,MAAM,OACN,MAAM,WACN,WAAW,MAAM,QAAQ,CAC3B,CACF;EAEA,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,YAAY;GACjD,MAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,UAAU;GAC3C,MAAM,eAAe,MAAM,QAAQ,IACjC,MAAM,KAAK,EAAE,UAAU,iBAAiB,OAAO,gBAC7C,KAAK,UACH,UACA,iBACA,OACA,WACA,WAAW,QAAQ,CACrB,CACF,CACF;GACA,KAAK,MAAM,OAAO,cAChB,OAAO,KAAK,GAAG,GAAG;EAEtB;EACA,OAAO;CACT;CAEA,QAAQ;EACN,KAAK,KAAK,KAAK;CACjB;AACF"}
@@ -0,0 +1,32 @@
1
+ interface HostStat {
2
+ isFile: boolean;
3
+ isDir: boolean;
4
+ isSymlink: boolean;
5
+ }
6
+ interface HostDirEntry extends HostStat {
7
+ name: string;
8
+ }
9
+ /** The file system NGP's WebAssembly backend reads through (`hostFs`). */
10
+ export interface NgpHostFs {
11
+ read(path: string): Uint8Array | null;
12
+ metadata(path: string): HostStat | null;
13
+ symlinkMetadata(path: string): HostStat | null;
14
+ readLink(path: string): string | null;
15
+ canonicalize(path: string): string | null;
16
+ readDir(path: string): HostDirEntry[] | null;
17
+ }
18
+ /**
19
+ * `path`, normalized, with the symlinks of its directory resolved. Lowered
20
+ * modules are keyed by these paths, whichever path a file is reached by.
21
+ */
22
+ export declare function canonicalPath(path: string): string;
23
+ /**
24
+ * The disk, with each module of a source format served as a TypeScript file
25
+ * named after it (`x.tsrx` as `x.tsrx.ts`) and the module itself hidden, so an
26
+ * import of `./x.tsrx` resolves to its TypeScript.
27
+ *
28
+ * @param programCode The TypeScript of a module's program file, by the file's
29
+ * normalized, canonical path.
30
+ */
31
+ export declare function createNgpHostFs(programCode: (path: string) => string | undefined): NgpHostFs;
32
+ export {};