@analogjs/vite-plugin-angular 3.0.0-beta.9 → 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.
Files changed (164) hide show
  1. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +3 -3
  2. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
  3. package/ngp/LICENSE +21 -0
  4. package/ngp/api.mjs +46806 -0
  5. package/ngp/build.json +4 -0
  6. package/ngp/ng_analyze.cjs +601 -0
  7. package/ngp/ng_analyze_bg.wasm +0 -0
  8. package/package.json +5 -2
  9. package/src/index.d.ts +2 -0
  10. package/src/index.js +4 -3
  11. package/src/index.js.map +1 -1
  12. package/src/lib/analog-plugin-interop.js +2 -3
  13. package/src/lib/angular-build-context.d.ts +217 -0
  14. package/src/lib/angular-build-context.js +374 -0
  15. package/src/lib/angular-build-context.js.map +1 -0
  16. package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
  17. package/src/lib/angular-build-optimizer-plugin.js +25 -11
  18. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  19. package/src/lib/angular-jit-plugin.d.ts +5 -3
  20. package/src/lib/angular-jit-plugin.js +16 -9
  21. package/src/lib/angular-jit-plugin.js.map +1 -1
  22. package/src/lib/angular-vite-plugin.d.ts +6 -109
  23. package/src/lib/angular-vite-plugin.js +9 -1251
  24. package/src/lib/angular-vite-plugin.js.map +1 -1
  25. package/src/lib/angular-vitest-plugin.d.ts +3 -2
  26. package/src/lib/angular-vitest-plugin.js +7 -5
  27. package/src/lib/angular-vitest-plugin.js.map +1 -1
  28. package/src/lib/companion-plugins.d.ts +7 -0
  29. package/src/lib/companion-plugins.js +37 -0
  30. package/src/lib/companion-plugins.js.map +1 -0
  31. package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
  32. package/src/lib/compilation-api/compilation-api-plugin.js +164 -289
  33. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  34. package/src/lib/compilation-api/index.js +1 -2
  35. package/src/lib/compiler/angular-version.js +0 -1
  36. package/src/lib/compiler/class-field-lowering.js +1 -2
  37. package/src/lib/compiler/compile.d.ts +1 -1
  38. package/src/lib/compiler/compile.js +224 -151
  39. package/src/lib/compiler/compile.js.map +1 -1
  40. package/src/lib/compiler/constants.js +1 -2
  41. package/src/lib/compiler/debug.js +1 -2
  42. package/src/lib/compiler/defer.d.ts +2 -3
  43. package/src/lib/compiler/defer.js +13 -16
  44. package/src/lib/compiler/defer.js.map +1 -1
  45. package/src/lib/compiler/dts-reader.d.ts +6 -1
  46. package/src/lib/compiler/dts-reader.js +20 -12
  47. package/src/lib/compiler/dts-reader.js.map +1 -1
  48. package/src/lib/compiler/hmr.d.ts +4 -0
  49. package/src/lib/compiler/hmr.js +8 -4
  50. package/src/lib/compiler/hmr.js.map +1 -1
  51. package/src/lib/compiler/index.d.ts +2 -2
  52. package/src/lib/compiler/index.js +6 -6
  53. package/src/lib/compiler/jit-metadata.js +1 -2
  54. package/src/lib/compiler/jit-transform.js +37 -15
  55. package/src/lib/compiler/jit-transform.js.map +1 -1
  56. package/src/lib/compiler/js-emitter.d.ts +0 -3
  57. package/src/lib/compiler/js-emitter.js +4 -23
  58. package/src/lib/compiler/js-emitter.js.map +1 -1
  59. package/src/lib/compiler/metadata.js +2 -3
  60. package/src/lib/compiler/registry.d.ts +9 -1
  61. package/src/lib/compiler/registry.js +36 -8
  62. package/src/lib/compiler/registry.js.map +1 -1
  63. package/src/lib/compiler/resource-inliner.d.ts +8 -9
  64. package/src/lib/compiler/resource-inliner.js +11 -20
  65. package/src/lib/compiler/resource-inliner.js.map +1 -1
  66. package/src/lib/compiler/style-ast.d.ts +22 -1
  67. package/src/lib/compiler/style-ast.js +37 -20
  68. package/src/lib/compiler/style-ast.js.map +1 -1
  69. package/src/lib/compiler/type-elision.d.ts +4 -3
  70. package/src/lib/compiler/type-elision.js +11 -13
  71. package/src/lib/compiler/type-elision.js.map +1 -1
  72. package/src/lib/compiler/utils.d.ts +9 -7
  73. package/src/lib/compiler/utils.js +50 -11
  74. package/src/lib/compiler/utils.js.map +1 -1
  75. package/src/lib/compiler-plugin.js +1 -2
  76. package/src/lib/component-resolvers.js +1 -2
  77. package/src/lib/component-scanner.d.ts +101 -0
  78. package/src/lib/component-scanner.js +331 -0
  79. package/src/lib/component-scanner.js.map +1 -0
  80. package/src/lib/component-styles-plugin.d.ts +52 -0
  81. package/src/lib/component-styles-plugin.js +352 -0
  82. package/src/lib/component-styles-plugin.js.map +1 -0
  83. package/src/lib/compose-angular-plugins.d.ts +12 -0
  84. package/src/lib/compose-angular-plugins.js +30 -0
  85. package/src/lib/compose-angular-plugins.js.map +1 -0
  86. package/src/lib/dev-server-mode-plugin.d.ts +7 -0
  87. package/src/lib/dev-server-mode-plugin.js +22 -0
  88. package/src/lib/dev-server-mode-plugin.js.map +1 -0
  89. package/src/lib/encapsulation-plugin.js +1 -2
  90. package/src/lib/fast-compile-api.d.ts +62 -0
  91. package/src/lib/fast-compile-api.js +11 -0
  92. package/src/lib/fast-compile-api.js.map +1 -0
  93. package/src/lib/fast-compile-plugin.d.ts +6 -1
  94. package/src/lib/fast-compile-plugin.js +222 -117
  95. package/src/lib/fast-compile-plugin.js.map +1 -1
  96. package/src/lib/host.d.ts +3 -0
  97. package/src/lib/host.js +5 -4
  98. package/src/lib/host.js.map +1 -1
  99. package/src/lib/hot-update-batch.js +1 -2
  100. package/src/lib/live-reload-plugin.d.ts +8 -5
  101. package/src/lib/live-reload-plugin.js +45 -10
  102. package/src/lib/live-reload-plugin.js.map +1 -1
  103. package/src/lib/models.d.ts +4 -1
  104. package/src/lib/ngp-compile-api.d.ts +55 -0
  105. package/src/lib/ngp-compile-api.js +11 -0
  106. package/src/lib/ngp-compile-api.js.map +1 -0
  107. package/src/lib/ngp-compile-plugin.d.ts +4 -0
  108. package/src/lib/ngp-compile-plugin.js +680 -0
  109. package/src/lib/ngp-compile-plugin.js.map +1 -0
  110. package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
  111. package/src/lib/ngtsc-compile-plugin.js +780 -0
  112. package/src/lib/ngtsc-compile-plugin.js.map +1 -0
  113. package/src/lib/nx-folder-plugin.d.ts +6 -5
  114. package/src/lib/nx-folder-plugin.js +13 -9
  115. package/src/lib/nx-folder-plugin.js.map +1 -1
  116. package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
  117. package/src/lib/plugins/file-replacements.plugin.js +2 -2
  118. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  119. package/src/lib/router-plugin.d.ts +5 -1
  120. package/src/lib/router-plugin.js +14 -6
  121. package/src/lib/router-plugin.js.map +1 -1
  122. package/src/lib/style-preprocessor.js +1 -2
  123. package/src/lib/stylesheet-registry.js +1 -2
  124. package/src/lib/stylesheet-registry.js.map +1 -1
  125. package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -3
  126. package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
  127. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js +1 -2
  128. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js.map +1 -1
  129. package/src/lib/utils/compilation-shared.d.ts +1 -4
  130. package/src/lib/utils/compilation-shared.js +9 -8
  131. package/src/lib/utils/compilation-shared.js.map +1 -1
  132. package/src/lib/utils/css-extension-resolver.js +1 -2
  133. package/src/lib/utils/css-preprocessor-workers.js +1 -2
  134. package/src/lib/utils/debug-harness.js +1 -2
  135. package/src/lib/utils/debug-log-file.js +1 -2
  136. package/src/lib/utils/debug.js +1 -2
  137. package/src/lib/utils/devkit.js +2 -3
  138. package/src/lib/utils/hmr-component-updates.d.ts +7 -0
  139. package/src/lib/utils/hmr-component-updates.js +86 -0
  140. package/src/lib/utils/hmr-component-updates.js.map +1 -0
  141. package/src/lib/utils/jit-inline-styles.js +1 -2
  142. package/src/lib/utils/lsp-type-checker.d.ts +75 -0
  143. package/src/lib/utils/lsp-type-checker.js +532 -0
  144. package/src/lib/utils/lsp-type-checker.js.map +1 -0
  145. package/src/lib/utils/ngp-host-fs.d.ts +43 -0
  146. package/src/lib/utils/ngp-host-fs.js +128 -0
  147. package/src/lib/utils/ngp-host-fs.js.map +1 -0
  148. package/src/lib/utils/plugin-config.d.ts +15 -8
  149. package/src/lib/utils/plugin-config.js +19 -7
  150. package/src/lib/utils/plugin-config.js.map +1 -1
  151. package/src/lib/utils/rolldown.js +1 -2
  152. package/src/lib/utils/safe-module-paths.js +1 -2
  153. package/src/lib/utils/stylesheet-warning.d.ts +2 -0
  154. package/src/lib/utils/stylesheet-warning.js +10 -0
  155. package/src/lib/utils/stylesheet-warning.js.map +1 -0
  156. package/src/lib/utils/transform-cache.js +1 -2
  157. package/src/lib/utils/transform-cache.js.map +1 -1
  158. package/src/lib/utils/tsconfig-resolver.js +2 -3
  159. package/src/lib/utils/virtual-ids.js +1 -2
  160. package/src/lib/utils/virtual-resources.js +1 -2
  161. package/src/lib/utils/virtual-resources.js.map +1 -1
  162. package/src/lib/virtual-modules-plugin.d.ts +11 -3
  163. package/src/lib/virtual-modules-plugin.js +70 -15
  164. package/src/lib/virtual-modules-plugin.js.map +1 -1
@@ -1,99 +1,53 @@
1
- import { SourceFileCache, angularFullVersion, createAngularCompilation } from "../utils/devkit.js";
2
- import { activateDeferredDebug, applyDebugOption, debugCompilationApi, debugCompiler, debugEmit, debugHmr, debugHmrV, debugStyles, debugStylesV } from "../utils/debug.js";
3
- import { createCompilerPlugin, createRolldownCompilerPlugin } from "../compiler-plugin.js";
4
- import { TS_EXT_REGEX, createTsConfigGetter, getTsConfigPath } from "../utils/plugin-config.js";
5
- import { TsconfigResolver } from "../utils/tsconfig-resolver.js";
6
- import { isRolldown } from "../utils/rolldown.js";
7
- import { normalizeStylesheetDependencies } from "../style-preprocessor.js";
8
- import { AnalogStylesheetRegistry, preprocessStylesheetResult, registerStylesheetContent, rewriteRelativeCssImports } from "../stylesheet-registry.js";
9
- import { discoverAnalogIntegrations } from "../analog-plugin-interop.js";
10
- import { DiagnosticModes, getBrowserModeCliOverride, injectViteIgnoreForHmrMetadata, isIgnoredHmrFile, isTestWatchMode, mapTemplateUpdatesToFiles, refreshStylesheetRegistryForFile, toAngularCompilationFileReplacements } from "../utils/compilation-shared.js";
1
+ import { createAngularBuildContext, isAngularBuildContext } from "../angular-build-context.js";
2
+ import { composeWithCompanions } from "../companion-plugins.js";
3
+ import { markModuleSelfAccepting } from "../component-styles-plugin.js";
11
4
  import { createHotUpdateBatcher } from "../hot-update-batch.js";
12
- import { angularVitestPlugins } from "../angular-vitest-plugin.js";
13
- import { buildOptimizerPlugin } from "../angular-build-optimizer-plugin.js";
14
- import { jitPlugin } from "../angular-jit-plugin.js";
15
- import { liveReloadPlugin } from "../live-reload-plugin.js";
16
- import { virtualModulesPlugin } from "../virtual-modules-plugin.js";
17
- import { encapsulationPlugin } from "../encapsulation-plugin.js";
18
- import { nxFolderPlugin } from "../nx-folder-plugin.js";
19
- import { routerPlugin } from "../router-plugin.js";
20
- import { replaceFiles } from "../plugins/file-replacements.plugin.js";
21
- import { cssExtensionStyleResolverPlugin } from "../utils/css-extension-resolver.js";
22
- import { loadVirtualRawModule } from "../utils/virtual-resources.js";
5
+ import { normalizeStylesheetDependencies } from "../style-preprocessor.js";
6
+ import { preprocessStylesheetResult, rewriteRelativeCssImports } from "../stylesheet-registry.js";
7
+ import { DiagnosticModes, injectViteIgnoreForHmrMetadata, mapTemplateUpdatesToFiles, toAngularCompilationFileReplacements } from "../utils/compilation-shared.js";
8
+ import { activateDeferredDebug, debugCompilationApi, debugCompiler, debugEmit, debugHmr, debugStyles } from "../utils/debug.js";
9
+ import { SourceFileCache, angularFullVersion, createAngularCompilation } from "../utils/devkit.js";
10
+ import { TS_EXT_REGEX, createDepOptimizerConfig } from "../utils/plugin-config.js";
11
+ import { loadAngularVirtualModule, resolveAngularVirtualId } from "../virtual-modules-plugin.js";
23
12
  import { union } from "es-toolkit";
24
13
  import { createHash } from "node:crypto";
25
14
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
26
- import { basename, isAbsolute, join, relative, resolve } from "node:path";
27
15
  import { createRequire } from "node:module";
28
- import { normalizePath, preprocessCSS } from "vite";
29
- //#region packages/vite-plugin-angular/src/lib/compilation-api/compilation-api-plugin.ts
30
- var ts = createRequire(import.meta.url)("typescript");
16
+ import { basename, isAbsolute, join, resolve } from "node:path";
17
+ import { normalizePath } from "vite";
18
+ // packages/vite-plugin-angular/src/lib/compilation-api/compilation-api-plugin.ts
19
+ var require = createRequire(import.meta.url);
20
+ function assertSupportedCompilationApi() {
21
+ if (angularFullVersion < 200100 || typeof createAngularCompilation !== "function") throw new Error("[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.");
22
+ }
31
23
  /**
32
- * Compiles Angular applications using Angular's private Compilation API.
24
+ * Single-responsibility compiler plugin backed by Angular's `@angular/build`
25
+ * Compilation API. Can be composed with custom pipelines via `AngularBuildContext`
26
+ * or mounted with default companions via `angularCompilationPlugin()`.
33
27
  *
34
28
  * @experimental This plugin may change in future releases.
35
29
  */
36
- function angularCompilationPlugin(options = {}) {
37
- if (angularFullVersion < 200100 || typeof createAngularCompilation !== "function") throw new Error("[@analogjs/vite-plugin-angular]: angularCompilationPlugin requires Angular v20.1 or later and a matching @angular/build package with the Compilation API.");
38
- applyDebugOption(options.debug, options.workspaceRoot);
39
- const isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
40
- const isStackBlitz = !!process.versions["webcontainer"];
41
- const pluginOptions = {
42
- tsconfigGetter: createTsConfigGetter(options.tsconfig),
43
- workspaceRoot: options.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd(),
44
- inlineStylesExtension: options.inlineStylesExtension ?? "css",
45
- jit: options.jit ?? isTest,
46
- liveReload: options.liveReload ?? true,
47
- disableTypeChecking: options.disableTypeChecking ?? true,
48
- supportedBrowsers: options.supportedBrowsers ?? ["safari 15"],
49
- fileReplacements: options.fileReplacements ?? [],
50
- include: options.include ?? [],
51
- isAstroIntegration: process.env["ANALOG_ASTRO"] === "true"
52
- };
53
- let resolvedConfig;
54
- let tsConfigResolutionContext = null;
55
- let watchMode = false;
56
- let stylePreprocessor;
57
- let transformFilter;
58
- let externalizeStylesRequested = false;
30
+ function compilationApiPlugin(ctxOrOptions) {
31
+ assertSupportedCompilationApi();
32
+ const ctx = isAngularBuildContext(ctxOrOptions) ? ctxOrOptions : createAngularBuildContext({
33
+ ...ctxOrOptions,
34
+ compilationBackend: "compilation-api"
35
+ });
36
+ const ts = require("typescript");
37
+ const { isTest } = ctx.options;
59
38
  let angularCompilation;
60
39
  const sourceFileCache = new SourceFileCache();
61
40
  const outputFiles = /* @__PURE__ */ new Map();
62
- const classNames = /* @__PURE__ */ new Map();
63
- let stylesheetRegistry;
64
41
  let compilationLock = Promise.resolve();
65
42
  let pendingCompilation = null;
66
43
  let initialCompilation = false;
67
44
  let viteServer;
68
- const hotUpdates = createHotUpdateBatcher((ids) => performCompilation(resolvedConfig, ids));
69
- const tsconfigResolver = new TsconfigResolver({
70
- workspaceRoot: pluginOptions.workspaceRoot,
71
- include: pluginOptions.include,
72
- liveReload: pluginOptions.liveReload,
73
- isTest
74
- });
75
- const isVitestVscode = !!process.env["VITEST_VSCODE"];
76
- let deferInitialCompilation = isVitestVscode;
77
- let testWatchMode = isTestWatchMode();
78
- function hasViteHmrTransport() {
79
- return resolvedConfig ? resolvedConfig.server.hmr !== false : true;
80
- }
81
- function shouldEnableLiveReload() {
82
- return !!((isTest ? testWatchMode : watchMode) && pluginOptions.liveReload && hasViteHmrTransport());
83
- }
84
- function shouldExternalizeStyles() {
85
- if (!(isTest ? testWatchMode : watchMode)) return false;
86
- return !!(shouldEnableLiveReload() || externalizeStylesRequested);
87
- }
88
- function resolveTsConfigPath() {
89
- const tsconfigValue = pluginOptions.tsconfigGetter();
90
- return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib);
91
- }
45
+ const hotUpdates = createHotUpdateBatcher((ids) => performCompilation(ctx.resolvedConfig, ids));
92
46
  function resolveCompilationApiTsConfigPath(resolvedTsConfigPath, config) {
93
- const includedFiles = tsconfigResolver.ensureIncludeCache();
94
- const cached = tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
95
- const expandedGraphRoots = tsconfigResolver.collectExpandedTsconfigRoots(resolvedTsConfigPath, config);
96
- const mergedRootNames = union(cached.rootNames, expandedGraphRoots, includedFiles).map((file) => normalizePath(file));
47
+ const includedFiles = ctx.tsconfigResolver.ensureIncludeCache();
48
+ const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
49
+ const expandedGraphRoots = ctx.tsconfigResolver.collectExpandedTsconfigRoots(resolvedTsConfigPath, config);
50
+ const mergedRootNames = union(union(cached.rootNames, expandedGraphRoots), includedFiles).map((file) => normalizePath(file));
97
51
  if (mergedRootNames.length === cached.rootNames.length) return resolvedTsConfigPath;
98
52
  const resolvedCacheDir = isAbsolute(config.cacheDir) ? config.cacheDir : resolve(config.root, config.cacheDir);
99
53
  const wrapperDir = join(resolvedCacheDir, "analog-angular", "compilation-api");
@@ -125,15 +79,29 @@ function angularCompilationPlugin(options = {}) {
125
79
  const normalizedFile = normalizeEmitterLookupId(file);
126
80
  return outputFiles.get(normalizedFile);
127
81
  };
82
+ ctx.hmr.setFileEmitter((file, className) => ({ hmrUpdateCode: fileEmitter(file)?.hmrUpdateCodes?.get(className) }));
83
+ const compilerApi = {
84
+ angularCompiler: true,
85
+ getTsConfigPath: () => ctx.resolveTsConfigPath(),
86
+ getSourceMap: (id) => outputFiles.get(normalizePath(id))?.map,
87
+ hasEmitted: (id) => outputFiles.has(normalizeEmitterLookupId(id))
88
+ };
89
+ ctx.registerCompiler({
90
+ name: "@analogjs/vite-plugin-angular-compilation-api",
91
+ getTsConfigPath: compilerApi.getTsConfigPath,
92
+ getSourceMap: compilerApi.getSourceMap,
93
+ hasEmitted: compilerApi.hasEmitted
94
+ });
128
95
  async function performAngularCompilation(config, ids) {
129
- const compilation = angularCompilation ??= await createAngularCompilation(!!pluginOptions.jit, false);
96
+ const stylesheetRegistry = ctx.styles.ensureRegistry();
97
+ const compilation = angularCompilation ??= await createAngularCompilation(!!ctx.options.jit, false);
130
98
  const modifiedFiles = ids?.length ? new Set(ids.map((file) => normalizePath(file))) : void 0;
131
99
  if (modifiedFiles?.size) sourceFileCache.invalidate(modifiedFiles);
132
100
  if (modifiedFiles?.size && compilation.update) {
133
101
  debugCompilationApi("incremental update", { files: [...modifiedFiles] });
134
102
  await compilation.update(modifiedFiles);
135
103
  }
136
- const resolvedTsConfigPath = resolveTsConfigPath();
104
+ const resolvedTsConfigPath = ctx.resolveTsConfigPath();
137
105
  const compilationApiTsConfigPath = resolveCompilationApiTsConfigPath(resolvedTsConfigPath, config);
138
106
  debugEmit("compilation initialize", {
139
107
  resolvedTsConfigPath,
@@ -141,17 +109,17 @@ function angularCompilationPlugin(options = {}) {
141
109
  modifiedFileCount: modifiedFiles?.size ?? 0
142
110
  });
143
111
  const transformCompilerOptions = (tsCompilerOptions) => {
144
- if (shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
145
- if (shouldEnableLiveReload()) {
112
+ if (ctx.shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
113
+ if (ctx.shouldEnableLiveReload()) {
146
114
  tsCompilerOptions["_enableHmr"] = true;
147
115
  tsCompilerOptions["supportTestBed"] = true;
148
116
  }
149
117
  debugCompiler("tsCompilerOptions (compilation API)", {
150
- liveReload: pluginOptions.liveReload,
151
- viteHmr: hasViteHmrTransport(),
152
- externalizeStylesRequested,
153
- watchMode,
154
- shouldExternalize: shouldExternalizeStyles(),
118
+ liveReload: ctx.options.liveReload,
119
+ viteHmr: ctx.hasViteHmrTransport(),
120
+ externalizeStylesRequested: ctx.externalizeStylesRequested,
121
+ watchMode: ctx.watchMode,
122
+ shouldExternalize: ctx.shouldExternalizeStyles(),
155
123
  externalRuntimeStyles: !!tsCompilerOptions["externalRuntimeStyles"],
156
124
  hmrEnabled: !!tsCompilerOptions["_enableHmr"]
157
125
  });
@@ -159,75 +127,41 @@ function angularCompilationPlugin(options = {}) {
159
127
  tsCompilerOptions["supportTestBed"] = true;
160
128
  tsCompilerOptions["supportJitMode"] = true;
161
129
  }
162
- if (!isTest && resolvedConfig.build?.lib) {
130
+ if (!isTest && config.build?.lib) {
163
131
  tsCompilerOptions["declaration"] = true;
164
- tsCompilerOptions["declarationMap"] = watchMode;
132
+ tsCompilerOptions["declarationMap"] = ctx.watchMode;
165
133
  tsCompilerOptions["inlineSources"] = true;
166
134
  }
167
135
  if (isTest) tsCompilerOptions["supportTestBed"] = true;
168
136
  return tsCompilerOptions;
169
137
  };
170
138
  const compilationResult = await compilation.initialize(compilationApiTsConfigPath, {
171
- fileReplacements: toAngularCompilationFileReplacements(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
139
+ fileReplacements: toAngularCompilationFileReplacements(ctx.options.fileReplacements, ctx.options.workspaceRoot),
172
140
  modifiedFiles,
173
141
  async transformStylesheet(data, containingFile, resourceFile, order, className) {
174
- const filename = resourceFile ?? containingFile.replace(".ts", `.${pluginOptions.inlineStylesExtension}`);
175
- const preprocessed = preprocessStylesheetResult(data, filename, stylePreprocessor, {
176
- filename,
142
+ if (ctx.shouldEnableLiveReload() && className && containingFile) ctx.hmr.addClassName(normalizePath(containingFile), className);
143
+ return (await ctx.styles.transformStylesheet({
144
+ data,
177
145
  containingFile,
178
146
  resourceFile,
179
- className,
180
147
  order,
181
- inline: !resourceFile
182
- });
183
- if (shouldEnableLiveReload() && className && containingFile) classNames.set(normalizePath(containingFile), className);
184
- if (shouldExternalizeStyles()) {
185
- const stylesheetId = registerStylesheetContent(stylesheetRegistry, {
186
- code: preprocessed.code,
187
- dependencies: normalizeStylesheetDependencies(preprocessed.dependencies),
188
- diagnostics: preprocessed.diagnostics,
189
- tags: preprocessed.tags,
190
- containingFile,
191
- className,
192
- order,
193
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
194
- resourceFile: resourceFile ?? void 0
195
- });
196
- debugStyles("stylesheet deferred to Vite pipeline", {
197
- stylesheetId,
198
- resourceFile: resourceFile ?? "(inline)"
199
- });
200
- return stylesheetId;
201
- }
202
- debugStyles("stylesheet processed inline via preprocessCSS", {
203
- filename,
204
- resourceFile: resourceFile ?? "(inline)",
205
- dataLength: preprocessed.code.length
206
- });
207
- let stylesheetResult;
208
- try {
209
- stylesheetResult = await preprocessCSS(preprocessed.code, `${filename}?direct`, resolvedConfig);
210
- } catch (e) {
211
- debugStyles("preprocessCSS error", {
212
- filename,
213
- resourceFile: resourceFile ?? "(inline)",
214
- error: String(e)
215
- });
216
- }
217
- return stylesheetResult?.code || "";
148
+ className,
149
+ readMissingResource: true,
150
+ logger: config.logger
151
+ }))?.content || "";
218
152
  },
219
153
  processWebWorker(workerFile) {
220
154
  return workerFile;
221
155
  }
222
156
  }, angularFullVersion >= 220200 ? {
223
- enableHmr: shouldEnableLiveReload(),
224
- externalRuntimeStyles: shouldExternalizeStyles(),
225
- includeTestMetadata: isTest || shouldEnableLiveReload(),
157
+ enableHmr: ctx.shouldEnableLiveReload(),
158
+ externalRuntimeStyles: ctx.shouldExternalizeStyles(),
159
+ includeTestMetadata: isTest || ctx.shouldEnableLiveReload(),
226
160
  instrumentForCoverage: !isTest
227
161
  } : transformCompilerOptions);
228
162
  debugStyles("external stylesheets from compilation API", {
229
163
  count: compilationResult.externalStylesheets?.size ?? 0,
230
- hasPreprocessor: !!stylePreprocessor,
164
+ hasPreprocessor: !!ctx.stylePreprocessor,
231
165
  hasInlineMap: !!stylesheetRegistry
232
166
  });
233
167
  const preprocessStats = {
@@ -239,10 +173,10 @@ function angularCompilationPlugin(options = {}) {
239
173
  for (const [key, value] of compilationResult.externalStylesheets ?? []) {
240
174
  preprocessStats.total++;
241
175
  const angularHash = `${value}.css`;
242
- stylesheetRegistry?.registerExternalRequest(angularHash, key);
243
- if (stylesheetRegistry && stylePreprocessor && existsSync(key)) try {
176
+ stylesheetRegistry.registerExternalRequest(angularHash, key);
177
+ if (ctx.stylePreprocessor && existsSync(key)) try {
244
178
  const rawCss = readFileSync(key, "utf-8");
245
- const preprocessed = preprocessStylesheetResult(rawCss, key, stylePreprocessor);
179
+ const preprocessed = preprocessStylesheetResult(rawCss, key, ctx.stylePreprocessor);
246
180
  const servedCss = rewriteRelativeCssImports(preprocessed.code, key);
247
181
  stylesheetRegistry.registerServedStylesheet({
248
182
  publicId: angularHash,
@@ -267,7 +201,7 @@ function angularCompilationPlugin(options = {}) {
267
201
  else preprocessStats.skipped++;
268
202
  }
269
203
  debugStyles("external stylesheet preprocessing complete", preprocessStats);
270
- const diagnostics = await compilation.diagnoseFiles(pluginOptions.disableTypeChecking ? DiagnosticModes.All & ~DiagnosticModes.Semantic : DiagnosticModes.All);
204
+ const diagnostics = await compilation.diagnoseFiles(ctx.options.disableTypeChecking ? DiagnosticModes.All & ~DiagnosticModes.Semantic : DiagnosticModes.All);
271
205
  const errors = diagnostics.errors?.length ? diagnostics.errors : [];
272
206
  const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];
273
207
  const templateUpdates = mapTemplateUpdatesToFiles(compilationResult.templateUpdates);
@@ -275,7 +209,7 @@ function angularCompilationPlugin(options = {}) {
275
209
  count: templateUpdates.size,
276
210
  files: [...templateUpdates.keys()]
277
211
  });
278
- const affectedFiles = await compilation.emitAffectedFiles();
212
+ const affectedFiles = Array.from(await compilation.emitAffectedFiles());
279
213
  debugEmit("emitAffectedFiles summary", {
280
214
  count: affectedFiles.length,
281
215
  templateUpdateCount: templateUpdates.size,
@@ -283,200 +217,145 @@ function angularCompilationPlugin(options = {}) {
283
217
  });
284
218
  for (const file of affectedFiles) {
285
219
  const normalizedFilename = normalizePath(file.filename);
286
- const templateUpdate = templateUpdates.get(normalizedFilename);
287
- if (templateUpdate) 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);
288
224
  outputFiles.set(normalizedFilename, {
289
225
  content: file.contents,
290
226
  dependencies: [],
291
227
  errors: errors.map((error) => error.text || ""),
292
228
  warnings: warnings.map((warning) => warning.text || ""),
293
- hmrUpdateCode: templateUpdate?.code,
294
- hmrEligible: !!templateUpdate?.code
229
+ hmrUpdateCodes: mergedUpdates?.size ? mergedUpdates : void 0,
230
+ hmrEligible: !!fileUpdates?.size
295
231
  });
296
232
  }
297
- if (!watchMode && !isTest) {
233
+ if (!ctx.watchMode && !isTest) {
298
234
  await compilation.close?.();
299
235
  angularCompilation = void 0;
300
236
  }
301
237
  }
302
238
  async function performCompilation(config, ids) {
303
- let resolve;
239
+ let releaseLock;
304
240
  const previousLock = compilationLock;
305
241
  compilationLock = new Promise((r) => {
306
- resolve = r;
242
+ releaseLock = r;
307
243
  });
308
244
  try {
309
245
  await previousLock;
310
- const integrations = await discoverAnalogIntegrations(config);
311
- stylePreprocessor = integrations.stylePreprocessor;
312
- transformFilter = integrations.transformFilter;
313
- tsconfigResolver.setIntegrationIncludes(integrations.include);
314
- externalizeStylesRequested = integrations.externalizeStyles;
246
+ await ctx.refreshIntegrations(config);
315
247
  await performAngularCompilation(config, ids);
316
248
  } finally {
317
- resolve();
249
+ releaseLock();
318
250
  }
319
251
  }
320
- function isComponentStyleSheet(id) {
321
- return id.includes("ngcomp=");
322
- }
323
- function getFilenameFromPath(id) {
324
- try {
325
- return new URL(id, "http://localhost").pathname.replace(/^\//, "");
326
- } catch {
327
- const queryIndex = id.indexOf("?");
328
- return (queryIndex >= 0 ? id.slice(0, queryIndex) : id).replace(/^\//, "");
329
- }
330
- }
331
- function sendHMRComponentUpdate(server, id) {
332
- debugHmrV("ws send: angular component update", {
333
- id,
334
- timestamp: Date.now()
335
- });
336
- server.ws.send("angular:component-update", {
337
- id: encodeURIComponent(id),
338
- timestamp: Date.now()
339
- });
340
- classNames.delete(id);
341
- }
342
- const compilerPlugin = {
252
+ return {
343
253
  name: "@analogjs/vite-plugin-angular-compilation-api",
344
- api: { getTsConfigPath: resolveTsConfigPath },
254
+ api: compilerApi,
345
255
  enforce: "pre",
346
- async config(config, { command }) {
256
+ async config(config, { command, mode }) {
347
257
  activateDeferredDebug(command);
348
- watchMode = command === "serve";
349
- const isProd = config.mode === "production" || process.env.NODE_ENV === "production";
350
- tsConfigResolutionContext = {
351
- root: config.root || ".",
352
- isProd,
353
- isLib: !!config?.build?.lib
354
- };
258
+ const resolution = ctx.initConfig(config, {
259
+ command,
260
+ mode
261
+ });
355
262
  debugCompilationApi("enabled (Angular %s)", angularFullVersion);
356
263
  debugCompilationApi("esbuild/oxc disabled, Angular handles transforms");
357
- const useRolldown = isRolldown();
358
- const compilerPluginOptions = {
359
- tsconfig: resolveTsConfigPath(),
360
- sourcemap: !isProd,
361
- advancedOptimizations: isProd,
362
- jit: pluginOptions.jit,
363
- incremental: watchMode
364
- };
264
+ const preliminaryTsConfigPath = ctx.resolveTsConfigPath();
365
265
  return {
366
266
  esbuild: void 0,
367
267
  oxc: void 0,
368
- optimizeDeps: {
369
- include: [
370
- "rxjs/operators",
371
- "rxjs",
372
- "tslib"
373
- ],
374
- exclude: ["@angular/platform-server"],
375
- ...useRolldown ? { rolldownOptions: { plugins: [createRolldownCompilerPlugin(compilerPluginOptions, !pluginOptions.isAstroIntegration)] } } : { esbuildOptions: { plugins: [createCompilerPlugin(compilerPluginOptions, isTest, !pluginOptions.isAstroIntegration)] } }
376
- }
268
+ ...createDepOptimizerConfig({
269
+ tsconfig: preliminaryTsConfigPath,
270
+ isProd: resolution.isProd,
271
+ jit: ctx.options.jit,
272
+ watchMode: ctx.watchMode,
273
+ isTest: ctx.options.isTest,
274
+ isAstroIntegration: ctx.options.isAstroIntegration
275
+ })
377
276
  };
378
277
  },
379
278
  async configResolved(config) {
380
- resolvedConfig = config;
381
- stylesheetRegistry = new AnalogStylesheetRegistry();
382
- (await discoverAnalogIntegrations(config)).configureStylesheetRegistry?.(stylesheetRegistry, { workspaceRoot: pluginOptions.workspaceRoot });
279
+ await ctx.resolveConfig(config);
280
+ ctx.styles.resetRegistry(true);
383
281
  debugStyles("stylesheet registry initialized (Angular Compilation API)");
384
- if (isTest) {
385
- const browser = config.test?.browser;
386
- deferInitialCompilation = isVitestVscode || !!browser && (getBrowserModeCliOverride() ?? browser.enabled) === true;
387
- testWatchMode = !(config.server.watch === null) || config.test?.watch === true || testWatchMode;
388
- }
389
282
  },
390
283
  configureServer(server) {
391
284
  viteServer = server;
392
285
  hotUpdates.configureServer(server);
393
286
  const invalidateCompilation = async () => {
394
- tsconfigResolver.invalidateAll();
395
- await performCompilation(resolvedConfig);
287
+ ctx.tsconfigResolver.invalidateAll();
288
+ await performCompilation(ctx.resolvedConfig);
396
289
  };
397
290
  server.watcher.on("add", invalidateCompilation);
398
291
  server.watcher.on("unlink", invalidateCompilation);
399
292
  server.watcher.on("change", (file) => {
400
- if (file.includes("tsconfig")) tsconfigResolver.invalidateTsconfigCaches();
293
+ if (file.includes("tsconfig")) ctx.tsconfigResolver.invalidateTsconfigCaches();
401
294
  });
402
295
  },
403
296
  async buildStart() {
404
- if (!deferInitialCompilation) {
405
- pendingCompilation = performCompilation(resolvedConfig);
297
+ if (!ctx.deferInitialCompilation) {
298
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
406
299
  await pendingCompilation;
407
300
  pendingCompilation = null;
408
301
  initialCompilation = true;
409
302
  }
410
303
  },
411
- async handleHotUpdate(ctx) {
412
- if (isIgnoredHmrFile(ctx.file)) {
413
- debugHmr("ignored file change", { file: ctx.file });
304
+ async handleHotUpdate(hmrCtx) {
305
+ if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {
306
+ debugHmr("ignored file change", { file: hmrCtx.file });
414
307
  return [];
415
308
  }
416
- if (TS_EXT_REGEX.test(ctx.file)) {
417
- const [fileId] = ctx.file.split("?");
309
+ if (TS_EXT_REGEX.test(hmrCtx.file)) {
310
+ const [fileId] = hmrCtx.file.split("?");
418
311
  debugHmr("TS file changed", {
419
- file: ctx.file,
312
+ file: hmrCtx.file,
420
313
  fileId
421
314
  });
422
- await hotUpdates.schedule(ctx.file, [fileId]);
315
+ await hotUpdates.schedule(hmrCtx.file, [fileId]);
423
316
  let result;
424
- if (shouldEnableLiveReload()) {
317
+ if (ctx.shouldEnableLiveReload()) {
425
318
  result = fileEmitter(fileId);
426
319
  debugHmr("TS file emitted", {
427
320
  fileId,
428
321
  hmrEligible: !!result?.hmrEligible,
429
- hasClassName: !!classNames.get(fileId)
322
+ hasClassName: !!ctx.hmr.classNames.get(fileId)?.size
430
323
  });
431
324
  }
432
- if (shouldEnableLiveReload() && result?.hmrEligible && classNames.get(fileId)) {
433
- const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
434
- debugHmr("sending component update", { relativeFileId });
435
- sendHMRComponentUpdate(ctx.server, relativeFileId);
436
- return ctx.modules.map((mod) => {
437
- if (mod.id === ctx.file) mod.isSelfAccepting = true;
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
+ }
331
+ return hmrCtx.modules.map((mod) => {
332
+ if (mod.id === hmrCtx.file) return markModuleSelfAccepting(mod);
438
333
  return mod;
439
334
  });
440
335
  }
441
336
  }
442
- if (/\.(html|htm)$/.test(ctx.file)) {
443
- debugHmr("template file changed", { file: ctx.file });
444
- pendingCompilation = performCompilation(resolvedConfig);
337
+ if (/\.(html|htm)$/.test(hmrCtx.file)) {
338
+ debugHmr("template file changed", { file: hmrCtx.file });
339
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
445
340
  }
446
- if (/\.(css|less|sass|scss)$/.test(ctx.file)) {
447
- debugHmr("stylesheet file changed", { file: ctx.file });
448
- refreshStylesheetRegistryForFile(ctx.file, stylesheetRegistry, stylePreprocessor);
341
+ if (/\.(css|less|sass|scss)$/.test(hmrCtx.file)) {
342
+ debugHmr("stylesheet file changed", { file: hmrCtx.file });
343
+ ctx.styles.refreshForFile(hmrCtx.file);
449
344
  }
450
- return ctx.modules;
345
+ return hmrCtx.modules;
451
346
  },
452
- resolveId(id) {
453
- if (isComponentStyleSheet(id)) {
454
- const filename = getFilenameFromPath(id);
455
- const search = new URL(id, "http://localhost").search;
456
- const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);
457
- if (servedSourcePath) {
458
- debugStylesV("resolveId: mapped served stylesheet to source", {
459
- filename,
460
- resolvedPath: servedSourcePath
461
- });
462
- return servedSourcePath + search;
463
- }
464
- if (stylesheetRegistry?.hasServed(filename)) return id;
465
- const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);
466
- if (componentStyles) return componentStyles + new URL(id, "http://localhost").search;
467
- }
347
+ resolveId(id, importer) {
348
+ const virtualId = resolveAngularVirtualId(id, importer, {
349
+ jit: ctx.options.jit,
350
+ resolvedConfig: ctx.resolvedConfig
351
+ });
352
+ if (virtualId !== void 0) return virtualId;
353
+ return ctx.styles.resolveComponentStyleId(id);
468
354
  },
469
355
  async load(id) {
470
- const rawModule = await loadVirtualRawModule(this, id);
471
- if (rawModule !== void 0) return rawModule;
472
- if (isComponentStyleSheet(id)) {
473
- const filename = getFilenameFromPath(id);
474
- const componentStyles = stylesheetRegistry?.getServedContent(filename);
475
- if (componentStyles) {
476
- stylesheetRegistry?.registerActiveRequest(id);
477
- return componentStyles;
478
- }
479
- }
356
+ const virtualModule = await loadAngularVirtualModule(this, id, ctx.resolvedConfig);
357
+ if (virtualModule !== void 0) return virtualModule;
358
+ return ctx.styles.loadComponentStyle(id);
480
359
  },
481
360
  transform: {
482
361
  filter: { id: {
@@ -490,18 +369,18 @@ function angularCompilationPlugin(options = {}) {
490
369
  } },
491
370
  async handler(code, id) {
492
371
  if (/[?&]raw\b/.test(id)) return;
493
- if (transformFilter && !transformFilter(code, id)) return;
372
+ if (ctx.transformFilter && !ctx.transformFilter(code, id)) return;
494
373
  const isAngular = /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
495
374
  if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
496
375
  if (isTest) {
497
- if (deferInitialCompilation && !initialCompilation) {
498
- pendingCompilation = performCompilation(resolvedConfig);
376
+ if (ctx.deferInitialCompilation && !initialCompilation) {
377
+ pendingCompilation = performCompilation(ctx.resolvedConfig);
499
378
  initialCompilation = true;
500
379
  }
501
380
  const tsMod = viteServer?.moduleGraph.getModuleById(id);
502
381
  if (tsMod) {
503
382
  const invalidated = tsMod.lastInvalidationTimestamp;
504
- if (testWatchMode && invalidated) pendingCompilation = performCompilation(resolvedConfig, [id]);
383
+ if (ctx.testWatchMode && invalidated) pendingCompilation = performCompilation(ctx.resolvedConfig, [id]);
505
384
  }
506
385
  }
507
386
  if (pendingCompilation) {
@@ -533,32 +412,28 @@ function angularCompilationPlugin(options = {}) {
533
412
  await angularCompilation?.close?.();
534
413
  angularCompilation = void 0;
535
414
  outputFiles.clear();
536
- classNames.clear();
415
+ ctx.hmr.clear();
537
416
  sourceFileCache.clear();
538
- tsconfigResolver.invalidateAll();
539
- stylesheetRegistry = void 0;
417
+ ctx.tsconfigResolver.invalidateAll();
418
+ ctx.styles.clear();
540
419
  pendingCompilation = null;
541
420
  initialCompilation = false;
542
421
  }
543
422
  };
544
- return [
545
- cssExtensionStyleResolverPlugin(),
546
- replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
547
- virtualModulesPlugin({ jit: pluginOptions.jit }),
548
- compilerPlugin,
549
- pluginOptions.liveReload && liveReloadPlugin({
550
- classNames,
551
- fileEmitter
552
- }),
553
- ...isTest && !isStackBlitz ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map) : [],
554
- pluginOptions.jit && jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),
555
- buildOptimizerPlugin({ jit: pluginOptions.jit }),
556
- routerPlugin(),
557
- nxFolderPlugin(),
558
- encapsulationPlugin()
559
- ].filter(Boolean);
560
423
  }
561
- //#endregion
562
- export { angularCompilationPlugin };
424
+ /**
425
+ * Compiles Angular applications using Angular's private Compilation API.
426
+ *
427
+ * @experimental This plugin may change in future releases.
428
+ */
429
+ function angularCompilationPlugin(options = {}) {
430
+ assertSupportedCompilationApi();
431
+ const ctx = createAngularBuildContext({
432
+ ...options,
433
+ compilationBackend: "compilation-api"
434
+ });
435
+ return composeWithCompanions(ctx, compilationApiPlugin(ctx));
436
+ }
437
+ export { angularCompilationPlugin, compilationApiPlugin };
563
438
 
564
439
  //# sourceMappingURL=compilation-api-plugin.js.map