@analogjs/vite-plugin-angular 3.0.0-alpha.90 → 3.0.0-alpha.91
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.
- package/package.json +1 -1
- package/src/lib/angular-vite-plugin.js +1 -0
- package/src/lib/angular-vite-plugin.js.map +1 -1
- package/src/lib/compilation-api/compilation-api-plugin.js +1 -0
- package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
- package/src/lib/fast-compile-plugin.js +1 -0
- package/src/lib/fast-compile-plugin.js.map +1 -1
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"angular-vite-plugin.js","names":[],"sources":["../../../src/lib/angular-vite-plugin.ts"],"sourcesContent":["import { NgtscProgram } from '@angular/compiler-cli';\nimport { union } from 'es-toolkit';\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { createRequire } from 'node:module';\nimport * as ts from 'typescript';\nimport {\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';\nimport { jitPlugin } from './angular-jit-plugin.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from './compiler-plugin.js';\nimport {\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport type {\n StylePreprocessor,\n StylesheetDependency,\n} from './style-preprocessor.js';\nimport {\n discoverAnalogIntegrations,\n type StylesheetRegistryConfigurator,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nimport { fastCompilePlugin } from './fast-compile-plugin.js';\nimport { ANGULAR_DECORATOR_CALL_RE } from './compiler/index.js';\nimport {\n encapsulationPlugin,\n isComponentStyleSheet,\n getComponentStyleSheetMeta,\n} from './encapsulation-plugin.js';\nimport { virtualModulesPlugin } from './virtual-modules-plugin.js';\nimport { angularVitestPlugins } from './angular-vitest-plugin.js';\nimport {\n createJitResourceTransformer,\n SourceFileCache,\n angularFullVersion,\n} from './utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompiler,\n debugCompilerV,\n debugEmit,\n debugEmitV,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from './utils/debug.js';\nimport {\n createTsConfigGetter,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { toJitInlineStyleId } from './utils/jit-inline-styles.js';\nimport { TsconfigResolver } from './utils/tsconfig-resolver.js';\nimport { cssExtensionStyleResolverPlugin } from './utils/css-extension-resolver.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\nimport {\n toVirtualRawId,\n toVirtualStyleId,\n VIRTUAL_RAW_PREFIX,\n} from './utils/virtual-ids.js';\nimport { type SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\n\nconst require = createRequire(import.meta.url);\n\nimport { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';\nimport { liveReloadPlugin } from './live-reload-plugin.js';\nimport { EmitFileResult } from './models.js';\nimport { nxFolderPlugin } from './nx-folder-plugin.js';\nimport {\n FileReplacement,\n FileReplacementSSR,\n FileReplacementWith,\n replaceFiles,\n} from './plugins/file-replacements.plugin.js';\nimport { routerPlugin } from './router-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\n\nexport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n toAngularCompilationFileReplacements,\n mapTemplateUpdatesToFiles,\n refreshStylesheetRegistryForFile,\n describeStylesheetContent,\n isTestWatchMode,\n} from './utils/compilation-shared.js';\nimport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n describeStylesheetContent,\n refreshStylesheetRegistryForFile,\n isTestWatchMode,\n} from './utils/compilation-shared.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\n\nexport interface PluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n supportedBrowsers?: string[];\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n /**\n * Enables Analog's Angular live-reload/HMR pipeline during development/watch mode.\n *\n * This is separate from Vite's `server.hmr` option, which configures the\n * HMR client transport.\n *\n * Defaults to `true` for watch mode. Set to `false` to disable Angular\n * reload updates while keeping other stylesheet externalization behavior\n * available when needed.\n */\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n fileReplacements?: FileReplacement[];\n /**\n * Opt into the fast compile path. Skips Angular's template type-checking\n * and routes compilation through an internal single-pass transform.\n * Defaults to `false`.\n */\n fastCompile?: boolean;\n /**\n * Compilation output mode used when `fastCompile` is enabled.\n * - `'full'` (default): Emit final Ivy definitions for application builds.\n * - `'partial'`: Emit partial declarations for library publishing.\n */\n fastCompileMode?: 'full' | 'partial';\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:hmr']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n}\n\nconst classNames = new Map();\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\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\nexport function angular(options?: PluginOptions): Plugin[] {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n const liveReload = options?.liveReload ?? true;\n // Set on each compilation from the Vite plugins' `analog.setup()` hooks.\n let externalizeStylesRequested = false;\n let configureStylesheetRegistry: StylesheetRegistryConfigurator | undefined;\n let transformFilter: TransformFilter | undefined;\n\n /**\n * Normalize plugin options so defaults\n * are used for values not provided.\n */\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot:\n options?.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n liveReload,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n fastCompile: options?.fastCompile ?? false,\n fastCompileMode: options?.fastCompileMode ?? 'full',\n // Set on each compilation from preprocessors registered by Vite plugins\n // through `analog.setup()`.\n stylePreprocessor: undefined as StylePreprocessor | undefined,\n };\n\n let resolvedConfig: ResolvedConfig;\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n\n const ts = require('typescript');\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n let nextProgram: NgtscProgram | undefined;\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: pluginOptions.workspaceRoot,\n include: pluginOptions.include,\n liveReload: pluginOptions.liveReload,\n isTest,\n });\n function invalidateFsCaches() {\n tsconfigResolver.invalidateIncludeCache();\n }\n function invalidateTsconfigCaches() {\n tsconfigResolver.invalidateTsconfigCaches();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n let watchMode = false;\n let testWatchMode = isTestWatchMode();\n\n function hasViteHmrTransport(): boolean {\n return resolvedConfig ? resolvedConfig.server.hmr !== false : true;\n }\n\n function shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(\n effectiveWatchMode &&\n pluginOptions.liveReload &&\n hasViteHmrTransport()\n );\n }\n\n /**\n * Determines whether Angular should externalize component styles.\n *\n * When true, Angular emits style references (hash-based IDs) instead of\n * inlining CSS strings. Vite's resolveId → load → transform pipeline\n * then serves these virtual modules, allowing @tailwindcss/vite to\n * process @reference directives.\n *\n * Required for TWO independent use-cases:\n * 1. HMR — Vite needs external modules for hot replacement\n * 2. A Vite plugin asked for it through `analog.setup()` so its styles\n * pass through Vite's CSS pipeline (e.g. @tailwindcss/vite)\n *\n * In production builds (!watchMode), styles are NOT externalized — they\n * are inlined after preprocessCSS runs eagerly in transformStylesheet.\n */\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableLiveReload() || externalizeStylesRequested);\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const tsSourceFileCache = new Map<string, ts.SourceFile>();\n\n function invalidateSourceFiles(files: Set<string>) {\n for (const file of files) {\n tsSourceFileCache.delete(normalizePath(file));\n }\n sourceFileCache.invalidate(files);\n }\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n\n const jit =\n typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;\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 const normalizeEmitterLookupId = (file: string) => {\n const normalizedFile = normalizePath(file);\n\n if (!normalizedFile.startsWith('/@fs/')) {\n return normalizedFile;\n }\n\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n\n return normalizePath(fsPath);\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) => {\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 let initialCompilation = 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;\n let compilationLock = Promise.resolve();\n function angularPlugin(): Plugin {\n let isProd = false;\n\n if (angularFullVersion < 190000 && pluginOptions.liveReload) {\n // Angular < 19 does not support externalRuntimeStyles or _enableHmr.\n debugHmr('hmr disabled: Angular version does not support HMR APIs', {\n angularVersion: angularFullVersion,\n isTest,\n });\n console.warn(\n '[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.',\n angularFullVersion,\n );\n pluginOptions.liveReload = false;\n }\n\n if (isTest) {\n // Test mode: disable HMR because\n // Vitest's runner doesn't support Vite's WebSocket-based HMR.\n // This does NOT block style externalization — shouldExternalizeStyles()\n // independently checks externalizeStylesRequested, so plugin-driven\n // component styles still work in unit tests.\n pluginOptions.liveReload = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n isProd = isProdMode(config.mode);\n\n // Store the config context for later resolution in configResolved\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n // Do a preliminary resolution for esbuild plugin (before configResolved)\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const esbuild = config.esbuild ?? false;\n const oxc = config.oxc ?? false;\n\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(watchMode ? {} : { ngDevMode: 'false' }),\n };\n const useRolldown = isRolldown();\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] =\n {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n // Astro manages the transformer lifecycle externally.\n !isAstroIntegration,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n !isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n // `resolve.conditions` is intentionally not extended with `style`\n // here: that condition is scoped to `.css`-extension requests via\n // `cssExtensionStyleResolverPlugin` (registered in the returned\n // plugin array). Adding `style` globally caused Tailwind v4's JS\n // plugin resolver — which inherits Vite's global conditions — to\n // pick the `style` export of packages like `tailwindcss-primeui`\n // and feed a `.css` file to Node's ESM loader.\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n\n // Suppress noisy sourcemap warnings from Angular packages that ship\n // FESM bundles whose sourcemaps reference source files not included\n // in the npm package.\n if (config.logger?.warnOnce) {\n const originalWarnOnce = config.logger.warnOnce;\n config.logger.warnOnce = (msg, options) => {\n if (\n typeof msg === 'string' &&\n msg.includes('Sourcemap') &&\n msg.includes('node_modules')\n ) {\n return;\n }\n originalWarnOnce(msg, options);\n };\n }\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n\n if (isTest) {\n // set test watch mode\n // - vite override from vitest-angular\n // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)\n // - vite config for test.watch variable\n // - vitest watch mode detected from the command line\n testWatchMode =\n !(config.server.watch === null) ||\n (config as any).test?.watch === true ||\n testWatchMode;\n }\n },\n configureServer(server) {\n viteServer = 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(resolvedConfig),\n );\n server.watcher.on('add', invalidateCompilationOnFsChange);\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: classNames as Map<string, string>,\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 // Defer the first compilation in test mode\n if (!isVitestVscode) {\n pendingCompilation = performCompilation(\n this.environment?.config ?? resolvedConfig,\n );\n await pendingCompilation;\n pendingCompilation = null;\n\n initialCompilation = true;\n }\n },\n buildEnd() {\n if (watchMode) return;\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 tsconfigResolver.invalidateAll();\n releaseCssPreprocessorWorkers();\n },\n async handleHotUpdate(ctx) {\n if (isIgnoredHmrFile(ctx.file)) {\n debugHmr('ignored file change', { file: ctx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n debugHmr('TS file changed', { file: ctx.file, fileId });\n\n pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableLiveReload()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: ctx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n className: 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 shouldEnableLiveReload() &&\n result?.hmrEligible &&\n classNames.get(fileId)\n ) {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), fileId),\n )}@${classNames.get(fileId)}`;\n\n debugHmr('sending component update', { relativeFileId });\n debugHmrV('ts hmr component update payload', {\n file: ctx.file,\n fileId,\n relativeFileId,\n className: classNames.get(fileId),\n });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('resource file changed', { file: ctx.file });\n fileTransformMap.delete(ctx.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 fileModules = await getModulesForChangedFile(\n ctx.server,\n ctx.file,\n ctx.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, ctx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: ctx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: ctx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n const { encapsulation } = getComponentStyleSheetMeta(\n isDirect.id,\n );\n // Angular exposes one component stylesheet through two module\n // shapes:\n // 1. a `?direct&ngcomp=...` CSS module that Vite can patch with\n // a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css`\n // for Angular's runtime consumption\n //\n // Value: invalidate the browser-visible wrapper before patching\n // the direct CSS module so Angular re-evaluates the same live\n // wrapper it is actually using.\n //\n // Guards against: a successful-looking CSS HMR event that\n // leaves the UI stale because the wrapper still holds the\n // pre-edit CSS string.\n const wrapperModules =\n await findComponentStylesheetWrapperModules(\n ctx.server,\n ctx.file,\n isDirect,\n fileModules,\n stylesheetRegistry,\n );\n const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n ctx.file,\n isDirect,\n stylesheetRegistry,\n wrapperModules,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('HMR: component stylesheet changed', {\n file: isDirect.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file: ctx.file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n debugHmrV(\n 'component stylesheet pipeline diagnosis',\n stylesheetDiagnosis,\n );\n\n // Drop Vite's cached direct-module transform before wrapper\n // lookup and patching continue.\n //\n // Value: later fetches and wrapper regeneration see the just\n // edited stylesheet instead of the last served transform result.\n ctx.server.moduleGraph.invalidateModule(isDirect);\n debugHmrV('component stylesheet direct module invalidated', {\n file: ctx.file,\n directModuleId: isDirect.id,\n directModuleUrl: isDirect.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // CSS-only HMR is safe only when the browser-visible wrapper is\n // known and the component is not using Shadow DOM. Vite's CSS\n // patching does not search shadow roots, so Shadow DOM still\n // falls back to reload for correctness.\n const trackedWrapperRequestIds =\n stylesheetDiagnosis.trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 ||\n trackedWrapperRequestIds.length > 0);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n // A live wrapper ModuleNode is ideal because we can\n // invalidate it directly, but it is not strictly required.\n //\n // Value: keep CSS-only HMR working when the browser has\n // already loaded the wrapper URL and the registry can still\n // prove that wrapper identity, even if this HMR pass did not\n // surface a live ModuleNode for it.\n debugHmrV('sending css-update for component stylesheet', {\n file: ctx.file,\n path: isDirect.url,\n acceptedPath: isDirect.file,\n wrapperCount: wrapperModules.length,\n trackedWrapperRequestIds,\n hint:\n wrapperModules.length > 0\n ? 'Live wrapper modules were found and invalidated before sending the CSS update.'\n : 'No live wrapper ModuleNode was available, but the wrapper request id is already tracked, so Analog is trusting the browser-visible wrapper identity and patching the direct stylesheet instead of forcing a reload.',\n });\n sendCssUpdate(ctx.server, {\n path: isDirect.url,\n acceptedPath: isDirect.file,\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n\n return union(\n fileModules\n .filter((mod) => {\n // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)\n // We remove the module with the query params to prevent vite double logging the stylesheet name \"hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x\"\n return mod.file !== ctx.file || mod.id !== isDirect.id;\n })\n .map((mod) => {\n if (mod.file === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n // If the browser-visible `?ngcomp=...` wrapper cannot be\n // trusted, prefer correctness over a partial patch and reload.\n //\n // Guards against: logging a \"successful\" CSS update while\n // Angular keeps running stale wrapper JS that still embeds the\n // old stylesheet contents.\n debugHmrV('component stylesheet hmr fallback: full reload', {\n file: ctx.file,\n encapsulation,\n reason:\n trackedWrapperRequestIds.length === 0\n ? 'missing-wrapper-module'\n : encapsulation === 'shadow'\n ? 'shadow-encapsulation'\n : 'tracked-wrapper-still-not-patchable',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n sendFullReload(ctx.server, {\n file: ctx.file,\n encapsulation,\n reason:\n wrapperModules.length === 0\n ? 'missing-wrapper-module'\n : 'shadow-encapsulation',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n return [];\n }\n }\n return fileModules;\n }\n\n if (\n shouldEnableLiveReload() &&\n /\\.(html|htm)$/.test(ctx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);\n debugHmrV('template owner lookup', {\n file: ctx.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 ctx.server.moduleGraph.invalidateModule(mod),\n );\n\n pendingCompilation = performCompilation(resolvedConfig, ownerIds);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerIds.filter((id) => classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: ctx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: 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: ctx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n sendHMRComponentUpdate(ctx.server, relativeFileId);\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 ctx.server.moduleGraph.invalidateModule(imp);\n\n if (shouldExternalizeStyles() && classNames.get(imp.id)) {\n updates.push(imp.id as string);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: ctx.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 pendingCompilation = performCompilation(resolvedConfig, [\n ...mods.map((mod) => mod.id).filter(Boolean),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n await pendingCompilation;\n pendingCompilation = null;\n\n debugHmr('resource importer component updates', {\n file: ctx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const impRelativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n\n sendHMRComponentUpdate(ctx.server, impRelativeFileId);\n });\n\n return fileModules.map((mod) => {\n if (mod.id === ctx.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: ctx.file });\n classNames.clear();\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n // Mark the style path as safe so Vite's Denied ID check\n // passes, then let Vite's native CSS pipeline handle the\n // ?inline import (preprocessing, test.css, etc.).\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n // User `.html?raw` imports get rewritten to virtual ids so\n // Vite's server.fs Denied ID check stays out of the way.\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n // Map angular external styleUrls to the source file\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath =\n stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n\n debugStyles(\n 'resolveId: component stylesheet NOT FOUND in either map',\n {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n },\n );\n }\n\n return undefined;\n },\n async load(id) {\n // Virtual raw ids (templates) come from the transform-time\n // substitution below and the resolveId rewrite for user\n // `.html?raw` imports. Style ?inline imports now flow through\n // Vite's native CSS pipeline via safeModulePaths.\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: the module-runner calls ensureEntryFromUrl\n // before transformRequest, which can skip resolveId. Mark the\n // path safe here so the Denied ID check passes, then let Vite's\n // CSS pipeline handle the rest.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n // Map angular inline styles to the source text\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles =\n stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n // Register the concrete request id that was just served. During HMR\n // the changed file event references the original source stylesheet\n // path, but the live browser module graph references hashed\n // stylesheet request ids such as `/abc123.css?ngcomp=...`. This is\n // the bridge between those two worlds.\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath:\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(\n filename.replace(/^\\//, ''),\n ),\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(\n filename.replace(/^\\//, ''),\n ) ??\n '',\n ) ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n length: componentStyles.length,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n }\n }\n\n return;\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 (transformFilter && !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 (isVitestVscode && !initialCompilation) {\n // Do full initial compilation\n pendingCompilation = performCompilation(\n this.environment?.config ?? 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 (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(\n this.environment?.config ?? 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 && (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 && 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\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 (\n typescriptResult.warnings &&\n typescriptResult.warnings.length > 0\n ) {\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) => toJitInlineStyleId(encodedStyles),\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(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 closeBundle() {\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 if (!watchMode) releaseCssPreprocessorWorkers();\n },\n };\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 const compilationPlugin = pluginOptions.fastCompile\n ? fastCompilePlugin({\n tsconfigGetter: pluginOptions.tsconfigGetter,\n workspaceRoot: pluginOptions.workspaceRoot,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n jit,\n liveReload: pluginOptions.liveReload,\n supportedBrowsers: pluginOptions.supportedBrowsers,\n isTest,\n isAstroIntegration,\n fastCompileMode: pluginOptions.fastCompileMode,\n })\n : angularPlugin();\n\n return [\n // Scope the `style` package-export condition to `.css`-extension\n // requests so packages like `@angular/material/prebuilt-themes/*.css`\n // (gated only under `style`) still resolve from JS imports, without\n // leaking `style` into Vite's global `resolve.conditions` and\n // breaking Tailwind v4's JS plugin resolver for packages with mixed\n // exports such as `tailwindcss-primeui`.\n cssExtensionStyleResolverPlugin(),\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit }),\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n // `compilationPlugin` is either `angularPlugin()` or `fastCompilePlugin()`\n // depending on `pluginOptions.fastCompile`. When fastCompile is off the\n // array used to also include an unconditional `angularPlugin()` right\n // before this line — invoking the same plugin twice and double-\n // registering its hooks. Removed: `compilationPlugin` already covers both\n // branches.\n compilationPlugin,\n !pluginOptions.fastCompile &&\n pluginOptions.liveReload &&\n liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz\n ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)\n : []),\n (jit &&\n jitPlugin({\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n })) as Plugin,\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit,\n }),\n routerPlugin(),\n angularFullVersion < 190004 && pendingTasksPlugin(),\n nxFolderPlugin(),\n encapsulationPlugin(),\n ].filter(Boolean) as Plugin[];\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n async function performCompilation(config: ResolvedConfig, ids?: string[]) {\n let resolve: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previousLock;\n const integrations = await discoverAnalogIntegrations(config);\n pluginOptions.stylePreprocessor = integrations.stylePreprocessor;\n externalizeStylesRequested = integrations.externalizeStyles;\n configureStylesheetRegistry = integrations.configureStylesheetRegistry;\n transformFilter = integrations.transformFilter;\n tsconfigResolver.setIntegrationIncludes(integrations.include);\n await _doPerformCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n /**\n * This method share mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(config: ResolvedConfig, ids?: string[]) {\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\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 = resolveTsConfigPath();\n const cached = 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 (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (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: pluginOptions.liveReload,\n viteHmr: hasViteHmrTransport(),\n externalizeStylesRequested,\n shouldExternalize: 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'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = pluginOptions.fileReplacements.map((rp) =>\n join(\n pluginOptions.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = union(\n rootNames,\n tsconfigResolver.ensureIncludeCache(),\n replacements,\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 cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (watchMode) {\n augmentHostWithCaching(host, tsSourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (stylesheetRegistry) {\n configureStylesheetRegistry?.(stylesheetRegistry, {\n workspaceRoot: pluginOptions.workspaceRoot,\n });\n }\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: pluginOptions.stylePreprocessor,\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'];\n const oldBuilder =\n builder ?? 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 (!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\n if (angularCompiler!) {\n await angularCompiler.analyzeAsync();\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 pluginOptions.liveReload,\n pluginOptions.disableTypeChecking,\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 = 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) => {\n const sourceFile = builder.getSourceFile(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 !watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const declarationPath = resolve(\n config.root,\n config.build.outDir,\n relative(config.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 (watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else {\n /**\n * Only block the server from starting up\n * during testing.\n */\n if (isTest) {\n // TypeScript will loop until there are no more affected files in the program\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\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\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 * Returns every live Vite module that can legitimately represent a changed\n * Angular resource file.\n *\n * For normal files, `getModulesByFile()` is enough. For Angular component\n * stylesheets, it is not: the browser often holds virtual hashed requests\n * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no\n * longer discoverable from the original source path alone. We therefore merge:\n * - watcher event modules\n * - module-graph modules by source file\n * - registry-tracked live request ids resolved back through the module graph\n */\nexport async function getModulesForChangedFile(\n server: ViteDevServer,\n file: string,\n eventModules: readonly ModuleNode[] = [],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const normalizedFile = normalizePath(file.split('?')[0]);\n const modules = new Map<string, ModuleNode>();\n\n for (const mod of eventModules) {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n }\n\n server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n\n const stylesheetRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];\n const requestIdHits: Array<{\n requestId: string;\n candidate: string;\n via: 'url' | 'id';\n moduleId?: string;\n }> = [];\n for (const requestId of stylesheetRequestIds) {\n const candidates = [\n requestId,\n requestId.startsWith('/') ? requestId : `/${requestId}`,\n ];\n\n for (const candidate of candidates) {\n // `getModuleByUrl()` is the important lookup here. Angular's wrapper\n // module is served by URL and can be absent from a straight `getModuleById`\n // lookup during CSS HMR, even though it is the browser-visible module\n // that must be refreshed. We keep `getModuleById()` as a compatibility\n // fallback for the simpler direct CSS case.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n requestIdHits.push({\n requestId,\n candidate,\n via: mod?.url === candidate ? 'url' : 'id',\n moduleId: mod?.id,\n });\n if (mod?.id) {\n modules.set(mod.id, mod);\n }\n }\n }\n\n debugHmrV('getModulesForChangedFile registry lookup', {\n file: normalizedFile,\n stylesheetRequestIds,\n requestIdHits,\n resolvedModuleIds: [...modules.keys()],\n });\n\n return [...modules.values()];\n}\n\nexport function isModuleForChangedResource(\n mod: ModuleNode,\n changedFile: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): boolean {\n const normalizedChangedFile = normalizePath(changedFile.split('?')[0]);\n\n if (normalizePath((mod.file ?? '').split('?')[0]) === normalizedChangedFile) {\n return true;\n }\n\n if (!mod.id) {\n return false;\n }\n\n // Virtual Angular stylesheet modules do not report the original source file\n // as `mod.file`; they point at the served hashed stylesheet asset instead.\n // Recover the source file through the stylesheet registry so HMR can still\n // answer \"does this live module belong to the resource that just changed?\"\n const requestPath = getFilenameFromPath(mod.id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, '')) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction safeStatMtimeMs(file: string): number | undefined {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\nfunction diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): {\n file: string;\n sourcePath?: string;\n source?: ReturnType<typeof describeStylesheetContent>;\n registry?: ReturnType<typeof describeStylesheetContent>;\n dependencies: StylesheetDependency[];\n diagnostics: ReturnType<AnalogStylesheetRegistry['getDiagnosticsForSource']>;\n tags: string[];\n directModuleId?: string;\n directModuleUrl?: string;\n trackedRequestIds: string[];\n wrapperCount: number;\n anomalies: string[];\n hints: string[];\n} {\n const normalizedFile = normalizePath(changedFile.split('?')[0]);\n const sourceExists = existsSync(normalizedFile);\n const sourceCode = sourceExists\n ? readFileSync(normalizedFile, 'utf-8')\n : undefined;\n\n const directRequestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = directRequestPath\n ? (stylesheetRegistry?.resolveExternalSource(directRequestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n directRequestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(directRequestPath) ??\n stylesheetRegistry?.getServedSourcePath(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n const registryCode = directRequestPath\n ? stylesheetRegistry?.getServedContent(directRequestPath)\n : undefined;\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n const dependencies =\n stylesheetRegistry?.getDependenciesForSource(sourcePath ?? '') ?? [];\n const diagnostics =\n stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? '') ?? [];\n const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? '') ?? [];\n\n const anomalies: string[] = [];\n const hints: string[] = [];\n\n if (!sourceExists) {\n anomalies.push('source_file_missing');\n hints.push(\n 'The stylesheet watcher fired for a file that no longer exists on disk.',\n );\n }\n\n if (!registryCode) {\n anomalies.push('registry_content_missing');\n hints.push(\n 'The stylesheet registry has no served content for the direct module request path.',\n );\n }\n\n if (sourceCode && registryCode) {\n // Compare against the same served representation that the registry stores,\n // not the raw file on disk. Analog intentionally prepends `@reference`\n // and rewrites relative imports before the stylesheet reaches Vite, so a\n // raw-source hash comparison would flag a false positive on every healthy\n // update.\n let expectedRegistryCode = preprocessStylesheet(\n sourceCode,\n normalizedFile,\n stylePreprocessor,\n );\n expectedRegistryCode = rewriteRelativeCssImports(\n expectedRegistryCode,\n normalizedFile,\n );\n const sourceDigest = describeStylesheetContent(expectedRegistryCode).digest;\n const registryDigest = describeStylesheetContent(registryCode).digest;\n if (sourceDigest !== registryDigest) {\n anomalies.push('source_registry_mismatch');\n hints.push(\n 'The source file changed, but the served stylesheet content in the registry is still stale.',\n );\n }\n }\n\n if (trackedRequestIds.length === 0) {\n anomalies.push('no_tracked_requests');\n hints.push(\n 'No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.',\n );\n }\n\n if (\n trackedRequestIds.some((id) => id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('tracked_wrapper_missing_from_module_graph');\n hints.push(\n 'A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.',\n );\n }\n\n if (\n trackedRequestIds.every((id) => !id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('wrapper_not_yet_tracked');\n hints.push(\n 'Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.',\n );\n }\n\n return {\n file: changedFile,\n sourcePath,\n source: sourceCode\n ? describeStylesheetContent(\n rewriteRelativeCssImports(\n preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor),\n normalizedFile,\n ),\n )\n : undefined,\n registry: registryCode\n ? describeStylesheetContent(registryCode)\n : undefined,\n dependencies,\n diagnostics,\n tags,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n trackedRequestIds,\n wrapperCount: wrapperModules.length,\n anomalies,\n hints,\n };\n}\n\nexport async function findComponentStylesheetWrapperModules(\n server: ViteDevServer,\n changedFile: string,\n directModule: ModuleNode,\n fileModules: ModuleNode[],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const wrapperModules = new Map<string, ModuleNode>();\n\n // Fast path: if the wrapper JS module is already present in the resolved\n // fileModules set for this HMR cycle, use it directly.\n for (const mod of fileModules) {\n if (\n mod.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n const directRequestIds = new Set<string>();\n if (directModule.id) {\n directRequestIds.add(directModule.id);\n }\n if (directModule.url) {\n directRequestIds.add(directModule.url);\n }\n\n const requestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = requestPath\n ? (stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n requestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, '')))\n : undefined;\n\n // HMR timing matters here. On a pure CSS edit, the browser often already has\n // the `?ngcomp=...` wrapper module loaded, but the registry may only know\n // about the `?direct&ngcomp=...` request at the moment the file watcher\n // fires. Pull in any already-tracked wrapper ids for the same source file,\n // then derive wrapper candidates from the known direct request ids.\n for (const requestId of stylesheetRegistry?.getRequestIdsForSource(\n sourcePath ?? '',\n ) ?? []) {\n if (requestId.includes('?ngcomp=')) {\n directRequestIds.add(requestId);\n }\n }\n\n const candidateWrapperIds = [...directRequestIds]\n .filter((id) => id.includes('?direct&ngcomp='))\n .map((id) => id.replace('?direct&ngcomp=', '?ngcomp='));\n\n const lookupHits: Array<{\n candidate: string;\n via?: 'url' | 'id';\n moduleId?: string;\n moduleType?: string;\n }> = [];\n\n for (const candidate of candidateWrapperIds) {\n // Wrapper modules are served by URL and can be absent from a straight\n // module-id lookup during HMR. Prefer URL resolution first, then fall back\n // to id lookup for compatibility with simpler module graph states.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n lookupHits.push({\n candidate,\n via: mod?.url === candidate ? 'url' : mod ? 'id' : undefined,\n moduleId: mod?.id,\n moduleType: mod?.type,\n });\n if (\n mod?.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n debugHmrV('component stylesheet wrapper lookup', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n lookupHits,\n });\n\n if (wrapperModules.size === 0) {\n debugHmrV('component stylesheet wrapper lookup empty', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n });\n }\n\n return [...wrapperModules.values()];\n}\n\nfunction sendHMRComponentUpdate(server: ViteDevServer, id: string) {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n\n classNames.delete(id);\n}\n\nfunction sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n) {\n const timestamp = Date.now();\n debugHmrV('ws send: css-update', {\n ...update,\n timestamp,\n });\n server.ws.send({\n type: 'update',\n updates: [\n {\n type: 'css-update',\n timestamp,\n path: update.path,\n acceptedPath: update.acceptedPath,\n },\n ],\n });\n}\n\nfunction sendFullReload(\n server: ViteDevServer,\n details: Record<string, unknown>,\n) {\n debugHmrV('ws send: full-reload', details);\n server.ws.send('analog:debug-full-reload', details);\n server.ws.send({ type: 'full-reload' });\n}\n\ntype ComponentStylesheetHmrOutcome = 'css-update' | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string | undefined;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n}) {\n const pitfalls: string[] = [];\n const rejectedPreferredPaths: string[] = [];\n const hints: string[] = [];\n\n if (details.encapsulation === 'shadow') {\n pitfalls.push('shadow-encapsulation');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.',\n );\n }\n\n if (details.diagnosis.anomalies.includes('wrapper_not_yet_tracked')) {\n pitfalls.push('wrapper-not-yet-tracked');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.',\n );\n }\n\n if (\n details.diagnosis.anomalies.includes(\n 'tracked_wrapper_missing_from_module_graph',\n )\n ) {\n pitfalls.push('tracked-wrapper-missing-from-module-graph');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.',\n );\n }\n\n debugHmrV('component stylesheet hmr outcome', {\n file: details.file,\n outcome: details.outcome,\n encapsulation: details.encapsulation,\n directModuleId: details.directModuleId,\n wrapperIds: details.wrapperIds ?? [],\n preferredPath:\n details.encapsulation === 'shadow' ? 'full-reload' : 'css-update',\n rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],\n pitfalls: [...new Set(pitfalls)],\n anomalies: details.diagnosis.anomalies,\n hints: [...new Set([...details.diagnosis.hints, ...hints])],\n });\n}\n\nexport function findTemplateOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateTsFiles = [\n normalizedResourceFile.replace(/\\.(html|htm)$/i, '.ts'),\n ];\n\n const modules = new Map<string, ModuleNode>();\n for (const candidate of candidateTsFiles) {\n const owners = server.moduleGraph.getModulesByFile(candidate);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\n/**\n * @internal\n */\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n) {\n const ts = require('typescript');\n return (\n file: string,\n ): {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n } => {\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 as any).name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node as any);\n if (hmrUpdateCode) {\n const className = (node as any).name.getText();\n classNames.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) {\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\nfunction markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as any)['_clientModule'].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\n}\n\n/**\n * Removes leading / and query string from a url path\n * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss\n * @param id\n */\nfunction getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n // Defensive fallback: if the ID cannot be parsed as a URL (e.g., it\n // contains characters that are invalid in URLs but valid in file paths\n // on some platforms), strip the query string manually.\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AA4F9C,IAAM,6BAAa,IAAI,KAAK;AAC5B,SAAgB,yBACd,MACA,EACE,eACA,oBAKI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,IAAI,CAAC,GAAG;AACxD,eAAc,OAAO,eAAe;AACpC,kBAAiB,OAAO,eAAe;;AASzC,SAAgB,QAAQ,SAAmC;AACzD,kBAAiB,SAAS,OAAO,SAAS,cAAc;CACxD,MAAM,aAAa,SAAS,cAAc;CAE1C,IAAI,6BAA6B;CACjC,IAAI;CACJ,IAAI;;;;;CAMJ,MAAM,gBAAgB;EACpB,gBAAgB,qBAAqB,SAAS,SAAS;EACvD,eACE,SAAS,iBACT,QAAQ,IAAI,wBACZ,QAAQ,KAAK;EACf,uBAAuB,SAAS,yBAAyB;EACzD,mBAAmB,SAAS,qBAAqB,CAAC,YAAY;EAC9D,KAAK,SAAS;EACd,SAAS,SAAS,WAAW,EAAE;EAC/B;EACA,qBAAqB,SAAS,uBAAuB;EACrD,kBAAkB,SAAS,oBAAoB,EAAE;EACjD,aAAa,SAAS,eAAe;EACrC,iBAAiB,SAAS,mBAAmB;EAG7C,mBAAmB,KAAA;EACpB;CAED,IAAI;CACJ,IAAI,4BAA8D;CAElE,MAAM,KAAK,QAAQ,aAAa;CAChC,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,SAAA,QAAA,IAAA,aAAqC,UAAU,CAAC,CAAC,QAAQ,IAAI;CACnE,MAAM,mBAAmB,IAAI,iBAAiB;EAC5C,eAAe,cAAc;EAC7B,SAAS,cAAc;EACvB,YAAY,cAAc;EAC1B;EACD,CAAC;CACF,SAAS,qBAAqB;A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EACH,GAAG;EACH,GAAG;EACJ;;AAGH,SAAS,wBAAwB,KAA6B;AAE5D,KAAI,mBAAmB,IACpB,KAAY,iBAAiB,kBAAkB;AAGlD,QAAO;EACL,GAAG;EACH,iBAAiB;EAClB;;;;;;;AAQH,SAAS,oBAAoB,IAAoB;AAC/C,KAAI;AACF,SAAO,IAAI,IAAI,IAAI,mBAAmB,CAAC,SAAS,QAAQ,OAAO,GAAG;SAC5D;EAIN,MAAM,aAAa,GAAG,QAAQ,IAAI;AAElC,UADiB,cAAc,IAAI,GAAG,MAAM,GAAG,WAAW,GAAG,IAC7C,QAAQ,OAAO,GAAG"}
|
|
1
|
+
{"version":3,"file":"angular-vite-plugin.js","names":[],"sources":["../../../src/lib/angular-vite-plugin.ts"],"sourcesContent":["import { NgtscProgram } from '@angular/compiler-cli';\nimport { union } from 'es-toolkit';\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { createRequire } from 'node:module';\nimport * as ts from 'typescript';\nimport {\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';\nimport { jitPlugin } from './angular-jit-plugin.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from './compiler-plugin.js';\nimport {\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport type {\n StylePreprocessor,\n StylesheetDependency,\n} from './style-preprocessor.js';\nimport {\n discoverAnalogIntegrations,\n type StylesheetRegistryConfigurator,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nimport { fastCompilePlugin } from './fast-compile-plugin.js';\nimport { ANGULAR_DECORATOR_CALL_RE } from './compiler/index.js';\nimport {\n encapsulationPlugin,\n isComponentStyleSheet,\n getComponentStyleSheetMeta,\n} from './encapsulation-plugin.js';\nimport { virtualModulesPlugin } from './virtual-modules-plugin.js';\nimport { angularVitestPlugins } from './angular-vitest-plugin.js';\nimport {\n createJitResourceTransformer,\n SourceFileCache,\n angularFullVersion,\n} from './utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompiler,\n debugCompilerV,\n debugEmit,\n debugEmitV,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from './utils/debug.js';\nimport {\n createTsConfigGetter,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { toJitInlineStyleId } from './utils/jit-inline-styles.js';\nimport { TsconfigResolver } from './utils/tsconfig-resolver.js';\nimport { cssExtensionStyleResolverPlugin } from './utils/css-extension-resolver.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\nimport {\n toVirtualRawId,\n toVirtualStyleId,\n VIRTUAL_RAW_PREFIX,\n} from './utils/virtual-ids.js';\nimport { type SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\n\nconst require = createRequire(import.meta.url);\n\nimport { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';\nimport { liveReloadPlugin } from './live-reload-plugin.js';\nimport { EmitFileResult } from './models.js';\nimport { nxFolderPlugin } from './nx-folder-plugin.js';\nimport {\n FileReplacement,\n FileReplacementSSR,\n FileReplacementWith,\n replaceFiles,\n} from './plugins/file-replacements.plugin.js';\nimport { routerPlugin } from './router-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheet,\n rewriteRelativeCssImports,\n} from './stylesheet-registry.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\n\nexport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n toAngularCompilationFileReplacements,\n mapTemplateUpdatesToFiles,\n refreshStylesheetRegistryForFile,\n describeStylesheetContent,\n isTestWatchMode,\n} from './utils/compilation-shared.js';\nimport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n describeStylesheetContent,\n refreshStylesheetRegistryForFile,\n isTestWatchMode,\n} from './utils/compilation-shared.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\n\nexport interface PluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n supportedBrowsers?: string[];\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n /**\n * Enables Analog's Angular live-reload/HMR pipeline during development/watch mode.\n *\n * This is separate from Vite's `server.hmr` option, which configures the\n * HMR client transport.\n *\n * Defaults to `true` for watch mode. Set to `false` to disable Angular\n * reload updates while keeping other stylesheet externalization behavior\n * available when needed.\n */\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n fileReplacements?: FileReplacement[];\n /**\n * Opt into the fast compile path. Skips Angular's template type-checking\n * and routes compilation through an internal single-pass transform.\n * Defaults to `false`.\n */\n fastCompile?: boolean;\n /**\n * Compilation output mode used when `fastCompile` is enabled.\n * - `'full'` (default): Emit final Ivy definitions for application builds.\n * - `'partial'`: Emit partial declarations for library publishing.\n */\n fastCompileMode?: 'full' | 'partial';\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:hmr']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n}\n\nconst classNames = new Map();\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\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\nexport function angular(options?: PluginOptions): Plugin[] {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n const liveReload = options?.liveReload ?? true;\n // Set on each compilation from the Vite plugins' `analog.setup()` hooks.\n let externalizeStylesRequested = false;\n let configureStylesheetRegistry: StylesheetRegistryConfigurator | undefined;\n let transformFilter: TransformFilter | undefined;\n\n /**\n * Normalize plugin options so defaults\n * are used for values not provided.\n */\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot:\n options?.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n liveReload,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n fastCompile: options?.fastCompile ?? false,\n fastCompileMode: options?.fastCompileMode ?? 'full',\n // Set on each compilation from preprocessors registered by Vite plugins\n // through `analog.setup()`.\n stylePreprocessor: undefined as StylePreprocessor | undefined,\n };\n\n let resolvedConfig: ResolvedConfig;\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n\n const ts = require('typescript');\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n let nextProgram: NgtscProgram | undefined;\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: pluginOptions.workspaceRoot,\n include: pluginOptions.include,\n liveReload: pluginOptions.liveReload,\n isTest,\n });\n function invalidateFsCaches() {\n tsconfigResolver.invalidateIncludeCache();\n }\n function invalidateTsconfigCaches() {\n tsconfigResolver.invalidateTsconfigCaches();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n let watchMode = false;\n let testWatchMode = isTestWatchMode();\n\n function hasViteHmrTransport(): boolean {\n return resolvedConfig ? resolvedConfig.server.hmr !== false : true;\n }\n\n function shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(\n effectiveWatchMode &&\n pluginOptions.liveReload &&\n hasViteHmrTransport()\n );\n }\n\n /**\n * Determines whether Angular should externalize component styles.\n *\n * When true, Angular emits style references (hash-based IDs) instead of\n * inlining CSS strings. Vite's resolveId → load → transform pipeline\n * then serves these virtual modules, allowing @tailwindcss/vite to\n * process @reference directives.\n *\n * Required for TWO independent use-cases:\n * 1. HMR — Vite needs external modules for hot replacement\n * 2. A Vite plugin asked for it through `analog.setup()` so its styles\n * pass through Vite's CSS pipeline (e.g. @tailwindcss/vite)\n *\n * In production builds (!watchMode), styles are NOT externalized — they\n * are inlined after preprocessCSS runs eagerly in transformStylesheet.\n */\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableLiveReload() || externalizeStylesRequested);\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const tsSourceFileCache = new Map<string, ts.SourceFile>();\n\n function invalidateSourceFiles(files: Set<string>) {\n for (const file of files) {\n tsSourceFileCache.delete(normalizePath(file));\n }\n sourceFileCache.invalidate(files);\n }\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n\n const jit =\n typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;\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 const normalizeEmitterLookupId = (file: string) => {\n const normalizedFile = normalizePath(file);\n\n if (!normalizedFile.startsWith('/@fs/')) {\n return normalizedFile;\n }\n\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n\n return normalizePath(fsPath);\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) => {\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 let initialCompilation = 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;\n let compilationLock = Promise.resolve();\n function angularPlugin(): Plugin {\n let isProd = false;\n\n if (angularFullVersion < 190000 && pluginOptions.liveReload) {\n // Angular < 19 does not support externalRuntimeStyles or _enableHmr.\n debugHmr('hmr disabled: Angular version does not support HMR APIs', {\n angularVersion: angularFullVersion,\n isTest,\n });\n console.warn(\n '[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.',\n angularFullVersion,\n );\n pluginOptions.liveReload = false;\n }\n\n if (isTest) {\n // Test mode: disable HMR because\n // Vitest's runner doesn't support Vite's WebSocket-based HMR.\n // This does NOT block style externalization — shouldExternalizeStyles()\n // independently checks externalizeStylesRequested, so plugin-driven\n // component styles still work in unit tests.\n pluginOptions.liveReload = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n api: { getTsConfigPath: resolveTsConfigPath },\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n isProd = isProdMode(config.mode);\n\n // Store the config context for later resolution in configResolved\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n // Do a preliminary resolution for esbuild plugin (before configResolved)\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const esbuild = config.esbuild ?? false;\n const oxc = config.oxc ?? false;\n\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(watchMode ? {} : { ngDevMode: 'false' }),\n };\n const useRolldown = isRolldown();\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] =\n {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n // Astro manages the transformer lifecycle externally.\n !isAstroIntegration,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit,\n incremental: watchMode,\n },\n isTest,\n !isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n // `resolve.conditions` is intentionally not extended with `style`\n // here: that condition is scoped to `.css`-extension requests via\n // `cssExtensionStyleResolverPlugin` (registered in the returned\n // plugin array). Adding `style` globally caused Tailwind v4's JS\n // plugin resolver — which inherits Vite's global conditions — to\n // pick the `style` export of packages like `tailwindcss-primeui`\n // and feed a `.css` file to Node's ESM loader.\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n\n // Suppress noisy sourcemap warnings from Angular packages that ship\n // FESM bundles whose sourcemaps reference source files not included\n // in the npm package.\n if (config.logger?.warnOnce) {\n const originalWarnOnce = config.logger.warnOnce;\n config.logger.warnOnce = (msg, options) => {\n if (\n typeof msg === 'string' &&\n msg.includes('Sourcemap') &&\n msg.includes('node_modules')\n ) {\n return;\n }\n originalWarnOnce(msg, options);\n };\n }\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n\n if (isTest) {\n // set test watch mode\n // - vite override from vitest-angular\n // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)\n // - vite config for test.watch variable\n // - vitest watch mode detected from the command line\n testWatchMode =\n !(config.server.watch === null) ||\n (config as any).test?.watch === true ||\n testWatchMode;\n }\n },\n configureServer(server) {\n viteServer = 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(resolvedConfig),\n );\n server.watcher.on('add', invalidateCompilationOnFsChange);\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: classNames as Map<string, string>,\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 // Defer the first compilation in test mode\n if (!isVitestVscode) {\n pendingCompilation = performCompilation(\n this.environment?.config ?? resolvedConfig,\n );\n await pendingCompilation;\n pendingCompilation = null;\n\n initialCompilation = true;\n }\n },\n buildEnd() {\n if (watchMode) return;\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 tsconfigResolver.invalidateAll();\n releaseCssPreprocessorWorkers();\n },\n async handleHotUpdate(ctx) {\n if (isIgnoredHmrFile(ctx.file)) {\n debugHmr('ignored file change', { file: ctx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n debugHmr('TS file changed', { file: ctx.file, fileId });\n\n pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableLiveReload()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: ctx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n className: 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 shouldEnableLiveReload() &&\n result?.hmrEligible &&\n classNames.get(fileId)\n ) {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), fileId),\n )}@${classNames.get(fileId)}`;\n\n debugHmr('sending component update', { relativeFileId });\n debugHmrV('ts hmr component update payload', {\n file: ctx.file,\n fileId,\n relativeFileId,\n className: classNames.get(fileId),\n });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('resource file changed', { file: ctx.file });\n fileTransformMap.delete(ctx.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 fileModules = await getModulesForChangedFile(\n ctx.server,\n ctx.file,\n ctx.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, ctx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, ctx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: ctx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: ctx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n const { encapsulation } = getComponentStyleSheetMeta(\n isDirect.id,\n );\n // Angular exposes one component stylesheet through two module\n // shapes:\n // 1. a `?direct&ngcomp=...` CSS module that Vite can patch with\n // a normal `css-update`\n // 2. a `?ngcomp=...` JS wrapper module that embeds `__vite__css`\n // for Angular's runtime consumption\n //\n // Value: invalidate the browser-visible wrapper before patching\n // the direct CSS module so Angular re-evaluates the same live\n // wrapper it is actually using.\n //\n // Guards against: a successful-looking CSS HMR event that\n // leaves the UI stale because the wrapper still holds the\n // pre-edit CSS string.\n const wrapperModules =\n await findComponentStylesheetWrapperModules(\n ctx.server,\n ctx.file,\n isDirect,\n fileModules,\n stylesheetRegistry,\n );\n const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(\n ctx.file,\n isDirect,\n stylesheetRegistry,\n wrapperModules,\n pluginOptions.stylePreprocessor,\n );\n debugStylesV('HMR: component stylesheet changed', {\n file: isDirect.file,\n encapsulation,\n });\n debugHmrV('component stylesheet wrapper modules', {\n file: ctx.file,\n wrapperCount: wrapperModules.length,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n availableModuleIds: fileModules.map((mod) => mod.id),\n });\n debugHmrV(\n 'component stylesheet pipeline diagnosis',\n stylesheetDiagnosis,\n );\n\n // Drop Vite's cached direct-module transform before wrapper\n // lookup and patching continue.\n //\n // Value: later fetches and wrapper regeneration see the just\n // edited stylesheet instead of the last served transform result.\n ctx.server.moduleGraph.invalidateModule(isDirect);\n debugHmrV('component stylesheet direct module invalidated', {\n file: ctx.file,\n directModuleId: isDirect.id,\n directModuleUrl: isDirect.url,\n reason:\n 'Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues.',\n });\n\n // CSS-only HMR is safe only when the browser-visible wrapper is\n // known and the component is not using Shadow DOM. Vite's CSS\n // patching does not search shadow roots, so Shadow DOM still\n // falls back to reload for correctness.\n const trackedWrapperRequestIds =\n stylesheetDiagnosis.trackedRequestIds.filter((id) =>\n id.includes('?ngcomp='),\n );\n const canUseCssUpdate =\n encapsulation !== 'shadow' &&\n (wrapperModules.length > 0 ||\n trackedWrapperRequestIds.length > 0);\n\n if (canUseCssUpdate) {\n wrapperModules.forEach((mod) =>\n ctx.server.moduleGraph.invalidateModule(mod),\n );\n // A live wrapper ModuleNode is ideal because we can\n // invalidate it directly, but it is not strictly required.\n //\n // Value: keep CSS-only HMR working when the browser has\n // already loaded the wrapper URL and the registry can still\n // prove that wrapper identity, even if this HMR pass did not\n // surface a live ModuleNode for it.\n debugHmrV('sending css-update for component stylesheet', {\n file: ctx.file,\n path: isDirect.url,\n acceptedPath: isDirect.file,\n wrapperCount: wrapperModules.length,\n trackedWrapperRequestIds,\n hint:\n wrapperModules.length > 0\n ? 'Live wrapper modules were found and invalidated before sending the CSS update.'\n : 'No live wrapper ModuleNode was available, but the wrapper request id is already tracked, so Analog is trusting the browser-visible wrapper identity and patching the direct stylesheet instead of forcing a reload.',\n });\n sendCssUpdate(ctx.server, {\n path: isDirect.url,\n acceptedPath: isDirect.file,\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'css-update',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n\n return union(\n fileModules\n .filter((mod) => {\n // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)\n // We remove the module with the query params to prevent vite double logging the stylesheet name \"hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x\"\n return mod.file !== ctx.file || mod.id !== isDirect.id;\n })\n .map((mod) => {\n if (mod.file === ctx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n }) as ModuleNode[],\n wrapperModules.map((mod) => markModuleSelfAccepting(mod)),\n );\n }\n\n // If the browser-visible `?ngcomp=...` wrapper cannot be\n // trusted, prefer correctness over a partial patch and reload.\n //\n // Guards against: logging a \"successful\" CSS update while\n // Angular keeps running stale wrapper JS that still embeds the\n // old stylesheet contents.\n debugHmrV('component stylesheet hmr fallback: full reload', {\n file: ctx.file,\n encapsulation,\n reason:\n trackedWrapperRequestIds.length === 0\n ? 'missing-wrapper-module'\n : encapsulation === 'shadow'\n ? 'shadow-encapsulation'\n : 'tracked-wrapper-still-not-patchable',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n logComponentStylesheetHmrOutcome({\n file: ctx.file,\n encapsulation,\n diagnosis: stylesheetDiagnosis,\n outcome: 'full-reload',\n directModuleId: isDirect.id,\n wrapperIds: wrapperModules.map((mod) => mod.id),\n });\n sendFullReload(ctx.server, {\n file: ctx.file,\n encapsulation,\n reason:\n wrapperModules.length === 0\n ? 'missing-wrapper-module'\n : 'shadow-encapsulation',\n directId: isDirect.id,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? [],\n });\n return [];\n }\n }\n return fileModules;\n }\n\n if (\n shouldEnableLiveReload() &&\n /\\.(html|htm)$/.test(ctx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);\n debugHmrV('template owner lookup', {\n file: ctx.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 ctx.server.moduleGraph.invalidateModule(mod),\n );\n\n pendingCompilation = performCompilation(resolvedConfig, ownerIds);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerIds.filter((id) => classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: ctx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: 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: ctx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n sendHMRComponentUpdate(ctx.server, relativeFileId);\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 ctx.server.moduleGraph.invalidateModule(imp);\n\n if (shouldExternalizeStyles() && classNames.get(imp.id)) {\n updates.push(imp.id as string);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: ctx.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 pendingCompilation = performCompilation(resolvedConfig, [\n ...mods.map((mod) => mod.id).filter(Boolean),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n await pendingCompilation;\n pendingCompilation = null;\n\n debugHmr('resource importer component updates', {\n file: ctx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n const impRelativeFileId = `${normalizePath(\n relative(process.cwd(), updateId),\n )}@${classNames.get(updateId)}`;\n\n sendHMRComponentUpdate(ctx.server, impRelativeFileId);\n });\n\n return fileModules.map((mod) => {\n if (mod.id === ctx.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: ctx.file });\n classNames.clear();\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n // Mark the style path as safe so Vite's Denied ID check\n // passes, then let Vite's native CSS pipeline handle the\n // ?inline import (preprocessing, test.css, etc.).\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n // User `.html?raw` imports get rewritten to virtual ids so\n // Vite's server.fs Denied ID check stays out of the way.\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n // Map angular external styleUrls to the source file\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath =\n stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n\n debugStyles(\n 'resolveId: component stylesheet NOT FOUND in either map',\n {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n },\n );\n }\n\n return undefined;\n },\n async load(id) {\n // Virtual raw ids (templates) come from the transform-time\n // substitution below and the resolveId rewrite for user\n // `.html?raw` imports. Style ?inline imports now flow through\n // Vite's native CSS pipeline via safeModulePaths.\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: the module-runner calls ensureEntryFromUrl\n // before transformRequest, which can skip resolveId. Mark the\n // path safe here so the Denied ID check passes, then let Vite's\n // CSS pipeline handle the rest.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n // Map angular inline styles to the source text\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles =\n stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n // Register the concrete request id that was just served. During HMR\n // the changed file event references the original source stylesheet\n // path, but the live browser module graph references hashed\n // stylesheet request ids such as `/abc123.css?ngcomp=...`. This is\n // the bridge between those two worlds.\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath:\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(\n filename.replace(/^\\//, ''),\n ),\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\n filename.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(\n filename.replace(/^\\//, ''),\n ) ??\n '',\n ) ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n length: componentStyles.length,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n }\n }\n\n return;\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 (transformFilter && !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 (isVitestVscode && !initialCompilation) {\n // Do full initial compilation\n pendingCompilation = performCompilation(\n this.environment?.config ?? 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 (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(\n this.environment?.config ?? 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 && (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 && 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\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 (\n typescriptResult.warnings &&\n typescriptResult.warnings.length > 0\n ) {\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) => toJitInlineStyleId(encodedStyles),\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(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 closeBundle() {\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 if (!watchMode) releaseCssPreprocessorWorkers();\n },\n };\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 const compilationPlugin = pluginOptions.fastCompile\n ? fastCompilePlugin({\n tsconfigGetter: pluginOptions.tsconfigGetter,\n workspaceRoot: pluginOptions.workspaceRoot,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n jit,\n liveReload: pluginOptions.liveReload,\n supportedBrowsers: pluginOptions.supportedBrowsers,\n isTest,\n isAstroIntegration,\n fastCompileMode: pluginOptions.fastCompileMode,\n })\n : angularPlugin();\n\n return [\n // Scope the `style` package-export condition to `.css`-extension\n // requests so packages like `@angular/material/prebuilt-themes/*.css`\n // (gated only under `style`) still resolve from JS imports, without\n // leaking `style` into Vite's global `resolve.conditions` and\n // breaking Tailwind v4's JS plugin resolver for packages with mixed\n // exports such as `tailwindcss-primeui`.\n cssExtensionStyleResolverPlugin(),\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit }),\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n // `compilationPlugin` is either `angularPlugin()` or `fastCompilePlugin()`\n // depending on `pluginOptions.fastCompile`. When fastCompile is off the\n // array used to also include an unconditional `angularPlugin()` right\n // before this line — invoking the same plugin twice and double-\n // registering its hooks. Removed: `compilationPlugin` already covers both\n // branches.\n compilationPlugin,\n !pluginOptions.fastCompile &&\n pluginOptions.liveReload &&\n liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz\n ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)\n : []),\n (jit &&\n jitPlugin({\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n })) as Plugin,\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit,\n }),\n routerPlugin(),\n angularFullVersion < 190004 && pendingTasksPlugin(),\n nxFolderPlugin(),\n encapsulationPlugin(),\n ].filter(Boolean) as Plugin[];\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n async function performCompilation(config: ResolvedConfig, ids?: string[]) {\n let resolve: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previousLock;\n const integrations = await discoverAnalogIntegrations(config);\n pluginOptions.stylePreprocessor = integrations.stylePreprocessor;\n externalizeStylesRequested = integrations.externalizeStyles;\n configureStylesheetRegistry = integrations.configureStylesheetRegistry;\n transformFilter = integrations.transformFilter;\n tsconfigResolver.setIntegrationIncludes(integrations.include);\n await _doPerformCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n /**\n * This method share mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(config: ResolvedConfig, ids?: string[]) {\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\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 = resolveTsConfigPath();\n const cached = 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 (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (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: pluginOptions.liveReload,\n viteHmr: hasViteHmrTransport(),\n externalizeStylesRequested,\n shouldExternalize: 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'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = pluginOptions.fileReplacements.map((rp) =>\n join(\n pluginOptions.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = union(\n rootNames,\n tsconfigResolver.ensureIncludeCache(),\n replacements,\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 cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (watchMode) {\n augmentHostWithCaching(host, tsSourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (stylesheetRegistry) {\n configureStylesheetRegistry?.(stylesheetRegistry, {\n workspaceRoot: pluginOptions.workspaceRoot,\n });\n }\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: pluginOptions.stylePreprocessor,\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'];\n const oldBuilder =\n builder ?? 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 (!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\n if (angularCompiler!) {\n await angularCompiler.analyzeAsync();\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 pluginOptions.liveReload,\n pluginOptions.disableTypeChecking,\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 = 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) => {\n const sourceFile = builder.getSourceFile(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 !watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const declarationPath = resolve(\n config.root,\n config.build.outDir,\n relative(config.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 (watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else {\n /**\n * Only block the server from starting up\n * during testing.\n */\n if (isTest) {\n // TypeScript will loop until there are no more affected files in the program\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\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\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 * Returns every live Vite module that can legitimately represent a changed\n * Angular resource file.\n *\n * For normal files, `getModulesByFile()` is enough. For Angular component\n * stylesheets, it is not: the browser often holds virtual hashed requests\n * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no\n * longer discoverable from the original source path alone. We therefore merge:\n * - watcher event modules\n * - module-graph modules by source file\n * - registry-tracked live request ids resolved back through the module graph\n */\nexport async function getModulesForChangedFile(\n server: ViteDevServer,\n file: string,\n eventModules: readonly ModuleNode[] = [],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const normalizedFile = normalizePath(file.split('?')[0]);\n const modules = new Map<string, ModuleNode>();\n\n for (const mod of eventModules) {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n }\n\n server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n\n const stylesheetRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];\n const requestIdHits: Array<{\n requestId: string;\n candidate: string;\n via: 'url' | 'id';\n moduleId?: string;\n }> = [];\n for (const requestId of stylesheetRequestIds) {\n const candidates = [\n requestId,\n requestId.startsWith('/') ? requestId : `/${requestId}`,\n ];\n\n for (const candidate of candidates) {\n // `getModuleByUrl()` is the important lookup here. Angular's wrapper\n // module is served by URL and can be absent from a straight `getModuleById`\n // lookup during CSS HMR, even though it is the browser-visible module\n // that must be refreshed. We keep `getModuleById()` as a compatibility\n // fallback for the simpler direct CSS case.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n requestIdHits.push({\n requestId,\n candidate,\n via: mod?.url === candidate ? 'url' : 'id',\n moduleId: mod?.id,\n });\n if (mod?.id) {\n modules.set(mod.id, mod);\n }\n }\n }\n\n debugHmrV('getModulesForChangedFile registry lookup', {\n file: normalizedFile,\n stylesheetRequestIds,\n requestIdHits,\n resolvedModuleIds: [...modules.keys()],\n });\n\n return [...modules.values()];\n}\n\nexport function isModuleForChangedResource(\n mod: ModuleNode,\n changedFile: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): boolean {\n const normalizedChangedFile = normalizePath(changedFile.split('?')[0]);\n\n if (normalizePath((mod.file ?? '').split('?')[0]) === normalizedChangedFile) {\n return true;\n }\n\n if (!mod.id) {\n return false;\n }\n\n // Virtual Angular stylesheet modules do not report the original source file\n // as `mod.file`; they point at the served hashed stylesheet asset instead.\n // Recover the source file through the stylesheet registry so HMR can still\n // answer \"does this live module belong to the resource that just changed?\"\n const requestPath = getFilenameFromPath(mod.id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\\//, '')) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, ''));\n\n return (\n normalizePath((sourcePath ?? '').split('?')[0]) === normalizedChangedFile\n );\n}\n\nfunction safeStatMtimeMs(file: string): number | undefined {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\nfunction diagnoseComponentStylesheetPipeline(\n changedFile: string,\n directModule: ModuleNode,\n stylesheetRegistry: AnalogStylesheetRegistry | undefined,\n wrapperModules: ModuleNode[],\n stylePreprocessor?: StylePreprocessor,\n): {\n file: string;\n sourcePath?: string;\n source?: ReturnType<typeof describeStylesheetContent>;\n registry?: ReturnType<typeof describeStylesheetContent>;\n dependencies: StylesheetDependency[];\n diagnostics: ReturnType<AnalogStylesheetRegistry['getDiagnosticsForSource']>;\n tags: string[];\n directModuleId?: string;\n directModuleUrl?: string;\n trackedRequestIds: string[];\n wrapperCount: number;\n anomalies: string[];\n hints: string[];\n} {\n const normalizedFile = normalizePath(changedFile.split('?')[0]);\n const sourceExists = existsSync(normalizedFile);\n const sourceCode = sourceExists\n ? readFileSync(normalizedFile, 'utf-8')\n : undefined;\n\n const directRequestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = directRequestPath\n ? (stylesheetRegistry?.resolveExternalSource(directRequestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n directRequestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(directRequestPath) ??\n stylesheetRegistry?.getServedSourcePath(\n directRequestPath.replace(/^\\//, ''),\n ))\n : normalizedFile;\n const registryCode = directRequestPath\n ? stylesheetRegistry?.getServedContent(directRequestPath)\n : undefined;\n const trackedRequestIds =\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [];\n const dependencies =\n stylesheetRegistry?.getDependenciesForSource(sourcePath ?? '') ?? [];\n const diagnostics =\n stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? '') ?? [];\n const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? '') ?? [];\n\n const anomalies: string[] = [];\n const hints: string[] = [];\n\n if (!sourceExists) {\n anomalies.push('source_file_missing');\n hints.push(\n 'The stylesheet watcher fired for a file that no longer exists on disk.',\n );\n }\n\n if (!registryCode) {\n anomalies.push('registry_content_missing');\n hints.push(\n 'The stylesheet registry has no served content for the direct module request path.',\n );\n }\n\n if (sourceCode && registryCode) {\n // Compare against the same served representation that the registry stores,\n // not the raw file on disk. Analog intentionally prepends `@reference`\n // and rewrites relative imports before the stylesheet reaches Vite, so a\n // raw-source hash comparison would flag a false positive on every healthy\n // update.\n let expectedRegistryCode = preprocessStylesheet(\n sourceCode,\n normalizedFile,\n stylePreprocessor,\n );\n expectedRegistryCode = rewriteRelativeCssImports(\n expectedRegistryCode,\n normalizedFile,\n );\n const sourceDigest = describeStylesheetContent(expectedRegistryCode).digest;\n const registryDigest = describeStylesheetContent(registryCode).digest;\n if (sourceDigest !== registryDigest) {\n anomalies.push('source_registry_mismatch');\n hints.push(\n 'The source file changed, but the served stylesheet content in the registry is still stale.',\n );\n }\n }\n\n if (trackedRequestIds.length === 0) {\n anomalies.push('no_tracked_requests');\n hints.push(\n 'No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.',\n );\n }\n\n if (\n trackedRequestIds.some((id) => id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('tracked_wrapper_missing_from_module_graph');\n hints.push(\n 'A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.',\n );\n }\n\n if (\n trackedRequestIds.every((id) => !id.includes('?ngcomp=')) &&\n wrapperModules.length === 0\n ) {\n anomalies.push('wrapper_not_yet_tracked');\n hints.push(\n 'Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.',\n );\n }\n\n return {\n file: changedFile,\n sourcePath,\n source: sourceCode\n ? describeStylesheetContent(\n rewriteRelativeCssImports(\n preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor),\n normalizedFile,\n ),\n )\n : undefined,\n registry: registryCode\n ? describeStylesheetContent(registryCode)\n : undefined,\n dependencies,\n diagnostics,\n tags,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n trackedRequestIds,\n wrapperCount: wrapperModules.length,\n anomalies,\n hints,\n };\n}\n\nexport async function findComponentStylesheetWrapperModules(\n server: ViteDevServer,\n changedFile: string,\n directModule: ModuleNode,\n fileModules: ModuleNode[],\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): Promise<ModuleNode[]> {\n const wrapperModules = new Map<string, ModuleNode>();\n\n // Fast path: if the wrapper JS module is already present in the resolved\n // fileModules set for this HMR cycle, use it directly.\n for (const mod of fileModules) {\n if (\n mod.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n const directRequestIds = new Set<string>();\n if (directModule.id) {\n directRequestIds.add(directModule.id);\n }\n if (directModule.url) {\n directRequestIds.add(directModule.url);\n }\n\n const requestPath = directModule.id\n ? getFilenameFromPath(directModule.id)\n : undefined;\n const sourcePath = requestPath\n ? (stylesheetRegistry?.resolveExternalSource(requestPath) ??\n stylesheetRegistry?.resolveExternalSource(\n requestPath.replace(/^\\//, ''),\n ) ??\n stylesheetRegistry?.getServedSourcePath(requestPath) ??\n stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\\//, '')))\n : undefined;\n\n // HMR timing matters here. On a pure CSS edit, the browser often already has\n // the `?ngcomp=...` wrapper module loaded, but the registry may only know\n // about the `?direct&ngcomp=...` request at the moment the file watcher\n // fires. Pull in any already-tracked wrapper ids for the same source file,\n // then derive wrapper candidates from the known direct request ids.\n for (const requestId of stylesheetRegistry?.getRequestIdsForSource(\n sourcePath ?? '',\n ) ?? []) {\n if (requestId.includes('?ngcomp=')) {\n directRequestIds.add(requestId);\n }\n }\n\n const candidateWrapperIds = [...directRequestIds]\n .filter((id) => id.includes('?direct&ngcomp='))\n .map((id) => id.replace('?direct&ngcomp=', '?ngcomp='));\n\n const lookupHits: Array<{\n candidate: string;\n via?: 'url' | 'id';\n moduleId?: string;\n moduleType?: string;\n }> = [];\n\n for (const candidate of candidateWrapperIds) {\n // Wrapper modules are served by URL and can be absent from a straight\n // module-id lookup during HMR. Prefer URL resolution first, then fall back\n // to id lookup for compatibility with simpler module graph states.\n const mod =\n (await server.moduleGraph.getModuleByUrl(candidate)) ??\n server.moduleGraph.getModuleById(candidate);\n lookupHits.push({\n candidate,\n via: mod?.url === candidate ? 'url' : mod ? 'id' : undefined,\n moduleId: mod?.id,\n moduleType: mod?.type,\n });\n if (\n mod?.id &&\n mod.type === 'js' &&\n isComponentStyleSheet(mod.id) &&\n isModuleForChangedResource(mod, changedFile, stylesheetRegistry)\n ) {\n wrapperModules.set(mod.id, mod);\n }\n }\n\n debugHmrV('component stylesheet wrapper lookup', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n lookupHits,\n });\n\n if (wrapperModules.size === 0) {\n debugHmrV('component stylesheet wrapper lookup empty', {\n file: changedFile,\n sourcePath,\n directModuleId: directModule.id,\n directModuleUrl: directModule.url,\n candidateWrapperIds,\n });\n }\n\n return [...wrapperModules.values()];\n}\n\nfunction sendHMRComponentUpdate(server: ViteDevServer, id: string) {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n\n classNames.delete(id);\n}\n\nfunction sendCssUpdate(\n server: ViteDevServer,\n update: {\n path: string;\n acceptedPath: string;\n },\n) {\n const timestamp = Date.now();\n debugHmrV('ws send: css-update', {\n ...update,\n timestamp,\n });\n server.ws.send({\n type: 'update',\n updates: [\n {\n type: 'css-update',\n timestamp,\n path: update.path,\n acceptedPath: update.acceptedPath,\n },\n ],\n });\n}\n\nfunction sendFullReload(\n server: ViteDevServer,\n details: Record<string, unknown>,\n) {\n debugHmrV('ws send: full-reload', details);\n server.ws.send('analog:debug-full-reload', details);\n server.ws.send({ type: 'full-reload' });\n}\n\ntype ComponentStylesheetHmrOutcome = 'css-update' | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string | undefined;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n}) {\n const pitfalls: string[] = [];\n const rejectedPreferredPaths: string[] = [];\n const hints: string[] = [];\n\n if (details.encapsulation === 'shadow') {\n pitfalls.push('shadow-encapsulation');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.',\n );\n }\n\n if (details.diagnosis.anomalies.includes('wrapper_not_yet_tracked')) {\n pitfalls.push('wrapper-not-yet-tracked');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.',\n );\n }\n\n if (\n details.diagnosis.anomalies.includes(\n 'tracked_wrapper_missing_from_module_graph',\n )\n ) {\n pitfalls.push('tracked-wrapper-missing-from-module-graph');\n rejectedPreferredPaths.push('css-update');\n hints.push(\n 'A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.',\n );\n }\n\n debugHmrV('component stylesheet hmr outcome', {\n file: details.file,\n outcome: details.outcome,\n encapsulation: details.encapsulation,\n directModuleId: details.directModuleId,\n wrapperIds: details.wrapperIds ?? [],\n preferredPath:\n details.encapsulation === 'shadow' ? 'full-reload' : 'css-update',\n rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],\n pitfalls: [...new Set(pitfalls)],\n anomalies: details.diagnosis.anomalies,\n hints: [...new Set([...details.diagnosis.hints, ...hints])],\n });\n}\n\nexport function findTemplateOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateTsFiles = [\n normalizedResourceFile.replace(/\\.(html|htm)$/i, '.ts'),\n ];\n\n const modules = new Map<string, ModuleNode>();\n for (const candidate of candidateTsFiles) {\n const owners = server.moduleGraph.getModulesByFile(candidate);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\n\n/**\n * @internal\n */\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n) {\n const ts = require('typescript');\n return (\n file: string,\n ): {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n } => {\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 as any).name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node as any);\n if (hmrUpdateCode) {\n const className = (node as any).name.getText();\n classNames.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) {\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\nfunction markModuleSelfAccepting(mod: ModuleNode): ModuleNode {\n // support Vite 6\n if ('_clientModule' in mod) {\n (mod as any)['_clientModule'].isSelfAccepting = true;\n }\n\n return {\n ...mod,\n isSelfAccepting: true,\n } as ModuleNode;\n}\n\n/**\n * Removes leading / and query string from a url path\n * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss\n * @param id\n */\nfunction getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n // Defensive fallback: if the ID cannot be parsed as a URL (e.g., it\n // contains characters that are invalid in URLs but valid in file paths\n // on some platforms), strip the query string manually.\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AA4F9C,IAAM,6BAAa,IAAI,KAAK;AAC5B,SAAgB,yBACd,MACA,EACE,eACA,oBAKI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,IAAI,CAAC,GAAG;AACxD,eAAc,OAAO,eAAe;AACpC,kBAAiB,OAAO,eAAe;;AASzC,SAAgB,QAAQ,SAAmC;AACzD,kBAAiB,SAAS,OAAO,SAAS,cAAc;CACxD,MAAM,aAAa,SAAS,cAAc;CAE1C,IAAI,6BAA6B;CACjC,IAAI;CACJ,IAAI;;;;;CAMJ,MAAM,gBAAgB;EACpB,gBAAgB,qBAAqB,SAAS,SAAS;EACvD,eACE,SAAS,iBACT,QAAQ,IAAI,wBACZ,QAAQ,KAAK;EACf,uBAAuB,SAAS,yBAAyB;EACzD,mBAAmB,SAAS,qBAAqB,CAAC,YAAY;EAC9D,KAAK,SAAS;EACd,SAAS,SAAS,WAAW,EAAE;EAC/B;EACA,qBAAqB,SAAS,uBAAuB;EACrD,kBAAkB,SAAS,oBAAoB,EAAE;EACjD,aAAa,SAAS,eAAe;EACrC,iBAAiB,SAAS,mBAAmB;EAG7C,mBAAmB,KAAA;EACpB;CAED,IAAI;CACJ,IAAI,4BAA8D;CAElE,MAAM,KAAK,QAAQ,aAAa;CAChC,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,SAAA,QAAA,IAAA,aAAqC,UAAU,CAAC,CAAC,QAAQ,IAAI;CACnE,MAAM,mBAAmB,IAAI,iBAAiB;EAC5C,eAAe,cAAc;EAC7B,SAAS,cAAc;EACvB,YAAY,cAA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BAAqB,kBACvB,gBAAgB,sBAAsB,YAAY,EAAE,GACpD,EAAE;AACN,QAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;EACJ;;AAGH,SAAS,wBAAwB,KAA6B;AAE5D,KAAI,mBAAmB,IACpB,KAAY,iBAAiB,kBAAkB;AAGlD,QAAO;EACL,GAAG;EACH,iBAAiB;EAClB;;;;;;;AAQH,SAAS,oBAAoB,IAAoB;AAC/C,KAAI;AACF,SAAO,IAAI,IAAI,IAAI,mBAAmB,CAAC,SAAS,QAAQ,OAAO,GAAG;SAC5D;EAIN,MAAM,aAAa,GAAG,QAAQ,IAAI;AAElC,UADiB,cAAc,IAAI,GAAG,MAAM,GAAG,WAAW,GAAG,IAC7C,QAAQ,OAAO,GAAG"}
|
|
@@ -327,6 +327,7 @@ function angularCompilationPlugin(options = {}) {
|
|
|
327
327
|
}
|
|
328
328
|
const compilerPlugin = {
|
|
329
329
|
name: "@analogjs/vite-plugin-angular-compilation-api",
|
|
330
|
+
api: { getTsConfigPath: resolveTsConfigPath },
|
|
330
331
|
enforce: "pre",
|
|
331
332
|
async config(config, { command }) {
|
|
332
333
|
activateDeferredDebug(command);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path';\nimport { createRequire } from 'node:module';\nimport {\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularCompilation,\n SourceFileCache,\n angularFullVersion,\n} from '../utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from '../utils/debug.js';\nimport {\n getTsConfigPath,\n createTsConfigGetter,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from '../utils/plugin-config.js';\nimport { TsconfigResolver } from '../utils/tsconfig-resolver.js';\nimport { isRolldown } from '../utils/rolldown.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheetResult,\n registerStylesheetContent,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport type { StylePreprocessor } from '../style-preprocessor.js';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from '../analog-plugin-interop.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport type { EmitFileResult } from '../models.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n toAngularCompilationFileReplacements,\n mapTemplateUpdatesToFiles,\n refreshStylesheetRegistryForFile,\n DiagnosticModes,\n isTestWatchMode,\n} from '../utils/compilation-shared.js';\nimport { angularVitestPlugins } from '../angular-vitest-plugin.js';\nimport { buildOptimizerPlugin } from '../angular-build-optimizer-plugin.js';\nimport { jitPlugin } from '../angular-jit-plugin.js';\nimport { liveReloadPlugin } from '../live-reload-plugin.js';\nimport { virtualModulesPlugin } from '../virtual-modules-plugin.js';\nimport { encapsulationPlugin } from '../encapsulation-plugin.js';\nimport { nxFolderPlugin } from '../nx-folder-plugin.js';\nimport { routerPlugin } from '../router-plugin.js';\nimport { replaceFiles } from '../plugins/file-replacements.plugin.js';\nimport { cssExtensionStyleResolverPlugin } from '../utils/css-extension-resolver.js';\nimport { loadVirtualRawModule } from '../utils/virtual-resources.js';\n\nconst require = createRequire(import.meta.url);\nconst ts = require('typescript');\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n\n applyDebugOption(options.debug, options.workspaceRoot);\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options.tsconfig),\n workspaceRoot:\n options.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options.inlineStylesExtension ?? 'css',\n jit: options.jit ?? isTest,\n liveReload: options.liveReload ?? true,\n disableTypeChecking: options.disableTypeChecking ?? true,\n supportedBrowsers: options.supportedBrowsers ?? ['safari 15'],\n fileReplacements: options.fileReplacements ?? [],\n include: options.include ?? [],\n isAstroIntegration: process.env['ANALOG_ASTRO'] === 'true',\n };\n let resolvedConfig: ResolvedConfig;\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n let stylePreprocessor: StylePreprocessor | undefined;\n let transformFilter: TransformFilter | undefined;\n let externalizeStylesRequested = false;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n const classNames = new Map<string, string>();\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: pluginOptions.workspaceRoot,\n include: pluginOptions.include,\n liveReload: pluginOptions.liveReload,\n isTest,\n });\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n let testWatchMode = isTestWatchMode();\n\n function hasViteHmrTransport(): boolean {\n return resolvedConfig ? resolvedConfig.server.hmr !== false : true;\n }\n\n function shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(\n effectiveWatchMode &&\n pluginOptions.liveReload &&\n hasViteHmrTransport()\n );\n }\n\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableLiveReload() || externalizeStylesRequested);\n }\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n );\n }\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = tsconfigResolver.ensureIncludeCache();\n const cached = tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots = tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n cached.rootNames,\n expandedGraphRoots,\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string) => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string) => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ) {\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!pluginOptions.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n pluginOptions.fileReplacements,\n pluginOptions.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile: string | null,\n order: number,\n className: string | null,\n ) {\n const filename =\n resourceFile ??\n containingFile.replace(\n '.ts',\n `.${pluginOptions.inlineStylesExtension}`,\n );\n\n const preprocessed = preprocessStylesheetResult(\n data,\n filename,\n stylePreprocessor,\n {\n filename,\n containingFile,\n resourceFile,\n className,\n order,\n inline: !resourceFile,\n },\n );\n\n if (shouldEnableLiveReload() && className && containingFile) {\n classNames.set(normalizePath(containingFile), className as string);\n }\n\n if (shouldExternalizeStyles()) {\n const stylesheetId = registerStylesheetContent(\n stylesheetRegistry!,\n {\n code: preprocessed.code,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n containingFile,\n className: className as string | undefined,\n order,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n resourceFile: resourceFile ?? undefined,\n },\n );\n\n debugStyles('stylesheet deferred to Vite pipeline', {\n stylesheetId,\n resourceFile: resourceFile ?? '(inline)',\n });\n\n return stylesheetId;\n }\n\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n\n let stylesheetResult;\n try {\n stylesheetResult = await preprocessCSS(\n preprocessed.code,\n `${filename}?direct`,\n resolvedConfig,\n );\n } catch (e) {\n debugStyles('preprocessCSS error', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n error: String(e),\n });\n }\n\n return stylesheetResult?.code || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n (tsCompilerOptions: Record<string, unknown>) => {\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: pluginOptions.liveReload,\n viteHmr: hasViteHmrTransport(),\n externalizeStylesRequested,\n watchMode,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && resolvedConfig.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n },\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry?.registerExternalRequest(angularHash, key);\n\n if (stylesheetRegistry && stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n pluginOptions.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = await compilation.emitAffectedFiles();\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const templateUpdate = templateUpdates.get(normalizedFilename);\n\n if (templateUpdate) {\n classNames.set(normalizedFilename, templateUpdate.className);\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCode: templateUpdate?.code,\n hmrEligible: !!templateUpdate?.code,\n });\n }\n }\n\n async function performCompilation(config: ResolvedConfig, ids?: string[]) {\n let resolve: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previousLock;\n const integrations = await discoverAnalogIntegrations(config);\n stylePreprocessor = integrations.stylePreprocessor;\n transformFilter = integrations.transformFilter;\n tsconfigResolver.setIntegrationIncludes(integrations.include);\n externalizeStylesRequested = integrations.externalizeStyles;\n await performAngularCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n function isComponentStyleSheet(id: string): boolean {\n return id.includes('ngcomp=');\n }\n\n function getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n }\n\n function sendHMRComponentUpdate(server: ViteDevServer, id: string) {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n classNames.delete(id);\n }\n\n const compilerPlugin: Plugin = {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n enforce: 'pre' as const,\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n const isProd =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Mirror the\n // deps-optimizer wiring from `angular-vite-plugin.ts` so the\n // linker runs on `.[cm]?js` deps under both rolldown and esbuild.\n const useRolldown = isRolldown();\n const preliminaryTsConfigPath = resolveTsConfigPath();\n const compilerPluginOptions = {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit: pluginOptions.jit,\n incremental: watchMode,\n };\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angularCompilationPlugin()` factory level. Adding `style` globally caused\n // Tailwind v4's JS plugin resolver to pick the `style` exports of\n // packages such as `tailwindcss-primeui`, which then crashed Node's\n // ESM loader when it tried to import the resulting `.css` file.\n return {\n esbuild: undefined,\n oxc: undefined,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown\n ? {\n rolldownOptions: {\n plugins: [\n createRolldownCompilerPlugin(\n compilerPluginOptions,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }\n : {\n esbuildOptions: {\n plugins: [\n createCompilerPlugin(\n compilerPluginOptions,\n isTest,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }),\n },\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n\n stylesheetRegistry = new AnalogStylesheetRegistry();\n const integrations = await discoverAnalogIntegrations(config);\n integrations.configureStylesheetRegistry?.(stylesheetRegistry, {\n workspaceRoot: pluginOptions.workspaceRoot,\n });\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n\n if (isTest) {\n testWatchMode =\n !(config.server.watch === null) ||\n (config as any).test?.watch === true ||\n testWatchMode;\n }\n },\n configureServer(server) {\n viteServer = server;\n\n const invalidateCompilation = async () => {\n tsconfigResolver.invalidateAll();\n await performCompilation(resolvedConfig);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!isVitestVscode) {\n pendingCompilation = performCompilation(resolvedConfig);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(ctx) {\n if (isIgnoredHmrFile(ctx.file)) {\n debugHmr('ignored file change', { file: ctx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n debugHmr('TS file changed', { file: ctx.file, fileId });\n\n pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableLiveReload()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n }\n\n if (\n shouldEnableLiveReload() &&\n result?.hmrEligible &&\n classNames.get(fileId)\n ) {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), fileId),\n )}@${classNames.get(fileId)}`;\n\n debugHmr('sending component update', { relativeFileId });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n mod.isSelfAccepting = true;\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(ctx.file)) {\n debugHmr('template file changed', { file: ctx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(resolvedConfig);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('stylesheet file changed', { file: ctx.file });\n refreshStylesheetRegistryForFile(\n ctx.file,\n stylesheetRegistry,\n stylePreprocessor,\n );\n }\n\n return ctx.modules;\n },\n resolveId(id) {\n // Map angular component stylesheets\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath =\n stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n }\n\n return undefined;\n },\n async load(id) {\n // Virtual raw ids back JIT-emitted templateUrl/styleUrl imports.\n // virtual-modules-plugin resolves them; this plugin is the active\n // compilation plugin in compilation-API mode, so load must read the\n // backing file (jit=true is the test-mode default).\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Serve component stylesheets from registry\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles = stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n return componentStyles;\n }\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (isVitestVscode && !initialCompilation) {\n pendingCompilation = performCompilation(resolvedConfig);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(resolvedConfig, [id]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\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 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\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n classNames.clear();\n sourceFileCache.clear();\n tsconfigResolver.invalidateAll();\n stylesheetRegistry = undefined;\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n\n return [\n cssExtensionStyleResolverPlugin(),\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit: pluginOptions.jit }),\n compilerPlugin,\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz\n ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)\n : []),\n pluginOptions.jit &&\n jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit: pluginOptions.jit,\n }),\n routerPlugin(),\n nxFolderPlugin(),\n encapsulationPlugin(),\n ].filter(Boolean) as Plugin[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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BAAqB,KAAA;AACrB,wBAAqB;AACrB,wBAAqB;;EAExB;AAED,QAAO;EACL,iCAAiC;EACjC,aAAa,cAAc,kBAAkB,cAAc,cAAc;EACzE,qBAAqB,EAAE,KAAK,cAAc,KAAK,CAAC;EAChD;EACA,cAAc,cAAc,iBAAiB;GAAE;GAAY;GAAa,CAAC;EACzE,GAAI,UAAU,CAAC,eACX,sBAAsB,OAAO,YAAY,IAAI,cAAc,GAAG,CAAC,EAAE,IAAI,GACrE,EAAE;EACN,cAAc,OACZ,UAAU,EAAE,uBAAuB,cAAc,uBAAuB,CAAC;EAC3E,qBAAqB;GACnB,mBAAmB,cAAc;GACjC,KAAK,cAAc;GACpB,CAAC;EACF,cAAc;EACd,gBAAgB;EAChB,qBAAqB;EACtB,CAAC,OAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path';\nimport { createRequire } from 'node:module';\nimport {\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularCompilation,\n SourceFileCache,\n angularFullVersion,\n} from '../utils/devkit.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from '../utils/debug.js';\nimport {\n getTsConfigPath,\n createTsConfigGetter,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from '../utils/plugin-config.js';\nimport { TsconfigResolver } from '../utils/tsconfig-resolver.js';\nimport { isRolldown } from '../utils/rolldown.js';\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheetResult,\n registerStylesheetContent,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport type { StylePreprocessor } from '../style-preprocessor.js';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from '../analog-plugin-interop.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport type { EmitFileResult } from '../models.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n injectViteIgnoreForHmrMetadata,\n isIgnoredHmrFile,\n toAngularCompilationFileReplacements,\n mapTemplateUpdatesToFiles,\n refreshStylesheetRegistryForFile,\n DiagnosticModes,\n isTestWatchMode,\n} from '../utils/compilation-shared.js';\nimport { angularVitestPlugins } from '../angular-vitest-plugin.js';\nimport { buildOptimizerPlugin } from '../angular-build-optimizer-plugin.js';\nimport { jitPlugin } from '../angular-jit-plugin.js';\nimport { liveReloadPlugin } from '../live-reload-plugin.js';\nimport { virtualModulesPlugin } from '../virtual-modules-plugin.js';\nimport { encapsulationPlugin } from '../encapsulation-plugin.js';\nimport { nxFolderPlugin } from '../nx-folder-plugin.js';\nimport { routerPlugin } from '../router-plugin.js';\nimport { replaceFiles } from '../plugins/file-replacements.plugin.js';\nimport { cssExtensionStyleResolverPlugin } from '../utils/css-extension-resolver.js';\nimport { loadVirtualRawModule } from '../utils/virtual-resources.js';\n\nconst require = createRequire(import.meta.url);\nconst ts = require('typescript');\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n\n applyDebugOption(options.debug, options.workspaceRoot);\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const pluginOptions = {\n tsconfigGetter: createTsConfigGetter(options.tsconfig),\n workspaceRoot:\n options.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options.inlineStylesExtension ?? 'css',\n jit: options.jit ?? isTest,\n liveReload: options.liveReload ?? true,\n disableTypeChecking: options.disableTypeChecking ?? true,\n supportedBrowsers: options.supportedBrowsers ?? ['safari 15'],\n fileReplacements: options.fileReplacements ?? [],\n include: options.include ?? [],\n isAstroIntegration: process.env['ANALOG_ASTRO'] === 'true',\n };\n let resolvedConfig: ResolvedConfig;\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n let stylePreprocessor: StylePreprocessor | undefined;\n let transformFilter: TransformFilter | undefined;\n let externalizeStylesRequested = false;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n const classNames = new Map<string, string>();\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: pluginOptions.workspaceRoot,\n include: pluginOptions.include,\n liveReload: pluginOptions.liveReload,\n isTest,\n });\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n let testWatchMode = isTestWatchMode();\n\n function hasViteHmrTransport(): boolean {\n return resolvedConfig ? resolvedConfig.server.hmr !== false : true;\n }\n\n function shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n return !!(\n effectiveWatchMode &&\n pluginOptions.liveReload &&\n hasViteHmrTransport()\n );\n }\n\n function shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = isTest ? testWatchMode : watchMode;\n if (!effectiveWatchMode) return false;\n return !!(shouldEnableLiveReload() || externalizeStylesRequested);\n }\n\n function resolveTsConfigPath() {\n const tsconfigValue = pluginOptions.tsconfigGetter();\n return getTsConfigPath(\n tsConfigResolutionContext!.root,\n tsconfigValue,\n tsConfigResolutionContext!.isProd,\n isTest,\n tsConfigResolutionContext!.isLib,\n );\n }\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = tsconfigResolver.ensureIncludeCache();\n const cached = tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots = tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n cached.rootNames,\n expandedGraphRoots,\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string) => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string) => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ) {\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!pluginOptions.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n pluginOptions.fileReplacements,\n pluginOptions.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile: string | null,\n order: number,\n className: string | null,\n ) {\n const filename =\n resourceFile ??\n containingFile.replace(\n '.ts',\n `.${pluginOptions.inlineStylesExtension}`,\n );\n\n const preprocessed = preprocessStylesheetResult(\n data,\n filename,\n stylePreprocessor,\n {\n filename,\n containingFile,\n resourceFile,\n className,\n order,\n inline: !resourceFile,\n },\n );\n\n if (shouldEnableLiveReload() && className && containingFile) {\n classNames.set(normalizePath(containingFile), className as string);\n }\n\n if (shouldExternalizeStyles()) {\n const stylesheetId = registerStylesheetContent(\n stylesheetRegistry!,\n {\n code: preprocessed.code,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n containingFile,\n className: className as string | undefined,\n order,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n resourceFile: resourceFile ?? undefined,\n },\n );\n\n debugStyles('stylesheet deferred to Vite pipeline', {\n stylesheetId,\n resourceFile: resourceFile ?? '(inline)',\n });\n\n return stylesheetId;\n }\n\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n\n let stylesheetResult;\n try {\n stylesheetResult = await preprocessCSS(\n preprocessed.code,\n `${filename}?direct`,\n resolvedConfig,\n );\n } catch (e) {\n debugStyles('preprocessCSS error', {\n filename,\n resourceFile: resourceFile ?? '(inline)',\n error: String(e),\n });\n }\n\n return stylesheetResult?.code || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n (tsCompilerOptions: Record<string, unknown>) => {\n if (shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: pluginOptions.liveReload,\n viteHmr: hasViteHmrTransport(),\n externalizeStylesRequested,\n watchMode,\n shouldExternalize: shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && resolvedConfig.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n },\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry?.registerExternalRequest(angularHash, key);\n\n if (stylesheetRegistry && stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n pluginOptions.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = await compilation.emitAffectedFiles();\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const templateUpdate = templateUpdates.get(normalizedFilename);\n\n if (templateUpdate) {\n classNames.set(normalizedFilename, templateUpdate.className);\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCode: templateUpdate?.code,\n hmrEligible: !!templateUpdate?.code,\n });\n }\n }\n\n async function performCompilation(config: ResolvedConfig, ids?: string[]) {\n let resolve: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previousLock;\n const integrations = await discoverAnalogIntegrations(config);\n stylePreprocessor = integrations.stylePreprocessor;\n transformFilter = integrations.transformFilter;\n tsconfigResolver.setIntegrationIncludes(integrations.include);\n externalizeStylesRequested = integrations.externalizeStyles;\n await performAngularCompilation(config, ids);\n } finally {\n resolve!();\n }\n }\n\n function isComponentStyleSheet(id: string): boolean {\n return id.includes('ngcomp=');\n }\n\n function getFilenameFromPath(id: string): string {\n try {\n return new URL(id, 'http://localhost').pathname.replace(/^\\//, '');\n } catch {\n const queryIndex = id.indexOf('?');\n const pathname = queryIndex >= 0 ? id.slice(0, queryIndex) : id;\n return pathname.replace(/^\\//, '');\n }\n }\n\n function sendHMRComponentUpdate(server: ViteDevServer, id: string) {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n classNames.delete(id);\n }\n\n const compilerPlugin: Plugin = {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n api: { getTsConfigPath: resolveTsConfigPath },\n enforce: 'pre' as const,\n async config(config, { command }) {\n activateDeferredDebug(command);\n watchMode = command === 'serve';\n const isProd =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Mirror the\n // deps-optimizer wiring from `angular-vite-plugin.ts` so the\n // linker runs on `.[cm]?js` deps under both rolldown and esbuild.\n const useRolldown = isRolldown();\n const preliminaryTsConfigPath = resolveTsConfigPath();\n const compilerPluginOptions = {\n tsconfig: preliminaryTsConfigPath,\n sourcemap: !isProd,\n advancedOptimizations: isProd,\n jit: pluginOptions.jit,\n incremental: watchMode,\n };\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angularCompilationPlugin()` factory level. Adding `style` globally caused\n // Tailwind v4's JS plugin resolver to pick the `style` exports of\n // packages such as `tailwindcss-primeui`, which then crashed Node's\n // ESM loader when it tried to import the resulting `.css` file.\n return {\n esbuild: undefined,\n oxc: undefined,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown\n ? {\n rolldownOptions: {\n plugins: [\n createRolldownCompilerPlugin(\n compilerPluginOptions,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }\n : {\n esbuildOptions: {\n plugins: [\n createCompilerPlugin(\n compilerPluginOptions,\n isTest,\n !pluginOptions.isAstroIntegration,\n ),\n ],\n },\n }),\n },\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n\n stylesheetRegistry = new AnalogStylesheetRegistry();\n const integrations = await discoverAnalogIntegrations(config);\n integrations.configureStylesheetRegistry?.(stylesheetRegistry, {\n workspaceRoot: pluginOptions.workspaceRoot,\n });\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n\n if (isTest) {\n testWatchMode =\n !(config.server.watch === null) ||\n (config as any).test?.watch === true ||\n testWatchMode;\n }\n },\n configureServer(server) {\n viteServer = server;\n\n const invalidateCompilation = async () => {\n tsconfigResolver.invalidateAll();\n await performCompilation(resolvedConfig);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!isVitestVscode) {\n pendingCompilation = performCompilation(resolvedConfig);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(ctx) {\n if (isIgnoredHmrFile(ctx.file)) {\n debugHmr('ignored file change', { file: ctx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n debugHmr('TS file changed', { file: ctx.file, fileId });\n\n pendingCompilation = performCompilation(resolvedConfig, [fileId]);\n\n let result;\n\n if (shouldEnableLiveReload()) {\n await pendingCompilation;\n pendingCompilation = null;\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!classNames.get(fileId),\n });\n }\n\n if (\n shouldEnableLiveReload() &&\n result?.hmrEligible &&\n classNames.get(fileId)\n ) {\n const relativeFileId = `${normalizePath(\n relative(process.cwd(), fileId),\n )}@${classNames.get(fileId)}`;\n\n debugHmr('sending component update', { relativeFileId });\n sendHMRComponentUpdate(ctx.server, relativeFileId);\n\n return ctx.modules.map((mod) => {\n if (mod.id === ctx.file) {\n mod.isSelfAccepting = true;\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(ctx.file)) {\n debugHmr('template file changed', { file: ctx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(resolvedConfig);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(ctx.file)) {\n debugHmr('stylesheet file changed', { file: ctx.file });\n refreshStylesheetRegistryForFile(\n ctx.file,\n stylesheetRegistry,\n stylePreprocessor,\n );\n }\n\n return ctx.modules;\n },\n resolveId(id) {\n // Map angular component stylesheets\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath =\n stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n return id;\n }\n\n const componentStyles =\n stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n return componentStyles + new URL(id, 'http://localhost').search;\n }\n }\n\n return undefined;\n },\n async load(id) {\n // Virtual raw ids back JIT-emitted templateUrl/styleUrl imports.\n // virtual-modules-plugin resolves them; this plugin is the active\n // compilation plugin in compilation-API mode, so load must read the\n // backing file (jit=true is the test-mode default).\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Serve component stylesheets from registry\n if (isComponentStyleSheet(id)) {\n const filename = getFilenameFromPath(id);\n const componentStyles = stylesheetRegistry?.getServedContent(filename);\n if (componentStyles) {\n stylesheetRegistry?.registerActiveRequest(id);\n return componentStyles;\n }\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (isVitestVscode && !initialCompilation) {\n pendingCompilation = performCompilation(resolvedConfig);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (testWatchMode && invalidated) {\n pendingCompilation = performCompilation(resolvedConfig, [id]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\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 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\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n classNames.clear();\n sourceFileCache.clear();\n tsconfigResolver.invalidateAll();\n stylesheetRegistry = undefined;\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n\n return [\n cssExtensionStyleResolverPlugin(),\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit: pluginOptions.jit }),\n compilerPlugin,\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz\n ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)\n : []),\n pluginOptions.jit &&\n jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),\n buildOptimizerPlugin({\n supportedBrowsers: pluginOptions.supportedBrowsers,\n jit: pluginOptions.jit,\n }),\n routerPlugin(),\n nxFolderPlugin(),\n encapsulationPlugin(),\n ].filter(Boolean) as Plugin[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,IAAM,KADU,cAAc,OAAO,KAAK,IAAI,CAC3B,aAAa;;;;;;AAuBhC,SAAgB,yBACd,UAA2C,EAAE,EACnC;AACV,KACE,qBAAqB,UACrB,OAAO,6BAA6B,WAEpC,OAAM,IAAI,MACR,4JACD;AAGH,kBAAiB,QAAQ,OAAO,QAAQ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c,iBAAiB;GAAE;GAAY;GAAa,CAAC;EACzE,GAAI,UAAU,CAAC,eACX,sBAAsB,OAAO,YAAY,IAAI,cAAc,GAAG,CAAC,EAAE,IAAI,GACrE,EAAE;EACN,cAAc,OACZ,UAAU,EAAE,uBAAuB,cAAc,uBAAuB,CAAC;EAC3E,qBAAqB;GACnB,mBAAmB,cAAc;GACjC,KAAK,cAAc;GACpB,CAAC;EACF,cAAc;EACd,gBAAgB;EAChB,qBAAqB;EACtB,CAAC,OAAO,QAAQ"}
|
|
@@ -332,6 +332,7 @@ function fastCompilePlugin(pluginOptions) {
|
|
|
332
332
|
}
|
|
333
333
|
return {
|
|
334
334
|
name: "@analogjs/vite-plugin-angular-fast-compile",
|
|
335
|
+
api: { getTsConfigPath: resolveTsConfigPath },
|
|
335
336
|
enforce: "pre",
|
|
336
337
|
async config(config, { command }) {
|
|
337
338
|
watchMode = command === "serve";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fast-compile-plugin.js","names":[],"sources":["../../../src/lib/fast-compile-plugin.ts"],"sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { parseSync } from 'oxc-parser';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { normalizePath, Plugin, preprocessCSS, ResolvedConfig } from 'vite';\n\nimport {\n compile,\n scanFile,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n collectAllImports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n ANGULAR_DECORATOR_CALL_RE,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { VIRTUAL_RAW_PREFIX, toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n supportedBrowsers: string[];\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n}\n\n/**\n * Directory that `compilerOptions.paths` targets resolve against. Mirrors\n * TypeScript: `baseUrl` when set, otherwise the directory of the config\n * that declares `paths` (`pathsBasePath`, since `baseUrl` is optional\n * from TS 4.1).\n */\nexport function getPathsBasePath(\n options: { baseUrl?: string; pathsBasePath?: string } | undefined,\n fallback: string,\n): string {\n return options?.baseUrl ?? options?.pathsBasePath ?? fallback;\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n\n // fast-compile plugin state\n const registry: ComponentRegistry = new Map();\n const resourceToSource = new Map<string, string>();\n const scannedDtsPackages = new Set<string>();\n let projectRoot = '';\n let useDefineForClassFields = true;\n\n /**\n * Scan a file into the registry, then recursively walk its relative\n * `export *` / `export { … } from './x'` chain so any underlying\n * directive classes also land in the registry. Used both at\n * `buildStart` (for tsconfig path entries) and at dev time (file\n * `add` and `handleHotUpdate`) so newly added barrels stay in sync\n * without requiring a server restart.\n *\n * The `visited` set prevents infinite recursion within a single\n * top-level call. Each fresh scan should pass an empty set (so HMR\n * re-scans aren't blocked by buildStart's earlier visits).\n *\n * `fileContents`/`scanResults` are cold-start dedup caches scoped to a\n * single `initFastCompile` call. HMR/watcher callers must omit them so\n * an edited file is always re-read from disk.\n */\n async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n fileContents?: Map<string, string>,\n scanResults?: Map<string, ReturnType<typeof scanFile>>,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code =\n fileContents?.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents?.set(file, code);\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: failed to read %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return;\n }\n // Single parse shared by scanFile and collectRelativeReExports. On a\n // parse error each consumer re-parses on its own, preserving their\n // individual failure semantics (scanFile throws past its pre-filter;\n // collectRelativeReExports swallows and returns []).\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults?.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults?.set(file, entries);\n }\n for (const entry of entries) {\n // At buildStart we want stable registry entries (don't overwrite\n // an earlier scan with a barrel re-scan); HMR explicitly asks\n // for overwrite so updated metadata replaces stale entries.\n if (overwrite || !registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n // Collect every relative re-export specifier via OXC AST so\n // recursive scans can't trip over each other (a shared `/g` regex\n // would have its `lastIndex` reset by each recursive call and\n // silently skip half of an outer barrel's re-exports, which\n // previously left directives like `HlmRadioGroup` unregistered).\n const dir = dirname(file);\n for (const rel of collectRelativeReExports(code, file, program)) {\n // NodeNext-style libraries write `export * from './foo.js'`\n // even though the source is `./foo.ts`. Strip the ESM\n // extension before probing or the candidates would be\n // `foo.js.ts` / `foo.js/index.ts`, which never exist.\n const normalizedRel = rel.replace(/\\.(?:js|mjs)$/u, '');\n const reExportCandidates = [\n resolve(dir, normalizedRel + '.ts'),\n resolve(dir, normalizedRel, 'index.ts'),\n ];\n let resolved = false;\n for (const candidate of reExportCandidates) {\n try {\n await fsPromises.access(candidate);\n await scanBarrelExports(\n candidate,\n visited,\n overwrite,\n fileContents,\n scanResults,\n );\n resolved = true;\n break;\n } catch {\n // try next candidate\n }\n }\n if (!resolved && debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: %s re-export %s did not resolve to %o',\n file,\n rel,\n reExportCandidates,\n );\n }\n }\n }\n\n async function initFastCompile() {\n if (pluginOptions.jit) return; // JIT: no registry scan needed\n\n // Scan all source files to build the registry\n registry.clear();\n scannedDtsPackages.clear();\n const resolvedTsConfigPath = resolveTsConfigPath();\n projectRoot = dirname(resolvedTsConfigPath);\n const config = compilerCli.readConfiguration(resolvedTsConfigPath);\n useDefineForClassFields = config.options?.useDefineForClassFields ?? true;\n\n // Collect candidate files: tsconfig rootNames PLUS the entry points\n // named in `compilerOptions.paths`. App tsconfigs typically only\n // include the app's own sources, so workspace library entry barrels\n // (e.g. `HlmSelectImports = [HlmSelect, HlmSelectContent, ...] as\n // const`) live outside `rootNames` and would otherwise miss the\n // initial scan. The compiler then can't see that `HlmSelectImports`\n // is a tuple barrel and emits the bare identifier into the parent\n // component's `dependencies()` list, where Angular's runtime\n // silently drops it because arrays don't have a directive def.\n const candidates = new Set<string>(config.rootNames);\n const tsPaths = config.options?.paths;\n const baseUrl = getPathsBasePath(config.options, projectRoot);\n // Cold-start dedup caches shared by the three scan phases below\n // (candidates scan, walkImports, scanBarrelExports). Scoped to this\n // init call only — HMR/watcher re-scans must hit disk fresh.\n const fileContents = new Map<string, string>();\n const scanResults = new Map<string, ReturnType<typeof scanFile>>();\n if (tsPaths) {\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n // Skip wildcard patterns — entry barrels are normally exact\n // file paths like \"libs/helm/select/src/index.ts\".\n if (target.includes('*')) continue;\n candidates.add(resolve(baseUrl, target));\n }\n }\n }\n const results = await Promise.all(\n Array.from(candidates).map(async (file) => {\n try {\n const code = await fsPromises.readFile(file, 'utf-8');\n fileContents.set(file, code);\n const entries = scanFile(code, file);\n scanResults.set(file, entries);\n return entries;\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'initFastCompile: skipping unreadable %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return []; // Skip unreadable files\n }\n }),\n );\n\n for (const entries of results) {\n for (const entry of entries) {\n registry.set(entry.className, entry);\n }\n }\n\n // Walk the transitive import graph from the root files so the registry also\n // contains declarations that live in files not directly in tsconfig\n // `files`/`include` (transitively-imported app sources) and in workspace\n // libraries reached through wildcard `paths` (e.g. `@bitwarden/*`). Without\n // this, a non-standalone component's owning module can't classify its\n // declarations and `ɵɵsetComponentScope` is never emitted for it. Only\n // relative imports and `paths`-mapped (project/workspace) bare specifiers are\n // followed; true `node_modules` packages are left to the lazy `.d.ts` scanner.\n // Return *all* candidate base paths a bare specifier maps to. A `paths`\n // entry can list several fallback targets (e.g. a built `dist` path first\n // and the workspace `src` second); the caller probes them in order.\n const resolvePathSpecifier = (spec: string): string[] => {\n if (!tsPaths) return [];\n for (const [key, targets] of Object.entries(tsPaths)) {\n const list = targets as string[];\n if (key.endsWith('/*')) {\n const prefix = key.slice(0, -1);\n if (spec.startsWith(prefix)) {\n // `split('*').join(...)` substitutes the single tsconfig `*`\n // wildcard without `String.replace`'s first-match-only behavior or\n // `$`-pattern interpretation of the replacement.\n return list.map((t) =>\n resolve(baseUrl, t.split('*').join(spec.slice(prefix.length))),\n );\n }\n } else if (key === spec) {\n return list.map((t) => resolve(baseUrl, t));\n }\n }\n return [];\n };\n const probeToSource = async (base: string): Promise<string | null> => {\n const candidates = base.endsWith('.ts')\n ? [base]\n : [base + '.ts', resolve(base, 'index.ts')];\n for (const candidate of candidates) {\n try {\n await fsPromises.access(candidate);\n return candidate;\n } catch {\n // try next candidate\n }\n }\n return null;\n };\n // Memoize fs probes per absolute base path. The cache stores the\n // Promise (not the settled value) so concurrent walks racing on the\n // same base collapse into a single probe.\n const baseResolveCache = new Map<string, Promise<string | null>>();\n const resolveToSource = (base: string): Promise<string | null> => {\n let probe = baseResolveCache.get(base);\n if (!probe) {\n probe = probeToSource(base);\n baseResolveCache.set(base, probe);\n }\n return probe;\n };\n // Probe each `paths` target in order; first one that resolves to source wins.\n const resolveFirstSource = async (\n bases: string[],\n ): Promise<string | null> => {\n for (const base of bases) {\n const resolved = await resolveToSource(base);\n if (resolved) return resolved;\n }\n return null;\n };\n const importWalkVisited = new Set<string>();\n // Paths-mapped resolution doesn't depend on the importer, so bare\n // specifiers can be memoized by their raw text. Relative specifiers\n // must NOT be — the same './foo' resolves differently per directory.\n const bareSpecResolveCache = new Map<string, Promise<string | null>>();\n const walkImports = async (file: string): Promise<void> => {\n if (importWalkVisited.has(file)) return;\n importWalkVisited.add(file);\n let code: string;\n try {\n code =\n fileContents.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents.set(file, code);\n } catch {\n return;\n }\n // Single parse shared by scanFile, collectImportedPackages, and\n // collectAllImports. On a parse error each consumer re-parses on\n // its own, preserving their individual failure semantics.\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults.set(file, entries);\n }\n for (const entry of entries) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n // Pre-scan the `.d.ts` of every external package this file imports (and,\n // transitively, packages those packages' NgModules re-export — e.g.\n // BrowserModule → CommonModule → NgIf). Doing this at buildStart means the\n // registry is complete before any component transforms, so non-standalone\n // component scope resolves regardless of file transform order.\n for (const pkg of collectImportedPackages(code, file, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n try {\n for (const entry of scanPackageDts(\n pkg,\n projectRoot,\n scannedDtsPackages,\n )) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n } catch {\n // Package may not have .d.ts or not be Angular\n }\n }\n const dir = dirname(file);\n const targets = await Promise.all(\n collectAllImports(code, file, program).map((spec) => {\n if (spec.startsWith('.')) {\n return resolveToSource(\n resolve(dir, spec.replace(/\\.(?:js|mjs)$/u, '')),\n );\n }\n let resolved = bareSpecResolveCache.get(spec);\n if (!resolved) {\n resolved = resolveFirstSource(resolvePathSpecifier(spec));\n bareSpecResolveCache.set(spec, resolved);\n }\n return resolved;\n }),\n );\n await Promise.all(\n targets.filter((t): t is string => !!t).map((t) => walkImports(t)),\n );\n };\n await Promise.all(config.rootNames.map((file) => walkImports(file)));\n\n // Library barrels typically `export * from './lib/...'` rather than\n // declaring directives directly, so the entry file alone gives us\n // the tuple consts but not the directive classes they reference.\n // Walk the relative `export *` chain so the underlying classes also\n // land in the registry. Use a SHARED visited set across all\n // barrels so recursive walks don't double-scan a file that's\n // re-exported from multiple entry points.\n const buildStartVisited = new Set<string>();\n if (tsPaths) {\n const barrelCandidates: string[] = [];\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n if (target.includes('*')) continue;\n barrelCandidates.push(resolve(baseUrl, target));\n }\n }\n await Promise.all(\n barrelCandidates.map((c) =>\n scanBarrelExports(\n c,\n buildStartVisited,\n false,\n fileContents,\n scanResults,\n ),\n ),\n );\n }\n debugRegistry(\n 'initFastCompile done: %d entries from %d candidate files',\n registry.size,\n candidates.size,\n );\n }\n\n function ensureDtsRegistryForSource(\n code: string,\n id: string,\n program?: ReturnType<typeof parseSync>['program'],\n ) {\n for (const pkg of collectImportedPackages(code, id, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot, scannedDtsPackages);\n for (const entry of dtsEntries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n } catch {\n // Package may not have .d.ts files or may not be Angular\n }\n }\n }\n\n async function handleFastCompileTransform(\n code: string,\n id: string,\n ): Promise<{ code: string; map: any } | undefined> {\n if (!ANGULAR_DECORATOR_CALL_RE.test(code)) {\n // Non-Angular file — strip TS-only syntax ourselves so barrels\n // like `export { Foo, type Bar } from './x'` and other TS-only\n // forms don't leak unstripped to Rolldown. In rolldown-vite the\n // built-in `vite:oxc` strip is registered as a Rust-side native\n // plugin (`viteTransformPlugin` from `rolldown/experimental`); if\n // its hook-filter treats files our `transform.filter.id.include`\n // claimed as already-handled, no JS-side fallback runs and raw\n // TS reaches the parser → `SyntaxError: Unexpected identifier`.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(code, id, {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(code, id, {\n loader: 'ts',\n sourcemap: true,\n });\n return { code: stripped.code, map: stripped.map };\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n // Strip TypeScript-only syntax (e.g. `readonly`, parameter property\n // modifiers, type annotations on fields) so the output is valid JS\n // for Rolldown. `angularVitestSourcemapPlugin` normally runs this\n // strip downstream in tests, but it is intentionally skipped on\n // StackBlitz / WebContainer — and the production build pipeline\n // does not register it either — so the JIT path must self-strip\n // to stay safe across environments.\n //\n // Pass the jitTransform map as `inMap` so OXC/esbuild emit a map\n // composed with the original `.ts` source — without this, debug\n // stack traces and breakpoints land on the wrong lines once the\n // strip removes any TS-only token. `jitTransform` returns\n // `map: null` for files with no Angular class (no edits made);\n // passing that to OXC/esbuild as `inMap` throws, so coerce to\n // `undefined` in that case.\n const inMap = result.map ?? undefined;\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n inMap,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n inMap,\n );\n return { code: stripped.code, map: stripped.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation.\n // `styleExtensions` carries the source extension of each inlined external\n // style so it can be preprocessed by its own file type (e.g. an external\n // `.scss` styleUrl) regardless of the `inlineStylesExtension` option.\n const inlined = await inlineResourceUrls(code, id);\n code = inlined.code;\n const { styleExtensions } = inlined;\n\n // Track inlined resources for HMR. `compile()` only reports resources it\n // reads through its own fallback (a templateUrl/styleUrl the inliner did\n // NOT already inline), so files inlined here must be recorded here or a\n // later edit to them never invalidates the owning module.\n for (const dep of inlined.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Single OXC parse of the post-inline source, shared by every AST\n // consumer below. `inlineResourceUrls` parsed the PRE-inline string,\n // so its program can never be reused here.\n const { program: oxcProgram } = parseSync(id, code);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less). Run\n // whenever a style needs a non-`css` preprocessor — either the configured\n // `inlineStylesExtension` for truly-inline styles, or an external styleUrl's\n // own extension.\n let resolvedStyles: Map<string, string> | undefined;\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n const inlineExt = pluginOptions.inlineStylesExtension;\n const styleNeedsPreprocess = (ext: string) => ext !== '' && ext !== 'css';\n\n if (styleNeedsPreprocess(inlineExt) || styleExtensions.size > 0) {\n const styleStrings = extractInlineStyles(code, id, oxcProgram);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n // External styleUrls are preprocessed by their own extension; truly\n // inline `styles: [...]` fall back to `inlineStylesExtension`.\n const ext = styleExtensions.get(i) ?? inlineExt;\n if (!styleNeedsPreprocess(ext)) continue;\n try {\n const fakePath = id.replace(/\\.ts$/, `.inline-${i}.${ext}`);\n const processed = await preprocessCSS(\n styleStrings[i],\n fakePath,\n resolvedConfig,\n );\n resolvedInlineStyles.set(i, processed.code);\n } catch (e) {\n if (debugCompile.enabled) {\n debugCompile(\n 'inline style #%d preprocessing failed in %s: %s',\n i,\n id,\n (e as Error)?.message,\n );\n }\n // Skip styles that can't be preprocessed\n }\n }\n if (resolvedInlineStyles.size === 0) resolvedInlineStyles = undefined;\n }\n }\n\n ensureDtsRegistryForSource(code, id, oxcProgram);\n\n // Merge registries contributed through `analog.setup()` into this\n // compile's lookup view. Out-of-tree compilers register directive\n // metadata for classes fastCompile can't reach through its\n // tsconfig-driven scan (e.g. `.tsrx` files compiled by `@tsrx/analog`).\n // Without this merge, a TS `@Component({ imports: [X] })` that\n // references such a class hits `_unresolved-${className}` as its\n // selector and the tag never matches at runtime.\n let compileRegistry: ComponentRegistry = registry;\n if (componentRegistries.some((external) => external.size > 0)) {\n compileRegistry = new Map(registry);\n for (const external of componentRegistries) {\n for (const [k, v] of external) compileRegistry.set(k, v);\n }\n }\n\n const result = compile(code, id, {\n registry: compileRegistry,\n resolvedStyles,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\n oxcProgram,\n });\n\n // Track resource dependencies for HMR\n for (const dep of result.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Strip TypeScript-only syntax and compose the compiler map with the\n // final generated code so downstream breakpoints map back to the source.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n result.map,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n result.map,\n );\n let outputCode = stripped.code;\n\n // Append HMR code in dev mode\n if (watchMode && pluginOptions.liveReload) {\n const fileDeclarations = [...registry.values()].filter(\n (e) => e.fileName === id,\n );\n if (fileDeclarations.length > 0) {\n const localDepClassNames = fileDeclarations.map((e) => e.className);\n outputCode += generateHmrCode(fileDeclarations, localDepClassNames);\n }\n }\n\n return { code: outputCode, map: stripped.map };\n }\n\n function resolveTsConfigPath() {\n const { root, isProd, isLib } = tsConfigResolutionContext!;\n return getTsConfigPath(\n root,\n pluginOptions.tsconfigGetter(),\n isProd,\n pluginOptions.isTest,\n isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-fast-compile',\n enforce: 'pre' as const,\n async config(config, { command }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd,\n jit: pluginOptions.jit,\n watchMode,\n isTest: pluginOptions.isTest,\n isAstroIntegration: pluginOptions.isAstroIntegration,\n });\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angular()` factory level (which is the only public entry point\n // that wires this plugin in).\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n },\n configureServer(server) {\n // Watch for new .ts files and scan them into the registry. Use\n // the barrel-aware scanner so a newly added re-export entry\n // (`export * from './x'`) also expands its underlying directive\n // classes — otherwise the registry stays stale until restart.\n server.watcher.on('add', async (filePath) => {\n if (\n filePath.endsWith('.ts') &&\n !filePath.endsWith('.spec.ts') &&\n !filePath.endsWith('.d.ts')\n ) {\n await scanBarrelExports(filePath, new Set(), true);\n }\n });\n },\n async buildStart() {\n await initFastCompile();\n },\n closeBundle() {\n if (!watchMode) {\n releaseCssPreprocessorWorkers();\n }\n },\n async handleHotUpdate(ctx) {\n // Resource file changes → invalidate parent .ts module\n if (resourceToSource.has(ctx.file)) {\n const parentSource = resourceToSource.get(ctx.file)!;\n const parentModule = ctx.server.moduleGraph.getModuleById(parentSource);\n if (parentModule) {\n return [parentModule];\n }\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n\n // Remove old entries from this file\n const oldEntries = [...registry.entries()]\n .filter(([_, v]) => v.fileName === fileId)\n .map(([k]) => k);\n for (const key of oldEntries) {\n registry.delete(key);\n }\n\n // Rescan the changed file via the barrel-aware scanner so an\n // edited barrel re-export picks up newly-referenced files.\n // Pass overwrite=true so updated metadata replaces stale\n // entries from the previous scan.\n await scanBarrelExports(fileId, new Set(), true);\n }\n\n // Let Vite handle the rest — the transform hook will recompile\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (pluginOptions.jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n return undefined;\n },\n async load(id) {\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: module-runner can skip resolveId, so the bare\n // ?inline query reaches load. Mark safe and let Vite handle it.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n // `?raw` ids already carry Vite's native raw-loader output\n // (`export default \"<source>\"`). Recompiling them as Angular/TS\n // would strip that default export, so leave them to Vite (#2356).\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (transformFilter && !transformFilter(code, id)) {\n return;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],"sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { parseSync } from 'oxc-parser';\nimport * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport { normalizePath, Plugin, preprocessCSS, ResolvedConfig } from 'vite';\n\nimport {\n compile,\n scanFile,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n collectAllImports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n ANGULAR_DECORATOR_CALL_RE,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { VIRTUAL_RAW_PREFIX, toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadVirtualRawModule,\n rewriteHtmlRawImport,\n} from './utils/virtual-resources.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport {\n discoverAnalogIntegrations,\n type ComponentRegistryEntries,\n type TransformFilter,\n} from './analog-plugin-interop.js';\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n supportedBrowsers: string[];\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n}\n\n/**\n * Directory that `compilerOptions.paths` targets resolve against. Mirrors\n * TypeScript: `baseUrl` when set, otherwise the directory of the config\n * that declares `paths` (`pathsBasePath`, since `baseUrl` is optional\n * from TS 4.1).\n */\nexport function getPathsBasePath(\n options: { baseUrl?: string; pathsBasePath?: string } | undefined,\n fallback: string,\n): string {\n return options?.baseUrl ?? options?.pathsBasePath ?? fallback;\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let componentRegistries: ComponentRegistryEntries[] = [];\n let tsConfigResolutionContext: TsConfigResolutionContext | null = null;\n let watchMode = false;\n\n // fast-compile plugin state\n const registry: ComponentRegistry = new Map();\n const resourceToSource = new Map<string, string>();\n const scannedDtsPackages = new Set<string>();\n let projectRoot = '';\n let useDefineForClassFields = true;\n\n /**\n * Scan a file into the registry, then recursively walk its relative\n * `export *` / `export { … } from './x'` chain so any underlying\n * directive classes also land in the registry. Used both at\n * `buildStart` (for tsconfig path entries) and at dev time (file\n * `add` and `handleHotUpdate`) so newly added barrels stay in sync\n * without requiring a server restart.\n *\n * The `visited` set prevents infinite recursion within a single\n * top-level call. Each fresh scan should pass an empty set (so HMR\n * re-scans aren't blocked by buildStart's earlier visits).\n *\n * `fileContents`/`scanResults` are cold-start dedup caches scoped to a\n * single `initFastCompile` call. HMR/watcher callers must omit them so\n * an edited file is always re-read from disk.\n */\n async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n fileContents?: Map<string, string>,\n scanResults?: Map<string, ReturnType<typeof scanFile>>,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code =\n fileContents?.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents?.set(file, code);\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: failed to read %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return;\n }\n // Single parse shared by scanFile and collectRelativeReExports. On a\n // parse error each consumer re-parses on its own, preserving their\n // individual failure semantics (scanFile throws past its pre-filter;\n // collectRelativeReExports swallows and returns []).\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults?.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults?.set(file, entries);\n }\n for (const entry of entries) {\n // At buildStart we want stable registry entries (don't overwrite\n // an earlier scan with a barrel re-scan); HMR explicitly asks\n // for overwrite so updated metadata replaces stale entries.\n if (overwrite || !registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n // Collect every relative re-export specifier via OXC AST so\n // recursive scans can't trip over each other (a shared `/g` regex\n // would have its `lastIndex` reset by each recursive call and\n // silently skip half of an outer barrel's re-exports, which\n // previously left directives like `HlmRadioGroup` unregistered).\n const dir = dirname(file);\n for (const rel of collectRelativeReExports(code, file, program)) {\n // NodeNext-style libraries write `export * from './foo.js'`\n // even though the source is `./foo.ts`. Strip the ESM\n // extension before probing or the candidates would be\n // `foo.js.ts` / `foo.js/index.ts`, which never exist.\n const normalizedRel = rel.replace(/\\.(?:js|mjs)$/u, '');\n const reExportCandidates = [\n resolve(dir, normalizedRel + '.ts'),\n resolve(dir, normalizedRel, 'index.ts'),\n ];\n let resolved = false;\n for (const candidate of reExportCandidates) {\n try {\n await fsPromises.access(candidate);\n await scanBarrelExports(\n candidate,\n visited,\n overwrite,\n fileContents,\n scanResults,\n );\n resolved = true;\n break;\n } catch {\n // try next candidate\n }\n }\n if (!resolved && debugRegistry.enabled) {\n debugRegistry(\n 'scanBarrelExports: %s re-export %s did not resolve to %o',\n file,\n rel,\n reExportCandidates,\n );\n }\n }\n }\n\n async function initFastCompile() {\n if (pluginOptions.jit) return; // JIT: no registry scan needed\n\n // Scan all source files to build the registry\n registry.clear();\n scannedDtsPackages.clear();\n const resolvedTsConfigPath = resolveTsConfigPath();\n projectRoot = dirname(resolvedTsConfigPath);\n const config = compilerCli.readConfiguration(resolvedTsConfigPath);\n useDefineForClassFields = config.options?.useDefineForClassFields ?? true;\n\n // Collect candidate files: tsconfig rootNames PLUS the entry points\n // named in `compilerOptions.paths`. App tsconfigs typically only\n // include the app's own sources, so workspace library entry barrels\n // (e.g. `HlmSelectImports = [HlmSelect, HlmSelectContent, ...] as\n // const`) live outside `rootNames` and would otherwise miss the\n // initial scan. The compiler then can't see that `HlmSelectImports`\n // is a tuple barrel and emits the bare identifier into the parent\n // component's `dependencies()` list, where Angular's runtime\n // silently drops it because arrays don't have a directive def.\n const candidates = new Set<string>(config.rootNames);\n const tsPaths = config.options?.paths;\n const baseUrl = getPathsBasePath(config.options, projectRoot);\n // Cold-start dedup caches shared by the three scan phases below\n // (candidates scan, walkImports, scanBarrelExports). Scoped to this\n // init call only — HMR/watcher re-scans must hit disk fresh.\n const fileContents = new Map<string, string>();\n const scanResults = new Map<string, ReturnType<typeof scanFile>>();\n if (tsPaths) {\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n // Skip wildcard patterns — entry barrels are normally exact\n // file paths like \"libs/helm/select/src/index.ts\".\n if (target.includes('*')) continue;\n candidates.add(resolve(baseUrl, target));\n }\n }\n }\n const results = await Promise.all(\n Array.from(candidates).map(async (file) => {\n try {\n const code = await fsPromises.readFile(file, 'utf-8');\n fileContents.set(file, code);\n const entries = scanFile(code, file);\n scanResults.set(file, entries);\n return entries;\n } catch (e) {\n if (debugRegistry.enabled) {\n debugRegistry(\n 'initFastCompile: skipping unreadable %s: %s',\n file,\n (e as Error)?.message,\n );\n }\n return []; // Skip unreadable files\n }\n }),\n );\n\n for (const entries of results) {\n for (const entry of entries) {\n registry.set(entry.className, entry);\n }\n }\n\n // Walk the transitive import graph from the root files so the registry also\n // contains declarations that live in files not directly in tsconfig\n // `files`/`include` (transitively-imported app sources) and in workspace\n // libraries reached through wildcard `paths` (e.g. `@bitwarden/*`). Without\n // this, a non-standalone component's owning module can't classify its\n // declarations and `ɵɵsetComponentScope` is never emitted for it. Only\n // relative imports and `paths`-mapped (project/workspace) bare specifiers are\n // followed; true `node_modules` packages are left to the lazy `.d.ts` scanner.\n // Return *all* candidate base paths a bare specifier maps to. A `paths`\n // entry can list several fallback targets (e.g. a built `dist` path first\n // and the workspace `src` second); the caller probes them in order.\n const resolvePathSpecifier = (spec: string): string[] => {\n if (!tsPaths) return [];\n for (const [key, targets] of Object.entries(tsPaths)) {\n const list = targets as string[];\n if (key.endsWith('/*')) {\n const prefix = key.slice(0, -1);\n if (spec.startsWith(prefix)) {\n // `split('*').join(...)` substitutes the single tsconfig `*`\n // wildcard without `String.replace`'s first-match-only behavior or\n // `$`-pattern interpretation of the replacement.\n return list.map((t) =>\n resolve(baseUrl, t.split('*').join(spec.slice(prefix.length))),\n );\n }\n } else if (key === spec) {\n return list.map((t) => resolve(baseUrl, t));\n }\n }\n return [];\n };\n const probeToSource = async (base: string): Promise<string | null> => {\n const candidates = base.endsWith('.ts')\n ? [base]\n : [base + '.ts', resolve(base, 'index.ts')];\n for (const candidate of candidates) {\n try {\n await fsPromises.access(candidate);\n return candidate;\n } catch {\n // try next candidate\n }\n }\n return null;\n };\n // Memoize fs probes per absolute base path. The cache stores the\n // Promise (not the settled value) so concurrent walks racing on the\n // same base collapse into a single probe.\n const baseResolveCache = new Map<string, Promise<string | null>>();\n const resolveToSource = (base: string): Promise<string | null> => {\n let probe = baseResolveCache.get(base);\n if (!probe) {\n probe = probeToSource(base);\n baseResolveCache.set(base, probe);\n }\n return probe;\n };\n // Probe each `paths` target in order; first one that resolves to source wins.\n const resolveFirstSource = async (\n bases: string[],\n ): Promise<string | null> => {\n for (const base of bases) {\n const resolved = await resolveToSource(base);\n if (resolved) return resolved;\n }\n return null;\n };\n const importWalkVisited = new Set<string>();\n // Paths-mapped resolution doesn't depend on the importer, so bare\n // specifiers can be memoized by their raw text. Relative specifiers\n // must NOT be — the same './foo' resolves differently per directory.\n const bareSpecResolveCache = new Map<string, Promise<string | null>>();\n const walkImports = async (file: string): Promise<void> => {\n if (importWalkVisited.has(file)) return;\n importWalkVisited.add(file);\n let code: string;\n try {\n code =\n fileContents.get(file) ?? (await fsPromises.readFile(file, 'utf-8'));\n fileContents.set(file, code);\n } catch {\n return;\n }\n // Single parse shared by scanFile, collectImportedPackages, and\n // collectAllImports. On a parse error each consumer re-parses on\n // its own, preserving their individual failure semantics.\n let program: ReturnType<typeof parseSync>['program'] | undefined;\n try {\n program = parseSync(file, code).program;\n } catch {\n program = undefined;\n }\n let entries = scanResults.get(file);\n if (!entries) {\n entries = scanFile(code, file, program);\n scanResults.set(file, entries);\n }\n for (const entry of entries) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n // Pre-scan the `.d.ts` of every external package this file imports (and,\n // transitively, packages those packages' NgModules re-export — e.g.\n // BrowserModule → CommonModule → NgIf). Doing this at buildStart means the\n // registry is complete before any component transforms, so non-standalone\n // component scope resolves regardless of file transform order.\n for (const pkg of collectImportedPackages(code, file, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n try {\n for (const entry of scanPackageDts(\n pkg,\n projectRoot,\n scannedDtsPackages,\n )) {\n if (!registry.has(entry.className))\n registry.set(entry.className, entry);\n }\n } catch {\n // Package may not have .d.ts or not be Angular\n }\n }\n const dir = dirname(file);\n const targets = await Promise.all(\n collectAllImports(code, file, program).map((spec) => {\n if (spec.startsWith('.')) {\n return resolveToSource(\n resolve(dir, spec.replace(/\\.(?:js|mjs)$/u, '')),\n );\n }\n let resolved = bareSpecResolveCache.get(spec);\n if (!resolved) {\n resolved = resolveFirstSource(resolvePathSpecifier(spec));\n bareSpecResolveCache.set(spec, resolved);\n }\n return resolved;\n }),\n );\n await Promise.all(\n targets.filter((t): t is string => !!t).map((t) => walkImports(t)),\n );\n };\n await Promise.all(config.rootNames.map((file) => walkImports(file)));\n\n // Library barrels typically `export * from './lib/...'` rather than\n // declaring directives directly, so the entry file alone gives us\n // the tuple consts but not the directive classes they reference.\n // Walk the relative `export *` chain so the underlying classes also\n // land in the registry. Use a SHARED visited set across all\n // barrels so recursive walks don't double-scan a file that's\n // re-exported from multiple entry points.\n const buildStartVisited = new Set<string>();\n if (tsPaths) {\n const barrelCandidates: string[] = [];\n for (const targets of Object.values(tsPaths)) {\n for (const target of targets as string[]) {\n if (target.includes('*')) continue;\n barrelCandidates.push(resolve(baseUrl, target));\n }\n }\n await Promise.all(\n barrelCandidates.map((c) =>\n scanBarrelExports(\n c,\n buildStartVisited,\n false,\n fileContents,\n scanResults,\n ),\n ),\n );\n }\n debugRegistry(\n 'initFastCompile done: %d entries from %d candidate files',\n registry.size,\n candidates.size,\n );\n }\n\n function ensureDtsRegistryForSource(\n code: string,\n id: string,\n program?: ReturnType<typeof parseSync>['program'],\n ) {\n for (const pkg of collectImportedPackages(code, id, program)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot, scannedDtsPackages);\n for (const entry of dtsEntries) {\n if (!registry.has(entry.className)) {\n registry.set(entry.className, entry);\n }\n }\n } catch {\n // Package may not have .d.ts files or may not be Angular\n }\n }\n }\n\n async function handleFastCompileTransform(\n code: string,\n id: string,\n ): Promise<{ code: string; map: any } | undefined> {\n if (!ANGULAR_DECORATOR_CALL_RE.test(code)) {\n // Non-Angular file — strip TS-only syntax ourselves so barrels\n // like `export { Foo, type Bar } from './x'` and other TS-only\n // forms don't leak unstripped to Rolldown. In rolldown-vite the\n // built-in `vite:oxc` strip is registered as a Rust-side native\n // plugin (`viteTransformPlugin` from `rolldown/experimental`); if\n // its hook-filter treats files our `transform.filter.id.include`\n // claimed as already-handled, no JS-side fallback runs and raw\n // TS reaches the parser → `SyntaxError: Unexpected identifier`.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(code, id, {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(code, id, {\n loader: 'ts',\n sourcemap: true,\n });\n return { code: stripped.code, map: stripped.map };\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n // Strip TypeScript-only syntax (e.g. `readonly`, parameter property\n // modifiers, type annotations on fields) so the output is valid JS\n // for Rolldown. `angularVitestSourcemapPlugin` normally runs this\n // strip downstream in tests, but it is intentionally skipped on\n // StackBlitz / WebContainer — and the production build pipeline\n // does not register it either — so the JIT path must self-strip\n // to stay safe across environments.\n //\n // Pass the jitTransform map as `inMap` so OXC/esbuild emit a map\n // composed with the original `.ts` source — without this, debug\n // stack traces and breakpoints land on the wrong lines once the\n // strip removes any TS-only token. `jitTransform` returns\n // `map: null` for files with no Angular class (no edits made);\n // passing that to OXC/esbuild as `inMap` throws, so coerce to\n // `undefined` in that case.\n const inMap = result.map ?? undefined;\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n inMap,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n inMap,\n );\n return { code: stripped.code, map: stripped.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation.\n // `styleExtensions` carries the source extension of each inlined external\n // style so it can be preprocessed by its own file type (e.g. an external\n // `.scss` styleUrl) regardless of the `inlineStylesExtension` option.\n const inlined = await inlineResourceUrls(code, id);\n code = inlined.code;\n const { styleExtensions } = inlined;\n\n // Track inlined resources for HMR. `compile()` only reports resources it\n // reads through its own fallback (a templateUrl/styleUrl the inliner did\n // NOT already inline), so files inlined here must be recorded here or a\n // later edit to them never invalidates the owning module.\n for (const dep of inlined.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Single OXC parse of the post-inline source, shared by every AST\n // consumer below. `inlineResourceUrls` parsed the PRE-inline string,\n // so its program can never be reused here.\n const { program: oxcProgram } = parseSync(id, code);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less). Run\n // whenever a style needs a non-`css` preprocessor — either the configured\n // `inlineStylesExtension` for truly-inline styles, or an external styleUrl's\n // own extension.\n let resolvedStyles: Map<string, string> | undefined;\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n const inlineExt = pluginOptions.inlineStylesExtension;\n const styleNeedsPreprocess = (ext: string) => ext !== '' && ext !== 'css';\n\n if (styleNeedsPreprocess(inlineExt) || styleExtensions.size > 0) {\n const styleStrings = extractInlineStyles(code, id, oxcProgram);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n // External styleUrls are preprocessed by their own extension; truly\n // inline `styles: [...]` fall back to `inlineStylesExtension`.\n const ext = styleExtensions.get(i) ?? inlineExt;\n if (!styleNeedsPreprocess(ext)) continue;\n try {\n const fakePath = id.replace(/\\.ts$/, `.inline-${i}.${ext}`);\n const processed = await preprocessCSS(\n styleStrings[i],\n fakePath,\n resolvedConfig,\n );\n resolvedInlineStyles.set(i, processed.code);\n } catch (e) {\n if (debugCompile.enabled) {\n debugCompile(\n 'inline style #%d preprocessing failed in %s: %s',\n i,\n id,\n (e as Error)?.message,\n );\n }\n // Skip styles that can't be preprocessed\n }\n }\n if (resolvedInlineStyles.size === 0) resolvedInlineStyles = undefined;\n }\n }\n\n ensureDtsRegistryForSource(code, id, oxcProgram);\n\n // Merge registries contributed through `analog.setup()` into this\n // compile's lookup view. Out-of-tree compilers register directive\n // metadata for classes fastCompile can't reach through its\n // tsconfig-driven scan (e.g. `.tsrx` files compiled by `@tsrx/analog`).\n // Without this merge, a TS `@Component({ imports: [X] })` that\n // references such a class hits `_unresolved-${className}` as its\n // selector and the tag never matches at runtime.\n let compileRegistry: ComponentRegistry = registry;\n if (componentRegistries.some((external) => external.size > 0)) {\n compileRegistry = new Map(registry);\n for (const external of componentRegistries) {\n for (const [k, v] of external) compileRegistry.set(k, v);\n }\n }\n\n const result = compile(code, id, {\n registry: compileRegistry,\n resolvedStyles,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\n oxcProgram,\n });\n\n // Track resource dependencies for HMR\n for (const dep of result.resourceDependencies) {\n resourceToSource.set(dep, id);\n }\n\n // Strip TypeScript-only syntax and compose the compiler map with the\n // final generated code so downstream breakpoints map back to the source.\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(\n result.code,\n id,\n {\n lang: 'ts',\n sourcemap: true,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n },\n result.map,\n )\n : await vite.transformWithEsbuild(\n result.code,\n id,\n { loader: 'ts', sourcemap: true },\n result.map,\n );\n let outputCode = stripped.code;\n\n // Append HMR code in dev mode\n if (watchMode && pluginOptions.liveReload) {\n const fileDeclarations = [...registry.values()].filter(\n (e) => e.fileName === id,\n );\n if (fileDeclarations.length > 0) {\n const localDepClassNames = fileDeclarations.map((e) => e.className);\n outputCode += generateHmrCode(fileDeclarations, localDepClassNames);\n }\n }\n\n return { code: outputCode, map: stripped.map };\n }\n\n function resolveTsConfigPath() {\n const { root, isProd, isLib } = tsConfigResolutionContext!;\n return getTsConfigPath(\n root,\n pluginOptions.tsconfigGetter(),\n isProd,\n pluginOptions.isTest,\n isLib,\n pluginOptions.workspaceRoot,\n );\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-fast-compile',\n api: { getTsConfigPath: resolveTsConfigPath },\n enforce: 'pre' as const,\n async config(config, { command }) {\n watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n\n tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n\n const preliminaryTsConfigPath = resolveTsConfigPath();\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd,\n jit: pluginOptions.jit,\n watchMode,\n isTest: pluginOptions.isTest,\n isAstroIntegration: pluginOptions.isAstroIntegration,\n });\n\n // No `resolve.conditions` extension here: the `style` condition is\n // scoped to `.css`-extension requests by\n // `cssExtensionStyleResolverPlugin`, registered once at the\n // `angular()` factory level (which is the only public entry point\n // that wires this plugin in).\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n componentRegistries = integrations.componentRegistries;\n },\n configureServer(server) {\n // Watch for new .ts files and scan them into the registry. Use\n // the barrel-aware scanner so a newly added re-export entry\n // (`export * from './x'`) also expands its underlying directive\n // classes — otherwise the registry stays stale until restart.\n server.watcher.on('add', async (filePath) => {\n if (\n filePath.endsWith('.ts') &&\n !filePath.endsWith('.spec.ts') &&\n !filePath.endsWith('.d.ts')\n ) {\n await scanBarrelExports(filePath, new Set(), true);\n }\n });\n },\n async buildStart() {\n await initFastCompile();\n },\n closeBundle() {\n if (!watchMode) {\n releaseCssPreprocessorWorkers();\n }\n },\n async handleHotUpdate(ctx) {\n // Resource file changes → invalidate parent .ts module\n if (resourceToSource.has(ctx.file)) {\n const parentSource = resourceToSource.get(ctx.file)!;\n const parentModule = ctx.server.moduleGraph.getModuleById(parentSource);\n if (parentModule) {\n return [parentModule];\n }\n }\n\n if (TS_EXT_REGEX.test(ctx.file)) {\n const [fileId] = ctx.file.split('?');\n\n // Remove old entries from this file\n const oldEntries = [...registry.entries()]\n .filter(([_, v]) => v.fileName === fileId)\n .map(([k]) => k);\n for (const key of oldEntries) {\n registry.delete(key);\n }\n\n // Rescan the changed file via the barrel-aware scanner so an\n // edited barrel re-export picks up newly-referenced files.\n // Pass overwrite=true so updated metadata replaces stale\n // entries from the previous scan.\n await scanBarrelExports(fileId, new Set(), true);\n }\n\n // Let Vite handle the rest — the transform hook will recompile\n return ctx.modules;\n },\n resolveId(id, importer) {\n if (id.startsWith(VIRTUAL_RAW_PREFIX)) {\n return `\\0${id}`;\n }\n\n if (pluginOptions.jit && id.startsWith('angular:jit:')) {\n const filePath = normalizePath(\n resolve(dirname(importer as string), id.split(';')[1]),\n );\n if (id.includes(':style')) {\n markStylePathSafe(resolvedConfig, filePath);\n return filePath + '?inline';\n }\n return toVirtualRawId(filePath);\n }\n\n const rawRewrite = rewriteHtmlRawImport(id, importer);\n if (rawRewrite) return rawRewrite;\n\n // User `.scss?inline` / `.css?inline` imports: resolve and mark\n // safe so Vite's native CSS pipeline handles them.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id) && importer) {\n const filePath = id.split('?')[0];\n const resolved = isAbsolute(filePath)\n ? normalizePath(filePath)\n : normalizePath(resolve(dirname(importer), filePath));\n markStylePathSafe(resolvedConfig, resolved);\n return resolved + '?inline';\n }\n\n return undefined;\n },\n async load(id) {\n const rawModule = await loadVirtualRawModule(this, id);\n if (rawModule !== undefined) return rawModule;\n\n // Vitest fallback: module-runner can skip resolveId, so the bare\n // ?inline query reaches load. Mark safe and let Vite handle it.\n if (/\\.(css|scss|sass|less)\\?inline$/.test(id)) {\n markStylePathSafe(resolvedConfig, id.split('?')[0]);\n }\n\n return;\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n // `?raw` ids already carry Vite's native raw-loader output\n // (`export default \"<source>\"`). Recompiling them as Angular/TS\n // would strip that default export, so leave them to Vite (#2356).\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (transformFilter && !transformFilter(code, id)) {\n return;\n }\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n return handleFastCompileTransform(code, id);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,iBACd,SACA,UACQ;AACR,QAAO,SAAS,WAAW,SAAS,iBAAiB;;AAGvD,SAAgB,kBACd,eACQ;CACR,IAAI;CACJ,IAAI;CACJ,IAAI,sBAAkD,EAAE;CACxD,IAAI,4BAA8D;CAClE,IAAI,YAAY;CAGhB,MAAM,2BAA8B,IAAI,KAAK;CAC7C,MAAM,mCAAmB,IAAI,KAAqB;CAClD,MAAM,qCAAqB,IAAI,KAAa;CAC5C,IAAI,cAAc;CAClB,IAAI,0BAA0B;;;;;;;;;;;;;;;;;CAkB9B,eAAe,kBACb,MACA,0BAAuB,IAAI,KAAK,EAChC,YAAY,OACZ,cACA,aACe;AACf,MAAI,QAAQ,IAAI,KAAK,CAAE;AACvB,UAAQ,IAAI,KAAK;EACjB,IAAI;AAC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