@analogjs/vite-plugin-angular 3.0.0-beta.52 → 3.0.0-beta.54

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":"ngtsc-compile-plugin.js","names":[],"sources":["../../../src/lib/ngtsc-compile-plugin.ts"],"sourcesContent":["import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport { union } from 'es-toolkit';\nimport * as compilerCli from '@angular/compiler-cli';\nimport type { NgtscProgram } from '@angular/compiler-cli';\nimport type * as ts from 'typescript';\nimport type * as vite from 'vite';\nimport {\n normalizePath,\n preprocessCSS,\n type ModuleNode,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport {\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n findTemplateOwnerModules,\n getModulesForChangedFile,\n handleDirectComponentStyleHmr,\n isModuleForChangedResource,\n markModuleSelfAccepting,\n} from './component-styles-plugin.js';\nimport { isComponentStyleSheet } from './encapsulation-plugin.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithModuleResolution,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport { createHotUpdateBatcher } from './hot-update-batch.js';\nimport type { EmitFileResult } from './models.js';\nimport type {\n FileReplacementSSR,\n FileReplacementWith,\n} from './plugins/file-replacements.plugin.js';\nimport {\n describeStylesheetContent,\n injectViteIgnoreForHmrMetadata,\n} from './utils/compilation-shared.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport {\n activateDeferredDebug,\n debugCompiler,\n debugCompilerV,\n debugEmit,\n debugEmitV,\n debugHmr,\n debugHmrV,\n debugStyles,\n} from './utils/debug.js';\nimport {\n createJitResourceTransformer,\n SourceFileCache,\n} from './utils/devkit.js';\nimport { toJitInlineStyleId } from './utils/jit-inline-styles.js';\nimport {\n createDepOptimizerConfig,\n EXCLUDED_TS_EXT_REGEX,\n TS_EXT_REGEX,\n} from './utils/plugin-config.js';\nimport { getJsTransformConfigKey } from './utils/rolldown.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport type { SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\nimport { toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\nexport interface FileMetadataResult {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n}\n\nexport function evictDeletedFileMetadata(\n file: string,\n {\n classNamesMap,\n fileTransformMap,\n }: {\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n classNamesMap.delete(normalizedFile);\n fileTransformMap.delete(normalizedFile);\n}\n\nexport function createFsWatcherCacheInvalidator(\n invalidateFsCaches: () => void,\n invalidateTsconfigCaches: () => void,\n performCompilation: () => Promise<void>,\n): () => Promise<void> {\n return async (): Promise<void> => {\n invalidateFsCaches();\n invalidateTsconfigCaches();\n await performCompilation();\n };\n}\n\n/**\n * Compiles Angular TypeScript sources using `@angular/compiler-cli` (`NgtscProgram`).\n */\nexport function ngtscCompilePlugin(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): Plugin {\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'ngtsc',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n\n let cachedBuilder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram\n | undefined;\n let nextProgram: NgtscProgram | undefined;\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n\n function invalidateFsCaches(): void {\n ctx.tsconfigResolver.invalidateIncludeCache();\n }\n\n function invalidateTsconfigCaches(): void {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const tsSourceFileCache = new Map<string, ts.SourceFile>();\n\n function invalidateSourceFiles(files: Set<string>): void {\n for (const file of files) {\n tsSourceFileCache.delete(normalizePath(file));\n }\n sourceFileCache.invalidate(files);\n }\n\n const { jit, isTest } = ctx.options;\n let viteServer: ViteDevServer | undefined;\n\n const styleUrlsResolver = new StyleUrlsResolver();\n const templateUrlsResolver = new TemplateUrlsResolver();\n let outputFile: ((file: string) => void) | undefined;\n const outputFiles = new Map<string, EmitFileResult>();\n\n // Vite resolves module ids through symlinks, while the TypeScript program\n // names files by the tsconfig path as given. Both sides go through\n // `toRealPath` so `/var/...` and `/private/var/...` (macOS) or a symlinked\n // workspace name the same file.\n const realPaths = new Map<string, string>();\n const toRealPath = (file: string): string => {\n const normalizedFile = normalizePath(file);\n const cachedPath = realPaths.get(normalizedFile);\n if (cachedPath !== undefined) {\n return cachedPath;\n }\n\n let realPath: string;\n try {\n realPath = normalizePath(realpathSync(normalizedFile));\n } catch {\n // Not on disk (yet): leave it as is and don't cache it.\n return normalizedFile;\n }\n realPaths.set(normalizedFile, realPath);\n return realPath;\n };\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n\n if (!normalizedFile.startsWith('/@fs/')) {\n return toRealPath(normalizedFile);\n }\n\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n\n return toRealPath(fsPath);\n };\n\n const describeEmitMarkers = (content: string) => ({\n contentLength: content.length,\n hasCmp: content.includes('ɵcmp'),\n hasFac: content.includes('ɵfac'),\n hasProv: content.includes('ɵprov'),\n hasDecorate: content.includes('__decorate'),\n hasMetadata: content.includes('__metadata'),\n });\n\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n const hadCachedEmit = outputFiles.has(normalizedFile);\n outputFile?.(normalizedFile);\n const emittedResult = outputFiles.get(normalizedFile);\n debugEmitV('fileEmitter lookup', {\n requestFile: file,\n normalizedFile,\n hadCachedEmit,\n hasOutputFileHook: !!outputFile,\n emitted: !!emittedResult,\n knownOutputCount: outputFiles.size,\n contentLength: emittedResult?.content?.length ?? 0,\n errorCount: emittedResult?.errors?.length ?? 0,\n warningCount: emittedResult?.warnings?.length ?? 0,\n });\n return emittedResult;\n };\n\n ctx.hmr.setFileEmitter((file) => fileEmitter(file));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizeEmitterLookupId(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n let initialCompilation = false;\n let activeBuilds = 0;\n let closeRequested = false;\n const declarationFiles: DeclarationFile[] = [];\n const fileTransformMap = new Map<string, string>();\n let styleTransform: (\n code: string,\n filename: string,\n ) => Promise<vite.PreprocessCSSResult>;\n let pendingCompilation: Promise<void> | null = null;\n let compilationLock = Promise.resolve();\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function releaseCompilation(): void {\n cachedBuilder = undefined;\n nextProgram = undefined;\n cachedHost = undefined;\n cachedHostKey = undefined;\n outputFile = undefined;\n outputFiles.clear();\n fileTransformMap.clear();\n tsSourceFileCache.clear();\n sourceFileCache.clear();\n sourceFileCache.modifiedFiles.clear();\n sourceFileCache.babelFileCache?.clear();\n sourceFileCache.typeScriptFileCache?.clear();\n sourceFileCache.referencedFiles = undefined;\n ctx.tsconfigResolver.invalidateAll();\n releaseCssPreprocessorWorkers();\n ctx.styles.clear();\n }\n\n async function closeCompilation(): Promise<void> {\n closeRequested = false;\n hotUpdates.close();\n await compilationLock;\n declarationFiles.forEach(\n ({ declarationFileDir, declarationPath, data }) => {\n mkdirSync(declarationFileDir, { recursive: true });\n writeFileSync(declarationPath, data, 'utf-8');\n },\n );\n declarationFiles.length = 0;\n releaseCompilation();\n }\n\n function normalizeSourceMapSources(map: string, id: string): string {\n const sourceMap = JSON.parse(map) as {\n sources?: string[];\n sourceRoot?: string;\n };\n const sourceDirectory = dirname(id);\n const sourceRoot = sourceMap.sourceRoot ?? '';\n sourceMap.sources = sourceMap.sources?.map((source) => {\n if (isAbsolute(source) || /^[a-z][a-z\\d+.-]*:/i.test(source)) {\n return normalizePath(source);\n }\n return normalizePath(resolve(sourceDirectory, sourceRoot, source));\n });\n delete sourceMap.sourceRoot;\n return JSON.stringify(sourceMap);\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await _doPerformCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n /**\n * This method shares mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps\n * this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n invalidateSourceFiles(modifiedFiles);\n\n if (ids?.length) {\n for (const id of ids) {\n fileTransformMap.delete(id);\n }\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n\n // Clone options before mutation (preserve cache purity)\n const tsCompilerOptions = { ...cached.options };\n let rootNames = [...cached.rootNames];\n\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (NgtscProgram path)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = ctx.options.fileReplacements.map((rp) =>\n join(\n ctx.options.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = [\n ...new Set(\n union(\n union(rootNames, ctx.tsconfigResolver.ensureIncludeCache()),\n replacements,\n ).map(toRealPath),\n ),\n ];\n const hostKey = JSON.stringify(tsCompilerOptions);\n let host: ts.CompilerHost;\n\n if (cachedHost && cachedHostKey === hostKey) {\n host = cachedHost;\n } else {\n host = ts.createIncrementalCompilerHost(tsCompilerOptions, {\n ...ts.sys,\n readFile(path: string, encoding?: string) {\n if (fileTransformMap.has(path)) {\n return fileTransformMap.get(path);\n }\n\n const file = ts.sys.readFile.call(null, path, encoding);\n\n if (file) {\n fileTransformMap.set(path, file);\n }\n\n return file;\n },\n });\n augmentHostWithModuleResolution(host, tsCompilerOptions);\n cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (ctx.watchMode) {\n augmentHostWithCaching(host, tsSourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n const stylesheetRegistry = ctx.styles.resetRegistry(externalizeStyles);\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: ctx.options.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: ctx.stylePreprocessor,\n logger: ctx.resolvedConfig?.logger,\n isBuild: ctx.resolvedConfig?.command === 'build',\n });\n }\n\n /**\n * Creates a new NgtscProgram to analyze/re-analyze\n * the source files and create a file emitter.\n * This is shared between an initial build and a hot update.\n */\n let typeScriptProgram: ts.Program;\n let angularCompiler: NgtscProgram['compiler'] | undefined;\n // Declaration changes can invalidate diagnostics in unchanged consumers.\n let builder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n const oldBuilder = ids?.some((id) => EXCLUDED_TS_EXT_REGEX.test(id))\n ? undefined\n : (cachedBuilder ?? ts.readBuilderProgram(tsCompilerOptions, host));\n\n if (!jit) {\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(\n rootNames,\n tsCompilerOptions,\n host,\n nextProgram,\n );\n angularCompiler = angularProgram.compiler;\n typeScriptProgram = angularProgram.compiler.getCurrentProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n nextProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n rootNames,\n tsCompilerOptions,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n typeScriptProgram = builder.getProgram();\n }\n\n if (!ctx.watchMode) {\n // When not in watch mode, the startup cost of the incremental analysis can be avoided by\n // using an abstract builder that only wraps a TypeScript program.\n builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);\n }\n cachedBuilder = builder;\n\n if (angularCompiler) {\n await angularCompiler.analyzeAsync();\n\n if (!ctx.options.disableTypeChecking) {\n // TypeScript builds the program diagnostics lazily and records why each\n // file is in the program as an index into `referencedFiles`, which\n // includes the shim references Angular tags onto every source file.\n // `prepareEmit()` below removes those tags, so a diagnostic that\n // explains a file (e.g. TS6059 for a file outside `rootDir`) would\n // otherwise throw while it is built for the first file's diagnostics.\n typeScriptProgram.getOptionsDiagnostics();\n }\n }\n\n const beforeTransformers = jit\n ? [\n compilerCli.constructorParametersDownlevelTransform(\n builder.getProgram(),\n ),\n createJitResourceTransformer(() =>\n builder.getProgram().getTypeChecker(),\n ),\n ]\n : [];\n\n const transformers = mergeTransformers(\n { before: beforeTransformers },\n jit ? {} : angularCompiler!.prepareEmit().transformers,\n );\n\n const fileMetadata = getFileMetadata(\n builder,\n angularCompiler,\n ctx.options.liveReload,\n ctx.options.disableTypeChecking,\n ctx.hmr.classNames,\n );\n\n const writeFileCallback: ts.WriteFileCallback = (\n _filename,\n content,\n _a,\n _b,\n sourceFiles,\n ) => {\n if (!sourceFiles?.length) {\n return;\n }\n\n const filename = normalizePath(sourceFiles[0].fileName);\n\n // Skip declaration outputs and declaration source files.\n if (\n filename.includes('ngtypecheck.ts') ||\n filename.includes('.d.') ||\n _filename.endsWith('.d.ts') ||\n _filename.endsWith('.d.mts') ||\n _filename.endsWith('.d.cts')\n ) {\n return;\n }\n\n // TS emits the .js.map file separately — attach it to the entry for\n // the same source file so the transform hook can return the map and\n // coverage tools can chain maps back to the original TS. The .map can\n // arrive before or after the .js, so upsert in either order. Match\n // only `.js.map` (not `.d.ts.map`) so a future `declarationMap: true`\n // doesn't clobber the JS source map with the declaration map.\n if (/\\.[cm]?js\\.map$/.test(_filename)) {\n const existing = outputFiles.get(filename);\n outputFiles.set(filename, {\n ...(existing ?? { dependencies: [] }),\n map: content,\n });\n return;\n }\n\n const metadata = ctx.watchMode ? fileMetadata(filename) : {};\n const existing = outputFiles.get(filename);\n\n outputFiles.set(filename, {\n ...(existing ?? {}),\n content,\n dependencies: [],\n errors: metadata.errors,\n warnings: metadata.warnings,\n hmrUpdateCode: metadata.hmrUpdateCode,\n hmrEligible: metadata.hmrEligible,\n });\n debugEmitV('registered ngtsc output', {\n filename,\n ...describeEmitMarkers(content),\n errorCount: metadata.errors?.length ?? 0,\n warningCount: metadata.warnings?.length ?? 0,\n hmrEligible: !!metadata.hmrEligible,\n knownOutputCount: outputFiles.size,\n });\n };\n\n const writeOutputFile = (id: string): void => {\n const sourceFile = builder.getSourceFile(toRealPath(id));\n if (!sourceFile) {\n return;\n }\n\n let content = '';\n let map: string | undefined;\n let mapFilename: string | undefined;\n builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\n }\n\n if (/\\.[cm]?js\\.map$/.test(filename)) {\n map = data;\n mapFilename = filename;\n }\n\n if (\n !ctx.watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const root = toRealPath(config.root);\n const declarationPath = resolve(\n root,\n config.build.outDir,\n relative(root, filename),\n ).replace('/src/', '/');\n\n const declarationFileDir = declarationPath\n .replace(basename(filename), '')\n .replace('/src/', '/');\n\n declarationFiles.push({\n declarationFileDir,\n declarationPath,\n data,\n });\n }\n },\n undefined /* cancellationToken */,\n undefined /* emitOnlyDtsFiles */,\n transformers,\n );\n\n writeFileCallback(id, content, false, undefined, [sourceFile]);\n if (map !== undefined && mapFilename !== undefined) {\n // Use the filename TypeScript emitted (handles `.cts`/`.mts` as well\n // as `.ts`) instead of regex-replacing the source `.ts` extension.\n writeFileCallback(mapFilename, map, false, undefined, [sourceFile]);\n }\n\n if (angularCompiler) {\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n };\n\n if (ctx.watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else if (isTest) {\n /**\n * Only block the server from starting up\n * during testing.\n */\n while (\n (\n builder as ts.EmitAndSemanticDiagnosticsBuilderProgram\n ).emitNextAffectedFile(\n writeFileCallback,\n undefined,\n undefined,\n transformers,\n )\n ) {\n /* empty */\n }\n }\n }\n\n if (!isTest) {\n /**\n * Perf: Output files on demand so the dev server\n * isn't blocked when emitting files.\n */\n outputFile = writeOutputFile;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n api: compilerApi,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n // Do a preliminary resolution for dep optimizer (before configResolved)\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n\n const esbuild = config.esbuild ?? false;\n const oxc = config.oxc ?? false;\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n ...depOptimizer,\n };\n },\n configResolved(config) {\n ctx.setResolvedConfig(config);\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n // Add/unlink changes the TypeScript program shape, not just file\n // contents, so we need to invalidate both include discovery and the\n // cached tsconfig root names before recompiling.\n const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(\n invalidateFsCaches,\n invalidateTsconfigCaches,\n () => performCompilation(ctx.resolvedConfig!),\n );\n server.watcher.on('add', (file) => {\n if (EXCLUDED_TS_EXT_REGEX.test(file)) {\n invalidateSourceFiles(new Set([normalizePath(file)]));\n }\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('unlink', (file) => {\n const id = normalizePath(file);\n outputFiles.delete(id);\n tsSourceFileCache.delete(id);\n sourceFileCache.invalidate(new Set([id]));\n evictDeletedFileMetadata(file, {\n classNamesMap: ctx.hmr.classNames,\n fileTransformMap,\n });\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n activeBuilds++;\n // Vite keys its CSS preprocessor worker cache by the top-level resolved\n // config object. Passing `this.environment.config` misses that cache\n // and falls back to a worker Vite never closes, which keeps Vitest\n // from exiting after AOT tests with `.scss` styleUrls. (#2556)\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, ctx.resolvedConfig!);\n }\n\n // Browser mode also creates a server that may never transform TypeScript.\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as ResolvedConfig | undefined) ??\n ctx.resolvedConfig!,\n );\n await pendingCompilation;\n pendingCompilation = null;\n\n initialCompilation = true;\n }\n },\n async buildEnd(): Promise<void> {\n // Environments (e.g. client and ssr) build in parallel and share this\n // plugin's compilation state, so only reset after the last one ends.\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (activeBuilds > 0) return;\n if (closeRequested) {\n await closeCompilation();\n return;\n }\n if (!ctx.watchMode) releaseCompilation();\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n if (EXCLUDED_TS_EXT_REGEX.test(fileId)) {\n // Declaration dependencies have no runtime modules for Vite to invalidate.\n hmrCtx.server.moduleGraph.invalidateAll();\n hmrCtx.server.ws.send({ type: 'full-reload', triggeredBy: fileId });\n return [];\n }\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: hmrCtx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n className: ctx.hmr.classNames.get(fileId),\n updateCode: result?.hmrUpdateCode\n ? describeStylesheetContent(result.hmrUpdateCode)\n : undefined,\n errors: result?.errors?.length ?? 0,\n warnings: result?.warnings?.length ?? 0,\n hint: result?.hmrEligible\n ? 'A TS-side component change, including inline template edits, produced an Angular HMR payload.'\n : 'No Angular HMR payload was emitted for this TS change; the change may not affect component template state.',\n });\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n result?.hmrEligible &&\n ctx.hmr.classNames.get(fileId)\n ) {\n const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);\n\n debugHmr('sending component update', { relativeFileId });\n debugHmrV('ts hmr component update payload', {\n file: hmrCtx.file,\n fileId,\n relativeFileId,\n className: ctx.hmr.classNames.get(fileId),\n });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('resource file changed', { file: hmrCtx.file });\n fileTransformMap.delete(hmrCtx.file.split('?')[0]);\n // Angular component resources frequently enter HMR with incomplete\n // watcher context. In practice `ctx.modules` may only contain the\n // source file, only the `?direct` module, or nothing at all after a\n // TS-driven component refresh. Resolve the full live module set from\n // Vite's module graph and our stylesheet registry before deciding how\n // to hot update the resource.\n const stylesheetRegistry = ctx.styles.registry;\n const fileModules = await getModulesForChangedFile(\n hmrCtx.server,\n hmrCtx.file,\n hmrCtx.modules,\n stylesheetRegistry,\n );\n /**\n * Check to see if this was a direct request\n * for an external resource (styles, html).\n */\n const isDirect = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?direct') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: hmrCtx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (ctx.shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: hmrCtx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n return handleDirectComponentStyleHmr({\n server: hmrCtx.server,\n file: hmrCtx.file,\n directModule: isDirect,\n fileModules,\n stylesheetRegistry,\n stylePreprocessor: ctx.stylePreprocessor,\n });\n }\n }\n return fileModules;\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n /\\.(html|htm)$/.test(hmrCtx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(\n hmrCtx.server,\n hmrCtx.file,\n );\n debugHmrV('template owner lookup', {\n file: hmrCtx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n hint:\n ownerModules.length > 0\n ? 'The external template has candidate TS owner modules that can be recompiled for HMR.'\n : 'No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path.',\n });\n if (ownerModules.length > 0) {\n const ownerIds = ownerModules\n .map((mod) => mod.id)\n .filter(Boolean) as string[];\n\n ownerModules.forEach((mod) =>\n hmrCtx.server.moduleGraph.invalidateModule(mod),\n );\n\n await hotUpdates.schedule(hmrCtx.file, ownerIds);\n\n const updates = ownerIds.filter((id) => ctx.hmr.classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: hmrCtx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: ctx.hmr.classNames.get(id),\n })),\n hint:\n updates.length > 0\n ? 'External template recompilation produced Angular component update targets.'\n : 'External template recompilation completed, but no Angular component update targets were surfaced.',\n });\n if (updates.length > 0) {\n debugHmr('template owner module invalidation', {\n file: hmrCtx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return ownerModules.map((mod) => markModuleSelfAccepting(mod));\n }\n }\n }\n\n const mods: ModuleNode[] = [];\n const updates: string[] = [];\n fileModules.forEach((mod) => {\n mod.importers.forEach((imp) => {\n hmrCtx.server.moduleGraph.invalidateModule(imp);\n\n if (\n ctx.shouldExternalizeStyles() &&\n imp.id &&\n ctx.hmr.classNames.get(imp.id)\n ) {\n updates.push(imp.id);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: hmrCtx.file,\n fileModuleCount: fileModules.length,\n importerCount: fileModules.reduce(\n (count, mod) => count + mod.importers.size,\n 0,\n ),\n updates,\n mods: mods.map((mod) => mod.id),\n });\n\n if (mods.length === 0 && updates.length === 0) return mods;\n\n await hotUpdates.schedule(hmrCtx.file, [\n ...mods.map((mod) => mod.id as string),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n debugHmr('resource importer component updates', {\n file: hmrCtx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return fileModules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n\n return mods;\n }\n\n // clear HMR updates with a full reload\n debugHmr('full reload — unrecognized file type', { file: hmrCtx.file });\n ctx.hmr.clear();\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Encapsulation of component stylesheets is handled by the\n // separate '@analogjs/vite-plugin-angular:encapsulation' plugin\n // with enforce: 'post'. This ensures @tailwindcss/vite (enforce:\n // 'pre') fully resolves @apply directives — including those inside\n // :host {} — before Angular's ShadowCss rewrites selectors. (#2293)\n\n if (id.includes('.ts?')) {\n // Strip the query string off the ID\n // in case of a dynamically loaded file\n id = id.replace(/\\?(.*)/, '');\n }\n\n fileTransformMap.set(id, code);\n\n /**\n * Re-analyze on each transform\n * for test(Vitest)\n */\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n // Do full initial compilation\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n );\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n [id],\n );\n }\n }\n }\n\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n // Resource URLs are only consumed for watch-file registration and\n // JIT rewrites, so skip resolution entirely in prod AOT builds.\n const resolveResourceUrls = hasComponent && (ctx.watchMode || jit);\n const templateUrls = resolveResourceUrls\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = resolveResourceUrls\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (resolveResourceUrls && ctx.watchMode) {\n for (const urlSet of [...templateUrls, ...styleUrls]) {\n // `urlSet` is a string where a relative path is joined with an\n // absolute path using the `|` symbol.\n // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.\n const [, absoluteFileUrl] = urlSet.split('|');\n this.addWatchFile(absoluteFileUrl);\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilerV('transform skip (file not emitted by Angular)', {\n id,\n });\n // File not in the Angular program — skip and let other plugins\n // or Vite's built-in transform handle it. Warn if it looks like\n // an Angular file that should have been compiled.\n const isAngular =\n !id.includes('@ng/component') &&\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n debugEmit('transform emit miss', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n knownOutputCount: outputFiles.size,\n hasOutputFileHook: !!outputFile,\n isAngular,\n });\n\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n debugEmitV('transform emit hit', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n ...describeEmitMarkers(data),\n errorCount: typescriptResult.errors?.length ?? 0,\n warningCount: typescriptResult.warnings?.length ?? 0,\n });\n\n if (jit && data.includes('angular:jit:')) {\n // The emitted id carries the base64 of the entire stylesheet,\n // and the bundler derives chunk names from it — hash it so a\n // large inline style can't produce an over-long filename (#2459).\n data = data.replace(\n /angular:jit:style:inline;([A-Za-z0-9+/=]*)/g,\n (_match, encodedStyles) =>\n toJitInlineStyleId(encodedStyles, isTest),\n );\n\n // Templates use virtual ids (no extension) so Vite's asset/CSS\n // plugins don't interfere. (#2263)\n templateUrls.forEach((templateUrlSet) => {\n const [templateFile, resolvedTemplateUrl] =\n templateUrlSet.split('|');\n data = data.replace(\n `angular:jit:template:file;${templateFile}`,\n toVirtualRawId(resolvedTemplateUrl),\n );\n });\n\n // External styles use native ?inline imports. We mark each\n // path as safe in Vite's safeModulePaths so the Denied ID\n // security check passes, and Vite's CSS pipeline handles\n // preprocessing, test.css, and browser/node differences\n // natively. (#2263, #2310)\n styleUrls.forEach((styleUrlSet) => {\n const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');\n markStylePathSafe(ctx.resolvedConfig, resolvedStyleUrl);\n data = data.replace(\n `angular:jit:style:file;${styleFile}`,\n resolvedStyleUrl + '?inline',\n );\n });\n }\n\n // Angular's HMR initializer emits dynamic import() calls that Vite's\n // import-analysis plugin cannot statically analyze, producing SSR\n // warnings. The Angular compiler's IR includes a @vite-ignore comment\n // but it can be lost during TypeScript emit. Re-inject it here so the\n // warning is suppressed regardless of the compilation path used.\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n debugHmrV('vite-ignore injection', {\n id,\n dataLength: data.length,\n hasMetaUrl,\n });\n if (hasMetaUrl) {\n const patched = injectViteIgnoreForHmrMetadata(data);\n if (patched !== data && !patched.includes('@vite-ignore')) {\n debugHmrV('vite-ignore regex fallback', { id });\n }\n data = patched;\n }\n }\n if (typescriptResult.map) {\n // TS emits `//# sourceMappingURL=foo.js.map` at the end of the\n // .js content, but the .map file isn't served by Vite — we\n // return the map object directly. Strip the stale reference so\n // downstream tools don't see two sourceMappingURL comments.\n data = data.replace(/\\s*\\/\\/# sourceMappingURL=[^\\r\\n]*\\s*$/, '');\n }\n\n return {\n code: data,\n map: typescriptResult.map\n ? normalizeSourceMapSources(typescriptResult.map, id)\n : null,\n };\n },\n },\n async closeBundle(): Promise<void> {\n closeRequested = true;\n if (activeBuilds === 0) {\n await closeCompilation();\n }\n },\n };\n}\n\n/**\n * @internal\n */\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n classNamesMap: Map<string, string> = new Map(),\n): (file: string) => FileMetadataResult {\n const ts = require('typescript') as typeof import('typescript');\n return (file: string): FileMetadataResult => {\n const sourceFile = program.getSourceFile(file);\n if (!sourceFile) {\n return {};\n }\n\n const diagnostics = getDiagnosticsForSourceFile(\n sourceFile,\n !!disableTypeChecking,\n program,\n angularCompiler,\n );\n\n const errors = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Error)\n .map((d) =>\n typeof d.messageText === 'object'\n ? d.messageText.messageText\n : d.messageText,\n );\n\n const warnings = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Warning)\n .map((d) => d.messageText);\n\n let hmrUpdateCode: string | null | undefined = undefined;\n\n let hmrEligible = false;\n if (hmrEnabled) {\n for (const node of sourceFile.statements) {\n if (ts.isClassDeclaration(node) && node.name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);\n if (hmrUpdateCode) {\n const className = node.name.getText();\n classNamesMap.set(file, className);\n hmrEligible = true;\n debugHmr('NgtscProgram emitHmrUpdateModule', { file, className });\n }\n }\n }\n }\n\n return { errors, warnings, hmrUpdateCode, hmrEligible };\n };\n}\n\nfunction getDiagnosticsForSourceFile(\n sourceFile: ts.SourceFile,\n disableTypeChecking: boolean,\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n): readonly ts.Diagnostic[] {\n const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n if (disableTypeChecking) {\n // Syntax errors are cheap to compute and the app will not run if there are any\n // So always show these types of errors regardless if type checking is disabled\n return syntacticDiagnostics;\n }\n\n const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);\n const angularDiagnostics = angularCompiler\n ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)\n : [];\n return [\n ...syntacticDiagnostics,\n ...semanticDiagnostics,\n ...angularDiagnostics,\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAM,UAAU,cAAc,YAAY,GAAG;AAe7C,SAAgB,yBACd,MACA,EACE,eACA,oBAKI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,GAAG,CAAC,CAAC,EAAE;CACvD,cAAc,OAAO,cAAc;CACnC,iBAAiB,OAAO,cAAc;AACxC;AAEA,SAAgB,gCACd,oBACA,0BACA,oBACqB;CACrB,OAAO,YAA2B;EAChC,mBAAmB;EACnB,yBAAyB;EACzB,MAAM,mBAAmB;CAC3B;AACF;;;;AAKA,SAAgB,mBACd,cACQ;CACR,MAAM,MAAM,sBAAsB,YAAY,IAC1C,eACA,0BAA0B;EACxB,GAAG;EACH,oBAAoB;CACtB,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AAG,oBAAoB,KAAK,CAAC,CAC1D,KAAK,MACJ,OAAO,EAAE,gBAAgB,WACrB,EAAE,YAAY,cACd,EAAE,WACR;EAEF,MAAM,WAAW,YACd,QAAQ,MAAM,EAAE,aAAa,GAAG,oBAAoB,OAAO,CAAC,CAC5D,KAAK,MAAM,EAAE,WAAW;EAE3B,IAAI,gBAA2C,KAAA;EAE/C,IAAI,cAAc;EAClB,IAAI,YACG;QAAA,MAAM,QAAQ,WAAW,YAC5B,IAAI,GAAG,mBAAmB,IAAI,KAAK,KAAK,QAAQ,MAAM;IACpD,gBAAgB,iBAAiB,oBAAoB,IAAI;IACzD,IAAI,eAAe;KACjB,MAAM,YAAY,KAAK,KAAK,QAAQ;KACpC,cAAc,IAAI,MAAM,SAAS;KACjC,cAAc;KACd,SAAS,oCAAoC;MAAE;MAAM;KAAU,CAAC;IAClE;GACF;;EAIJ,OAAO;GAAE;GAAQ;GAAU;GAAe;EAAY;CACxD;AACF;AAEA,SAAS,4BACP,YACA,qBACA,SACA,iBAC0B;CAC1B,MAAM,uBAAuB,QAAQ,wBAAwB,UAAU;CAEvE,IAAI,qBAGF,OAAO;CAGT,MAAM,sBAAsB,QAAQ,uBAAuB,UAAU;CACrE,MAAM,qBAAqB,kBACvB,gBAAgB,sBAAsB,YAAY,CAAC,IACnD,CAAC;CACL,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;CACL;AACF"}
1
+ {"version":3,"file":"ngtsc-compile-plugin.js","names":[],"sources":["../../../src/lib/ngtsc-compile-plugin.ts"],"sourcesContent":["import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport { union } from 'es-toolkit';\nimport * as compilerCli from '@angular/compiler-cli';\nimport type { NgtscProgram } from '@angular/compiler-cli';\nimport type * as ts from 'typescript';\nimport type * as vite from 'vite';\nimport {\n normalizePath,\n preprocessCSS,\n type ModuleNode,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport {\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n findTemplateOwnerModules,\n getModulesForChangedFile,\n handleDirectComponentStyleHmr,\n isModuleForChangedResource,\n markModuleSelfAccepting,\n} from './component-styles-plugin.js';\nimport { isComponentStyleSheet } from './encapsulation-plugin.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithModuleResolution,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport { createHotUpdateBatcher } from './hot-update-batch.js';\nimport type { EmitFileResult } from './models.js';\nimport type {\n FileReplacementSSR,\n FileReplacementWith,\n} from './plugins/file-replacements.plugin.js';\nimport {\n describeStylesheetContent,\n injectViteIgnoreForHmrMetadata,\n} from './utils/compilation-shared.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport {\n activateDeferredDebug,\n debugCompiler,\n debugCompilerV,\n debugEmit,\n debugEmitV,\n debugHmr,\n debugHmrV,\n debugStyles,\n} from './utils/debug.js';\nimport {\n createJitResourceTransformer,\n SourceFileCache,\n} from './utils/devkit.js';\nimport { toJitInlineStyleId } from './utils/jit-inline-styles.js';\nimport {\n createDepOptimizerConfig,\n EXCLUDED_TS_EXT_REGEX,\n TS_EXT_REGEX,\n} from './utils/plugin-config.js';\nimport { getJsTransformConfigKey } from './utils/rolldown.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport type { SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\nimport { toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\nexport interface FileMetadataResult {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n}\n\nexport function evictDeletedFileMetadata(\n file: string,\n {\n classNamesMap,\n fileTransformMap,\n }: {\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n classNamesMap.delete(normalizedFile);\n fileTransformMap.delete(normalizedFile);\n}\n\nexport function createFsWatcherCacheInvalidator(\n invalidateFsCaches: () => void,\n invalidateTsconfigCaches: () => void,\n performCompilation: () => Promise<void>,\n): () => Promise<void> {\n return async (): Promise<void> => {\n invalidateFsCaches();\n invalidateTsconfigCaches();\n await performCompilation();\n };\n}\n\n/**\n * Compiles Angular TypeScript sources using `@angular/compiler-cli` (`NgtscProgram`).\n */\nexport function ngtscCompilePlugin(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): Plugin {\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'ngtsc',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n\n let cachedBuilder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram\n | undefined;\n let nextProgram: NgtscProgram | undefined;\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n\n function invalidateFsCaches(): void {\n ctx.tsconfigResolver.invalidateIncludeCache();\n }\n\n function invalidateTsconfigCaches(): void {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const tsSourceFileCache = new Map<string, ts.SourceFile>();\n\n function invalidateSourceFiles(files: Set<string>): void {\n for (const file of files) {\n tsSourceFileCache.delete(normalizePath(file));\n }\n sourceFileCache.invalidate(files);\n }\n\n const { jit, isTest } = ctx.options;\n let viteServer: ViteDevServer | undefined;\n\n const styleUrlsResolver = new StyleUrlsResolver();\n const templateUrlsResolver = new TemplateUrlsResolver();\n let outputFile: ((file: string) => void) | undefined;\n const outputFiles = new Map<string, EmitFileResult>();\n\n // Vite resolves module ids through symlinks, while the TypeScript program\n // names files by the tsconfig path as given. Both sides go through\n // `toRealPath` so `/var/...` and `/private/var/...` (macOS) or a symlinked\n // workspace name the same file.\n const realPaths = new Map<string, string>();\n const toRealPath = (file: string): string => {\n const normalizedFile = normalizePath(file);\n const cachedPath = realPaths.get(normalizedFile);\n if (cachedPath !== undefined) {\n return cachedPath;\n }\n\n let realPath: string;\n try {\n realPath = normalizePath(realpathSync(normalizedFile));\n } catch {\n // Not on disk (yet): leave it as is and don't cache it.\n return normalizedFile;\n }\n realPaths.set(normalizedFile, realPath);\n return realPath;\n };\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n\n if (!normalizedFile.startsWith('/@fs/')) {\n return toRealPath(normalizedFile);\n }\n\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n\n return toRealPath(fsPath);\n };\n\n const describeEmitMarkers = (content: string) => ({\n contentLength: content.length,\n hasCmp: content.includes('ɵcmp'),\n hasFac: content.includes('ɵfac'),\n hasProv: content.includes('ɵprov'),\n hasDecorate: content.includes('__decorate'),\n hasMetadata: content.includes('__metadata'),\n });\n\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n const hadCachedEmit = outputFiles.has(normalizedFile);\n outputFile?.(normalizedFile);\n const emittedResult = outputFiles.get(normalizedFile);\n debugEmitV('fileEmitter lookup', {\n requestFile: file,\n normalizedFile,\n hadCachedEmit,\n hasOutputFileHook: !!outputFile,\n emitted: !!emittedResult,\n knownOutputCount: outputFiles.size,\n contentLength: emittedResult?.content?.length ?? 0,\n errorCount: emittedResult?.errors?.length ?? 0,\n warningCount: emittedResult?.warnings?.length ?? 0,\n });\n return emittedResult;\n };\n\n ctx.hmr.setFileEmitter((file) => fileEmitter(file));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizeEmitterLookupId(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n let initialCompilation = false;\n let activeBuilds = 0;\n let closeRequested = false;\n const declarationFiles: DeclarationFile[] = [];\n const fileTransformMap = new Map<string, string>();\n let styleTransform: (\n code: string,\n filename: string,\n ) => Promise<vite.PreprocessCSSResult>;\n let pendingCompilation: Promise<void> | null = null;\n let compilationLock = Promise.resolve();\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function releaseCompilation(): void {\n cachedBuilder = undefined;\n nextProgram = undefined;\n cachedHost = undefined;\n cachedHostKey = undefined;\n outputFile = undefined;\n outputFiles.clear();\n fileTransformMap.clear();\n tsSourceFileCache.clear();\n sourceFileCache.clear();\n sourceFileCache.modifiedFiles.clear();\n sourceFileCache.babelFileCache?.clear();\n sourceFileCache.typeScriptFileCache?.clear();\n sourceFileCache.referencedFiles = undefined;\n ctx.tsconfigResolver.invalidateAll();\n releaseCssPreprocessorWorkers();\n ctx.styles.clear();\n }\n\n async function closeCompilation(): Promise<void> {\n closeRequested = false;\n hotUpdates.close();\n await compilationLock;\n declarationFiles.forEach(\n ({ declarationFileDir, declarationPath, data }) => {\n mkdirSync(declarationFileDir, { recursive: true });\n writeFileSync(declarationPath, data, 'utf-8');\n },\n );\n declarationFiles.length = 0;\n releaseCompilation();\n }\n\n function normalizeSourceMapSources(map: string, id: string): string {\n const sourceMap = JSON.parse(map) as {\n sources?: string[];\n sourceRoot?: string;\n };\n const sourceDirectory = dirname(id);\n const sourceRoot = sourceMap.sourceRoot ?? '';\n sourceMap.sources = sourceMap.sources?.map((source) => {\n if (isAbsolute(source) || /^[a-z][a-z\\d+.-]*:/i.test(source)) {\n return normalizePath(source);\n }\n return normalizePath(resolve(sourceDirectory, sourceRoot, source));\n });\n delete sourceMap.sourceRoot;\n return JSON.stringify(sourceMap);\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await _doPerformCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n /**\n * This method shares mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps\n * this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n invalidateSourceFiles(modifiedFiles);\n\n if (ids?.length) {\n for (const id of ids) {\n fileTransformMap.delete(id);\n }\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n\n // Clone options before mutation (preserve cache purity)\n const tsCompilerOptions = { ...cached.options };\n let rootNames = [...cached.rootNames];\n\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (NgtscProgram path)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = ctx.options.fileReplacements.map((rp) =>\n join(\n ctx.options.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = [\n ...new Set(\n union(\n union(rootNames, ctx.tsconfigResolver.ensureIncludeCache()),\n replacements,\n ).map(toRealPath),\n ),\n ];\n const hostKey = JSON.stringify(tsCompilerOptions);\n let host: ts.CompilerHost;\n\n if (cachedHost && cachedHostKey === hostKey) {\n host = cachedHost;\n } else {\n host = ts.createIncrementalCompilerHost(tsCompilerOptions, {\n ...ts.sys,\n readFile(path: string, encoding?: string) {\n if (fileTransformMap.has(path)) {\n return fileTransformMap.get(path);\n }\n\n const file = ts.sys.readFile.call(null, path, encoding);\n\n if (file) {\n fileTransformMap.set(path, file);\n }\n\n return file;\n },\n });\n augmentHostWithModuleResolution(host, tsCompilerOptions);\n cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (ctx.watchMode) {\n augmentHostWithCaching(host, tsSourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n const stylesheetRegistry = ctx.styles.resetRegistry(externalizeStyles);\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: ctx.options.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: ctx.stylePreprocessor,\n logger: ctx.resolvedConfig?.logger,\n isBuild: ctx.resolvedConfig?.command === 'build',\n });\n }\n\n /**\n * Creates a new NgtscProgram to analyze/re-analyze\n * the source files and create a file emitter.\n * This is shared between an initial build and a hot update.\n */\n let typeScriptProgram: ts.Program;\n let angularCompiler: NgtscProgram['compiler'] | undefined;\n // Declaration changes can invalidate diagnostics in unchanged consumers.\n let builder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n const oldBuilder = ids?.some((id) => EXCLUDED_TS_EXT_REGEX.test(id))\n ? undefined\n : (cachedBuilder ?? ts.readBuilderProgram(tsCompilerOptions, host));\n\n if (!jit) {\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(\n rootNames,\n tsCompilerOptions,\n host,\n nextProgram,\n );\n angularCompiler = angularProgram.compiler;\n typeScriptProgram = angularProgram.compiler.getCurrentProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n nextProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n rootNames,\n tsCompilerOptions,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n typeScriptProgram = builder.getProgram();\n }\n\n if (!ctx.watchMode) {\n // When not in watch mode, the startup cost of the incremental analysis can be avoided by\n // using an abstract builder that only wraps a TypeScript program.\n builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);\n }\n cachedBuilder = builder;\n\n if (angularCompiler) {\n await angularCompiler.analyzeAsync();\n\n if (!ctx.options.disableTypeChecking) {\n // TypeScript builds the program diagnostics lazily and records why each\n // file is in the program as an index into `referencedFiles`, which\n // includes the shim references Angular tags onto every source file.\n // `prepareEmit()` below removes those tags, so a diagnostic that\n // explains a file (e.g. TS6059 for a file outside `rootDir`) would\n // otherwise throw while it is built for the first file's diagnostics.\n typeScriptProgram.getOptionsDiagnostics();\n }\n }\n\n const beforeTransformers = jit\n ? [\n compilerCli.constructorParametersDownlevelTransform(\n builder.getProgram(),\n ),\n createJitResourceTransformer(() =>\n builder.getProgram().getTypeChecker(),\n ),\n ]\n : [];\n\n const transformers = mergeTransformers(\n { before: beforeTransformers },\n jit ? {} : angularCompiler!.prepareEmit().transformers,\n );\n\n const fileMetadata = getFileMetadata(\n builder,\n angularCompiler,\n ctx.options.liveReload,\n ctx.options.disableTypeChecking,\n ctx.hmr.classNames,\n );\n\n const writeFileCallback: ts.WriteFileCallback = (\n _filename,\n content,\n _a,\n _b,\n sourceFiles,\n ) => {\n if (!sourceFiles?.length) {\n return;\n }\n\n const filename = normalizePath(sourceFiles[0].fileName);\n\n // Skip declaration outputs and declaration source files.\n if (\n filename.includes('ngtypecheck.ts') ||\n filename.includes('.d.') ||\n _filename.endsWith('.d.ts') ||\n _filename.endsWith('.d.mts') ||\n _filename.endsWith('.d.cts')\n ) {\n return;\n }\n\n // TS emits the .js.map file separately — attach it to the entry for\n // the same source file so the transform hook can return the map and\n // coverage tools can chain maps back to the original TS. The .map can\n // arrive before or after the .js, so upsert in either order. Match\n // only `.js.map` (not `.d.ts.map`) so a future `declarationMap: true`\n // doesn't clobber the JS source map with the declaration map.\n if (/\\.[cm]?js\\.map$/.test(_filename)) {\n const existing = outputFiles.get(filename);\n outputFiles.set(filename, {\n ...(existing ?? { dependencies: [] }),\n map: content,\n });\n return;\n }\n\n const metadata = ctx.watchMode ? fileMetadata(filename) : {};\n const existing = outputFiles.get(filename);\n\n outputFiles.set(filename, {\n ...(existing ?? {}),\n content,\n dependencies: [],\n errors: metadata.errors,\n warnings: metadata.warnings,\n hmrUpdateCode: metadata.hmrUpdateCode,\n hmrEligible: metadata.hmrEligible,\n });\n debugEmitV('registered ngtsc output', {\n filename,\n ...describeEmitMarkers(content),\n errorCount: metadata.errors?.length ?? 0,\n warningCount: metadata.warnings?.length ?? 0,\n hmrEligible: !!metadata.hmrEligible,\n knownOutputCount: outputFiles.size,\n });\n };\n\n const writeOutputFile = (id: string): void => {\n const sourceFile = builder.getSourceFile(toRealPath(id));\n if (!sourceFile) {\n return;\n }\n\n let content = '';\n let map: string | undefined;\n let mapFilename: string | undefined;\n builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\n }\n\n if (/\\.[cm]?js\\.map$/.test(filename)) {\n map = data;\n mapFilename = filename;\n }\n\n if (\n !ctx.watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const root = toRealPath(config.root);\n const declarationPath = resolve(\n root,\n config.build.outDir,\n relative(root, filename),\n ).replace('/src/', '/');\n\n const declarationFileDir = declarationPath\n .replace(basename(filename), '')\n .replace('/src/', '/');\n\n declarationFiles.push({\n declarationFileDir,\n declarationPath,\n data,\n });\n }\n },\n undefined /* cancellationToken */,\n undefined /* emitOnlyDtsFiles */,\n transformers,\n );\n\n writeFileCallback(id, content, false, undefined, [sourceFile]);\n if (map !== undefined && mapFilename !== undefined) {\n // Use the filename TypeScript emitted (handles `.cts`/`.mts` as well\n // as `.ts`) instead of regex-replacing the source `.ts` extension.\n writeFileCallback(mapFilename, map, false, undefined, [sourceFile]);\n }\n\n if (angularCompiler) {\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n };\n\n if (ctx.watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else if (isTest) {\n /**\n * Only block the server from starting up\n * during testing.\n */\n while (\n (\n builder as ts.EmitAndSemanticDiagnosticsBuilderProgram\n ).emitNextAffectedFile(\n writeFileCallback,\n undefined,\n undefined,\n transformers,\n )\n ) {\n /* empty */\n }\n }\n }\n\n if (!isTest) {\n /**\n * Perf: Output files on demand so the dev server\n * isn't blocked when emitting files.\n */\n outputFile = writeOutputFile;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n api: compilerApi,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n // Do a preliminary resolution for dep optimizer (before configResolved)\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n\n const esbuild = config.esbuild ?? false;\n const oxc = config.oxc ?? false;\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n ...depOptimizer,\n };\n },\n configResolved(config) {\n ctx.setResolvedConfig(config);\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n // Add/unlink changes the TypeScript program shape, not just file\n // contents, so we need to invalidate both include discovery and the\n // cached tsconfig root names before recompiling.\n const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(\n invalidateFsCaches,\n invalidateTsconfigCaches,\n () => performCompilation(ctx.resolvedConfig!),\n );\n server.watcher.on('add', (file) => {\n if (EXCLUDED_TS_EXT_REGEX.test(file)) {\n invalidateSourceFiles(new Set([normalizePath(file)]));\n }\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('unlink', (file) => {\n const id = normalizePath(file);\n outputFiles.delete(id);\n tsSourceFileCache.delete(id);\n sourceFileCache.invalidate(new Set([id]));\n evictDeletedFileMetadata(file, {\n classNamesMap: ctx.hmr.classNames,\n fileTransformMap,\n });\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n activeBuilds++;\n // Vite keys its CSS preprocessor worker cache by the top-level resolved\n // config object. Passing `this.environment.config` misses that cache\n // and falls back to a worker Vite never closes, which keeps Vitest\n // from exiting after AOT tests with `.scss` styleUrls. (#2556)\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, ctx.resolvedConfig!);\n }\n\n // Browser mode also creates a server that may never transform TypeScript.\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as ResolvedConfig | undefined) ??\n ctx.resolvedConfig!,\n );\n await pendingCompilation;\n pendingCompilation = null;\n\n initialCompilation = true;\n }\n },\n async buildEnd(): Promise<void> {\n // Environments (e.g. client and ssr) build in parallel and share this\n // plugin's compilation state, so only reset after the last one ends.\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (activeBuilds > 0) return;\n if (closeRequested) {\n await closeCompilation();\n return;\n }\n if (!ctx.watchMode) releaseCompilation();\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n if (EXCLUDED_TS_EXT_REGEX.test(fileId)) {\n // Declaration dependencies have no runtime modules for Vite to invalidate.\n hmrCtx.server.moduleGraph.invalidateAll();\n hmrCtx.server.ws.send({ type: 'full-reload', triggeredBy: fileId });\n return [];\n }\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: hmrCtx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n className: ctx.hmr.classNames.get(fileId),\n updateCode: result?.hmrUpdateCode\n ? describeStylesheetContent(result.hmrUpdateCode)\n : undefined,\n errors: result?.errors?.length ?? 0,\n warnings: result?.warnings?.length ?? 0,\n hint: result?.hmrEligible\n ? 'A TS-side component change, including inline template edits, produced an Angular HMR payload.'\n : 'No Angular HMR payload was emitted for this TS change; the change may not affect component template state.',\n });\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n result?.hmrEligible &&\n ctx.hmr.classNames.get(fileId)\n ) {\n const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);\n\n debugHmr('sending component update', { relativeFileId });\n debugHmrV('ts hmr component update payload', {\n file: hmrCtx.file,\n fileId,\n relativeFileId,\n className: ctx.hmr.classNames.get(fileId),\n });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('resource file changed', { file: hmrCtx.file });\n fileTransformMap.delete(hmrCtx.file.split('?')[0]);\n // Angular component resources frequently enter HMR with incomplete\n // watcher context. In practice `ctx.modules` may only contain the\n // source file, only the `?direct` module, or nothing at all after a\n // TS-driven component refresh. Resolve the full live module set from\n // Vite's module graph and our stylesheet registry before deciding how\n // to hot update the resource.\n const stylesheetRegistry = ctx.styles.registry;\n const fileModules = await getModulesForChangedFile(\n hmrCtx.server,\n hmrCtx.file,\n hmrCtx.modules,\n stylesheetRegistry,\n );\n /**\n * Check to see if this was a direct request\n * for an external resource (styles, html).\n */\n const isDirect = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?direct') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: hmrCtx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (ctx.shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: hmrCtx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n return handleDirectComponentStyleHmr({\n server: hmrCtx.server,\n file: hmrCtx.file,\n directModule: isDirect,\n fileModules,\n stylesheetRegistry,\n stylePreprocessor: ctx.stylePreprocessor,\n });\n }\n }\n return fileModules;\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n /\\.(html|htm)$/.test(hmrCtx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(\n hmrCtx.server,\n hmrCtx.file,\n );\n debugHmrV('template owner lookup', {\n file: hmrCtx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n hint:\n ownerModules.length > 0\n ? 'The external template has candidate TS owner modules that can be recompiled for HMR.'\n : 'No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path.',\n });\n if (ownerModules.length > 0) {\n const ownerIds = ownerModules\n .map((mod) => mod.id)\n .filter(Boolean) as string[];\n\n ownerModules.forEach((mod) =>\n hmrCtx.server.moduleGraph.invalidateModule(mod),\n );\n\n await hotUpdates.schedule(hmrCtx.file, ownerIds);\n\n const updates = ownerIds.filter((id) => ctx.hmr.classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: hmrCtx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: ctx.hmr.classNames.get(id),\n })),\n hint:\n updates.length > 0\n ? 'External template recompilation produced Angular component update targets.'\n : 'External template recompilation completed, but no Angular component update targets were surfaced.',\n });\n if (updates.length > 0) {\n debugHmr('template owner module invalidation', {\n file: hmrCtx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return ownerModules.map((mod) => markModuleSelfAccepting(mod));\n }\n }\n }\n\n const importers = fileModules.flatMap((mod) => [...mod.importers]);\n if (importers.length === 0) return [];\n\n importers.forEach((imp) =>\n hmrCtx.server.moduleGraph.invalidateModule(imp),\n );\n await hotUpdates.schedule(\n hmrCtx.file,\n importers.map((imp) => imp.id as string),\n );\n\n // Classify after compiling: the compile is what records component\n // class names, and the map may have been cleared since the last one.\n const mods: ModuleNode[] = [];\n const updates: string[] = [];\n importers.forEach((imp) => {\n if (\n ctx.shouldExternalizeStyles() &&\n imp.id &&\n ctx.hmr.classNames.get(imp.id)\n ) {\n updates.push(imp.id);\n } else {\n mods.push(imp);\n }\n });\n debugHmrV('resource importer analysis', {\n file: hmrCtx.file,\n fileModuleCount: fileModules.length,\n importerCount: importers.length,\n updates,\n mods: mods.map((mod) => mod.id),\n });\n\n if (updates.length > 0) {\n debugHmr('resource importer component updates', {\n file: hmrCtx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return fileModules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n\n return mods;\n }\n\n // clear HMR updates with a full reload\n debugHmr('full reload — unrecognized file type', { file: hmrCtx.file });\n ctx.hmr.clear();\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Encapsulation of component stylesheets is handled by the\n // separate '@analogjs/vite-plugin-angular:encapsulation' plugin\n // with enforce: 'post'. This ensures @tailwindcss/vite (enforce:\n // 'pre') fully resolves @apply directives — including those inside\n // :host {} — before Angular's ShadowCss rewrites selectors. (#2293)\n\n if (id.includes('.ts?')) {\n // Strip the query string off the ID\n // in case of a dynamically loaded file\n id = id.replace(/\\?(.*)/, '');\n }\n\n fileTransformMap.set(id, code);\n\n /**\n * Re-analyze on each transform\n * for test(Vitest)\n */\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n // Do full initial compilation\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n );\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n [id],\n );\n }\n }\n }\n\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n // Resource URLs are only consumed for watch-file registration and\n // JIT rewrites, so skip resolution entirely in prod AOT builds.\n const resolveResourceUrls = hasComponent && (ctx.watchMode || jit);\n const templateUrls = resolveResourceUrls\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = resolveResourceUrls\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (resolveResourceUrls && ctx.watchMode) {\n for (const urlSet of [...templateUrls, ...styleUrls]) {\n // `urlSet` is a string where a relative path is joined with an\n // absolute path using the `|` symbol.\n // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.\n const [, absoluteFileUrl] = urlSet.split('|');\n this.addWatchFile(absoluteFileUrl);\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilerV('transform skip (file not emitted by Angular)', {\n id,\n });\n // File not in the Angular program — skip and let other plugins\n // or Vite's built-in transform handle it. Warn if it looks like\n // an Angular file that should have been compiled.\n const isAngular =\n !id.includes('@ng/component') &&\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n debugEmit('transform emit miss', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n knownOutputCount: outputFiles.size,\n hasOutputFileHook: !!outputFile,\n isAngular,\n });\n\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n debugEmitV('transform emit hit', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n ...describeEmitMarkers(data),\n errorCount: typescriptResult.errors?.length ?? 0,\n warningCount: typescriptResult.warnings?.length ?? 0,\n });\n\n if (jit && data.includes('angular:jit:')) {\n // The emitted id carries the base64 of the entire stylesheet,\n // and the bundler derives chunk names from it — hash it so a\n // large inline style can't produce an over-long filename (#2459).\n data = data.replace(\n /angular:jit:style:inline;([A-Za-z0-9+/=]*)/g,\n (_match, encodedStyles) =>\n toJitInlineStyleId(encodedStyles, isTest),\n );\n\n // Templates use virtual ids (no extension) so Vite's asset/CSS\n // plugins don't interfere. (#2263)\n templateUrls.forEach((templateUrlSet) => {\n const [templateFile, resolvedTemplateUrl] =\n templateUrlSet.split('|');\n data = data.replace(\n `angular:jit:template:file;${templateFile}`,\n toVirtualRawId(resolvedTemplateUrl),\n );\n });\n\n // External styles use native ?inline imports. We mark each\n // path as safe in Vite's safeModulePaths so the Denied ID\n // security check passes, and Vite's CSS pipeline handles\n // preprocessing, test.css, and browser/node differences\n // natively. (#2263, #2310)\n styleUrls.forEach((styleUrlSet) => {\n const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');\n markStylePathSafe(ctx.resolvedConfig, resolvedStyleUrl);\n data = data.replace(\n `angular:jit:style:file;${styleFile}`,\n resolvedStyleUrl + '?inline',\n );\n });\n }\n\n // Angular's HMR initializer emits dynamic import() calls that Vite's\n // import-analysis plugin cannot statically analyze, producing SSR\n // warnings. The Angular compiler's IR includes a @vite-ignore comment\n // but it can be lost during TypeScript emit. Re-inject it here so the\n // warning is suppressed regardless of the compilation path used.\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n debugHmrV('vite-ignore injection', {\n id,\n dataLength: data.length,\n hasMetaUrl,\n });\n if (hasMetaUrl) {\n const patched = injectViteIgnoreForHmrMetadata(data);\n if (patched !== data && !patched.includes('@vite-ignore')) {\n debugHmrV('vite-ignore regex fallback', { id });\n }\n data = patched;\n }\n }\n if (typescriptResult.map) {\n // TS emits `//# sourceMappingURL=foo.js.map` at the end of the\n // .js content, but the .map file isn't served by Vite — we\n // return the map object directly. Strip the stale reference so\n // downstream tools don't see two sourceMappingURL comments.\n data = data.replace(/\\s*\\/\\/# sourceMappingURL=[^\\r\\n]*\\s*$/, '');\n }\n\n return {\n code: data,\n map: typescriptResult.map\n ? normalizeSourceMapSources(typescriptResult.map, id)\n : null,\n };\n },\n },\n async closeBundle(): Promise<void> {\n closeRequested = true;\n if (activeBuilds === 0) {\n await closeCompilation();\n }\n },\n };\n}\n\n/**\n * @internal\n */\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n classNamesMap: Map<string, string> = new Map(),\n): (file: string) => FileMetadataResult {\n const ts = require('typescript') as typeof import('typescript');\n return (file: string): FileMetadataResult => {\n const sourceFile = program.getSourceFile(file);\n if (!sourceFile) {\n return {};\n }\n\n const diagnostics = getDiagnosticsForSourceFile(\n sourceFile,\n !!disableTypeChecking,\n program,\n angularCompiler,\n );\n\n const errors = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Error)\n .map((d) =>\n typeof d.messageText === 'object'\n ? d.messageText.messageText\n : d.messageText,\n );\n\n const warnings = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Warning)\n .map((d) => d.messageText);\n\n let hmrUpdateCode: string | null | undefined = undefined;\n\n let hmrEligible = false;\n if (hmrEnabled) {\n for (const node of sourceFile.statements) {\n if (ts.isClassDeclaration(node) && node.name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);\n if (hmrUpdateCode) {\n const className = node.name.getText();\n classNamesMap.set(file, className);\n hmrEligible = true;\n debugHmr('NgtscProgram emitHmrUpdateModule', { file, className });\n }\n }\n }\n }\n\n return { errors, warnings, hmrUpdateCode, hmrEligible };\n };\n}\n\nfunction getDiagnosticsForSourceFile(\n sourceFile: ts.SourceFile,\n disableTypeChecking: boolean,\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n): readonly ts.Diagnostic[] {\n const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n if (disableTypeChecking) {\n // Syntax errors are cheap to compute and the app will not run if there are any\n // So always show these types of errors regardless if type checking is disabled\n return syntacticDiagnostics;\n }\n\n const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);\n const angularDiagnostics = angularCompiler\n ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)\n : [];\n return [\n ...syntacticDiagnostics,\n ...semanticDiagnostics,\n ...angularDiagnostics,\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAM,UAAU,cAAc,YAAY,GAAG;AAe7C,SAAgB,yBACd,MACA,EACE,eACA,oBAKI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,GAAG,CAAC,CAAC,EAAE;CACvD,cAAc,OAAO,cAAc;CACnC,iBAAiB,OAAO,cAAc;AACxC;AAEA,SAAgB,gCACd,oBACA,0BACA,oBACqB;CACrB,OAAO,YAA2B;EAChC,mBAAmB;EACnB,yBAAyB;EACzB,MAAM,mBAAmB;CAC3B;AACF;;;;AAKA,SAAgB,mBACd,cACQ;CACR,MAAM,MAAM,sBAAsB,YAAY,IAC1C,eACA,0BAA0B;EACxB,GAAG;EACH,oBAAoB;CACtB,CAAC;CAEL,MAAM,KAAK,QAAQ,YAAY;CAE/B,IAAI;CAIJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,SAAS,qBAA2B;EAClC,IAAI,iBAAiB,uBAAuB;CAC9C;CAEA,SAAS,2BAAiC;EACxC,IAAI,iBAAiB,yBAAyB;EAC9C,aAAa,KAAA;EACb,gBAAgB,KAAA;CAClB;CAEA,MAAM,kBAAuC,IAAI,gBAAgB;CACjE,MAAM,oCAAoB,IAAI,IAA2B;CAEzD,SAAS,sBAAsB,OAA0B;EACvD,KAAK,MAAM,QAAQ,OACjB,kBAAkB,OAAO,cAAc,IAAI,CAAC;EAE9C,gBAAgB,WAAW,KAAK;CAClC;CAEA,MAAM,EAAE,KAAK,WAAW,IAAI;CAC5B,IAAI;CAEJ,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ACF;;EAIJ,OAAO;GAAE;GAAQ;GAAU;GAAe;EAAY;CACxD;AACF;AAEA,SAAS,4BACP,YACA,qBACA,SACA,iBAC0B;CAC1B,MAAM,uBAAuB,QAAQ,wBAAwB,UAAU;CAEvE,IAAI,qBAGF,OAAO;CAGT,MAAM,sBAAsB,QAAQ,uBAAuB,UAAU;CACrE,MAAM,qBAAqB,kBACvB,gBAAgB,sBAAsB,YAAY,CAAC,IACnD,CAAC;CACL,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;CACL;AACF"}
@@ -1,3 +1,4 @@
1
+ import { fromWasmPath } from "./ngp-host-fs.js";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { createRequire } from "node:module";
3
4
  import { dirname, relative, resolve } from "node:path";
@@ -128,10 +129,11 @@ function templateLocation(range, lines, position) {
128
129
  if (!tcbFunction || !span) return null;
129
130
  const id = /(tcb\d+)$/.exec(tcbFunction.id.name)[1];
130
131
  const source = range.templateSources[id];
131
- const file = source?.templateFile ?? range.filePath;
132
+ const templateFile = source?.templateFile ? fromWasmPath(source.templateFile) : void 0;
133
+ const file = templateFile ?? range.filePath;
132
134
  let content = range.sourceCode;
133
- if (source?.templateFile) try {
134
- content = readFileSync(source.templateFile, "utf-8");
135
+ if (templateFile) try {
136
+ content = readFileSync(templateFile, "utf-8");
135
137
  } catch {
136
138
  return null;
137
139
  }
@@ -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]);\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,MAAM,KAAK,OAAO,KAAK;EAC3C;CACF;CACA,IAAI,CAAC,QAAQ,OAAO,KAAK,SAAS,UAAU;CAC5C,MAAM,IAAI;CACV,KAA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AgB,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"}
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';\nimport { fromWasmPath } from './ngp-host-fs.js';\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 templateFile = source?.templateFile\n ? fromWasmPath(source.templateFile)\n : undefined;\n const file = templateFile ?? range.filePath;\n let content = range.sourceCode;\n if (templateFile) {\n try {\n content = readFileSync(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":";;;;;;;;;;AAwCA,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,MAAM,KAAK,OAAO,KAAK;EAC3C;C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AAK,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,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"}
@@ -21,12 +21,23 @@ export interface NgpHostFs {
21
21
  */
22
22
  export declare function canonicalPath(path: string): string;
23
23
  /**
24
+ * Converts a host path to the POSIX-absolute form NGP's WebAssembly backend
25
+ * expects (`D:\a\b` → `/D:/a/b`). POSIX and relative paths are unchanged.
26
+ */
27
+ export declare function toWasmPath(path: string): string;
28
+ /**
29
+ * Converts a path returned by NGP's WebAssembly backend back to a normalized
30
+ * host path (`/D:/a/b` → `D:/a/b`).
31
+ */
32
+ export declare function fromWasmPath(path: string): string;
33
+ /**
24
34
  * The disk, with each module of a source format served as a TypeScript file
25
35
  * 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.
36
+ * import of `./x.tsrx` resolves to its TypeScript. Also translates Windows
37
+ * drive paths at the WebAssembly boundary.
27
38
  *
28
39
  * @param programCode The TypeScript of a module's program file, by the file's
29
40
  * normalized, canonical path.
30
41
  */
31
- export declare function createNgpHostFs(programCode: (path: string) => string | undefined): NgpHostFs;
42
+ export declare function createNgpHostFs(programCode?: (path: string) => string | undefined): NgpHostFs;
32
43
  export {};