@analogjs/vite-plugin-angular 3.0.0-alpha.45 → 3.0.0-alpha.46

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/vite-plugin-angular",
3
- "version": "3.0.0-alpha.45",
3
+ "version": "3.0.0-alpha.46",
4
4
  "description": "Vite Plugin for Angular",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -781,7 +781,6 @@ function angular(options) {
781
781
  virtualModulesPlugin({ jit }),
782
782
  templateClassBindingGuardPlugin(guardContext),
783
783
  pluginOptions.hasTailwindCss && tailwindReferencePlugin({ tailwindCss: pluginOptions.tailwindCss }),
784
- angularPlugin(),
785
784
  pluginOptions.liveReload && liveReloadPlugin({
786
785
  classNames,
787
786
  fileEmitter
@@ -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 defaultClientConditions,\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\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 getAngularComponentMetadata,\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';\n\nimport { compilationAPIPlugin } from './compilation-api/index.js';\nimport { fastCompilePlugin } from './fast-compile-plugin.js';\nimport {\n templateClassBindingGuardPlugin,\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n type ActiveGraphComponentRecord,\n type StyleOwnerRecord,\n type TemplateClassBindingGuardContext,\n} from './template-class-binding-guard-plugin.js';\nimport {\n tailwindReferencePlugin,\n buildStylePreprocessor,\n validateTailwindConfig,\n} from './tailwind-plugin.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 TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { TsconfigResolver } from './utils/tsconfig-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 {\n AngularStylePipelineOptions,\n configureStylePipelineRegistry,\n} from './style-pipeline.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';\nexport {\n findStaticClassAndBoundClassConflicts,\n findBoundClassAndNgClassConflicts,\n} from './template-class-binding-guard-plugin.js';\nexport { buildStylePreprocessor } from './tailwind-plugin.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 advanced?: {\n /**\n * Custom TypeScript transformers that are run before Angular compilation\n */\n tsTransformers?: ts.CustomTransformers;\n };\n supportedBrowsers?: string[];\n transformFilter?: (code: string, id: string) => boolean;\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n additionalContentDirs?: 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 experimental?: {\n useAngularCompilationAPI?: boolean;\n };\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:tailwind']`)\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 * Optional preprocessor that transforms component CSS before it enters Vite's\n * preprocessCSS pipeline. Runs on every component stylesheet (both external\n * `.component.css` files and inline `styles: [...]` blocks).\n *\n * @param code - Raw CSS content of the component stylesheet\n * @param filename - Resolved file path of the stylesheet (or containing .ts file for inline styles)\n * @returns Transformed CSS string, or the original code if no transformation is needed\n */\n stylePreprocessor?: StylePreprocessor;\n /**\n * Experimental Angular stylesheet-resource hooks for community-maintained\n * style-pipeline plugins.\n *\n * These hooks run inside the Angular resource pipeline, which is the seam a\n * standalone Vite plugin cannot own on its own.\n */\n stylePipeline?: AngularStylePipelineOptions;\n /**\n * First-class Tailwind CSS v4 integration for Angular component styles.\n *\n * Angular's compiler processes component CSS through Vite's `preprocessCSS()`,\n * which runs `@tailwindcss/vite` — but each component stylesheet is processed\n * in isolation without access to the root Tailwind configuration (prefix, @theme,\n * @custom-variant, @plugin definitions). This causes errors like:\n *\n * \"Cannot apply utility class `sa:grid` because the `sa` variant does not exist\"\n *\n * The `tailwindCss` option solves this by auto-injecting a `@reference` directive\n * into every component CSS file that uses Tailwind utilities, pointing it to the\n * root Tailwind stylesheet so `@tailwindcss/vite` can resolve the full configuration.\n *\n * @example Basic usage — reference a root Tailwind CSS file:\n * ```ts\n * import { resolve } from 'node:path';\n *\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * },\n * })\n * ```\n *\n * @example With prefix detection — only inject for files using specific prefixes:\n * ```ts\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * // Only inject @reference into files that use these prefixed classes\n * prefixes: ['sa:', 'tw:'],\n * },\n * })\n * ```\n *\n * @example AnalogJS platform — passed through the `vite` option:\n * ```ts\n * analog({\n * vite: {\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, '../../../libs/meritos/tailwind.config.css'),\n * },\n * },\n * })\n * ```\n */\n tailwindCss?: {\n /**\n * Absolute path to the root Tailwind CSS file that contains `@import \"tailwindcss\"`,\n * `@theme`, `@custom-variant`, and `@plugin` definitions.\n *\n * A `@reference` directive pointing to this file will be auto-injected into\n * component CSS files that use Tailwind utilities.\n */\n rootStylesheet: string;\n /**\n * Optional list of class prefixes to detect (e.g. `['sa:', 'tw:']`).\n * When provided, `@reference` is only injected into component CSS files that\n * contain at least one of these prefixes. When omitted, `@reference` is injected\n * into all component CSS files that contain `@apply` or `@` directives.\n *\n * @default undefined — inject into all component CSS files with `@apply`\n */\n prefixes?: string[];\n };\n}\n\nconst classNames = new Map();\nexport function evictDeletedFileMetadata(\n file: string,\n {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap,\n fileTransformMap,\n }: {\n removeActiveGraphMetadata: (file: string) => void;\n removeStyleOwnerMetadata: (file: string) => void;\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n removeActiveGraphMetadata(normalizedFile);\n removeStyleOwnerMetadata(normalizedFile);\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\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: options?.workspaceRoot ?? process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n advanced: {\n tsTransformers: {\n before: options?.advanced?.tsTransformers?.before ?? [],\n after: options?.advanced?.tsTransformers?.after ?? [],\n afterDeclarations:\n options?.advanced?.tsTransformers?.afterDeclarations ?? [],\n },\n },\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n additionalContentDirs: options?.additionalContentDirs ?? [],\n liveReload,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n useAngularCompilationAPI:\n options?.experimental?.useAngularCompilationAPI ?? false,\n fastCompile: options?.fastCompile ?? false,\n fastCompileMode: options?.fastCompileMode ?? 'full',\n hasTailwindCss: !!options?.tailwindCss,\n tailwindCss: options?.tailwindCss,\n stylePreprocessor: buildStylePreprocessor(options),\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 hasTailwindCss: pluginOptions.hasTailwindCss,\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 // Dev-time component identity index for the currently active Vite graph.\n // We intentionally populate this during the pre-transform pass instead of a\n // workspace-wide scan so diagnostics stay tied to the app the developer is\n // actually serving, and so they track hot-updated files incrementally.\n const activeGraphComponentMetadata = new Map<\n string,\n ActiveGraphComponentRecord[]\n >();\n const selectorOwners = new Map<string, Set<string>>();\n const classNameOwners = new Map<string, Set<string>>();\n const transformedStyleOwnerMetadata = new Map<string, StyleOwnerRecord[]>();\n const styleSourceOwners = new Map<string, Set<string>>();\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. Tailwind CSS (hasTailwindCss) — styles must pass through Vite's\n * CSS pipeline so @tailwindcss/vite can resolve @apply directives\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() || pluginOptions.hasTailwindCss);\n }\n\n function validateNoDuplicateAnalogPlugins(config: ResolvedConfig): void {\n const analogInstances = (config.plugins ?? []).filter(\n (p) => p.name === '@analogjs/vite-plugin-angular',\n );\n if (analogInstances.length > 1 && !config.build?.ssr) {\n throw new Error(\n `[@analogjs/vite-plugin-angular] analog() is registered ${analogInstances.length} times. ` +\n `Each instance creates separate style maps, causing component ` +\n `styles to be lost. Remove duplicate registrations.`,\n );\n }\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\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 guardContext: TemplateClassBindingGuardContext = {\n styleUrlsResolver,\n activeGraphComponentMetadata,\n selectorOwners,\n classNameOwners,\n transformedStyleOwnerMetadata,\n styleSourceOwners,\n };\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 hasTailwindCss, so Tailwind utilities in\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 =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\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 // 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 return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: [\n 'style',\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\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 (pluginOptions.hasTailwindCss) {\n validateTailwindConfig(pluginOptions.tailwindCss, config, watchMode);\n validateNoDuplicateAnalogPlugins(config);\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 evictDeletedFileMetadata(file, {\n removeActiveGraphMetadata: (f) =>\n removeActiveGraphMetadata(guardContext, f),\n removeStyleOwnerMetadata: (f) =>\n removeStyleOwnerMetadata(guardContext, f),\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 await performCompilation(resolvedConfig);\n pendingCompilation = null;\n\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 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 /**\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 const ownerModules = findStyleOwnerModules(\n ctx.server,\n ctx.file,\n styleSourceOwners,\n );\n debugHmrV('component stylesheet owner fallback lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n ownerFiles: [\n ...(styleSourceOwners.get(normalizePath(ctx.file)) ?? []),\n ],\n });\n\n if (ownerModules.length > 0) {\n pendingCompilation = performCompilation(resolvedConfig, [\n ...ownerModules.map((mod) => mod.id).filter(Boolean),\n ]);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id && !!classNames.get(id));\n const derivedUpdates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id)\n .flatMap((ownerId) =>\n resolveComponentClassNamesForStyleOwner(\n ownerId,\n ctx.file,\n ).map((className) => ({\n ownerId,\n className,\n via: 'raw-component-metadata' as const,\n })),\n );\n debugHmrV('component stylesheet owner fallback compilation', {\n file: ctx.file,\n ownerIds: ownerModules.map((mod) => mod.id),\n updateIds: updates,\n classNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n derivedUpdates,\n });\n // Keep owner recompilation and metadata derivation as\n // diagnostics only.\n //\n // Value: the fallback log can still point at the affected\n // components.\n //\n // Guards against: treating a component-update as a safe\n // substitute for a missing wrapper module. Angular can\n // re-render the component without forcing the browser to\n // refresh the wrapper CSS, which leaves the UI visually stale.\n if (derivedUpdates.length > 0) {\n debugHmrV(\n 'component stylesheet owner fallback derived updates',\n {\n file: ctx.file,\n updates: derivedUpdates,\n hint: 'Angular did not repopulate classNames during CSS-only owner recompilation, so Analog derived component identities from raw component metadata.',\n },\n );\n }\n }\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 ownerIds: ownerModules.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-and-no-owner-updates'\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\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 trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\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 /**\n * Check for options.transformFilter\n */\n if (\n options?.transformFilter &&\n !(options?.transformFilter(code, id) ?? true)\n ) {\n return;\n }\n\n /**\n * Skip transforming content files\n */\n if (id.includes('?') && id.includes('analog-content-')) {\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(resolvedConfig);\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(resolvedConfig, [id]);\n }\n }\n }\n\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n const templateUrls = hasComponent\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = hasComponent\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (hasComponent && 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 data = data.replace(\n /angular:jit:style:inline;/g,\n 'virtual:angular:jit:style:inline;',\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\n return {\n code: data,\n map: 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 },\n };\n }\n\n const compilationPlugin = pluginOptions.useAngularCompilationAPI\n ? compilationAPIPlugin({\n tsconfigGetter: pluginOptions.tsconfigGetter,\n workspaceRoot: pluginOptions.workspaceRoot,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n jit,\n liveReload: pluginOptions.liveReload,\n disableTypeChecking: pluginOptions.disableTypeChecking,\n supportedBrowsers: pluginOptions.supportedBrowsers,\n transformFilter: options?.transformFilter,\n fileReplacements: pluginOptions.fileReplacements,\n stylePreprocessor: pluginOptions.stylePreprocessor,\n stylePipeline: options?.stylePipeline,\n hasTailwindCss: pluginOptions.hasTailwindCss,\n tailwindCss: pluginOptions.tailwindCss,\n isTest,\n isAstroIntegration,\n include: pluginOptions.include,\n additionalContentDirs: pluginOptions.additionalContentDirs,\n debug: options?.debug,\n })\n : 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 transformFilter: options?.transformFilter,\n isTest,\n isAstroIntegration,\n fastCompileMode: pluginOptions.fastCompileMode,\n })\n : angularPlugin();\n\n return [\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit }),\n templateClassBindingGuardPlugin(guardContext),\n pluginOptions.hasTailwindCss &&\n tailwindReferencePlugin({ tailwindCss: pluginOptions.tailwindCss }),\n angularPlugin(),\n pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),\n compilationPlugin,\n !pluginOptions.fastCompile &&\n pluginOptions.liveReload &&\n liveReloadPlugin({ classNames, fileEmitter }),\n ...(isTest && !isStackBlitz ? angularVitestPlugins() : []),\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(shouldExternalizeStyles),\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 );\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 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 const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n sourceFileCache.invalidate(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 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, sourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (stylesheetRegistry) {\n configureStylePipelineRegistry(\n pluginOptions.stylePipeline,\n stylesheetRegistry,\n {\n workspaceRoot: pluginOptions.workspaceRoot,\n },\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 if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {\n return;\n }\n\n const metadata = watchMode ? fileMetadata(filename) : {};\n\n outputFiles.set(filename, {\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 builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\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\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\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 : 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(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\nfunction resolveComponentClassNamesForStyleOwner(\n ownerFile: string,\n sourcePath: string,\n): string[] {\n if (!existsSync(ownerFile)) {\n return [];\n }\n\n const ownerCode = readFileSync(ownerFile, 'utf-8');\n const components = getAngularComponentMetadata(ownerCode);\n const normalizedSourcePath = normalizePath(sourcePath);\n\n return components\n .filter((component) =>\n component.styleUrls.some(\n (styleUrl) =>\n normalizePath(resolve(dirname(ownerFile), styleUrl)) ===\n normalizedSourcePath,\n ),\n )\n .map((component) => component.className);\n}\n\ntype ComponentStylesheetHmrOutcome =\n | 'css-update'\n | 'owner-component-update'\n | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n ownerIds?: Array<string | undefined>;\n updateIds?: 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 rejectedPreferredPaths.push('owner-component-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 if ((details.ownerIds?.filter(Boolean).length ?? 0) === 0) {\n pitfalls.push('no-owner-modules');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'No owning TS component modules were available in the module graph for owner-based fallback.',\n );\n }\n } else if ((details.updateIds?.length ?? 0) === 0) {\n pitfalls.push('owner-modules-without-class-identities');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Owner modules were found, but Angular did not expose component class identities after recompilation, so no targeted component update could be sent.',\n );\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 ownerIds: details.ownerIds ?? [],\n updateIds: details.updateIds ?? [],\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\nfunction findStyleOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n styleSourceOwners: Map<string, Set<string>>,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateOwnerFiles = [\n ...(styleSourceOwners.get(normalizedResourceFile) ?? []),\n ];\n const modules = new Map<string, ModuleNode>();\n\n for (const ownerFile of candidateOwnerFiles) {\n const owners = server.moduleGraph.getModulesByFile(ownerFile);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\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\n/**\n * Checks for vitest run from the command line\n * @returns boolean\n */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAoM9C,IAAM,6BAAa,IAAI,KAAK;AAC5B,SAAgB,yBACd,MACA,EACE,2BACA,0BACA,eACA,oBAOI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,IAAI,CAAC,GAAG;AACxD,2BAA0B,eAAe;AACzC,0BAAyB,eAAe;AACxC,eAAc,OAAO,eAAe;AACpC,kBAAiB,OAAO,eAAe;;AASzC,SAAgB,QAAQ,SAAmC;AACzD,kBAAiB,SAAS,OAAO,SAAS,cAAc;CACxD,MAAM,aAAa,SAAS,cAAc;;;;;CAM1C,MAAM,gBAAgB;EACpB,gBAAgB,qBAAqB,SAAS,SAAS;EACvD,eAAe,SAAS,iBAAiB,QAAQ,KAAK;EACtD,uBAAuB,SAAS,yBAAyB;EACzD,UAAU,EACR,gBAAgB;GACd,QAAQ,SAAS,UAAU,gBAAgB,UAAU,EAAE;GACvD,OAAO,SAAS,UAAU,gBAAgB,SAAS,EAAE;GACrD,mBACE,SAAS,UAAU,gBAAgB,qBAAqB,EAAE;GAC7D,EACF;EACD,mBAAmB,SAAS,qBAAqB,CAAC,YAAY;EAC9D,KAAK,SAAS;EACd,SAAS,SAAS,WAAW,EAAE;EAC/B,uBAAuB,SAAS,yBAAyB,EAAE;EAC3D;EACA,qBAAqB,SAAS,uBAAuB;EACrD,kBAAkB,SAAS,oBAAoB,EAAE;EACjD,0BACE,SAAS,cAAc,4BAA4B;EACrD,aAAa,SAAS,eAAe;EACrC,iBAAiB,SAAS,mBAAmB;EAC7C,gBAAgB,CAAC,CAAC,SAAS;EAC3B,aAAa,SAAS;EACtB,mBAAmB,uBAAuB,QAAQ;EACnD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O;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"}
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 defaultClientConditions,\n ModuleNode,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n ViteDevServer,\n} from 'vite';\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 getAngularComponentMetadata,\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';\n\nimport { compilationAPIPlugin } from './compilation-api/index.js';\nimport { fastCompilePlugin } from './fast-compile-plugin.js';\nimport {\n templateClassBindingGuardPlugin,\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n type ActiveGraphComponentRecord,\n type StyleOwnerRecord,\n type TemplateClassBindingGuardContext,\n} from './template-class-binding-guard-plugin.js';\nimport {\n tailwindReferencePlugin,\n buildStylePreprocessor,\n validateTailwindConfig,\n} from './tailwind-plugin.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 TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { TsconfigResolver } from './utils/tsconfig-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 {\n AngularStylePipelineOptions,\n configureStylePipelineRegistry,\n} from './style-pipeline.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';\nexport {\n findStaticClassAndBoundClassConflicts,\n findBoundClassAndNgClassConflicts,\n} from './template-class-binding-guard-plugin.js';\nexport { buildStylePreprocessor } from './tailwind-plugin.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 advanced?: {\n /**\n * Custom TypeScript transformers that are run before Angular compilation\n */\n tsTransformers?: ts.CustomTransformers;\n };\n supportedBrowsers?: string[];\n transformFilter?: (code: string, id: string) => boolean;\n /**\n * Additional files to include in compilation\n */\n include?: string[];\n additionalContentDirs?: 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 experimental?: {\n useAngularCompilationAPI?: boolean;\n };\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:tailwind']`)\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 * Optional preprocessor that transforms component CSS before it enters Vite's\n * preprocessCSS pipeline. Runs on every component stylesheet (both external\n * `.component.css` files and inline `styles: [...]` blocks).\n *\n * @param code - Raw CSS content of the component stylesheet\n * @param filename - Resolved file path of the stylesheet (or containing .ts file for inline styles)\n * @returns Transformed CSS string, or the original code if no transformation is needed\n */\n stylePreprocessor?: StylePreprocessor;\n /**\n * Experimental Angular stylesheet-resource hooks for community-maintained\n * style-pipeline plugins.\n *\n * These hooks run inside the Angular resource pipeline, which is the seam a\n * standalone Vite plugin cannot own on its own.\n */\n stylePipeline?: AngularStylePipelineOptions;\n /**\n * First-class Tailwind CSS v4 integration for Angular component styles.\n *\n * Angular's compiler processes component CSS through Vite's `preprocessCSS()`,\n * which runs `@tailwindcss/vite` — but each component stylesheet is processed\n * in isolation without access to the root Tailwind configuration (prefix, @theme,\n * @custom-variant, @plugin definitions). This causes errors like:\n *\n * \"Cannot apply utility class `sa:grid` because the `sa` variant does not exist\"\n *\n * The `tailwindCss` option solves this by auto-injecting a `@reference` directive\n * into every component CSS file that uses Tailwind utilities, pointing it to the\n * root Tailwind stylesheet so `@tailwindcss/vite` can resolve the full configuration.\n *\n * @example Basic usage — reference a root Tailwind CSS file:\n * ```ts\n * import { resolve } from 'node:path';\n *\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * },\n * })\n * ```\n *\n * @example With prefix detection — only inject for files using specific prefixes:\n * ```ts\n * angular({\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, 'src/styles/tailwind.css'),\n * // Only inject @reference into files that use these prefixed classes\n * prefixes: ['sa:', 'tw:'],\n * },\n * })\n * ```\n *\n * @example AnalogJS platform — passed through the `vite` option:\n * ```ts\n * analog({\n * vite: {\n * tailwindCss: {\n * rootStylesheet: resolve(__dirname, '../../../libs/meritos/tailwind.config.css'),\n * },\n * },\n * })\n * ```\n */\n tailwindCss?: {\n /**\n * Absolute path to the root Tailwind CSS file that contains `@import \"tailwindcss\"`,\n * `@theme`, `@custom-variant`, and `@plugin` definitions.\n *\n * A `@reference` directive pointing to this file will be auto-injected into\n * component CSS files that use Tailwind utilities.\n */\n rootStylesheet: string;\n /**\n * Optional list of class prefixes to detect (e.g. `['sa:', 'tw:']`).\n * When provided, `@reference` is only injected into component CSS files that\n * contain at least one of these prefixes. When omitted, `@reference` is injected\n * into all component CSS files that contain `@apply` or `@` directives.\n *\n * @default undefined — inject into all component CSS files with `@apply`\n */\n prefixes?: string[];\n };\n}\n\nconst classNames = new Map();\nexport function evictDeletedFileMetadata(\n file: string,\n {\n removeActiveGraphMetadata,\n removeStyleOwnerMetadata,\n classNamesMap,\n fileTransformMap,\n }: {\n removeActiveGraphMetadata: (file: string) => void;\n removeStyleOwnerMetadata: (file: string) => void;\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n removeActiveGraphMetadata(normalizedFile);\n removeStyleOwnerMetadata(normalizedFile);\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\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: options?.workspaceRoot ?? process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n advanced: {\n tsTransformers: {\n before: options?.advanced?.tsTransformers?.before ?? [],\n after: options?.advanced?.tsTransformers?.after ?? [],\n afterDeclarations:\n options?.advanced?.tsTransformers?.afterDeclarations ?? [],\n },\n },\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n jit: options?.jit,\n include: options?.include ?? [],\n additionalContentDirs: options?.additionalContentDirs ?? [],\n liveReload,\n disableTypeChecking: options?.disableTypeChecking ?? true,\n fileReplacements: options?.fileReplacements ?? [],\n useAngularCompilationAPI:\n options?.experimental?.useAngularCompilationAPI ?? false,\n fastCompile: options?.fastCompile ?? false,\n fastCompileMode: options?.fastCompileMode ?? 'full',\n hasTailwindCss: !!options?.tailwindCss,\n tailwindCss: options?.tailwindCss,\n stylePreprocessor: buildStylePreprocessor(options),\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 hasTailwindCss: pluginOptions.hasTailwindCss,\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 // Dev-time component identity index for the currently active Vite graph.\n // We intentionally populate this during the pre-transform pass instead of a\n // workspace-wide scan so diagnostics stay tied to the app the developer is\n // actually serving, and so they track hot-updated files incrementally.\n const activeGraphComponentMetadata = new Map<\n string,\n ActiveGraphComponentRecord[]\n >();\n const selectorOwners = new Map<string, Set<string>>();\n const classNameOwners = new Map<string, Set<string>>();\n const transformedStyleOwnerMetadata = new Map<string, StyleOwnerRecord[]>();\n const styleSourceOwners = new Map<string, Set<string>>();\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. Tailwind CSS (hasTailwindCss) — styles must pass through Vite's\n * CSS pipeline so @tailwindcss/vite can resolve @apply directives\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() || pluginOptions.hasTailwindCss);\n }\n\n function validateNoDuplicateAnalogPlugins(config: ResolvedConfig): void {\n const analogInstances = (config.plugins ?? []).filter(\n (p) => p.name === '@analogjs/vite-plugin-angular',\n );\n if (analogInstances.length > 1 && !config.build?.ssr) {\n throw new Error(\n `[@analogjs/vite-plugin-angular] analog() is registered ${analogInstances.length} times. ` +\n `Each instance creates separate style maps, causing component ` +\n `styles to be lost. Remove duplicate registrations.`,\n );\n }\n }\n\n let stylesheetRegistry: AnalogStylesheetRegistry | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\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 guardContext: TemplateClassBindingGuardContext = {\n styleUrlsResolver,\n activeGraphComponentMetadata,\n selectorOwners,\n classNameOwners,\n transformedStyleOwnerMetadata,\n styleSourceOwners,\n };\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 hasTailwindCss, so Tailwind utilities in\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 =\n config.mode === 'production' ||\n process.env['NODE_ENV'] === 'production';\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 // 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 return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs', 'tslib'],\n exclude: ['@angular/platform-server'],\n ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: [\n 'style',\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\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 (pluginOptions.hasTailwindCss) {\n validateTailwindConfig(pluginOptions.tailwindCss, config, watchMode);\n validateNoDuplicateAnalogPlugins(config);\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 evictDeletedFileMetadata(file, {\n removeActiveGraphMetadata: (f) =>\n removeActiveGraphMetadata(guardContext, f),\n removeStyleOwnerMetadata: (f) =>\n removeStyleOwnerMetadata(guardContext, f),\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 await performCompilation(resolvedConfig);\n pendingCompilation = null;\n\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 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 /**\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 const ownerModules = findStyleOwnerModules(\n ctx.server,\n ctx.file,\n styleSourceOwners,\n );\n debugHmrV('component stylesheet owner fallback lookup', {\n file: ctx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n ownerFiles: [\n ...(styleSourceOwners.get(normalizePath(ctx.file)) ?? []),\n ],\n });\n\n if (ownerModules.length > 0) {\n pendingCompilation = performCompilation(resolvedConfig, [\n ...ownerModules.map((mod) => mod.id).filter(Boolean),\n ]);\n await pendingCompilation;\n pendingCompilation = null;\n\n const updates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id && !!classNames.get(id));\n const derivedUpdates = ownerModules\n .map((mod) => mod.id)\n .filter((id): id is string => !!id)\n .flatMap((ownerId) =>\n resolveComponentClassNamesForStyleOwner(\n ownerId,\n ctx.file,\n ).map((className) => ({\n ownerId,\n className,\n via: 'raw-component-metadata' as const,\n })),\n );\n debugHmrV('component stylesheet owner fallback compilation', {\n file: ctx.file,\n ownerIds: ownerModules.map((mod) => mod.id),\n updateIds: updates,\n classNames: updates.map((id) => ({\n id,\n className: classNames.get(id),\n })),\n derivedUpdates,\n });\n // Keep owner recompilation and metadata derivation as\n // diagnostics only.\n //\n // Value: the fallback log can still point at the affected\n // components.\n //\n // Guards against: treating a component-update as a safe\n // substitute for a missing wrapper module. Angular can\n // re-render the component without forcing the browser to\n // refresh the wrapper CSS, which leaves the UI visually stale.\n if (derivedUpdates.length > 0) {\n debugHmrV(\n 'component stylesheet owner fallback derived updates',\n {\n file: ctx.file,\n updates: derivedUpdates,\n hint: 'Angular did not repopulate classNames during CSS-only owner recompilation, so Analog derived component identities from raw component metadata.',\n },\n );\n }\n }\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 ownerIds: ownerModules.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-and-no-owner-updates'\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\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 trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(\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 /**\n * Check for options.transformFilter\n */\n if (\n options?.transformFilter &&\n !(options?.transformFilter(code, id) ?? true)\n ) {\n return;\n }\n\n /**\n * Skip transforming content files\n */\n if (id.includes('?') && id.includes('analog-content-')) {\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(resolvedConfig);\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(resolvedConfig, [id]);\n }\n }\n }\n\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n const templateUrls = hasComponent\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = hasComponent\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (hasComponent && 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 data = data.replace(\n /angular:jit:style:inline;/g,\n 'virtual:angular:jit:style:inline;',\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\n return {\n code: data,\n map: 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 },\n };\n }\n\n const compilationPlugin = pluginOptions.useAngularCompilationAPI\n ? compilationAPIPlugin({\n tsconfigGetter: pluginOptions.tsconfigGetter,\n workspaceRoot: pluginOptions.workspaceRoot,\n inlineStylesExtension: pluginOptions.inlineStylesExtension,\n jit,\n liveReload: pluginOptions.liveReload,\n disableTypeChecking: pluginOptions.disableTypeChecking,\n supportedBrowsers: pluginOptions.supportedBrowsers,\n transformFilter: options?.transformFilter,\n fileReplacements: pluginOptions.fileReplacements,\n stylePreprocessor: pluginOptions.stylePreprocessor,\n stylePipeline: options?.stylePipeline,\n hasTailwindCss: pluginOptions.hasTailwindCss,\n tailwindCss: pluginOptions.tailwindCss,\n isTest,\n isAstroIntegration,\n include: pluginOptions.include,\n additionalContentDirs: pluginOptions.additionalContentDirs,\n debug: options?.debug,\n })\n : 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 transformFilter: options?.transformFilter,\n isTest,\n isAstroIntegration,\n fastCompileMode: pluginOptions.fastCompileMode,\n })\n : angularPlugin();\n\n return [\n replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),\n virtualModulesPlugin({ jit }),\n templateClassBindingGuardPlugin(guardContext),\n pluginOptions.hasTailwindCss &&\n tailwindReferencePlugin({ tailwindCss: pluginOptions.tailwindCss }),\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 ? angularVitestPlugins() : []),\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(shouldExternalizeStyles),\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 );\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 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 const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n sourceFileCache.invalidate(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 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, sourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n stylesheetRegistry = externalizeStyles\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (stylesheetRegistry) {\n configureStylePipelineRegistry(\n pluginOptions.stylePipeline,\n stylesheetRegistry,\n {\n workspaceRoot: pluginOptions.workspaceRoot,\n },\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 if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {\n return;\n }\n\n const metadata = watchMode ? fileMetadata(filename) : {};\n\n outputFiles.set(filename, {\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 builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\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\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\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 : 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(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\nfunction resolveComponentClassNamesForStyleOwner(\n ownerFile: string,\n sourcePath: string,\n): string[] {\n if (!existsSync(ownerFile)) {\n return [];\n }\n\n const ownerCode = readFileSync(ownerFile, 'utf-8');\n const components = getAngularComponentMetadata(ownerCode);\n const normalizedSourcePath = normalizePath(sourcePath);\n\n return components\n .filter((component) =>\n component.styleUrls.some(\n (styleUrl) =>\n normalizePath(resolve(dirname(ownerFile), styleUrl)) ===\n normalizedSourcePath,\n ),\n )\n .map((component) => component.className);\n}\n\ntype ComponentStylesheetHmrOutcome =\n | 'css-update'\n | 'owner-component-update'\n | 'full-reload';\n\nfunction logComponentStylesheetHmrOutcome(details: {\n file: string;\n encapsulation: string;\n diagnosis: ReturnType<typeof diagnoseComponentStylesheetPipeline>;\n outcome: ComponentStylesheetHmrOutcome;\n directModuleId?: string;\n wrapperIds?: string[];\n ownerIds?: Array<string | undefined>;\n updateIds?: 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 rejectedPreferredPaths.push('owner-component-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 if ((details.ownerIds?.filter(Boolean).length ?? 0) === 0) {\n pitfalls.push('no-owner-modules');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'No owning TS component modules were available in the module graph for owner-based fallback.',\n );\n }\n } else if ((details.updateIds?.length ?? 0) === 0) {\n pitfalls.push('owner-modules-without-class-identities');\n if (details.outcome === 'full-reload') {\n rejectedPreferredPaths.push('owner-component-update');\n hints.push(\n 'Owner modules were found, but Angular did not expose component class identities after recompilation, so no targeted component update could be sent.',\n );\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 ownerIds: details.ownerIds ?? [],\n updateIds: details.updateIds ?? [],\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\nfunction findStyleOwnerModules(\n server: ViteDevServer,\n resourceFile: string,\n styleSourceOwners: Map<string, Set<string>>,\n): ModuleNode[] {\n const normalizedResourceFile = normalizePath(resourceFile.split('?')[0]);\n const candidateOwnerFiles = [\n ...(styleSourceOwners.get(normalizedResourceFile) ?? []),\n ];\n const modules = new Map<string, ModuleNode>();\n\n for (const ownerFile of candidateOwnerFiles) {\n const owners = server.moduleGraph.getModulesByFile(ownerFile);\n owners?.forEach((mod) => {\n if (mod.id) {\n modules.set(mod.id, mod);\n }\n });\n }\n\n return [...modules.values()];\n}\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\n/**\n * Checks for vitest run from the command line\n * @returns boolean\n */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAoM9C,IAAM,6BAAa,IAAI,KAAK;AAC5B,SAAgB,yBACd,MACA,EACE,2BACA,0BACA,eACA,oBAOI;CACN,MAAM,iBAAiB,cAAc,KAAK,MAAM,IAAI,CAAC,GAAG;AACxD,2BAA0B,eAAe;AACzC,0BAAyB,eAAe;AACxC,eAAc,OAAO,eAAe;AACpC,kBAAiB,OAAO,eAAe;;AASzC,SAAgB,QAAQ,SAAmC;AACzD,kBAAiB,SAAS,OAAO,SAAS,cAAc;CACxD,MAAM,aAAa,SAAS,cAAc;;;;;CAM1C,MAAM,gBAAgB;EACpB,gBAAgB,qBAAqB,SAAS,SAAS;EACvD,eAAe,SAAS,iBAAiB,QAAQ,KAAK;EACtD,uBAAuB,SAAS,yBAAyB;EACzD,UAAU,EACR,gBAAgB;GACd,QAAQ,SAAS,UAAU,gBAAgB,UAAU,EAAE;GACvD,OAAO,SAAS,UAAU,gBAAgB,SAAS,EAAE;GACrD,mBACE,SAAS,UAAU,gBAAgB,qBAAqB,EAAE;GAC7D,EACF;EACD,mBAAmB,SAAS,qBAAqB,CAAC,YAAY;EAC9D,KAAK,SAAS;EACd,SAAS,SAAS,WAAW,EAAE;EAC/B,uBAAuB,SAAS,yBAAyB,EAAE;EAC3D;EACA,qBAAqB,SAAS,uBAAuB;EACrD,kBAAkB,SAAS,oBAAoB,EAAE;EACjD,0BACE,SAAS,cAAc,4BAA4B;EACrD,aAAa,SAAS,eAAe;EACrC,iBAAiB,SAAS,mBAAmB;EAC7C,gBAAgB,CAAC,CAAC,SAAS;EAC3B,aAAa,SAAS;EACtB,mBAAmB,uBAAuB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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"}
@@ -1,4 +1,18 @@
1
1
  import { Plugin } from "vite";
2
+ import { type ComponentRegistry } from "./compiler/index.js";
3
+ declare global {
4
+ /**
5
+ * Shared convention for out-of-tree compilers (e.g. `@tsrx/analog`) that
6
+ * produce Angular Ivy definitions from a non-TS source format. Populate
7
+ * this map with directive/component metadata for any class fastCompile
8
+ * can't reach through its own tsconfig-driven scan, and the per-compile
9
+ * registry lookup in `fastCompilePlugin` will merge those entries in —
10
+ * so TS `@Component({ imports: [X] })` references to such classes
11
+ * resolve statically instead of hitting the `_unresolved-${className}`
12
+ * sentinel.
13
+ */
14
+ var __ANALOG_EXTERNAL_REGISTRY__: ComponentRegistry | undefined;
15
+ }
2
16
  export interface FastCompilePluginOptions {
3
17
  tsconfigGetter: () => string;
4
18
  workspaceRoot: string;
@@ -135,8 +135,14 @@ function fastCompilePlugin(pluginOptions) {
135
135
  }
136
136
  }
137
137
  ensureDtsRegistryForSource(code, id);
138
+ let compileRegistry = registry;
139
+ const externalRegistry = globalThis.__ANALOG_EXTERNAL_REGISTRY__;
140
+ if (externalRegistry && externalRegistry.size > 0) {
141
+ compileRegistry = new Map(registry);
142
+ for (const [k, v] of externalRegistry) compileRegistry.set(k, v);
143
+ }
138
144
  const result = compile(code, id, {
139
- registry,
145
+ registry: compileRegistry,
140
146
  resolvedStyles,
141
147
  resolvedInlineStyles,
142
148
  useDefineForClassFields,
@@ -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 * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport {\n defaultClientConditions,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n} from 'vite';\n\nimport {\n compile,\n scanFile,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.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';\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n supportedBrowsers: string[];\n transformFilter?: (code: string, id: string) => boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\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 async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code = await fsPromises.readFile(file, 'utf-8');\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 const entries = scanFile(code, file);\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)) {\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(candidate, visited, overwrite);\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 = (config.options?.baseUrl ?? projectRoot) as string;\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 return scanFile(code, file);\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 // 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) => scanBarrelExports(c, buildStartVisited)),\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(code: string, id: string) {\n for (const pkg of collectImportedPackages(code, id)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot);\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 (!/(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code)) {\n // Non-Angular file — leave it alone so a downstream plugin (or\n // Vite's built-in TS handler) can process it.\n return undefined;\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n return { code: result.code, map: result.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation\n code = inlineResourceUrls(code, id);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less)\n let resolvedStyles: Map<string, string> | undefined;\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n if (pluginOptions.inlineStylesExtension !== 'css') {\n const styleStrings = extractInlineStyles(code, id);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n try {\n const fakePath = id.replace(\n /\\.ts$/,\n `.inline-${i}.${pluginOptions.inlineStylesExtension}`,\n );\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);\n\n const result = compile(code, id, {\n registry,\n resolvedStyles,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\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\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(result.code, id, {\n lang: 'ts',\n sourcemap: false,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(result.code, id, {\n loader: 'ts',\n sourcemap: false,\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: result.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 );\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 =\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 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 return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n resolve: {\n conditions: [\n ...depOptimizer.resolve.conditions,\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\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 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 exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n if (\n pluginOptions.transformFilter &&\n !(pluginOptions.transformFilter(code, id) ?? true)\n ) {\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":";;;;;;;;;;;;;;;;;;AAsDA,SAAgB,kBACd,eACQ;CACR,IAAI;CACJ,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;;;;;;;;;;;;;CAc9B,eAAe,kBACb,MACA,0BAAuB,IAAI,KAAK,EAChC,YAAY,OACG;AACf,MAAI,QAAQ,IAAI,KAAK,CAAE;AACvB,UAAQ,IAAI,KAAK;EAC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AAgB,MAAM,GAAG,IAAI,MAE7C;AAGF,QAAI,GAAG,SAAS,OAAO,CACrB,MAAK,GAAG,QAAQ,UAAU,GAAG;AAE/B,WAAO,2BAA2B,MAAM,GAAG;;GAE9C;EACF"}
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 * as vite from 'vite';\n\nimport * as compilerCli from '@angular/compiler-cli';\nimport {\n defaultClientConditions,\n normalizePath,\n Plugin,\n preprocessCSS,\n ResolvedConfig,\n} from 'vite';\n\nimport {\n compile,\n scanFile,\n scanPackageDts,\n collectImportedPackages,\n collectRelativeReExports,\n jitTransform,\n inlineResourceUrls,\n extractInlineStyles,\n generateHmrCode,\n debugCompile,\n debugRegistry,\n type ComponentRegistry,\n} from './compiler/index.js';\n\nimport {\n TS_EXT_REGEX,\n getTsConfigPath,\n createDepOptimizerConfig,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.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';\n\ndeclare global {\n /**\n * Shared convention for out-of-tree compilers (e.g. `@tsrx/analog`) that\n * produce Angular Ivy definitions from a non-TS source format. Populate\n * this map with directive/component metadata for any class fastCompile\n * can't reach through its own tsconfig-driven scan, and the per-compile\n * registry lookup in `fastCompilePlugin` will merge those entries in —\n * so TS `@Component({ imports: [X] })` references to such classes\n * resolve statically instead of hitting the `_unresolved-${className}`\n * sentinel.\n */\n // eslint-disable-next-line no-var\n var __ANALOG_EXTERNAL_REGISTRY__: ComponentRegistry | undefined;\n}\n\nexport interface FastCompilePluginOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n liveReload: boolean;\n supportedBrowsers: string[];\n transformFilter?: (code: string, id: string) => boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n fastCompileMode?: 'full' | 'partial';\n}\n\nexport function fastCompilePlugin(\n pluginOptions: FastCompilePluginOptions,\n): Plugin {\n let resolvedConfig: ResolvedConfig;\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 async function scanBarrelExports(\n file: string,\n visited: Set<string> = new Set(),\n overwrite = false,\n ): Promise<void> {\n if (visited.has(file)) return;\n visited.add(file);\n let code: string;\n try {\n code = await fsPromises.readFile(file, 'utf-8');\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 const entries = scanFile(code, file);\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)) {\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(candidate, visited, overwrite);\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 = (config.options?.baseUrl ?? projectRoot) as string;\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 return scanFile(code, file);\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 // 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) => scanBarrelExports(c, buildStartVisited)),\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(code: string, id: string) {\n for (const pkg of collectImportedPackages(code, id)) {\n if (scannedDtsPackages.has(pkg)) continue;\n scannedDtsPackages.add(pkg);\n\n try {\n const dtsEntries = scanPackageDts(pkg, projectRoot);\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 (!/(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code)) {\n // Non-Angular file — leave it alone so a downstream plugin (or\n // Vite's built-in TS handler) can process it.\n return undefined;\n }\n\n // JIT mode\n if (pluginOptions.jit) {\n const result = jitTransform(code, id);\n return { code: result.code, map: result.map };\n }\n\n // Inline external templateUrl/styleUrl(s) into the source before compilation\n code = inlineResourceUrls(code, id);\n\n // Pre-resolve inline styles that need preprocessing (SCSS/Sass/Less)\n let resolvedStyles: Map<string, string> | undefined;\n let resolvedInlineStyles: Map<number, string> | undefined;\n\n if (pluginOptions.inlineStylesExtension !== 'css') {\n const styleStrings = extractInlineStyles(code, id);\n\n if (styleStrings.length > 0) {\n resolvedInlineStyles = new Map();\n for (let i = 0; i < styleStrings.length; i++) {\n try {\n const fakePath = id.replace(\n /\\.ts$/,\n `.inline-${i}.${pluginOptions.inlineStylesExtension}`,\n );\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);\n\n // Merge entries from the shared external-registry global into this\n // compile's lookup view. Convention: out-of-tree compilers populate\n // `globalThis.__ANALOG_EXTERNAL_REGISTRY__` with directive metadata\n // for classes fastCompile can't reach through its tsconfig-driven\n // scan (e.g. `.tsrx` files compiled by `@tsrx/analog`). Without this\n // merge, a TS `@Component({ imports: [X] })` that references such a\n // class hits `_unresolved-${className}` as its selector and the tag\n // never matches at runtime.\n let compileRegistry: ComponentRegistry = registry;\n const externalRegistry = globalThis.__ANALOG_EXTERNAL_REGISTRY__;\n if (externalRegistry && externalRegistry.size > 0) {\n compileRegistry = new Map(registry);\n for (const [k, v] of externalRegistry) compileRegistry.set(k, v);\n }\n\n const result = compile(code, id, {\n registry: compileRegistry,\n resolvedStyles,\n resolvedInlineStyles,\n useDefineForClassFields,\n compilationMode: pluginOptions.fastCompileMode,\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\n const stripped = vite.transformWithOxc\n ? await vite.transformWithOxc(result.code, id, {\n lang: 'ts',\n sourcemap: false,\n decorator: { legacy: false, emitDecoratorMetadata: false },\n })\n : await vite.transformWithEsbuild(result.code, id, {\n loader: 'ts',\n sourcemap: false,\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: result.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 );\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 =\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 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 return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n resolve: {\n conditions: [\n ...depOptimizer.resolve.conditions,\n ...(config.resolve?.conditions || defaultClientConditions),\n ],\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\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 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 exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n if (\n pluginOptions.transformFilter &&\n !(pluginOptions.transformFilter(code, id) ?? true)\n ) {\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":";;;;;;;;;;;;;;;;;;AAqEA,SAAgB,kBACd,eACQ;CACR,IAAI;CACJ,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;;;;;;;;;;;;;CAc9B,eAAe,kBACb,MACA,0BAAuB,IAAI,KAAK,EAChC,YAAY,OACG;AACf,MAAI,QAAQ,IAAI,KAAK,CAAE;AACvB,UAAQ,IAAI,KAAK;EACjB,IAAI;AACJ,MAAI;AACF,UAAO,MAAM,SAAW,SAAS,MAAM,QAAQ;WACxC,GAAG;AACV,OAAI,cAAc,QAChB,eACE,4CACA,MACC,GAAa,QACf;AAEH;;EAEF,MAAM,UAAU,SAAS,MAAM,KAAK;AACpC,OAAK,MAAM,SAAS,QAIlB,KAAI,aAAa,CAAC,SAAS,IAAI,MAAM,UAAU,CAC7C,UAAS,IAAI,MAAM,WAAW,MAAM;EAQxC,MAAM,MAAM,QAAQ,KAAK;AACzB,OAAK,MAAM,OAAO,yBAAyB,MAAM,KAAK,EAAE;GAKtD,MAAM,gBAAgB,I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ypeScript file extension regex
3
- * Match .(c or m)ts, .ts extensions with an optional ? for query params
4
- * Ignore .tsx extensions
3
+ * Match .ts / .cts / .mts extensions with an optional ?query suffix.
4
+ * Reject .tsx — and any other `.ts<letter>…` extension like .tsrx — via
5
+ * a negative-lookahead on a following ASCII letter, so only genuine TS
6
+ * files pass.
7
+ *
8
+ * Previous form `/\.[cm]?(ts)[^x]?\??/` was intended to exclude `.tsx`
9
+ * specifically (`[^x]?` = not-an-x), but the `?` quantifier also allows
10
+ * zero characters, and any non-`x` letter was admitted — so `.tsrx`
11
+ * and similar extensions matched by accident.
5
12
  */
6
13
  export declare const TS_EXT_REGEX: unknown;
7
14
  export interface TsConfigResolutionContext {
@@ -5,10 +5,17 @@ import * as vite from "vite";
5
5
  //#region packages/vite-plugin-angular/src/lib/utils/plugin-config.ts
6
6
  /**
7
7
  * TypeScript file extension regex
8
- * Match .(c or m)ts, .ts extensions with an optional ? for query params
9
- * Ignore .tsx extensions
8
+ * Match .ts / .cts / .mts extensions with an optional ?query suffix.
9
+ * Reject .tsx — and any other `.ts<letter>…` extension like .tsrx — via
10
+ * a negative-lookahead on a following ASCII letter, so only genuine TS
11
+ * files pass.
12
+ *
13
+ * Previous form `/\.[cm]?(ts)[^x]?\??/` was intended to exclude `.tsx`
14
+ * specifically (`[^x]?` = not-an-x), but the `?` quantifier also allows
15
+ * zero characters, and any non-`x` letter was admitted — so `.tsrx`
16
+ * and similar extensions matched by accident.
10
17
  */
11
- var TS_EXT_REGEX = /\.[cm]?(ts)[^x]?\??/;
18
+ var TS_EXT_REGEX = /\.[cm]?ts(?![a-z])/;
12
19
  function getTsConfigPath(root, tsconfig, isProd, isTest, isLib) {
13
20
  if (tsconfig && isAbsolute(tsconfig)) {
14
21
  if (!existsSync(tsconfig)) console.error(`[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the "tsconfig" property with an absolute path.`);
@@ -1 +1 @@
1
- {"version":3,"file":"plugin-config.js","names":[],"sources":["../../../../src/lib/utils/plugin-config.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { isAbsolute, resolve } from 'node:path';\nimport * as vite from 'vite';\nimport { defaultClientConditions } from 'vite';\n\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\n\n/**\n * TypeScript file extension regex\n * Match .(c or m)ts, .ts extensions with an optional ? for query params\n * Ignore .tsx extensions\n */\nexport const TS_EXT_REGEX = /\\.[cm]?(ts)[^x]?\\??/;\n\nexport interface TsConfigResolutionContext {\n root: string;\n isProd: boolean;\n isLib: boolean;\n}\n\nexport function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (!existsSync(resolvedPath)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return resolvedPath;\n}\n\nexport function createTsConfigGetter(\n tsconfigOrGetter?: string | (() => string),\n) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n}\n\nexport interface DepOptimizerOptions {\n tsconfig: string;\n isProd: boolean;\n jit: boolean;\n watchMode: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n}\n\nexport function createDepOptimizerConfig(opts: DepOptimizerOptions) {\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(opts.watchMode ? {} : { ngDevMode: 'false' }),\n };\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] = {\n plugins: [\n createRolldownCompilerPlugin({\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n }),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n return {\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs'],\n exclude: ['@angular/platform-server'],\n ...(vite.rolldownVersion ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: ['style'],\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAeA,IAAa,eAAe;AAQ5B,SAAgB,gBACd,MACA,UACA,QACA,QACA,OACA;AACA,KAAI,YAAY,WAAW,SAAS,EAAE;AACpC,MAAI,CAAC,WAAW,SAAS,CACvB,SAAQ,MACN,kEAAkE,SAAS,wGAC5E;AAGH,SAAO;;CAGT,IAAI,mBAAmB;AAEvB,KAAI,MACF,oBAAmB,SACf,6BACA;AAGN,KAAI,OACF,oBAAmB;AAGrB,KAAI,SACF,oBAAmB;CAGrB,MAAM,eAAe,QAAQ,MAAM,iBAAiB;AAEpD,KAAI,CAAC,WAAW,aAAa,CAC3B,SAAQ,MACN,kEAAkE,aAAa,wGAChF;AAGH,QAAO;;AAGT,SAAgB,qBACd,kBACA;AACA,KAAI,OAAO,qBAAqB,WAC9B,QAAO;AAGT,cAAa,oBAAoB;;AAYnC,SAAgB,yBAAyB,MAA2B;CAClE,MAAM,gBAAgB;EACpB,WAAW;EACX,mBAAmB;EACnB,GAAI,KAAK,YAAY,EAAE,GAAG,EAAE,WAAW,SAAS;EACjD;CAED,MAAM,kBAAkE,EACtE,SAAS,CACP,6BAA6B;EAC3B,UAAU,KAAK;EACf,WAAW,CAAC,KAAK;EACjB,uBAAuB,KAAK;EAC5B,KAAK,KAAK;EACV,aAAa,KAAK;EACnB,CAAC,CACH,EACF;CAED,MAAM,iBAAgE;EACpE,SAAS,CACP,qBACE;GACE,UAAU,KAAK;GACf,WAAW,CAAC,KAAK;GACjB,uBAAuB,KAAK;GAC5B,KAAK,KAAK;GACV,aAAa,KAAK;GACnB,EACD,KAAK,QACL,CAAC,KAAK,mBACP,CACF;EACD,QAAQ;EACT;AAED,QAAO;EACL,cAAc;GACZ,SAAS,CAAC,kBAAkB,OAAO;GACnC,SAAS,CAAC,2BAA2B;GACrC,GAAI,KAAK,kBAAkB,EAAE,iBAAiB,GAAG,EAAE,gBAAgB;GACpE;EACD,SAAS,EACP,YAAY,CAAC,QAAQ,EACtB;EACF"}
1
+ {"version":3,"file":"plugin-config.js","names":[],"sources":["../../../../src/lib/utils/plugin-config.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { isAbsolute, resolve } from 'node:path';\nimport * as vite from 'vite';\nimport { defaultClientConditions } from 'vite';\n\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\n\n/**\n * TypeScript file extension regex\n * Match .ts / .cts / .mts extensions with an optional ?query suffix.\n * Reject .tsx — and any other `.ts<letter>…` extension like .tsrx — via\n * a negative-lookahead on a following ASCII letter, so only genuine TS\n * files pass.\n *\n * Previous form `/\\.[cm]?(ts)[^x]?\\??/` was intended to exclude `.tsx`\n * specifically (`[^x]?` = not-an-x), but the `?` quantifier also allows\n * zero characters, and any non-`x` letter was admitted — so `.tsrx`\n * and similar extensions matched by accident.\n */\nexport const TS_EXT_REGEX = /\\.[cm]?ts(?![a-z])/;\n\nexport interface TsConfigResolutionContext {\n root: string;\n isProd: boolean;\n isLib: boolean;\n}\n\nexport function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (!existsSync(resolvedPath)) {\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n }\n\n return resolvedPath;\n}\n\nexport function createTsConfigGetter(\n tsconfigOrGetter?: string | (() => string),\n) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n}\n\nexport interface DepOptimizerOptions {\n tsconfig: string;\n isProd: boolean;\n jit: boolean;\n watchMode: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n}\n\nexport function createDepOptimizerConfig(opts: DepOptimizerOptions) {\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(opts.watchMode ? {} : { ngDevMode: 'false' }),\n };\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] = {\n plugins: [\n createRolldownCompilerPlugin({\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n }),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n ),\n ],\n define: defineOptions,\n };\n\n return {\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs'],\n exclude: ['@angular/platform-server'],\n ...(vite.rolldownVersion ? { rolldownOptions } : { esbuildOptions }),\n },\n resolve: {\n conditions: ['style'],\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,IAAa,eAAe;AAQ5B,SAAgB,gBACd,MACA,UACA,QACA,QACA,OACA;AACA,KAAI,YAAY,WAAW,SAAS,EAAE;AACpC,MAAI,CAAC,WAAW,SAAS,CACvB,SAAQ,MACN,kEAAkE,SAAS,wGAC5E;AAGH,SAAO;;CAGT,IAAI,mBAAmB;AAEvB,KAAI,MACF,oBAAmB,SACf,6BACA;AAGN,KAAI,OACF,oBAAmB;AAGrB,KAAI,SACF,oBAAmB;CAGrB,MAAM,eAAe,QAAQ,MAAM,iBAAiB;AAEpD,KAAI,CAAC,WAAW,aAAa,CAC3B,SAAQ,MACN,kEAAkE,aAAa,wGAChF;AAGH,QAAO;;AAGT,SAAgB,qBACd,kBACA;AACA,KAAI,OAAO,qBAAqB,WAC9B,QAAO;AAGT,cAAa,oBAAoB;;AAYnC,SAAgB,yBAAyB,MAA2B;CAClE,MAAM,gBAAgB;EACpB,WAAW;EACX,mBAAmB;EACnB,GAAI,KAAK,YAAY,EAAE,GAAG,EAAE,WAAW,SAAS;EACjD;CAED,MAAM,kBAAkE,EACtE,SAAS,CACP,6BAA6B;EAC3B,UAAU,KAAK;EACf,WAAW,CAAC,KAAK;EACjB,uBAAuB,KAAK;EAC5B,KAAK,KAAK;EACV,aAAa,KAAK;EACnB,CAAC,CACH,EACF;C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