@analogjs/vite-plugin-angular 3.0.0 → 3.0.1-beta.1

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",
3
+ "version": "3.0.1-beta.1",
4
4
  "description": "Vite Plugin for Angular",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  import { type Logger, type Plugin, type ResolvedConfig, type UserConfig, type ViteDevServer } from "vite";
2
2
  import { type AnalogIntegrations, type ComponentRegistryEntries, type StylesheetRegistryConfigurator, type TransformFilter } from "./analog-plugin-interop.js";
3
- import type { EmitFileResult } from "./models.js";
3
+ import type { HmrUpdateResult } from "./models.js";
4
4
  import type { FileReplacement } from "./plugins/file-replacements.plugin.js";
5
5
  import { type StylePreprocessor } from "./style-preprocessor.js";
6
6
  import { AnalogStylesheetRegistry } from "./stylesheet-registry.js";
@@ -134,10 +134,12 @@ export interface AngularCompilerCapabilities {
134
134
  export type HmrIgnorePredicate = (file: string) => boolean;
135
135
  export interface AngularHmrStore {
136
136
  readonly rootDir: string;
137
- readonly classNames: Map<string, string>;
138
- fileEmitter: (file: string, className: string) => Pick<EmitFileResult, "hmrUpdateCode"> | undefined;
139
- setFileEmitter(emitter: (file: string, className: string) => Pick<EmitFileResult, "hmrUpdateCode"> | undefined): void;
137
+ readonly classNames: Map<string, Set<string>>;
138
+ fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;
139
+ setFileEmitter(emitter: (file: string, className: string) => HmrUpdateResult | undefined): void;
140
+ addClassName(fileId: string, className: string): void;
140
141
  toComponentUpdateId(fileId: string, className?: string): string;
142
+ toComponentUpdateIds(fileId: string): string[];
141
143
  resolveComponentFileId(fileId: string): string;
142
144
  sendComponentUpdate(server: ViteDevServer, id: string): void;
143
145
  addIgnoreFilter(predicate: HmrIgnorePredicate): void;
@@ -92,10 +92,25 @@ function createAngularHmrStore(rootDir = process.cwd()) {
92
92
  setFileEmitter(emitter) {
93
93
  activeEmitter = emitter;
94
94
  },
95
+ addClassName(fileId, className) {
96
+ if (!className) return;
97
+ let names = classNames.get(fileId);
98
+ if (!names) {
99
+ names = /* @__PURE__ */ new Set();
100
+ classNames.set(fileId, names);
101
+ }
102
+ names.add(className);
103
+ },
95
104
  toComponentUpdateId(fileId, className) {
96
- const resolvedClassName = className ?? classNames.get(fileId) ?? "";
105
+ const resolvedClassName = className ?? classNames.get(fileId)?.values().next().value ?? "";
97
106
  return `${normalizePath(relative(rootDir, fileId))}@${resolvedClassName}`;
98
107
  },
108
+ toComponentUpdateIds(fileId) {
109
+ const names = classNames.get(fileId);
110
+ if (!names?.size) return [];
111
+ const relativeFile = normalizePath(relative(rootDir, fileId));
112
+ return [...names].map((name) => `${relativeFile}@${name}`);
113
+ },
99
114
  resolveComponentFileId(fileId) {
100
115
  return normalizePath(resolve(rootDir, fileId));
101
116
  },
@@ -108,7 +123,6 @@ function createAngularHmrStore(rootDir = process.cwd()) {
108
123
  id: encodeURIComponent(id),
109
124
  timestamp: Date.now()
110
125
  });
111
- classNames.delete(id);
112
126
  },
113
127
  addIgnoreFilter(predicate) {
114
128
  if (!ignoreFilters.includes(predicate)) ignoreFilters.push(predicate);
@@ -1 +1 @@
1
- {"version":3,"file":"angular-build-context.js","names":[],"sources":["../../../src/lib/angular-build-context.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport {\n normalizePath,\n preprocessCSS,\n type Logger,\n type Plugin,\n type ResolvedConfig,\n type UserConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n discoverAnalogIntegrations,\n type AnalogIntegrations,\n type ComponentRegistryEntries,\n type StylesheetRegistryConfigurator,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport { isComponentStyleSheet } from './encapsulation-plugin.js';\nimport type { EmitFileResult } from './models.js';\nimport type { FileReplacement } from './plugins/file-replacements.plugin.js';\nimport {\n normalizeStylesheetDependencies,\n type StylePreprocessor,\n} from './style-preprocessor.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheetResult,\n registerStylesheetContent,\n} from './stylesheet-registry.js';\nimport {\n describeStylesheetContent,\n getBrowserModeCliOverride,\n isIgnoredHmrFile,\n isTestWatchMode,\n refreshStylesheetRegistryForFile,\n} from './utils/compilation-shared.js';\nimport {\n applyDebugOption,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from './utils/debug.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport type { TypeCheckerOption } from './utils/lsp-type-checker.js';\nimport {\n createTsConfigGetter,\n getTsConfigPath,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { reportStylesheetError } from './utils/stylesheet-warning.js';\nimport { TsconfigResolver } from './utils/tsconfig-resolver.js';\n\nexport interface PluginOptions {\n /**\n * Path to the tsconfig used for compilation, or a function returning it.\n * Defaults to `tsconfig.app.json` (`tsconfig.lib.json` for libraries,\n * `tsconfig.spec.json` in tests).\n */\n tsconfig?: string | (() => string);\n /**\n * Absolute path to the workspace root. Defaults to `NX_WORKSPACE_ROOT`,\n * then `process.cwd()`.\n */\n workspaceRoot?: string;\n /**\n * Stylesheet extension used for inline component `styles`. Defaults to `css`.\n */\n inlineStylesExtension?: string;\n /**\n * Compile components in JIT mode. Defaults to `true` in tests and `false`\n * otherwise.\n */\n jit?: boolean;\n /**\n * Additional files to include in compilation, as globs relative to the\n * workspace root.\n */\n include?: string[];\n /**\n * Enables Analog's Angular live-reload/HMR pipeline during development/watch mode.\n *\n * This is separate from Vite's `server.hmr` option, which configures the\n * HMR client transport.\n *\n * Defaults to `true` for watch mode, or `false` with `compilation: 'ngp'`,\n * which reloads the page on every change unless this is `true`. Set to\n * `false` to disable Angular reload updates while keeping other stylesheet\n * externalization behavior available when needed.\n */\n liveReload?: boolean;\n /**\n * Skip semantic and Angular template diagnostics during compilation.\n * Defaults to `true`, or `false` with `compilation: 'ngp'`, which requires\n * a TypeScript 7 type checker (see `typeChecker`).\n */\n disableTypeChecking?: boolean;\n /**\n * TypeScript 7 type checker used with `compilation: 'ngp'`: `'tsgo'`\n * (default), `'tsrs'`, or a command serving the TypeScript 7 language\n * server over stdio (`args` defaults to `['--lsp', '--stdio']`).\n */\n typeChecker?: TypeCheckerOption;\n /**\n * Replace source files at build time, like `fileReplacements` in\n * `angular.json`.\n */\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 when\n * `compilation` is not specified.\n * Defaults to `false`.\n */\n fastCompile?: boolean;\n /**\n * Selects the compilation path, overriding fastCompile. Defaults to 'ngtsc';\n * 'ngp' is experimental and falls back to 'ngtsc' under Vitest's JIT default.\n */\n compilation?: 'ngtsc' | 'ngp';\n /**\n * Compilation output mode used when `fastCompile` is enabled.\n * - `'full'` (default): Emit final Ivy definitions for application builds.\n * - `'partial'`: Emit partial declarations for library publishing.\n */\n fastCompileMode?: 'full' | 'partial';\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:hmr']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n}\n\nexport type AngularCompilationBackend =\n | 'ngtsc'\n | 'fast'\n | 'ngp'\n | 'compilation-api';\n\nexport interface AngularBuildContextOptions extends PluginOptions {\n /**\n * Explicit compiler backend selection when composing plugins directly.\n * Overrides `compilation` and `fastCompile` when set.\n */\n compilationBackend?: AngularCompilationBackend;\n /**\n * Target browser list used by `@angular/build` Compilation API.\n */\n supportedBrowsers?: string[];\n}\n\nexport interface NormalizedAngularOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n include: string[];\n liveReload: boolean;\n disableTypeChecking: boolean;\n typeChecker?: TypeCheckerOption;\n fileReplacements: FileReplacement[];\n compilation: AngularCompilationBackend;\n fastCompile: boolean;\n fastCompileMode: 'full' | 'partial';\n supportedBrowsers: string[];\n isTest: boolean;\n isStackBlitz: boolean;\n isAstroIntegration: boolean;\n isVitestVscode: boolean;\n}\n\nexport interface AngularCompilerCapabilities {\n readonly name: string;\n readonly getTsConfigPath: () => string;\n readonly getSourceMap?: (id: string) => string | undefined;\n readonly hasEmitted?: (id: string) => boolean;\n}\n\nexport type HmrIgnorePredicate = (file: string) => boolean;\n\nexport interface AngularHmrStore {\n readonly rootDir: string;\n readonly classNames: Map<string, string>;\n fileEmitter: (\n file: string,\n className: string,\n ) => Pick<EmitFileResult, 'hmrUpdateCode'> | undefined;\n setFileEmitter(\n emitter: (\n file: string,\n className: string,\n ) => Pick<EmitFileResult, 'hmrUpdateCode'> | undefined,\n ): void;\n toComponentUpdateId(fileId: string, className?: string): string;\n resolveComponentFileId(fileId: string): string;\n sendComponentUpdate(server: ViteDevServer, id: string): void;\n addIgnoreFilter(predicate: HmrIgnorePredicate): void;\n isIgnoredFile(file: string): boolean;\n clear(): void;\n}\n\nexport interface StylesheetTransformInput {\n data: string;\n containingFile: string;\n resourceFile?: string | null;\n order?: number;\n className?: string | null;\n readMissingResource?: boolean;\n eagerTransform?: (\n code: string,\n id: string,\n ) => Promise<{ code?: string } | null | undefined>;\n logger?: Logger;\n}\n\nexport interface AngularStylesheetService {\n registry: AnalogStylesheetRegistry | undefined;\n resetRegistry(externalize: boolean): AnalogStylesheetRegistry | undefined;\n ensureRegistry(): AnalogStylesheetRegistry;\n transformStylesheet(\n input: StylesheetTransformInput,\n ): Promise<{ content: string; externalized: boolean } | null>;\n resolveComponentStyleId(id: string): string | undefined;\n loadComponentStyle(id: string): string | undefined;\n refreshForFile(file: string): void;\n clear(): void;\n}\n\nconst ANGULAR_BUILD_CONTEXT_BRAND = Symbol.for(\n '@analogjs/vite-plugin-angular:build-context',\n);\n\nexport const ANGULAR_COMPILER_PLUGIN_NAMES: readonly string[] = [\n '@analogjs/vite-plugin-angular',\n '@analogjs/vite-plugin-angular-fast-compile',\n '@analogjs/vite-plugin-angular-compilation-api',\n '@analogjs/vite-plugin-angular-ngp',\n];\n\nexport interface AngularBuildContext {\n readonly kind: 'angular-build-context';\n readonly options: NormalizedAngularOptions;\n readonly tsconfigResolver: TsconfigResolver;\n readonly hmr: AngularHmrStore;\n readonly styles: AngularStylesheetService;\n compiler: AngularCompilerCapabilities | undefined;\n watchMode: boolean;\n testWatchMode: boolean;\n deferInitialCompilation: boolean;\n resolvedConfig: ResolvedConfig | undefined;\n tsConfigResolutionContext: TsConfigResolutionContext | null;\n stylePreprocessor: StylePreprocessor | undefined;\n configureStylesheetRegistry: StylesheetRegistryConfigurator | undefined;\n transformFilter: TransformFilter | undefined;\n componentRegistries: ComponentRegistryEntries[];\n externalizeStylesRequested: boolean;\n initConfig(\n config: UserConfig,\n env: { command: 'build' | 'serve'; mode?: string },\n ): TsConfigResolutionContext;\n setResolvedConfig(config: ResolvedConfig): void;\n resolveConfig(config: ResolvedConfig): Promise<AnalogIntegrations>;\n refreshIntegrations(config?: ResolvedConfig): Promise<AnalogIntegrations>;\n resolveTsConfigPath(): string;\n hasViteHmrTransport(): boolean;\n shouldEnableLiveReload(): boolean;\n shouldExternalizeStyles(): boolean;\n registerCompiler(capabilities: AngularCompilerCapabilities): void;\n}\n\nconst patchedLoggers = new WeakSet<Logger>();\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 */\nexport function 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\nexport function resolveComponentStyleId(\n id: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): string | undefined {\n if (!isComponentStyleSheet(id)) {\n return undefined;\n }\n\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + search;\n }\n\n debugStyles('resolveId: component stylesheet NOT FOUND in either map', {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n });\n\n return undefined;\n}\n\nexport function loadComponentStyle(\n id: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): string | undefined {\n if (!isComponentStyleSheet(id)) {\n return undefined;\n }\n\n const filename = getFilenameFromPath(id);\n const componentStyles = stylesheetRegistry?.getServedContent(filename);\n if (!componentStyles) {\n return undefined;\n }\n\n stylesheetRegistry?.registerActiveRequest(id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(filename.replace(/^\\//, '')) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(filename.replace(/^\\//, ''));\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n}\n\nexport function isAngularBuildContext(\n value: unknown,\n): value is AngularBuildContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n ANGULAR_BUILD_CONTEXT_BRAND in value\n );\n}\n\nexport function createAngularHmrStore(\n rootDir: string = process.cwd(),\n): AngularHmrStore {\n const classNames = new Map<string, string>();\n const ignoreFilters: HmrIgnorePredicate[] = [isIgnoredHmrFile];\n let activeEmitter: (\n file: string,\n className: string,\n ) => Pick<EmitFileResult, 'hmrUpdateCode'> | undefined = () => undefined;\n\n return {\n rootDir,\n classNames,\n fileEmitter(file: string, className: string) {\n return activeEmitter(file, className);\n },\n setFileEmitter(emitter) {\n activeEmitter = emitter;\n },\n toComponentUpdateId(fileId: string, className?: string): string {\n const resolvedClassName = className ?? classNames.get(fileId) ?? '';\n return `${normalizePath(relative(rootDir, fileId))}@${resolvedClassName}`;\n },\n resolveComponentFileId(fileId: string): string {\n return normalizePath(resolve(rootDir, fileId));\n },\n sendComponentUpdate(server: ViteDevServer, id: string): void {\n debugHmrV('ws send: angular component update', {\n id,\n timestamp: Date.now(),\n });\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(id),\n timestamp: Date.now(),\n });\n classNames.delete(id);\n },\n addIgnoreFilter(predicate: HmrIgnorePredicate): void {\n if (!ignoreFilters.includes(predicate)) {\n ignoreFilters.push(predicate);\n }\n },\n isIgnoredFile(file: string): boolean {\n return ignoreFilters.some((predicate) => predicate(file));\n },\n clear(): void {\n classNames.clear();\n },\n };\n}\n\nfunction resolveBackend(\n options: AngularBuildContextOptions | undefined,\n isTest: boolean,\n): AngularCompilationBackend {\n if (options?.compilationBackend) {\n return options.compilationBackend;\n }\n\n const compilation =\n options?.compilation === 'ngp' && !(isTest && options.jit === undefined)\n ? 'ngp'\n : 'ngtsc';\n\n if (compilation === 'ngp') {\n return 'ngp';\n }\n\n if (options?.compilation === undefined && options?.fastCompile) {\n return 'fast';\n }\n\n return 'ngtsc';\n}\n\nexport function createAngularBuildContext(\n options?: AngularBuildContextOptions,\n): AngularBuildContext {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const compilation = resolveBackend(options, isTest);\n\n // Test mode under NgtscProgram disables WebSocket-based liveReload because\n // Vitest's runner does not consume Angular's component-update WS events.\n // Style externalization still checks `externalizeStylesRequested` separately.\n let liveReload =\n options?.liveReload ?? (compilation !== 'ngp' ? true : false);\n if (compilation === 'ngtsc' && isTest) {\n liveReload = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n const normalizedOptions: NormalizedAngularOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot:\n options?.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n jit: typeof options?.jit !== 'undefined' ? options.jit : isTest,\n include: options?.include ?? [],\n liveReload,\n disableTypeChecking:\n options?.disableTypeChecking ?? (compilation !== 'ngp' ? true : false),\n typeChecker: options?.typeChecker,\n fileReplacements: options?.fileReplacements ?? [],\n compilation,\n fastCompile: compilation === 'fast',\n fastCompileMode: options?.fastCompileMode ?? 'full',\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n isTest,\n isStackBlitz,\n isAstroIntegration,\n isVitestVscode,\n };\n\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: normalizedOptions.workspaceRoot,\n include: normalizedOptions.include,\n liveReload: normalizedOptions.liveReload,\n isTest: normalizedOptions.isTest,\n });\n\n const hmr = createAngularHmrStore();\n\n let ctx!: AngularBuildContext;\n\n const styles: AngularStylesheetService = {\n registry: undefined,\n\n resetRegistry(externalize: boolean): AnalogStylesheetRegistry | undefined {\n styles.registry = externalize\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (styles.registry) {\n ctx.configureStylesheetRegistry?.(styles.registry, {\n workspaceRoot: normalizedOptions.workspaceRoot,\n });\n }\n return styles.registry;\n },\n\n ensureRegistry(): AnalogStylesheetRegistry {\n if (!styles.registry) {\n styles.registry = new AnalogStylesheetRegistry();\n ctx.configureStylesheetRegistry?.(styles.registry, {\n workspaceRoot: normalizedOptions.workspaceRoot,\n });\n }\n return styles.registry;\n },\n\n async transformStylesheet(\n input: StylesheetTransformInput,\n ): Promise<{ content: string; externalized: boolean } | null> {\n let data = input.data;\n if (input.readMissingResource && input.resourceFile && !data) {\n data = readFileSync(input.resourceFile, 'utf-8');\n }\n\n const filename =\n input.resourceFile ??\n input.containingFile.replace(\n '.ts',\n `.${normalizedOptions.inlineStylesExtension}`,\n );\n\n const preprocessed = preprocessStylesheetResult(\n data,\n filename,\n ctx.stylePreprocessor,\n {\n filename,\n containingFile: input.containingFile,\n resourceFile: input.resourceFile ?? undefined,\n className: input.className ?? undefined,\n order: input.order,\n inline: !input.resourceFile,\n },\n );\n\n if (ctx.shouldExternalizeStyles() && styles.registry) {\n const stylesheetId = registerStylesheetContent(styles.registry, {\n code: preprocessed.code,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n containingFile: input.containingFile,\n className: input.className ?? undefined,\n order: input.order,\n inlineStylesExtension: normalizedOptions.inlineStylesExtension,\n resourceFile: input.resourceFile ?? undefined,\n });\n\n debugStyles('stylesheet deferred to Vite pipeline', {\n stylesheetId,\n resourceFile: input.resourceFile ?? '(inline)',\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n });\n\n return { content: stylesheetId, externalized: true };\n }\n\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: input.resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n\n let stylesheetResult: { code?: string } | null | undefined;\n try {\n if (input.eagerTransform) {\n stylesheetResult = await input.eagerTransform(\n preprocessed.code,\n `${filename}?direct`,\n );\n } else if (ctx.resolvedConfig) {\n stylesheetResult = await preprocessCSS(\n preprocessed.code,\n `${filename}?direct`,\n ctx.resolvedConfig,\n );\n }\n } catch (e) {\n debugStyles('stylesheet transform error', {\n filename,\n resourceFile: input.resourceFile ?? '(inline)',\n error: String(e),\n });\n reportStylesheetError(\n input.logger ?? ctx.resolvedConfig?.logger,\n filename,\n e,\n ctx.resolvedConfig?.command === 'build',\n );\n }\n\n if (!stylesheetResult?.code) {\n return null;\n }\n\n return { content: stylesheetResult.code, externalized: false };\n },\n\n resolveComponentStyleId(id: string): string | undefined {\n return resolveComponentStyleId(id, styles.registry);\n },\n\n loadComponentStyle(id: string): string | undefined {\n return loadComponentStyle(id, styles.registry);\n },\n\n refreshForFile(file: string): void {\n refreshStylesheetRegistryForFile(\n file,\n styles.registry,\n ctx.stylePreprocessor,\n );\n },\n\n clear(): void {\n styles.registry = undefined;\n },\n };\n\n ctx = {\n kind: 'angular-build-context',\n options: normalizedOptions,\n tsconfigResolver,\n hmr,\n styles,\n compiler: undefined,\n watchMode: false,\n testWatchMode: isTestWatchMode(),\n deferInitialCompilation: isVitestVscode,\n resolvedConfig: undefined,\n tsConfigResolutionContext: null,\n stylePreprocessor: undefined,\n configureStylesheetRegistry: undefined,\n transformFilter: undefined,\n componentRegistries: [],\n externalizeStylesRequested: false,\n\n initConfig(config, { command }) {\n ctx.watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n ctx.tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n return ctx.tsConfigResolutionContext;\n },\n\n setResolvedConfig(config: ResolvedConfig) {\n ctx.resolvedConfig = config;\n ctx.tsConfigResolutionContext ??= {\n root: config.root || '.',\n isProd: isProdMode(config.mode),\n isLib: !!config?.build?.lib,\n };\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 && !patchedLoggers.has(config.logger)) {\n patchedLoggers.add(config.logger);\n const originalWarnOnce = config.logger.warnOnce;\n config.logger.warnOnce = (msg, warnOptions) => {\n if (\n typeof msg === 'string' &&\n msg.includes('Sourcemap') &&\n msg.includes('node_modules')\n ) {\n return;\n }\n originalWarnOnce(msg, warnOptions);\n };\n }\n\n if (normalizedOptions.isTest) {\n const browser = (\n config as unknown as {\n test?: { browser?: { enabled?: boolean }; watch?: boolean };\n }\n ).test?.browser;\n ctx.deferInitialCompilation =\n normalizedOptions.isVitestVscode ||\n (!!browser &&\n (getBrowserModeCliOverride() ?? browser.enabled) === true);\n\n ctx.testWatchMode =\n !(config.server?.watch === null) ||\n (config as unknown as { test?: { watch?: boolean } }).test?.watch ===\n true ||\n ctx.testWatchMode;\n }\n },\n\n async resolveConfig(config: ResolvedConfig): Promise<AnalogIntegrations> {\n ctx.setResolvedConfig(config);\n return ctx.refreshIntegrations(config);\n },\n\n async refreshIntegrations(\n config?: ResolvedConfig,\n ): Promise<AnalogIntegrations> {\n const targetConfig = config ?? ctx.resolvedConfig;\n if (!targetConfig) {\n return {\n componentRegistries: [],\n include: [],\n externalizeStyles: false,\n };\n }\n\n const integrations = await discoverAnalogIntegrations(targetConfig);\n ctx.stylePreprocessor = integrations.stylePreprocessor;\n ctx.configureStylesheetRegistry =\n integrations.configureStylesheetRegistry;\n ctx.transformFilter = integrations.transformFilter;\n ctx.componentRegistries = integrations.componentRegistries;\n ctx.externalizeStylesRequested = integrations.externalizeStyles;\n ctx.tsconfigResolver.setIntegrationIncludes(integrations.include);\n return integrations;\n },\n\n resolveTsConfigPath(): string {\n const resolution = ctx.tsConfigResolutionContext ?? {\n root: ctx.resolvedConfig?.root || '.',\n isProd: isProdMode(ctx.resolvedConfig?.mode),\n isLib: !!ctx.resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n resolution.root,\n normalizedOptions.tsconfigGetter(),\n resolution.isProd,\n normalizedOptions.isTest,\n resolution.isLib,\n normalizedOptions.workspaceRoot,\n );\n },\n\n hasViteHmrTransport(): boolean {\n return ctx.resolvedConfig\n ? ctx.resolvedConfig.server?.hmr !== false\n : true;\n },\n\n shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = normalizedOptions.isTest\n ? ctx.testWatchMode\n : ctx.watchMode;\n return !!(\n effectiveWatchMode &&\n normalizedOptions.liveReload &&\n ctx.hasViteHmrTransport()\n );\n },\n\n shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = normalizedOptions.isTest\n ? ctx.testWatchMode\n : ctx.watchMode;\n if (!effectiveWatchMode) return false;\n return !!(ctx.shouldEnableLiveReload() || ctx.externalizeStylesRequested);\n },\n\n registerCompiler(capabilities: AngularCompilerCapabilities): void {\n ctx.compiler = capabilities;\n },\n };\n\n Object.defineProperty(ctx, ANGULAR_BUILD_CONTEXT_BRAND, {\n value: true,\n enumerable: false,\n });\n\n return ctx;\n}\n\nexport function ensureAngularBuildContext(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): AngularBuildContext {\n if (isAngularBuildContext(ctxOrOptions)) {\n return ctxOrOptions;\n }\n return createAngularBuildContext(ctxOrOptions);\n}\n\nexport function isAngularCompilerPlugin(plugin: Plugin): boolean {\n const api = plugin.api as\n | { angularCompiler?: boolean; getTsConfigPath?: unknown }\n | undefined;\n return (\n api?.angularCompiler === true ||\n ANGULAR_COMPILER_PLUGIN_NAMES.includes(plugin.name)\n );\n}\n\nexport function getAngularCompilerApi(\n plugins: readonly Plugin[],\n): AngularCompilerCapabilities | undefined {\n for (const plugin of plugins) {\n if (!isAngularCompilerPlugin(plugin)) {\n continue;\n }\n const api = plugin.api as Partial<AngularCompilerCapabilities> | undefined;\n if (typeof api?.getTsConfigPath === 'function') {\n return {\n name: plugin.name,\n getTsConfigPath: api.getTsConfigP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ACrB;GAGF,MAAM,eAAe,MAAM,2BAA2B,YAAY;GAClE,IAAI,oBAAoB,aAAa;GACrC,IAAI,8BACF,aAAa;GACf,IAAI,kBAAkB,aAAa;GACnC,IAAI,sBAAsB,aAAa;GACvC,IAAI,6BAA6B,aAAa;GAC9C,IAAI,iBAAiB,uBAAuB,aAAa,OAAO;GAChE,OAAO;EACT;EAEA,sBAA8B;GAC5B,MAAM,aAAa,IAAI,6BAA6B;IAClD,MAAM,IAAI,gBAAgB,QAAQ;IAClC,QAAQ,WAAW,IAAI,gBAAgB,IAAI;IAC3C,OAAO,CAAC,CAAC,IAAI,gBAAgB,OAAO;GACtC;GACA,OAAO,gBACL,WAAW,MACX,kBAAkB,eAAe,GACjC,WAAW,QACX,kBAAkB,QAClB,WAAW,OACX,kBAAkB,aACpB;EACF;EAEA,sBAA+B;GAC7B,OAAO,IAAI,iBACP,IAAI,eAAe,QAAQ,QAAQ,QACnC;EACN;EAEA,yBAAkC;GAIhC,OAAO,CAAC,GAHmB,kBAAkB,SACzC,IAAI,gBACJ,IAAI,cAGN,kBAAkB,cAClB,IAAI,oBAAoB;EAE5B;EAEA,0BAAmC;GAIjC,IAAI,EAHuB,kBAAkB,SACzC,IAAI,gBACJ,IAAI,YACiB,OAAO;GAChC,OAAO,CAAC,EAAE,IAAI,uBAAuB,KAAK,IAAI;EAChD;EAEA,iBAAiB,cAAiD;GAChE,IAAI,WAAW;EACjB;CACF;CAEA,OAAO,eAAe,KAAK,6BAA6B;EACtD,OAAO;EACP,YAAY;CACd,CAAC;CAED,OAAO;AACT;AAEA,SAAgB,0BACd,cACqB;CACrB,IAAI,sBAAsB,YAAY,GACpC,OAAO;CAET,OAAO,0BAA0B,YAAY;AAC/C"}
1
+ {"version":3,"file":"angular-build-context.js","names":[],"sources":["../../../src/lib/angular-build-context.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport {\n normalizePath,\n preprocessCSS,\n type Logger,\n type Plugin,\n type ResolvedConfig,\n type UserConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n discoverAnalogIntegrations,\n type AnalogIntegrations,\n type ComponentRegistryEntries,\n type StylesheetRegistryConfigurator,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport { isComponentStyleSheet } from './encapsulation-plugin.js';\nimport type { HmrUpdateResult } from './models.js';\nimport type { FileReplacement } from './plugins/file-replacements.plugin.js';\nimport {\n normalizeStylesheetDependencies,\n type StylePreprocessor,\n} from './style-preprocessor.js';\nimport {\n AnalogStylesheetRegistry,\n preprocessStylesheetResult,\n registerStylesheetContent,\n} from './stylesheet-registry.js';\nimport {\n describeStylesheetContent,\n getBrowserModeCliOverride,\n isIgnoredHmrFile,\n isTestWatchMode,\n refreshStylesheetRegistryForFile,\n} from './utils/compilation-shared.js';\nimport {\n applyDebugOption,\n debugHmr,\n debugHmrV,\n debugStyles,\n debugStylesV,\n type DebugOption,\n} from './utils/debug.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport type { TypeCheckerOption } from './utils/lsp-type-checker.js';\nimport {\n createTsConfigGetter,\n getTsConfigPath,\n isProdMode,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { reportStylesheetError } from './utils/stylesheet-warning.js';\nimport { TsconfigResolver } from './utils/tsconfig-resolver.js';\n\nexport interface PluginOptions {\n /**\n * Path to the tsconfig used for compilation, or a function returning it.\n * Defaults to `tsconfig.app.json` (`tsconfig.lib.json` for libraries,\n * `tsconfig.spec.json` in tests).\n */\n tsconfig?: string | (() => string);\n /**\n * Absolute path to the workspace root. Defaults to `NX_WORKSPACE_ROOT`,\n * then `process.cwd()`.\n */\n workspaceRoot?: string;\n /**\n * Stylesheet extension used for inline component `styles`. Defaults to `css`.\n */\n inlineStylesExtension?: string;\n /**\n * Compile components in JIT mode. Defaults to `true` in tests and `false`\n * otherwise.\n */\n jit?: boolean;\n /**\n * Additional files to include in compilation, as globs relative to the\n * workspace root.\n */\n include?: string[];\n /**\n * Enables Analog's Angular live-reload/HMR pipeline during development/watch mode.\n *\n * This is separate from Vite's `server.hmr` option, which configures the\n * HMR client transport.\n *\n * Defaults to `true` for watch mode, or `false` with `compilation: 'ngp'`,\n * which reloads the page on every change unless this is `true`. Set to\n * `false` to disable Angular reload updates while keeping other stylesheet\n * externalization behavior available when needed.\n */\n liveReload?: boolean;\n /**\n * Skip semantic and Angular template diagnostics during compilation.\n * Defaults to `true`, or `false` with `compilation: 'ngp'`, which requires\n * a TypeScript 7 type checker (see `typeChecker`).\n */\n disableTypeChecking?: boolean;\n /**\n * TypeScript 7 type checker used with `compilation: 'ngp'`: `'tsgo'`\n * (default), `'tsrs'`, or a command serving the TypeScript 7 language\n * server over stdio (`args` defaults to `['--lsp', '--stdio']`).\n */\n typeChecker?: TypeCheckerOption;\n /**\n * Replace source files at build time, like `fileReplacements` in\n * `angular.json`.\n */\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 when\n * `compilation` is not specified.\n * Defaults to `false`.\n */\n fastCompile?: boolean;\n /**\n * Selects the compilation path, overriding fastCompile. Defaults to 'ngtsc';\n * 'ngp' is experimental and falls back to 'ngtsc' under Vitest's JIT default.\n */\n compilation?: 'ngtsc' | 'ngp';\n /**\n * Compilation output mode used when `fastCompile` is enabled.\n * - `'full'` (default): Emit final Ivy definitions for application builds.\n * - `'partial'`: Emit partial declarations for library publishing.\n */\n fastCompileMode?: 'full' | 'partial';\n /**\n * Enable debug logging for specific scopes.\n *\n * - `true` → enables all `analog:angular:*` scopes\n * - `string[]` → enables listed namespaces (e.g. `['analog:angular:hmr']`)\n * - `{ scopes?, mode? }` → object form with optional `mode: 'build' | 'dev'`\n * to restrict output to a specific Vite command (omit for both)\n *\n * Also responds to the `DEBUG` env var (Node.js) or `localStorage.debug`\n * (browser), using the `obug` convention.\n */\n debug?: DebugOption;\n}\n\nexport type AngularCompilationBackend =\n | 'ngtsc'\n | 'fast'\n | 'ngp'\n | 'compilation-api';\n\nexport interface AngularBuildContextOptions extends PluginOptions {\n /**\n * Explicit compiler backend selection when composing plugins directly.\n * Overrides `compilation` and `fastCompile` when set.\n */\n compilationBackend?: AngularCompilationBackend;\n /**\n * Target browser list used by `@angular/build` Compilation API.\n */\n supportedBrowsers?: string[];\n}\n\nexport interface NormalizedAngularOptions {\n tsconfigGetter: () => string;\n workspaceRoot: string;\n inlineStylesExtension: string;\n jit: boolean;\n include: string[];\n liveReload: boolean;\n disableTypeChecking: boolean;\n typeChecker?: TypeCheckerOption;\n fileReplacements: FileReplacement[];\n compilation: AngularCompilationBackend;\n fastCompile: boolean;\n fastCompileMode: 'full' | 'partial';\n supportedBrowsers: string[];\n isTest: boolean;\n isStackBlitz: boolean;\n isAstroIntegration: boolean;\n isVitestVscode: boolean;\n}\n\nexport interface AngularCompilerCapabilities {\n readonly name: string;\n readonly getTsConfigPath: () => string;\n readonly getSourceMap?: (id: string) => string | undefined;\n readonly hasEmitted?: (id: string) => boolean;\n}\n\nexport type HmrIgnorePredicate = (file: string) => boolean;\n\nexport interface AngularHmrStore {\n readonly rootDir: string;\n readonly classNames: Map<string, Set<string>>;\n fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;\n setFileEmitter(\n emitter: (file: string, className: string) => HmrUpdateResult | undefined,\n ): void;\n addClassName(fileId: string, className: string): void;\n toComponentUpdateId(fileId: string, className?: string): string;\n toComponentUpdateIds(fileId: string): string[];\n resolveComponentFileId(fileId: string): string;\n sendComponentUpdate(server: ViteDevServer, id: string): void;\n addIgnoreFilter(predicate: HmrIgnorePredicate): void;\n isIgnoredFile(file: string): boolean;\n clear(): void;\n}\n\nexport interface StylesheetTransformInput {\n data: string;\n containingFile: string;\n resourceFile?: string | null;\n order?: number;\n className?: string | null;\n readMissingResource?: boolean;\n eagerTransform?: (\n code: string,\n id: string,\n ) => Promise<{ code?: string } | null | undefined>;\n logger?: Logger;\n}\n\nexport interface AngularStylesheetService {\n registry: AnalogStylesheetRegistry | undefined;\n resetRegistry(externalize: boolean): AnalogStylesheetRegistry | undefined;\n ensureRegistry(): AnalogStylesheetRegistry;\n transformStylesheet(\n input: StylesheetTransformInput,\n ): Promise<{ content: string; externalized: boolean } | null>;\n resolveComponentStyleId(id: string): string | undefined;\n loadComponentStyle(id: string): string | undefined;\n refreshForFile(file: string): void;\n clear(): void;\n}\n\nconst ANGULAR_BUILD_CONTEXT_BRAND = Symbol.for(\n '@analogjs/vite-plugin-angular:build-context',\n);\n\nexport const ANGULAR_COMPILER_PLUGIN_NAMES: readonly string[] = [\n '@analogjs/vite-plugin-angular',\n '@analogjs/vite-plugin-angular-fast-compile',\n '@analogjs/vite-plugin-angular-compilation-api',\n '@analogjs/vite-plugin-angular-ngp',\n];\n\nexport interface AngularBuildContext {\n readonly kind: 'angular-build-context';\n readonly options: NormalizedAngularOptions;\n readonly tsconfigResolver: TsconfigResolver;\n readonly hmr: AngularHmrStore;\n readonly styles: AngularStylesheetService;\n compiler: AngularCompilerCapabilities | undefined;\n watchMode: boolean;\n testWatchMode: boolean;\n deferInitialCompilation: boolean;\n resolvedConfig: ResolvedConfig | undefined;\n tsConfigResolutionContext: TsConfigResolutionContext | null;\n stylePreprocessor: StylePreprocessor | undefined;\n configureStylesheetRegistry: StylesheetRegistryConfigurator | undefined;\n transformFilter: TransformFilter | undefined;\n componentRegistries: ComponentRegistryEntries[];\n externalizeStylesRequested: boolean;\n initConfig(\n config: UserConfig,\n env: { command: 'build' | 'serve'; mode?: string },\n ): TsConfigResolutionContext;\n setResolvedConfig(config: ResolvedConfig): void;\n resolveConfig(config: ResolvedConfig): Promise<AnalogIntegrations>;\n refreshIntegrations(config?: ResolvedConfig): Promise<AnalogIntegrations>;\n resolveTsConfigPath(): string;\n hasViteHmrTransport(): boolean;\n shouldEnableLiveReload(): boolean;\n shouldExternalizeStyles(): boolean;\n registerCompiler(capabilities: AngularCompilerCapabilities): void;\n}\n\nconst patchedLoggers = new WeakSet<Logger>();\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 */\nexport function 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\nexport function resolveComponentStyleId(\n id: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): string | undefined {\n if (!isComponentStyleSheet(id)) {\n return undefined;\n }\n\n const filename = getFilenameFromPath(id);\n const search = new URL(id, 'http://localhost').search;\n const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);\n\n if (servedSourcePath) {\n debugStylesV('resolveId: mapped served stylesheet to source', {\n filename,\n resolvedPath: servedSourcePath,\n });\n return servedSourcePath + search;\n }\n\n if (stylesheetRegistry?.hasServed(filename)) {\n debugStylesV('resolveId: kept preprocessed ID', { filename });\n return id;\n }\n\n const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);\n if (componentStyles) {\n debugStylesV('resolveId: mapped external stylesheet', {\n filename,\n resolvedPath: componentStyles,\n });\n return componentStyles + search;\n }\n\n debugStyles('resolveId: component stylesheet NOT FOUND in either map', {\n filename,\n inlineMapSize: stylesheetRegistry?.servedCount ?? 0,\n externalMapSize: stylesheetRegistry?.externalCount ?? 0,\n });\n\n return undefined;\n}\n\nexport function loadComponentStyle(\n id: string,\n stylesheetRegistry?: AnalogStylesheetRegistry,\n): string | undefined {\n if (!isComponentStyleSheet(id)) {\n return undefined;\n }\n\n const filename = getFilenameFromPath(id);\n const componentStyles = stylesheetRegistry?.getServedContent(filename);\n if (!componentStyles) {\n return undefined;\n }\n\n stylesheetRegistry?.registerActiveRequest(id);\n const sourcePath =\n stylesheetRegistry?.resolveExternalSource(filename) ??\n stylesheetRegistry?.resolveExternalSource(filename.replace(/^\\//, '')) ??\n stylesheetRegistry?.getServedSourcePath(filename) ??\n stylesheetRegistry?.getServedSourcePath(filename.replace(/^\\//, ''));\n debugHmrV('stylesheet active request registered', {\n requestId: id,\n filename,\n sourcePath,\n trackedRequestIds:\n stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? '') ?? [],\n });\n debugStylesV('load: served inline component stylesheet', {\n filename,\n requestId: id,\n ...describeStylesheetContent(componentStyles),\n });\n return componentStyles;\n}\n\nexport function isAngularBuildContext(\n value: unknown,\n): value is AngularBuildContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n ANGULAR_BUILD_CONTEXT_BRAND in value\n );\n}\n\nexport function createAngularHmrStore(\n rootDir: string = process.cwd(),\n): AngularHmrStore {\n const classNames = new Map<string, Set<string>>();\n const ignoreFilters: HmrIgnorePredicate[] = [isIgnoredHmrFile];\n let activeEmitter: (\n file: string,\n className: string,\n ) => HmrUpdateResult | undefined = () => undefined;\n\n return {\n rootDir,\n classNames,\n fileEmitter(file: string, className: string) {\n return activeEmitter(file, className);\n },\n setFileEmitter(emitter) {\n activeEmitter = emitter;\n },\n addClassName(fileId: string, className: string): void {\n if (!className) {\n return;\n }\n let names = classNames.get(fileId);\n if (!names) {\n names = new Set<string>();\n classNames.set(fileId, names);\n }\n names.add(className);\n },\n toComponentUpdateId(fileId: string, className?: string): string {\n const resolvedClassName =\n className ?? classNames.get(fileId)?.values().next().value ?? '';\n return `${normalizePath(relative(rootDir, fileId))}@${resolvedClassName}`;\n },\n toComponentUpdateIds(fileId: string): string[] {\n const names = classNames.get(fileId);\n if (!names?.size) {\n return [];\n }\n const relativeFile = normalizePath(relative(rootDir, fileId));\n return [...names].map((name) => `${relativeFile}@${name}`);\n },\n resolveComponentFileId(fileId: string): string {\n return normalizePath(resolve(rootDir, fileId));\n },\n sendComponentUpdate(server: ViteDevServer, id: string): void {\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 addIgnoreFilter(predicate: HmrIgnorePredicate): void {\n if (!ignoreFilters.includes(predicate)) {\n ignoreFilters.push(predicate);\n }\n },\n isIgnoredFile(file: string): boolean {\n return ignoreFilters.some((predicate) => predicate(file));\n },\n clear(): void {\n classNames.clear();\n },\n };\n}\n\nfunction resolveBackend(\n options: AngularBuildContextOptions | undefined,\n isTest: boolean,\n): AngularCompilationBackend {\n if (options?.compilationBackend) {\n return options.compilationBackend;\n }\n\n const compilation =\n options?.compilation === 'ngp' && !(isTest && options.jit === undefined)\n ? 'ngp'\n : 'ngtsc';\n\n if (compilation === 'ngp') {\n return 'ngp';\n }\n\n if (options?.compilation === undefined && options?.fastCompile) {\n return 'fast';\n }\n\n return 'ngtsc';\n}\n\nexport function createAngularBuildContext(\n options?: AngularBuildContextOptions,\n): AngularBuildContext {\n applyDebugOption(options?.debug, options?.workspaceRoot);\n\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const isStackBlitz = !!process.versions['webcontainer'];\n const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';\n const isVitestVscode = !!process.env['VITEST_VSCODE'];\n const compilation = resolveBackend(options, isTest);\n\n // Test mode under NgtscProgram disables WebSocket-based liveReload because\n // Vitest's runner does not consume Angular's component-update WS events.\n // Style externalization still checks `externalizeStylesRequested` separately.\n let liveReload =\n options?.liveReload ?? (compilation !== 'ngp' ? true : false);\n if (compilation === 'ngtsc' && isTest) {\n liveReload = false;\n debugHmr('hmr disabled', {\n angularVersion: angularFullVersion,\n isTest,\n });\n }\n\n const normalizedOptions: NormalizedAngularOptions = {\n tsconfigGetter: createTsConfigGetter(options?.tsconfig),\n workspaceRoot:\n options?.workspaceRoot ??\n process.env['NX_WORKSPACE_ROOT'] ??\n process.cwd(),\n inlineStylesExtension: options?.inlineStylesExtension ?? 'css',\n jit: typeof options?.jit !== 'undefined' ? options.jit : isTest,\n include: options?.include ?? [],\n liveReload,\n disableTypeChecking:\n options?.disableTypeChecking ?? (compilation !== 'ngp' ? true : false),\n typeChecker: options?.typeChecker,\n fileReplacements: options?.fileReplacements ?? [],\n compilation,\n fastCompile: compilation === 'fast',\n fastCompileMode: options?.fastCompileMode ?? 'full',\n supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],\n isTest,\n isStackBlitz,\n isAstroIntegration,\n isVitestVscode,\n };\n\n const tsconfigResolver = new TsconfigResolver({\n workspaceRoot: normalizedOptions.workspaceRoot,\n include: normalizedOptions.include,\n liveReload: normalizedOptions.liveReload,\n isTest: normalizedOptions.isTest,\n });\n\n const hmr = createAngularHmrStore();\n\n let ctx!: AngularBuildContext;\n\n const styles: AngularStylesheetService = {\n registry: undefined,\n\n resetRegistry(externalize: boolean): AnalogStylesheetRegistry | undefined {\n styles.registry = externalize\n ? new AnalogStylesheetRegistry()\n : undefined;\n if (styles.registry) {\n ctx.configureStylesheetRegistry?.(styles.registry, {\n workspaceRoot: normalizedOptions.workspaceRoot,\n });\n }\n return styles.registry;\n },\n\n ensureRegistry(): AnalogStylesheetRegistry {\n if (!styles.registry) {\n styles.registry = new AnalogStylesheetRegistry();\n ctx.configureStylesheetRegistry?.(styles.registry, {\n workspaceRoot: normalizedOptions.workspaceRoot,\n });\n }\n return styles.registry;\n },\n\n async transformStylesheet(\n input: StylesheetTransformInput,\n ): Promise<{ content: string; externalized: boolean } | null> {\n let data = input.data;\n if (input.readMissingResource && input.resourceFile && !data) {\n data = readFileSync(input.resourceFile, 'utf-8');\n }\n\n const filename =\n input.resourceFile ??\n input.containingFile.replace(\n '.ts',\n `.${normalizedOptions.inlineStylesExtension}`,\n );\n\n const preprocessed = preprocessStylesheetResult(\n data,\n filename,\n ctx.stylePreprocessor,\n {\n filename,\n containingFile: input.containingFile,\n resourceFile: input.resourceFile ?? undefined,\n className: input.className ?? undefined,\n order: input.order,\n inline: !input.resourceFile,\n },\n );\n\n if (ctx.shouldExternalizeStyles() && styles.registry) {\n const stylesheetId = registerStylesheetContent(styles.registry, {\n code: preprocessed.code,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n containingFile: input.containingFile,\n className: input.className ?? undefined,\n order: input.order,\n inlineStylesExtension: normalizedOptions.inlineStylesExtension,\n resourceFile: input.resourceFile ?? undefined,\n });\n\n debugStyles('stylesheet deferred to Vite pipeline', {\n stylesheetId,\n resourceFile: input.resourceFile ?? '(inline)',\n dependencies: preprocessed.dependencies,\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n });\n\n return { content: stylesheetId, externalized: true };\n }\n\n debugStyles('stylesheet processed inline via preprocessCSS', {\n filename,\n resourceFile: input.resourceFile ?? '(inline)',\n dataLength: preprocessed.code.length,\n });\n\n let stylesheetResult: { code?: string } | null | undefined;\n try {\n if (input.eagerTransform) {\n stylesheetResult = await input.eagerTransform(\n preprocessed.code,\n `${filename}?direct`,\n );\n } else if (ctx.resolvedConfig) {\n stylesheetResult = await preprocessCSS(\n preprocessed.code,\n `${filename}?direct`,\n ctx.resolvedConfig,\n );\n }\n } catch (e) {\n debugStyles('stylesheet transform error', {\n filename,\n resourceFile: input.resourceFile ?? '(inline)',\n error: String(e),\n });\n reportStylesheetError(\n input.logger ?? ctx.resolvedConfig?.logger,\n filename,\n e,\n ctx.resolvedConfig?.command === 'build',\n );\n }\n\n if (!stylesheetResult?.code) {\n return null;\n }\n\n return { content: stylesheetResult.code, externalized: false };\n },\n\n resolveComponentStyleId(id: string): string | undefined {\n return resolveComponentStyleId(id, styles.registry);\n },\n\n loadComponentStyle(id: string): string | undefined {\n return loadComponentStyle(id, styles.registry);\n },\n\n refreshForFile(file: string): void {\n refreshStylesheetRegistryForFile(\n file,\n styles.registry,\n ctx.stylePreprocessor,\n );\n },\n\n clear(): void {\n styles.registry = undefined;\n },\n };\n\n ctx = {\n kind: 'angular-build-context',\n options: normalizedOptions,\n tsconfigResolver,\n hmr,\n styles,\n compiler: undefined,\n watchMode: false,\n testWatchMode: isTestWatchMode(),\n deferInitialCompilation: isVitestVscode,\n resolvedConfig: undefined,\n tsConfigResolutionContext: null,\n stylePreprocessor: undefined,\n configureStylesheetRegistry: undefined,\n transformFilter: undefined,\n componentRegistries: [],\n externalizeStylesRequested: false,\n\n initConfig(config, { command }) {\n ctx.watchMode = command === 'serve';\n const isProd = isProdMode(config.mode);\n ctx.tsConfigResolutionContext = {\n root: config.root || '.',\n isProd,\n isLib: !!config?.build?.lib,\n };\n return ctx.tsConfigResolutionContext;\n },\n\n setResolvedConfig(config: ResolvedConfig) {\n ctx.resolvedConfig = config;\n ctx.tsConfigResolutionContext ??= {\n root: config.root || '.',\n isProd: isProdMode(config.mode),\n isLib: !!config?.build?.lib,\n };\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 && !patchedLoggers.has(config.logger)) {\n patchedLoggers.add(config.logger);\n const originalWarnOnce = config.logger.warnOnce;\n config.logger.warnOnce = (msg, warnOptions) => {\n if (\n typeof msg === 'string' &&\n msg.includes('Sourcemap') &&\n msg.includes('node_modules')\n ) {\n return;\n }\n originalWarnOnce(msg, warnOptions);\n };\n }\n\n if (normalizedOptions.isTest) {\n const browser = (\n config as unknown as {\n test?: { browser?: { enabled?: boolean }; watch?: boolean };\n }\n ).test?.browser;\n ctx.deferInitialCompilation =\n normalizedOptions.isVitestVscode ||\n (!!browser &&\n (getBrowserModeCliOverride() ?? browser.enabled) === true);\n\n ctx.testWatchMode =\n !(config.server?.watch === null) ||\n (config as unknown as { test?: { watch?: boolean } }).test?.watch ===\n true ||\n ctx.testWatchMode;\n }\n },\n\n async resolveConfig(config: ResolvedConfig): Promise<AnalogIntegrations> {\n ctx.setResolvedConfig(config);\n return ctx.refreshIntegrations(config);\n },\n\n async refreshIntegrations(\n config?: ResolvedConfig,\n ): Promise<AnalogIntegrations> {\n const targetConfig = config ?? ctx.resolvedConfig;\n if (!targetConfig) {\n return {\n componentRegistries: [],\n include: [],\n externalizeStyles: false,\n };\n }\n\n const integrations = await discoverAnalogIntegrations(targetConfig);\n ctx.stylePreprocessor = integrations.stylePreprocessor;\n ctx.configureStylesheetRegistry =\n integrations.configureStylesheetRegistry;\n ctx.transformFilter = integrations.transformFilter;\n ctx.componentRegistries = integrations.componentRegistries;\n ctx.externalizeStylesRequested = integrations.externalizeStyles;\n ctx.tsconfigResolver.setIntegrationIncludes(integrations.include);\n return integrations;\n },\n\n resolveTsConfigPath(): string {\n const resolution = ctx.tsConfigResolutionContext ?? {\n root: ctx.resolvedConfig?.root || '.',\n isProd: isProdMode(ctx.resolvedConfig?.mode),\n isLib: !!ctx.resolvedConfig?.build?.lib,\n };\n return getTsConfigPath(\n resolution.root,\n normalizedOptions.tsconfigGetter(),\n resolution.isProd,\n normalizedOptions.isTest,\n resolution.isLib,\n normalizedOptions.workspaceRoot,\n );\n },\n\n hasViteHmrTransport(): boolean {\n return ctx.resolvedConfig\n ? ctx.resolvedConfig.server?.hmr !== false\n : true;\n },\n\n shouldEnableLiveReload(): boolean {\n const effectiveWatchMode = normalizedOptions.isTest\n ? ctx.testWatchMode\n : ctx.watchMode;\n return !!(\n effectiveWatchMode &&\n normalizedOptions.liveReload &&\n ctx.hasViteHmrTransport()\n );\n },\n\n shouldExternalizeStyles(): boolean {\n const effectiveWatchMode = normalizedOptions.isTest\n ? ctx.testWatchMode\n : ctx.watchMode;\n if (!effectiveWatchMode) return false;\n return !!(ctx.shouldEnableLiveReload() || ctx.externalizeStylesRequested);\n },\n\n registerCompiler(capabilities: AngularCompilerCapabilities): void {\n ctx.compiler = capabilities;\n },\n };\n\n Object.defineProperty(ctx, ANGULAR_BUILD_CONTEXT_BRAND, {\n value: true,\n enumerable: false,\n });\n\n return ctx;\n}\n\nexport function ensureAngularBuildContext(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): AngularBuildContext {\n if (isAngularBuildContext(ctxOrOptions)) {\n return ctxOrOptions;\n }\n return createAngularBuildContext(ctxOrOptions);\n}\n\nexport function isAngularCompilerPlugin(plugin: Plugin): boolean {\n const api = plugin.api as\n | { angularCompiler?: boolean; getTsConfigPath?: unknown }\n | undefined;\n return (\n api?.angularCompiler === true ||\n ANGULAR_COMPILER_PLUGIN_NAMES.includes(plugin.name)\n );\n}\n\nexport function getAngularCompilerApi(\n plugins: readonly Plugin[],\n): AngularCompilerCapabilities | undefined {\n for (const plugin of plugins) {\n if (!isAngularCompilerPlugin(plugin)) {\n continue;\n }\n const api = plugin.api as Partial<AngularCompilerCapabilities> | undefined;\n if (typeof api?.getTsConfigPath === 'function') {\n return {\n name: plugin.name,\n getTsConfigPath: api.getTsConfigPath,\n getSourceMap: api.getSourceMap,\n hasEmitted: api.hasEmitted,\n };\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2OA,IAAM,8BAA8B,OAAO,IACzC,6CACF;AAwCA,IAAM,iCAAiB,IAAI,QAAgB;;;;;AAM3C,SAAgB,oBAAoB,IAAoB;CACtD,IAAI;EACF,OAAO,IAAI,IAAI,IAAI,kBAAkB,CAAC,CAAC,SAAS,QAAQ,OAAO,EAAE;CACnE,QAAQ;EAIN,MAAM,aAAa,GAAG,QAAQ,GAAG;EAEjC,QADiB,cAAc,IAAI,GAAG,MAAM,GAAG,UAAU,IAAI,GAAA,CAC7C,QAAQ,OAAO,EAAE;CACnC;AACF;AAEA,SAAgB,wBACd,IACA,oBACoB;CACpB,IAAI,CAAC,sBAAsB,EAAE,GAC3B;CAGF,MAAM,WAAW,oBAAoB,EAAE;CACvC,MAAM,SAAS,IAAI,IAAI,IAAI,kBAAkB,CAAC,CAAC;CAC/C,MAAM,mBAAmB,oBAAoB,oBAAoB,QAAQ;CAEzE,IAAI,kBAAkB;EACpB,aAAa,iDAAiD;GAC5D;GACA,cAAc;EAChB,CAAC;EACD,OAAO,mBAAmB;CAC5B;CAEA,IAAI,oBA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B,QAAQ;IAClC,QAAQ,WAAW,IAAI,gBAAgB,IAAI;IAC3C,OAAO,CAAC,CAAC,IAAI,gBAAgB,OAAO;GACtC;GACA,OAAO,gBACL,WAAW,MACX,kBAAkB,eAAe,GACjC,WAAW,QACX,kBAAkB,QAClB,WAAW,OACX,kBAAkB,aACpB;EACF;EAEA,sBAA+B;GAC7B,OAAO,IAAI,iBACP,IAAI,eAAe,QAAQ,QAAQ,QACnC;EACN;EAEA,yBAAkC;GAIhC,OAAO,CAAC,GAHmB,kBAAkB,SACzC,IAAI,gBACJ,IAAI,cAGN,kBAAkB,cAClB,IAAI,oBAAoB;EAE5B;EAEA,0BAAmC;GAIjC,IAAI,EAHuB,kBAAkB,SACzC,IAAI,gBACJ,IAAI,YACiB,OAAO;GAChC,OAAO,CAAC,EAAE,IAAI,uBAAuB,KAAK,IAAI;EAChD;EAEA,iBAAiB,cAAiD;GAChE,IAAI,WAAW;EACjB;CACF;CAEA,OAAO,eAAe,KAAK,6BAA6B;EACtD,OAAO;EACP,YAAY;CACd,CAAC;CAED,OAAO;AACT;AAEA,SAAgB,0BACd,cACqB;CACrB,IAAI,sBAAsB,YAAY,GACpC,OAAO;CAET,OAAO,0BAA0B,YAAY;AAC/C"}
@@ -79,7 +79,7 @@ function compilationApiPlugin(ctxOrOptions) {
79
79
  const normalizedFile = normalizeEmitterLookupId(file);
80
80
  return outputFiles.get(normalizedFile);
81
81
  };
82
- ctx.hmr.setFileEmitter((file) => fileEmitter(file));
82
+ ctx.hmr.setFileEmitter((file, className) => ({ hmrUpdateCode: fileEmitter(file)?.hmrUpdateCodes?.get(className) }));
83
83
  const compilerApi = {
84
84
  angularCompiler: true,
85
85
  getTsConfigPath: () => ctx.resolveTsConfigPath(),
@@ -139,7 +139,7 @@ function compilationApiPlugin(ctxOrOptions) {
139
139
  fileReplacements: toAngularCompilationFileReplacements(ctx.options.fileReplacements, ctx.options.workspaceRoot),
140
140
  modifiedFiles,
141
141
  async transformStylesheet(data, containingFile, resourceFile, order, className) {
142
- if (ctx.shouldEnableLiveReload() && className && containingFile) ctx.hmr.classNames.set(normalizePath(containingFile), className);
142
+ if (ctx.shouldEnableLiveReload() && className && containingFile) ctx.hmr.addClassName(normalizePath(containingFile), className);
143
143
  return (await ctx.styles.transformStylesheet({
144
144
  data,
145
145
  containingFile,
@@ -217,15 +217,17 @@ function compilationApiPlugin(ctxOrOptions) {
217
217
  });
218
218
  for (const file of affectedFiles) {
219
219
  const normalizedFilename = normalizePath(file.filename);
220
- const templateUpdate = templateUpdates.get(normalizedFilename);
221
- if (templateUpdate) ctx.hmr.classNames.set(normalizedFilename, templateUpdate.className);
220
+ const fileUpdates = templateUpdates.get(normalizedFilename);
221
+ const existingUpdates = outputFiles.get(normalizedFilename)?.hmrUpdateCodes;
222
+ const mergedUpdates = fileUpdates?.size ? new Map([...existingUpdates ?? [], ...fileUpdates]) : existingUpdates;
223
+ if (fileUpdates?.size) for (const className of fileUpdates.keys()) ctx.hmr.addClassName(normalizedFilename, className);
222
224
  outputFiles.set(normalizedFilename, {
223
225
  content: file.contents,
224
226
  dependencies: [],
225
227
  errors: errors.map((error) => error.text || ""),
226
228
  warnings: warnings.map((warning) => warning.text || ""),
227
- hmrUpdateCode: templateUpdate?.code,
228
- hmrEligible: !!templateUpdate?.code
229
+ hmrUpdateCodes: mergedUpdates?.size ? mergedUpdates : void 0,
230
+ hmrEligible: !!fileUpdates?.size
229
231
  });
230
232
  }
231
233
  if (!ctx.watchMode && !isTest) {
@@ -317,13 +319,15 @@ function compilationApiPlugin(ctxOrOptions) {
317
319
  debugHmr("TS file emitted", {
318
320
  fileId,
319
321
  hmrEligible: !!result?.hmrEligible,
320
- hasClassName: !!ctx.hmr.classNames.get(fileId)
322
+ hasClassName: !!ctx.hmr.classNames.get(fileId)?.size
321
323
  });
322
324
  }
323
- if (ctx.shouldEnableLiveReload() && result?.hmrEligible && ctx.hmr.classNames.get(fileId)) {
324
- const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);
325
- debugHmr("sending component update", { relativeFileId });
326
- ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);
325
+ const updateIds = ctx.shouldEnableLiveReload() && result?.hmrEligible ? ctx.hmr.toComponentUpdateIds(fileId) : [];
326
+ if (updateIds.length > 0) {
327
+ for (const relativeFileId of updateIds) {
328
+ debugHmr("sending component update", { relativeFileId });
329
+ ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);
330
+ }
327
331
  return hmrCtx.modules.map((mod) => {
328
332
  if (mod.id === hmrCtx.file) return markModuleSelfAccepting(mod);
329
333
  return mod;
@@ -1 +1 @@
1
- {"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { basename, isAbsolute, join, resolve } from 'node:path';\nimport {\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from '../angular-build-context.js';\nimport { composeWithCompanions } from '../companion-plugins.js';\nimport { markModuleSelfAccepting } from '../component-styles-plugin.js';\nimport { createHotUpdateBatcher } from '../hot-update-batch.js';\nimport type { EmitFileResult } from '../models.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport {\n preprocessStylesheetResult,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n mapTemplateUpdatesToFiles,\n toAngularCompilationFileReplacements,\n} from '../utils/compilation-shared.js';\nimport {\n activateDeferredDebug,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugStyles,\n type DebugOption,\n} from '../utils/debug.js';\nimport {\n angularFullVersion,\n createAngularCompilation,\n SourceFileCache,\n} from '../utils/devkit.js';\nimport {\n createDepOptimizerConfig,\n TS_EXT_REGEX,\n} from '../utils/plugin-config.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from '../virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\nfunction assertSupportedCompilationApi(): void {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n}\n\n/**\n * Single-responsibility compiler plugin backed by Angular's `@angular/build`\n * Compilation API. Can be composed with custom pipelines via `AngularBuildContext`\n * or mounted with default companions via `angularCompilationPlugin()`.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function compilationApiPlugin(\n ctxOrOptions?:\n | AngularBuildContext\n | AngularCompilationPluginOptions\n | AngularBuildContextOptions,\n): Plugin {\n assertSupportedCompilationApi();\n\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'compilation-api',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n const { isTest } = ctx.options;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = ctx.tsconfigResolver.ensureIncludeCache();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots =\n ctx.tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n union(cached.rootNames, expandedGraphRoots),\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n ctx.hmr.setFileEmitter((file) => fileEmitter(file));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizePath(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular-compilation-api',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const stylesheetRegistry = ctx.styles.ensureRegistry();\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!ctx.options.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const transformCompilerOptions = (\n tsCompilerOptions: Record<string, unknown>,\n ) => {\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n watchMode: ctx.watchMode,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n };\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n ctx.options.fileReplacements,\n ctx.options.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile?: string | null,\n order?: number,\n className?: string | null,\n ) {\n if (ctx.shouldEnableLiveReload() && className && containingFile) {\n ctx.hmr.classNames.set(normalizePath(containingFile), className);\n }\n\n const result = await ctx.styles.transformStylesheet({\n data,\n containingFile,\n resourceFile,\n order,\n className,\n readMissingResource: true,\n logger: config.logger,\n });\n\n return result?.content || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n angularFullVersion >= 220200\n ? {\n enableHmr: ctx.shouldEnableLiveReload(),\n externalRuntimeStyles: ctx.shouldExternalizeStyles(),\n includeTestMetadata: isTest || ctx.shouldEnableLiveReload(),\n instrumentForCoverage: !isTest,\n }\n : (transformCompilerOptions as unknown as Parameters<\n typeof compilation.initialize\n >[2]),\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!ctx.stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry.registerExternalRequest(angularHash, key);\n\n if (ctx.stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n ctx.stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n ctx.options.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = Array.from(await compilation.emitAffectedFiles());\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const templateUpdate = templateUpdates.get(normalizedFilename);\n\n if (templateUpdate) {\n ctx.hmr.classNames.set(normalizedFilename, templateUpdate.className);\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCode: templateUpdate?.code,\n hmrEligible: !!templateUpdate?.code,\n });\n }\n\n // Free the compilation before chunks render; `transform` still reads `outputFiles`.\n if (!ctx.watchMode && !isTest) {\n await compilation.close?.();\n angularCompilation = undefined;\n }\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await performAngularCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n api: compilerApi,\n enforce: 'pre' as const,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Use the shared\n // `createDepOptimizerConfig` helper so the linker runs with identical\n // test/astro/cache arguments under both rolldown and esbuild.\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n esbuild: undefined,\n oxc: undefined,\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n await ctx.resolveConfig(config);\n ctx.styles.resetRegistry(true);\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n const invalidateCompilation = async (): Promise<void> => {\n ctx.tsconfigResolver.invalidateAll();\n await performCompilation(ctx.resolvedConfig!);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n });\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n result?.hmrEligible &&\n ctx.hmr.classNames.get(fileId)\n ) {\n const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);\n\n debugHmr('sending component update', { relativeFileId });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(hmrCtx.file)) {\n debugHmr('template file changed', { file: hmrCtx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('stylesheet file changed', { file: hmrCtx.file });\n ctx.styles.refreshForFile(hmrCtx.file);\n }\n\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit: ctx.options.jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!, [\n id,\n ]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n hotUpdates.close();\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n ctx.hmr.clear();\n sourceFileCache.clear();\n ctx.tsconfigResolver.invalidateAll();\n ctx.styles.clear();\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n assertSupportedCompilationApi();\n const ctx = createAngularBuildContext({\n ...options,\n compilationBackend: 'compilation-api',\n });\n return composeWithCompanions(ctx, compilationApiPlugin(ctx));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,IAAM,UAAU,cAAc,YAAY,GAAG;AAkB7C,SAAS,gCAAsC;CAC7C,IACE,qBAAqB,UACrB,OAAO,6BAA6B,YAEpC,MAAM,IAAI,MACR,2JACF;AAEJ;;;;;;;;AASA,SAAgB,qBACd,cAIQ;CACR,8BAA8B;CAE9B,MAAM,MAAM,sBAAsB,YAAY,IAC1C,eACA,0BAA0B;EACxB,GAAG;EACH,oBAAoB;CACtB,CAAC;CAEL,MAAM,KAAK,QAAQ,YAAY;CAC/B,MAAM,EAAE,WAAW,IAAI;CAIvB,IAAI;CAGJ,MAAM,kBAAuC,IAAI,gBAAgB;CACjE,MAAM,8BAAc,IAAI,IAA4B;CACpD,IAAI,kBAAkB,QAAQ,QAAQ;CACtC,IAAI,qBAA2C;CAC/C,IAAI,qBAAqB;CACzB,IAAI;CACJ,MAAM,aAAa,wBAAwB,QACzC,mBAAmB,IAAI,gBAAiB,GAAG,CAC7C;CAEA,SAAS,kCACP,sBACA,QACQ;EACR,MAAM,gBAAgB,IAAI,iBAAiB,mBAAmB;EAC9D,MAAM,SAAS,IAAI,iBAAiB,yBAClC,sBACA,MACF;EACA,MAAM,qBACJ,IAAI,iBAAiB,6BACnB,sBACA,MACF;EACF,MAAM,kBAAkB,MACtB,MAAM,OAAO,WAAW,kBAAkB,GAC1C,aACF,CAAC,CAAC,KAAK,SAAS,cAAc,IAAI,CAAC;EAEnC,IAAI,gBAAgB,WAAW,OAAO,UAAU,QAC9C,OAAO;EAGT,MAAM,mBAAmB,WAAW,OAAO,QAAQ,IAC/C,OAAO,WACP,QAAQ,OAAO,MAAM,OAAO,QAAQ;EACx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AI,oBAAoB;KACtB,MAAM;KACN,qBAAqB;IACvB;IACA,MAAM,WAAW,KAAK;IAEtB,MAAM,mBAAmB,YAAY,EAAE;IACvC,IAAI,CAAC,kBAAkB;KACrB,oBAAoB,qCAAqC,EAAE,GAAG,CAAC;KAC/D,IAAI,WACF,KAAK,KACH,qCAAqC,GAAG,4GAE1C;KAEF;IACF;IAEA,IAAI,iBAAiB,YAAY,iBAAiB,SAAS,SAAS,GAClE,KAAK,KAAK,GAAG,iBAAiB,SAAS,KAAK,IAAI,GAAG;IAGrD,IAAI,iBAAiB,UAAU,iBAAiB,OAAO,SAAS,GAC9D,KAAK,MAAM,GAAG,iBAAiB,OAAO,KAAK,IAAI,GAAG;IAGpD,IAAI,OAAO,iBAAiB,WAAW;IAGvC,IAAI,KAAK,SAAS,SAAS,GACN;SAAA,KAAK,SAAS,uBAC7B,GACF,OAAO,+BAA+B,IAAI;IAAA;IAI9C,OAAO;KACL,MAAM;KACN,KAAK;IACP;GACF;EACF;EACA,MAAM,cAAc;GAClB,WAAW,MAAM;GACjB,MAAM;GACN,MAAM,oBAAoB,QAAQ;GAClC,qBAAqB,KAAA;GACrB,YAAY,MAAM;GAClB,IAAI,IAAI,MAAM;GACd,gBAAgB,MAAM;GACtB,IAAI,iBAAiB,cAAc;GACnC,IAAI,OAAO,MAAM;GACjB,qBAAqB;GACrB,qBAAqB;EACvB;CACF;AACF;;;;;;AAOA,SAAgB,yBACd,UAA2C,CAAC,GAClC;CACV,8BAA8B;CAC9B,MAAM,MAAM,0BAA0B;EACpC,GAAG;EACH,oBAAoB;CACtB,CAAC;CACD,OAAO,sBAAsB,KAAK,qBAAqB,GAAG,CAAC;AAC7D"}
1
+ {"version":3,"file":"compilation-api-plugin.js","names":[],"sources":["../../../../src/lib/compilation-api/compilation-api-plugin.ts"],"sourcesContent":["import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';\nimport { union } from 'es-toolkit';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { basename, isAbsolute, join, resolve } from 'node:path';\nimport {\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from '../angular-build-context.js';\nimport { composeWithCompanions } from '../companion-plugins.js';\nimport { markModuleSelfAccepting } from '../component-styles-plugin.js';\nimport { createHotUpdateBatcher } from '../hot-update-batch.js';\nimport type { EmitFileResult } from '../models.js';\nimport { type FileReplacement } from '../plugins/file-replacements.plugin.js';\nimport { normalizeStylesheetDependencies } from '../style-preprocessor.js';\nimport {\n preprocessStylesheetResult,\n rewriteRelativeCssImports,\n} from '../stylesheet-registry.js';\nimport {\n DiagnosticModes,\n injectViteIgnoreForHmrMetadata,\n mapTemplateUpdatesToFiles,\n toAngularCompilationFileReplacements,\n} from '../utils/compilation-shared.js';\nimport {\n activateDeferredDebug,\n debugCompilationApi,\n debugCompiler,\n debugEmit,\n debugHmr,\n debugStyles,\n type DebugOption,\n} from '../utils/debug.js';\nimport {\n angularFullVersion,\n createAngularCompilation,\n SourceFileCache,\n} from '../utils/devkit.js';\nimport {\n createDepOptimizerConfig,\n TS_EXT_REGEX,\n} from '../utils/plugin-config.js';\nimport type { SourceFileCache as SourceFileCacheType } from '../utils/source-file-cache.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from '../virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * @experimental The Angular Compilation API plugin may change in future releases.\n */\nexport interface AngularCompilationPluginOptions {\n tsconfig?: string | (() => string);\n workspaceRoot?: string;\n inlineStylesExtension?: string;\n jit?: boolean;\n liveReload?: boolean;\n disableTypeChecking?: boolean;\n supportedBrowsers?: string[];\n fileReplacements?: FileReplacement[];\n include?: string[];\n debug?: DebugOption;\n}\n\nfunction assertSupportedCompilationApi(): void {\n if (\n angularFullVersion < 200100 ||\n typeof createAngularCompilation !== 'function'\n ) {\n throw new Error(\n '[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.',\n );\n }\n}\n\n/**\n * Single-responsibility compiler plugin backed by Angular's `@angular/build`\n * Compilation API. Can be composed with custom pipelines via `AngularBuildContext`\n * or mounted with default companions via `angularCompilationPlugin()`.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function compilationApiPlugin(\n ctxOrOptions?:\n | AngularBuildContext\n | AngularCompilationPluginOptions\n | AngularBuildContextOptions,\n): Plugin {\n assertSupportedCompilationApi();\n\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'compilation-api',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n const { isTest } = ctx.options;\n\n // Persistent compilation instance — kept alive across rebuilds so Angular\n // can diff prior state and emit `templateUpdates` for HMR.\n let angularCompilation:\n | Awaited<ReturnType<typeof createAngularCompilationType>>\n | undefined;\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const outputFiles = new Map<string, EmitFileResult>();\n let compilationLock = Promise.resolve();\n let pendingCompilation: Promise<void> | null = null;\n let initialCompilation = false;\n let viteServer: ViteDevServer | undefined;\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath: string,\n config: ResolvedConfig,\n ): string {\n const includedFiles = ctx.tsconfigResolver.ensureIncludeCache();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n const expandedGraphRoots =\n ctx.tsconfigResolver.collectExpandedTsconfigRoots(\n resolvedTsConfigPath,\n config,\n );\n const mergedRootNames = union(\n union(cached.rootNames, expandedGraphRoots),\n includedFiles,\n ).map((file) => normalizePath(file));\n\n if (mergedRootNames.length === cached.rootNames.length) {\n return resolvedTsConfigPath;\n }\n\n const resolvedCacheDir = isAbsolute(config.cacheDir)\n ? config.cacheDir\n : resolve(config.root, config.cacheDir);\n const wrapperDir = join(\n resolvedCacheDir,\n 'analog-angular',\n 'compilation-api',\n );\n const rawTsconfig = (ts.readConfigFile(\n resolvedTsConfigPath,\n ts.sys.readFile,\n ).config ?? {}) as { references?: unknown[] };\n const wrapperPayload = {\n extends: normalizePath(resolvedTsConfigPath),\n files: [...mergedRootNames].sort(),\n ...(rawTsconfig.references ? { references: rawTsconfig.references } : {}),\n };\n const wrapperHash = createHash('sha1')\n .update(JSON.stringify(wrapperPayload))\n .digest('hex')\n .slice(0, 12);\n const wrapperPath = join(\n wrapperDir,\n `tsconfig.includes.${wrapperHash}.json`,\n );\n\n mkdirSync(wrapperDir, { recursive: true });\n if (!existsSync(wrapperPath)) {\n writeFileSync(\n wrapperPath,\n `${JSON.stringify(wrapperPayload, null, 2)}\\n`,\n 'utf-8',\n );\n }\n\n debugCompilationApi('generated include wrapper tsconfig', {\n originalTsconfig: resolvedTsConfigPath,\n wrapperTsconfig: wrapperPath,\n includeCount: includedFiles.length,\n rootNameCount: mergedRootNames.length,\n });\n\n return wrapperPath;\n }\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n if (!normalizedFile.startsWith('/@fs/')) return normalizedFile;\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n return normalizePath(fsPath);\n };\n\n let outputFile: ((file: string) => void) | undefined;\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n outputFile?.(normalizedFile);\n return outputFiles.get(normalizedFile);\n };\n\n ctx.hmr.setFileEmitter((file, className) => ({\n hmrUpdateCode: fileEmitter(file)?.hmrUpdateCodes?.get(className),\n }));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizePath(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular-compilation-api',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n async function performAngularCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const stylesheetRegistry = ctx.styles.ensureRegistry();\n const compilation = (angularCompilation ??= await (\n createAngularCompilation as typeof createAngularCompilationType\n )(!!ctx.options.jit, false));\n const modifiedFiles = ids?.length\n ? new Set(ids.map((file) => normalizePath(file)))\n : undefined;\n if (modifiedFiles?.size) {\n sourceFileCache.invalidate(modifiedFiles);\n }\n if (modifiedFiles?.size && compilation.update) {\n debugCompilationApi('incremental update', {\n files: [...modifiedFiles],\n });\n await compilation.update(modifiedFiles);\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(\n resolvedTsConfigPath,\n config,\n );\n debugEmit('compilation initialize', {\n resolvedTsConfigPath,\n compilationApiTsConfigPath,\n modifiedFileCount: modifiedFiles?.size ?? 0,\n });\n const transformCompilerOptions = (\n tsCompilerOptions: Record<string, unknown>,\n ) => {\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (compilation API)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n watchMode: ctx.watchMode,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n return tsCompilerOptions;\n };\n const compilationResult = await compilation.initialize(\n compilationApiTsConfigPath,\n {\n fileReplacements: toAngularCompilationFileReplacements(\n ctx.options.fileReplacements,\n ctx.options.workspaceRoot,\n ),\n modifiedFiles,\n async transformStylesheet(\n data: string,\n containingFile: string,\n resourceFile?: string | null,\n order?: number,\n className?: string | null,\n ) {\n if (ctx.shouldEnableLiveReload() && className && containingFile) {\n ctx.hmr.addClassName(normalizePath(containingFile), className);\n }\n\n const result = await ctx.styles.transformStylesheet({\n data,\n containingFile,\n resourceFile,\n order,\n className,\n readMissingResource: true,\n logger: config.logger,\n });\n\n return result?.content || '';\n },\n processWebWorker(workerFile: string) {\n return workerFile;\n },\n },\n angularFullVersion >= 220200\n ? {\n enableHmr: ctx.shouldEnableLiveReload(),\n externalRuntimeStyles: ctx.shouldExternalizeStyles(),\n includeTestMetadata: isTest || ctx.shouldEnableLiveReload(),\n instrumentForCoverage: !isTest,\n }\n : (transformCompilerOptions as unknown as Parameters<\n typeof compilation.initialize\n >[2]),\n );\n\n // Preprocess external stylesheets for Tailwind CSS @reference\n debugStyles('external stylesheets from compilation API', {\n count: compilationResult.externalStylesheets?.size ?? 0,\n hasPreprocessor: !!ctx.stylePreprocessor,\n hasInlineMap: !!stylesheetRegistry,\n });\n const preprocessStats = { total: 0, injected: 0, skipped: 0, errors: 0 };\n for (const [key, value] of compilationResult.externalStylesheets ?? []) {\n preprocessStats.total++;\n const angularHash = `${value}.css`;\n stylesheetRegistry.registerExternalRequest(angularHash, key);\n\n if (ctx.stylePreprocessor && existsSync(key)) {\n try {\n const rawCss = readFileSync(key, 'utf-8');\n const preprocessed = preprocessStylesheetResult(\n rawCss,\n key,\n ctx.stylePreprocessor,\n );\n const servedCss = rewriteRelativeCssImports(preprocessed.code, key);\n stylesheetRegistry.registerServedStylesheet(\n {\n publicId: angularHash,\n sourcePath: key,\n originalCode: rawCss,\n normalizedCode: servedCss,\n dependencies: normalizeStylesheetDependencies(\n preprocessed.dependencies,\n ),\n diagnostics: preprocessed.diagnostics,\n tags: preprocessed.tags,\n },\n [key, normalizePath(key), basename(key), key.replace(/^\\//, '')],\n );\n\n if (servedCss && servedCss !== rawCss) {\n preprocessStats.injected++;\n } else {\n preprocessStats.skipped++;\n }\n } catch (e) {\n preprocessStats.errors++;\n console.warn(\n `[@analogjs/vite-plugin-angular] failed to preprocess external stylesheet: ${key}: ${e}`,\n );\n }\n } else {\n preprocessStats.skipped++;\n }\n }\n debugStyles('external stylesheet preprocessing complete', preprocessStats);\n\n const diagnostics = await compilation.diagnoseFiles(\n ctx.options.disableTypeChecking\n ? DiagnosticModes.All & ~DiagnosticModes.Semantic\n : DiagnosticModes.All,\n );\n\n const errors = diagnostics.errors?.length ? diagnostics.errors : [];\n const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];\n\n const templateUpdates = mapTemplateUpdatesToFiles(\n compilationResult.templateUpdates,\n );\n if (templateUpdates.size > 0) {\n debugHmr('compilation API template updates', {\n count: templateUpdates.size,\n files: [...templateUpdates.keys()],\n });\n }\n\n const affectedFiles = Array.from(await compilation.emitAffectedFiles());\n debugEmit('emitAffectedFiles summary', {\n count: affectedFiles.length,\n templateUpdateCount: templateUpdates.size,\n knownOutputCountBefore: outputFiles.size,\n });\n\n for (const file of affectedFiles) {\n const normalizedFilename = normalizePath(file.filename);\n const fileUpdates = templateUpdates.get(normalizedFilename);\n const existingUpdates =\n outputFiles.get(normalizedFilename)?.hmrUpdateCodes;\n const mergedUpdates = fileUpdates?.size\n ? new Map([...(existingUpdates ?? []), ...fileUpdates])\n : existingUpdates;\n\n if (fileUpdates?.size) {\n for (const className of fileUpdates.keys()) {\n ctx.hmr.addClassName(normalizedFilename, className);\n }\n }\n\n outputFiles.set(normalizedFilename, {\n content: file.contents,\n dependencies: [],\n errors: errors.map((error: { text?: string }) => error.text || ''),\n warnings: warnings.map(\n (warning: { text?: string }) => warning.text || '',\n ),\n hmrUpdateCodes: mergedUpdates?.size ? mergedUpdates : undefined,\n hmrEligible: !!fileUpdates?.size,\n });\n }\n\n // Free the compilation before chunks render; `transform` still reads `outputFiles`.\n if (!ctx.watchMode && !isTest) {\n await compilation.close?.();\n angularCompilation = undefined;\n }\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await performAngularCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-compilation-api',\n api: compilerApi,\n enforce: 'pre' as const,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n debugCompilationApi('enabled (Angular %s)', angularFullVersion);\n\n // Angular Compilation API handles TypeScript transforms — disable\n // esbuild/oxc so they don't compete.\n debugCompilationApi('esbuild/oxc disabled, Angular handles transforms');\n\n // The compilation API owns user-source transforms, but deps\n // optimization still bundles partial-compiled Angular libs from\n // node_modules (`ɵɵngDeclareInjectable/Factory`). Without the\n // linker plugin, those declarations reach the browser unprocessed\n // and Angular tries to JIT-compile them at runtime. Use the shared\n // `createDepOptimizerConfig` helper so the linker runs with identical\n // test/astro/cache arguments under both rolldown and esbuild.\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n esbuild: undefined,\n oxc: undefined,\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n await ctx.resolveConfig(config);\n ctx.styles.resetRegistry(true);\n debugStyles('stylesheet registry initialized (Angular Compilation API)');\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n const invalidateCompilation = async (): Promise<void> => {\n ctx.tsconfigResolver.invalidateAll();\n await performCompilation(ctx.resolvedConfig!);\n };\n server.watcher.on('add', invalidateCompilation);\n server.watcher.on('unlink', invalidateCompilation);\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n await pendingCompilation;\n pendingCompilation = null;\n initialCompilation = true;\n }\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId)?.size,\n });\n }\n\n const updateIds =\n ctx.shouldEnableLiveReload() && result?.hmrEligible\n ? ctx.hmr.toComponentUpdateIds(fileId)\n : [];\n\n if (updateIds.length > 0) {\n for (const relativeFileId of updateIds) {\n debugHmr('sending component update', { relativeFileId });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n }\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm)$/.test(hmrCtx.file)) {\n debugHmr('template file changed', { file: hmrCtx.file });\n // Recompile to pick up template changes\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n }\n\n if (/\\.(css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('stylesheet file changed', { file: hmrCtx.file });\n ctx.styles.refreshForFile(hmrCtx.file);\n }\n\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit: ctx.options.jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [\n /node_modules/,\n 'type=script',\n '@ng/component',\n /[?&]raw\\b/,\n ],\n },\n },\n async handler(code, id) {\n if (/[?&]raw\\b/.test(id)) return;\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Angular emits every file in the program, not only files with\n // Angular decorators, and `@analogjs/platform` excludes `.ts` from\n // Vite's own transform. So serve Angular's output for any emitted\n // file; only the \"not emitted\" warning below is decorator-specific.\n const isAngular =\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n\n if (id.includes('.ts?')) {\n id = id.replace(/\\?(.*)/, '');\n }\n\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!);\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(ctx.resolvedConfig!, [\n id,\n ]);\n }\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilationApi('transform skip (file not emitted)', { id });\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n\n // Re-inject @vite-ignore for Angular HMR dynamic imports\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n if (hasMetaUrl) {\n data = injectViteIgnoreForHmrMetadata(data);\n }\n }\n\n return {\n code: data,\n map: null,\n };\n },\n },\n async closeBundle() {\n hotUpdates.close();\n await compilationLock;\n await angularCompilation?.close?.();\n angularCompilation = undefined;\n outputFiles.clear();\n ctx.hmr.clear();\n sourceFileCache.clear();\n ctx.tsconfigResolver.invalidateAll();\n ctx.styles.clear();\n pendingCompilation = null;\n initialCompilation = false;\n },\n };\n}\n\n/**\n * Compiles Angular applications using Angular's private Compilation API.\n *\n * @experimental This plugin may change in future releases.\n */\nexport function angularCompilationPlugin(\n options: AngularCompilationPluginOptions = {},\n): Plugin[] {\n assertSupportedCompilationApi();\n const ctx = createAngularBuildContext({\n ...options,\n compilationBackend: 'compilation-api',\n });\n return composeWithCompanions(ctx, compilationApiPlugin(ctx));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,IAAM,UAAU,cAAc,YAAY,GAAG;AAkB7C,SAAS,gCAAsC;CAC7C,IACE,qBAAqB,UACrB,OAAO,6BAA6B,YAEpC,MAAM,IAAI,M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AAW,KAAK;IAEtB,MAAM,mBAAmB,YAAY,EAAE;IACvC,IAAI,CAAC,kBAAkB;KACrB,oBAAoB,qCAAqC,EAAE,GAAG,CAAC;KAC/D,IAAI,WACF,KAAK,KACH,qCAAqC,GAAG,4GAE1C;KAEF;IACF;IAEA,IAAI,iBAAiB,YAAY,iBAAiB,SAAS,SAAS,GAClE,KAAK,KAAK,GAAG,iBAAiB,SAAS,KAAK,IAAI,GAAG;IAGrD,IAAI,iBAAiB,UAAU,iBAAiB,OAAO,SAAS,GAC9D,KAAK,MAAM,GAAG,iBAAiB,OAAO,KAAK,IAAI,GAAG;IAGpD,IAAI,OAAO,iBAAiB,WAAW;IAGvC,IAAI,KAAK,SAAS,SAAS,GACN;SAAA,KAAK,SAAS,uBAC7B,GACF,OAAO,+BAA+B,IAAI;IAAA;IAI9C,OAAO;KACL,MAAM;KACN,KAAK;IACP;GACF;EACF;EACA,MAAM,cAAc;GAClB,WAAW,MAAM;GACjB,MAAM;GACN,MAAM,oBAAoB,QAAQ;GAClC,qBAAqB,KAAA;GACrB,YAAY,MAAM;GAClB,IAAI,IAAI,MAAM;GACd,gBAAgB,MAAM;GACtB,IAAI,iBAAiB,cAAc;GACnC,IAAI,OAAO,MAAM;GACjB,qBAAqB;GACrB,qBAAqB;EACvB;CACF;AACF;;;;;;AAOA,SAAgB,yBACd,UAA2C,CAAC,GAClC;CACV,8BAA8B;CAC9B,MAAM,MAAM,0BAA0B;EACpC,GAAG;EACH,oBAAoB;CACtB,CAAC;CACD,OAAO,sBAAsB,KAAK,qBAAqB,GAAG,CAAC;AAC7D"}
@@ -1,9 +1,9 @@
1
1
  import { Plugin } from "vite";
2
2
  import { type AngularBuildContext } from "./angular-build-context.js";
3
- import { EmitFileResult } from "./models.js";
3
+ import { HmrUpdateResult } from "./models.js";
4
4
  export interface ComponentUpdates {
5
- classNames: Map<string, string>;
6
- fileEmitter: (file: string, className: string) => Pick<EmitFileResult, "hmrUpdateCode"> | undefined;
5
+ classNames: Map<string, Set<string>>;
6
+ fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;
7
7
  rootDir?: string;
8
8
  }
9
9
  export declare function liveReloadPlugin(ctxOrUpdates?: AngularBuildContext | ComponentUpdates): Plugin;
@@ -5,6 +5,19 @@ import { normalizePath } from "vite";
5
5
  // packages/vite-plugin-angular/src/lib/live-reload-plugin.ts
6
6
  var ANGULAR_COMPONENT_PREFIX = "/@ng/component";
7
7
  var FILE_PREFIX = "file:";
8
+ function createProxyMatchers(proxy) {
9
+ if (!proxy) return [];
10
+ const matchers = [];
11
+ for (const [context, opts] of Object.entries(proxy)) {
12
+ if (!opts) continue;
13
+ if (typeof opts === "object" && typeof opts.bypass === "function") continue;
14
+ if (context.startsWith("^")) {
15
+ const regex = new RegExp(context);
16
+ matchers.push((url) => regex.test(url));
17
+ } else matchers.push((url) => url.startsWith(context));
18
+ }
19
+ return matchers;
20
+ }
8
21
  function liveReloadPlugin(ctxOrUpdates) {
9
22
  const updates = isAngularBuildContext(ctxOrUpdates) ? ctxOrUpdates.hmr : ctxOrUpdates ?? {
10
23
  classNames: /* @__PURE__ */ new Map(),
@@ -19,9 +32,10 @@ function liveReloadPlugin(ctxOrUpdates) {
19
32
  debugHmr("middleware disabled: vite server.hmr is false");
20
33
  return;
21
34
  }
35
+ const proxyMatchers = createProxyMatchers(server.config.server.proxy);
22
36
  const angularComponentMiddleware = async (req, res, next) => {
23
37
  if (req.url === void 0 || res.writableEnded) return;
24
- if (!req.url.includes(ANGULAR_COMPONENT_PREFIX)) {
38
+ if (!req.url.includes(ANGULAR_COMPONENT_PREFIX) || proxyMatchers.some((match) => match(req.url))) {
25
39
  next();
26
40
  return;
27
41
  }
@@ -33,8 +47,22 @@ function liveReloadPlugin(ctxOrUpdates) {
33
47
  }
34
48
  const [fileId, className] = decodeURIComponent(componentId).split("@");
35
49
  const resolvedId = resolveFileId(fileId);
36
- if (!(!!server.moduleGraph.getModuleById(resolvedId)?.lastInvalidationTimestamp && updates.classNames.get(resolvedId))) {
37
- debugHmr("middleware: skipped (not invalidated)", { resolvedId });
50
+ const moduleNode = server.moduleGraph.getModuleById(resolvedId);
51
+ const knownClasses = updates.classNames.get(resolvedId);
52
+ if (!moduleNode && !knownClasses?.size) {
53
+ debugHmr("middleware: passed through (unknown component)", {
54
+ resolvedId,
55
+ className
56
+ });
57
+ next();
58
+ return;
59
+ }
60
+ const hasKnownClass = className ? !!knownClasses?.has(className) : !!knownClasses?.size;
61
+ if (!(!!moduleNode?.lastInvalidationTimestamp && hasKnownClass)) {
62
+ debugHmr("middleware: skipped (not invalidated)", {
63
+ resolvedId,
64
+ className
65
+ });
38
66
  res.setHeader("Content-Type", "text/javascript");
39
67
  res.setHeader("Cache-Control", "no-cache");
40
68
  res.end("");
@@ -43,6 +71,7 @@ function liveReloadPlugin(ctxOrUpdates) {
43
71
  const result = updates.fileEmitter(resolvedId, className);
44
72
  debugHmr("middleware: served component update", {
45
73
  resolvedId,
74
+ className,
46
75
  hasCode: !!result?.hmrUpdateCode
47
76
  });
48
77
  res.setHeader("Content-Type", "text/javascript");
@@ -1 +1 @@
1
- {"version":3,"file":"live-reload-plugin.js","names":[],"sources":["../../../src/lib/live-reload-plugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { ServerResponse } from 'node:http';\nimport { Connect, normalizePath, Plugin, ViteDevServer } from 'vite';\n\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\nimport { EmitFileResult } from './models.js';\nimport { debugHmr } from './utils/debug.js';\n\nconst ANGULAR_COMPONENT_PREFIX = '/@ng/component';\nconst FILE_PREFIX = 'file:';\n\nexport interface ComponentUpdates {\n classNames: Map<string, string>;\n fileEmitter: (\n file: string,\n className: string,\n ) => Pick<EmitFileResult, 'hmrUpdateCode'> | undefined;\n rootDir?: string;\n}\n\nexport function liveReloadPlugin(\n ctxOrUpdates?: AngularBuildContext | ComponentUpdates,\n): Plugin {\n const updates: ComponentUpdates = isAngularBuildContext(ctxOrUpdates)\n ? ctxOrUpdates.hmr\n : (ctxOrUpdates ?? {\n classNames: new Map<string, string>(),\n fileEmitter: () => undefined,\n });\n\n const resolveFileId = (fileId: string): string =>\n normalizePath(resolve(updates.rootDir ?? process.cwd(), fileId));\n\n return {\n name: 'analogjs-live-reload-plugin',\n apply: 'serve',\n configureServer(server: ViteDevServer) {\n if (server.config.server.hmr === false) {\n debugHmr('middleware disabled: vite server.hmr is false');\n return;\n }\n\n const angularComponentMiddleware: Connect.HandleFunction = async (\n req: Connect.IncomingMessage,\n res: ServerResponse<Connect.IncomingMessage>,\n next: Connect.NextFunction,\n ) => {\n if (req.url === undefined || res.writableEnded) {\n return;\n }\n\n if (!req.url.includes(ANGULAR_COMPONENT_PREFIX)) {\n next();\n\n return;\n }\n\n const requestUrl = new URL(req.url, 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n res.statusCode = 400;\n res.end();\n\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const resolvedId = resolveFileId(fileId);\n const invalidated =\n !!server.moduleGraph.getModuleById(resolvedId)\n ?.lastInvalidationTimestamp && updates.classNames.get(resolvedId);\n\n // don't send an HMR update until the file has been invalidated\n if (!invalidated) {\n debugHmr('middleware: skipped (not invalidated)', { resolvedId });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end('');\n return;\n }\n\n const result = updates.fileEmitter(resolvedId, className);\n debugHmr('middleware: served component update', {\n resolvedId,\n hasCode: !!result?.hmrUpdateCode,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(`${result?.hmrUpdateCode || ''}`);\n };\n\n server.middlewares.use(angularComponentMiddleware);\n },\n resolveId(id, _importer, options) {\n if (\n options?.ssr &&\n id.startsWith(FILE_PREFIX) &&\n id.includes(ANGULAR_COMPONENT_PREFIX)\n ) {\n return `\\0${id}`;\n }\n\n return undefined;\n },\n load(id, options) {\n if (options?.ssr && id.includes(ANGULAR_COMPONENT_PREFIX)) {\n const requestUrl = new URL(id.slice(1), 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const result = updates.fileEmitter(resolveFileId(fileId), className);\n\n return result?.hmrUpdateCode || '';\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;;;AAWA,IAAM,2BAA2B;AACjC,IAAM,cAAc;AAWpB,SAAgB,iBACd,cACQ;CACR,MAAM,UAA4B,sBAAsB,YAAY,IAChE,aAAa,MACZ,gBAAgB;EACf,4BAAY,IAAI,IAAoB;EACpC,mBAAmB,KAAA;CACrB;CAEJ,MAAM,iBAAiB,WACrB,cAAc,QAAQ,QAAQ,WAAW,QAAQ,IAAI,GAAG,MAAM,CAAC;CAEjE,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAuB;GACrC,IAAI,OAAO,OAAO,OAAO,QAAQ,OAAO;IACtC,SAAS,+CAA+C;IACxD;GACF;GAEA,MAAM,6BAAqD,OACzD,KACA,KACA,SACG;IACH,IAAI,IAAI,QAAQ,KAAA,KAAa,IAAI,eAC/B;IAGF,IAAI,CAAC,IAAI,IAAI,SAAS,wBAAwB,GAAG;KAC/C,KAAK;KAEL;IACF;IAGA,MAAM,cAAc,IADG,IAAI,IAAI,KAAK,kBAChB,CAAA,CAAW,aAAa,IAAI,GAAG;IAEnD,IAAI,CAAC,aAAa;KAChB,IAAI,aAAa;KACjB,IAAI,IAAI;KAER;IACF;IAEA,MAAM,CAAC,QAAQ,aAAa,mBAAmB,WAAW,CAAC,CAAC,MAAM,GAAG;IACrE,MAAM,aAAa,cAAc,MAAM;IAMvC,IAAI,EAJF,CAAC,CAAC,OAAO,YAAY,cAAc,UAAU,CAAC,EAC1C,6BAA6B,QAAQ,WAAW,IAAI,UAAU,IAGlD;KAChB,SAAS,yCAAyC,EAAE,WAAW,CAAC;KAChE,IAAI,UAAU,gBAAgB,iBAAiB;KAC/C,IAAI,UAAU,iBAAiB,UAAU;KACzC,IAAI,IAAI,EAAE;KACV;IACF;IAEA,MAAM,SAAS,QAAQ,YAAY,YAAY,SAAS;IACxD,SAAS,uCAAuC;KAC9C;KACA,SAAS,CAAC,CAAC,QAAQ;IACrB,CAAC;IACD,IAAI,UAAU,gBAAgB,iBAAiB;IAC/C,IAAI,UAAU,iBAAiB,UAAU;IACzC,IAAI,IAAI,GAAG,QAAQ,iBAAiB,IAAI;GAC1C;GAEA,OAAO,YAAY,IAAI,0BAA0B;EACnD;EACA,UAAU,IAAI,WAAW,SAAS;GAChC,IACE,SAAS,OACT,GAAG,WAAW,WAAW,KACzB,GAAG,SAAS,wBAAwB,GAEpC,OAAO,KAAK;EAIhB;EACA,KAAK,IAAI,SAAS;GAChB,IAAI,SAAS,OAAO,GAAG,SAAS,wBAAwB,GAAG;IAEzD,MAAM,cAAc,IADG,IAAI,GAAG,MAAM,CAAC,GAAG,kBACpB,CAAA,CAAW,aAAa,IAAI,GAAG;IAEnD,IAAI,CAAC,aACH;IAGF,MAAM,CAAC,QAAQ,aAAa,mBAAmB,WAAW,CAAC,CAAC,MAAM,GAAG;IAGrE,OAFe,QAAQ,YAAY,cAAc,MAAM,GAAG,SAEnD,CAAA,EAAQ,iBAAiB;GAClC;EAGF;CACF;AACF"}
1
+ {"version":3,"file":"live-reload-plugin.js","names":[],"sources":["../../../src/lib/live-reload-plugin.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport { ServerResponse } from 'node:http';\nimport { Connect, normalizePath, Plugin, ViteDevServer } from 'vite';\n\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\nimport { HmrUpdateResult } from './models.js';\nimport { debugHmr } from './utils/debug.js';\n\nconst ANGULAR_COMPONENT_PREFIX = '/@ng/component';\nconst FILE_PREFIX = 'file:';\n\nexport interface ComponentUpdates {\n classNames: Map<string, Set<string>>;\n fileEmitter: (file: string, className: string) => HmrUpdateResult | undefined;\n rootDir?: string;\n}\n\nfunction createProxyMatchers(\n proxy: ViteDevServer['config']['server']['proxy'],\n): Array<(url: string) => boolean> {\n if (!proxy) {\n return [];\n }\n\n const matchers: Array<(url: string) => boolean> = [];\n for (const [context, opts] of Object.entries(proxy)) {\n if (!opts) {\n continue;\n }\n // Skip proxy rules with custom bypass handlers that may route local\n // requests back to this dev server.\n if (typeof opts === 'object' && typeof opts.bypass === 'function') {\n continue;\n }\n if (context.startsWith('^')) {\n const regex = new RegExp(context);\n matchers.push((url) => regex.test(url));\n } else {\n matchers.push((url) => url.startsWith(context));\n }\n }\n return matchers;\n}\n\nexport function liveReloadPlugin(\n ctxOrUpdates?: AngularBuildContext | ComponentUpdates,\n): Plugin {\n const updates: ComponentUpdates = isAngularBuildContext(ctxOrUpdates)\n ? ctxOrUpdates.hmr\n : (ctxOrUpdates ?? {\n classNames: new Map<string, Set<string>>(),\n fileEmitter: () => undefined,\n });\n\n const resolveFileId = (fileId: string): string =>\n normalizePath(resolve(updates.rootDir ?? process.cwd(), fileId));\n\n return {\n name: 'analogjs-live-reload-plugin',\n apply: 'serve',\n configureServer(server: ViteDevServer) {\n if (server.config.server.hmr === false) {\n debugHmr('middleware disabled: vite server.hmr is false');\n return;\n }\n\n const proxyMatchers = createProxyMatchers(server.config.server.proxy);\n\n const angularComponentMiddleware: Connect.HandleFunction = async (\n req: Connect.IncomingMessage,\n res: ServerResponse<Connect.IncomingMessage>,\n next: Connect.NextFunction,\n ) => {\n if (req.url === undefined || res.writableEnded) {\n return;\n }\n\n if (\n !req.url.includes(ANGULAR_COMPONENT_PREFIX) ||\n proxyMatchers.some((match) => match(req.url!))\n ) {\n next();\n\n return;\n }\n\n const requestUrl = new URL(req.url, 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n res.statusCode = 400;\n res.end();\n\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const resolvedId = resolveFileId(fileId);\n const moduleNode = server.moduleGraph.getModuleById(resolvedId);\n const knownClasses = updates.classNames.get(resolvedId);\n\n if (!moduleNode && !knownClasses?.size) {\n debugHmr('middleware: passed through (unknown component)', {\n resolvedId,\n className,\n });\n next();\n return;\n }\n\n const hasKnownClass = className\n ? !!knownClasses?.has(className)\n : !!knownClasses?.size;\n const invalidated =\n !!moduleNode?.lastInvalidationTimestamp && hasKnownClass;\n\n // don't send an HMR update until the file has been invalidated\n if (!invalidated) {\n debugHmr('middleware: skipped (not invalidated)', {\n resolvedId,\n className,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end('');\n return;\n }\n\n const result = updates.fileEmitter(resolvedId, className);\n debugHmr('middleware: served component update', {\n resolvedId,\n className,\n hasCode: !!result?.hmrUpdateCode,\n });\n res.setHeader('Content-Type', 'text/javascript');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(`${result?.hmrUpdateCode || ''}`);\n };\n\n server.middlewares.use(angularComponentMiddleware);\n },\n resolveId(id, _importer, options) {\n if (\n options?.ssr &&\n id.startsWith(FILE_PREFIX) &&\n id.includes(ANGULAR_COMPONENT_PREFIX)\n ) {\n return `\\0${id}`;\n }\n\n return undefined;\n },\n load(id, options) {\n if (options?.ssr && id.includes(ANGULAR_COMPONENT_PREFIX)) {\n const requestUrl = new URL(id.slice(1), 'http://localhost');\n const componentId = requestUrl.searchParams.get('c');\n\n if (!componentId) {\n return;\n }\n\n const [fileId, className] = decodeURIComponent(componentId).split('@');\n const result = updates.fileEmitter(resolveFileId(fileId), className);\n\n return result?.hmrUpdateCode || '';\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;;;AAWA,IAAM,2BAA2B;AACjC,IAAM,cAAc;AAQpB,SAAS,oBACP,OACiC;CACjC,IAAI,CAAC,OACH,OAAO,CAAC;CAGV,MAAM,WAA4C,CAAC;CACnD,KAAK,MAAM,CAAC,SAAS,SAAS,OAAO,QAAQ,KAAK,GAAG;EACnD,IAAI,CAAC,MACH;EAIF,IAAI,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,MAAM;KACtC,SAAS,kDAAkD;MACzD;MACA;KACF,CAAC;KACD,KAAK;KACL;IACF;IAEA,MAAM,gBAAgB,YAClB,CAAC,CAAC,cAAc,IAAI,SAAS,IAC7B,CAAC,CAAC,cAAc;IAKpB,IAAI,EAHF,CAAC,CAAC,YAAY,6BAA6B,gBAG3B;KAChB,SAAS,yCAAyC;MAChD;MACA;KACF,CAAC;KACD,IAAI,UAAU,gBAAgB,iBAAiB;KAC/C,IAAI,UAAU,iBAAiB,UAAU;KACzC,IAAI,IAAI,EAAE;KACV;IACF;IAEA,MAAM,SAAS,QAAQ,YAAY,YAAY,SAAS;IACxD,SAAS,uCAAuC;KAC9C;KACA;KACA,SAAS,CAAC,CAAC,QAAQ;IACrB,CAAC;IACD,IAAI,UAAU,gBAAgB,iBAAiB;IAC/C,IAAI,UAAU,iBAAiB,UAAU;IACzC,IAAI,IAAI,GAAG,QAAQ,iBAAiB,IAAI;GAC1C;GAEA,OAAO,YAAY,IAAI,0BAA0B;EACnD;EACA,UAAU,IAAI,WAAW,SAAS;GAChC,IACE,SAAS,OACT,GAAG,WAAW,WAAW,KACzB,GAAG,SAAS,wBAAwB,GAEpC,OAAO,KAAK;EAIhB;EACA,KAAK,IAAI,SAAS;GAChB,IAAI,SAAS,OAAO,GAAG,SAAS,wBAAwB,GAAG;IAEzD,MAAM,cAAc,IADG,IAAI,GAAG,MAAM,CAAC,GAAG,kBACpB,CAAA,CAAW,aAAa,IAAI,GAAG;IAEnD,IAAI,CAAC,aACH;IAGF,MAAM,CAAC,QAAQ,aAAa,mBAAmB,WAAW,CAAC,CAAC,MAAM,GAAG;IAGrE,OAFe,QAAQ,YAAY,cAAc,MAAM,GAAG,SAEnD,CAAA,EAAQ,iBAAiB;GAClC;EAGF;CACF;AACF"}
@@ -1,4 +1,7 @@
1
1
  import type ts from "typescript";
2
+ export interface HmrUpdateResult {
3
+ hmrUpdateCode?: string | null;
4
+ }
2
5
  export interface EmitFileResult {
3
6
  content?: string;
4
7
  map?: string;
@@ -6,6 +9,6 @@ export interface EmitFileResult {
6
9
  hash?: Uint8Array;
7
10
  errors?: (string | ts.DiagnosticMessageChain)[];
8
11
  warnings?: (string | ts.DiagnosticMessageChain)[];
9
- hmrUpdateCode?: string | null;
12
+ hmrUpdateCodes?: Map<string, string>;
10
13
  hmrEligible?: boolean | null;
11
14
  }