@analogjs/vite-plugin-angular 3.0.0-alpha.8 → 3.0.0-alpha.81

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 (194) hide show
  1. package/README.md +30 -0
  2. package/migrations/migrate-setup-vitest/migrate-setup-vitest.d.ts +2 -0
  3. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +49 -0
  4. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -0
  5. package/migrations/migration.json +7 -1
  6. package/migrations/migrations.json +9 -0
  7. package/migrations/update-3-0-0/migrate-setup-vitest.d.ts +2 -0
  8. package/migrations/update-3-0-0/migrate-setup-vitest.js +36 -0
  9. package/migrations/update-3-0-0/migrate-setup-vitest.js.map +1 -0
  10. package/package.json +51 -14
  11. package/src/index.d.ts +6 -2
  12. package/src/index.js +6 -2
  13. package/src/index.js.map +1 -1
  14. package/src/lib/analog-plugin-interop.d.ts +78 -0
  15. package/src/lib/analog-plugin-interop.js +97 -0
  16. package/src/lib/analog-plugin-interop.js.map +1 -0
  17. package/src/lib/angular-build-optimizer-plugin.d.ts +4 -4
  18. package/src/lib/angular-build-optimizer-plugin.js +57 -63
  19. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  20. package/src/lib/angular-jit-plugin.d.ts +3 -3
  21. package/src/lib/angular-jit-plugin.js +49 -37
  22. package/src/lib/angular-jit-plugin.js.map +1 -1
  23. package/src/lib/angular-pending-tasks.plugin.d.ts +7 -7
  24. package/src/lib/angular-pending-tasks.plugin.js +17 -18
  25. package/src/lib/angular-pending-tasks.plugin.js.map +1 -1
  26. package/src/lib/angular-vite-plugin.d.ts +82 -69
  27. package/src/lib/angular-vite-plugin.js +1201 -1085
  28. package/src/lib/angular-vite-plugin.js.map +1 -1
  29. package/src/lib/angular-vitest-plugin.d.ts +26 -21
  30. package/src/lib/angular-vitest-plugin.js +106 -135
  31. package/src/lib/angular-vitest-plugin.js.map +1 -1
  32. package/src/lib/compilation-api/compilation-api-plugin.d.ts +18 -0
  33. package/src/lib/compilation-api/compilation-api-plugin.js +488 -0
  34. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -0
  35. package/src/lib/compilation-api/index.d.ts +1 -0
  36. package/src/lib/compilation-api/index.js +1 -0
  37. package/src/lib/compiler/angular-version.d.ts +19 -0
  38. package/src/lib/compiler/angular-version.js +31 -0
  39. package/src/lib/compiler/angular-version.js.map +1 -0
  40. package/src/lib/compiler/class-field-lowering.d.ts +23 -0
  41. package/src/lib/compiler/class-field-lowering.js +131 -0
  42. package/src/lib/compiler/class-field-lowering.js.map +1 -0
  43. package/src/lib/compiler/compile.d.ts +50 -0
  44. package/src/lib/compiler/compile.js +814 -0
  45. package/src/lib/compiler/compile.js.map +1 -0
  46. package/src/lib/compiler/constants.d.ts +24 -0
  47. package/src/lib/compiler/constants.js +59 -0
  48. package/src/lib/compiler/constants.js.map +1 -0
  49. package/src/lib/compiler/debug.d.ts +22 -0
  50. package/src/lib/compiler/debug.js +20 -0
  51. package/src/lib/compiler/debug.js.map +1 -0
  52. package/src/lib/compiler/defer.d.ts +57 -0
  53. package/src/lib/compiler/defer.js +154 -0
  54. package/src/lib/compiler/defer.js.map +1 -0
  55. package/src/lib/compiler/dts-reader.d.ts +45 -0
  56. package/src/lib/compiler/dts-reader.js +395 -0
  57. package/src/lib/compiler/dts-reader.js.map +1 -0
  58. package/src/lib/compiler/hmr.d.ts +16 -0
  59. package/src/lib/compiler/hmr.js +69 -0
  60. package/src/lib/compiler/hmr.js.map +1 -0
  61. package/src/lib/compiler/index.d.ts +8 -0
  62. package/src/lib/compiler/index.js +8 -0
  63. package/src/lib/compiler/jit-metadata.d.ts +14 -0
  64. package/src/lib/compiler/jit-metadata.js +168 -0
  65. package/src/lib/compiler/jit-metadata.js.map +1 -0
  66. package/src/lib/compiler/jit-transform.d.ts +24 -0
  67. package/src/lib/compiler/jit-transform.js +204 -0
  68. package/src/lib/compiler/jit-transform.js.map +1 -0
  69. package/src/lib/compiler/js-emitter.d.ts +10 -0
  70. package/src/lib/compiler/js-emitter.js +446 -0
  71. package/src/lib/compiler/js-emitter.js.map +1 -0
  72. package/src/lib/compiler/metadata.d.ts +36 -0
  73. package/src/lib/compiler/metadata.js +710 -0
  74. package/src/lib/compiler/metadata.js.map +1 -0
  75. package/src/lib/compiler/registry.d.ts +56 -0
  76. package/src/lib/compiler/registry.js +176 -0
  77. package/src/lib/compiler/registry.js.map +1 -0
  78. package/src/lib/compiler/resource-inliner.d.ts +43 -0
  79. package/src/lib/compiler/resource-inliner.js +230 -0
  80. package/src/lib/compiler/resource-inliner.js.map +1 -0
  81. package/src/lib/compiler/style-ast.d.ts +9 -0
  82. package/src/lib/compiler/style-ast.js +54 -0
  83. package/src/lib/compiler/style-ast.js.map +1 -0
  84. package/src/lib/compiler/styles.d.ts +13 -0
  85. package/src/lib/compiler/test-helpers.d.ts +7 -0
  86. package/src/lib/compiler/type-elision.d.ts +28 -0
  87. package/src/lib/compiler/type-elision.js +211 -0
  88. package/src/lib/compiler/type-elision.js.map +1 -0
  89. package/src/lib/compiler/utils.d.ts +40 -0
  90. package/src/lib/compiler/utils.js +76 -0
  91. package/src/lib/compiler/utils.js.map +1 -0
  92. package/src/lib/compiler-plugin.d.ts +13 -12
  93. package/src/lib/compiler-plugin.js +40 -44
  94. package/src/lib/compiler-plugin.js.map +1 -1
  95. package/src/lib/component-resolvers.d.ts +20 -4
  96. package/src/lib/component-resolvers.js +101 -120
  97. package/src/lib/component-resolvers.js.map +1 -1
  98. package/src/lib/encapsulation-plugin.d.ts +18 -0
  99. package/src/lib/encapsulation-plugin.js +53 -0
  100. package/src/lib/encapsulation-plugin.js.map +1 -0
  101. package/src/lib/fast-compile-plugin.d.ts +13 -0
  102. package/src/lib/fast-compile-plugin.js +419 -0
  103. package/src/lib/fast-compile-plugin.js.map +1 -0
  104. package/src/lib/host.d.ts +10 -8
  105. package/src/lib/host.js +111 -101
  106. package/src/lib/host.js.map +1 -1
  107. package/src/lib/live-reload-plugin.d.ts +5 -5
  108. package/src/lib/live-reload-plugin.js +61 -63
  109. package/src/lib/live-reload-plugin.js.map +1 -1
  110. package/src/lib/models.d.ts +9 -9
  111. package/src/lib/nx-folder-plugin.d.ts +5 -5
  112. package/src/lib/nx-folder-plugin.js +18 -16
  113. package/src/lib/nx-folder-plugin.js.map +1 -1
  114. package/src/lib/plugins/file-replacements.plugin.d.ts +4 -4
  115. package/src/lib/plugins/file-replacements.plugin.js +40 -62
  116. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  117. package/src/lib/router-plugin.d.ts +1 -1
  118. package/src/lib/router-plugin.js +35 -23
  119. package/src/lib/router-plugin.js.map +1 -1
  120. package/src/lib/style-preprocessor.d.ts +35 -0
  121. package/src/lib/style-preprocessor.js +35 -0
  122. package/src/lib/style-preprocessor.js.map +1 -0
  123. package/src/lib/stylesheet-registry.d.ts +74 -0
  124. package/src/lib/stylesheet-registry.js +174 -0
  125. package/src/lib/stylesheet-registry.js.map +1 -0
  126. package/src/lib/tools/package.json +2 -7
  127. package/src/lib/tools/src/builders/vite/vite-build.impl.js +33 -38
  128. package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
  129. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js +51 -62
  130. package/src/lib/tools/src/builders/vite-dev-server/dev-server.impl.js.map +1 -1
  131. package/src/lib/tools/src/index.js +0 -2
  132. package/src/lib/utils/compilation-shared.d.ts +62 -0
  133. package/src/lib/utils/compilation-shared.js +138 -0
  134. package/src/lib/utils/compilation-shared.js.map +1 -0
  135. package/src/lib/utils/compiler-plugin-options.d.ts +11 -11
  136. package/src/lib/utils/css-extension-resolver.d.ts +32 -0
  137. package/src/lib/utils/css-extension-resolver.js +73 -0
  138. package/src/lib/utils/css-extension-resolver.js.map +1 -0
  139. package/src/lib/utils/debug-harness.d.ts +23 -0
  140. package/src/lib/utils/debug-harness.js +88 -0
  141. package/src/lib/utils/debug-harness.js.map +1 -0
  142. package/src/lib/utils/debug-log-file.d.ts +5 -0
  143. package/src/lib/utils/debug-log-file.js +56 -0
  144. package/src/lib/utils/debug-log-file.js.map +1 -0
  145. package/src/lib/utils/debug.d.ts +26 -0
  146. package/src/lib/utils/debug.js +35 -0
  147. package/src/lib/utils/debug.js.map +1 -0
  148. package/src/lib/utils/devkit.d.ts +6 -6
  149. package/src/lib/utils/devkit.js +34 -38
  150. package/src/lib/utils/devkit.js.map +1 -1
  151. package/src/lib/utils/hmr-candidates.d.ts +28 -28
  152. package/src/lib/utils/jit-inline-styles.d.ts +3 -0
  153. package/src/lib/utils/jit-inline-styles.js +16 -0
  154. package/src/lib/utils/jit-inline-styles.js.map +1 -0
  155. package/src/lib/utils/plugin-config.d.ts +41 -0
  156. package/src/lib/utils/plugin-config.js +85 -0
  157. package/src/lib/utils/plugin-config.js.map +1 -0
  158. package/src/lib/utils/rolldown.d.ts +1 -1
  159. package/src/lib/utils/rolldown.js +9 -5
  160. package/src/lib/utils/rolldown.js.map +1 -1
  161. package/src/lib/utils/safe-module-paths.d.ts +16 -0
  162. package/src/lib/utils/safe-module-paths.js +29 -0
  163. package/src/lib/utils/safe-module-paths.js.map +1 -0
  164. package/src/lib/utils/source-file-cache.d.ts +8 -15
  165. package/src/lib/utils/source-file-cache.js +35 -37
  166. package/src/lib/utils/source-file-cache.js.map +1 -1
  167. package/src/lib/utils/transform-cache.d.ts +43 -0
  168. package/src/lib/utils/transform-cache.js +97 -0
  169. package/src/lib/utils/transform-cache.js.map +1 -0
  170. package/src/lib/utils/tsconfig-resolver.d.ts +34 -0
  171. package/src/lib/utils/tsconfig-resolver.js +203 -0
  172. package/src/lib/utils/tsconfig-resolver.js.map +1 -0
  173. package/src/lib/utils/virtual-ids.d.ts +4 -0
  174. package/src/lib/utils/virtual-ids.js +23 -0
  175. package/src/lib/utils/virtual-ids.js.map +1 -0
  176. package/src/lib/utils/virtual-resources.d.ts +19 -0
  177. package/src/lib/utils/virtual-resources.js +38 -0
  178. package/src/lib/utils/virtual-resources.js.map +1 -0
  179. package/src/lib/virtual-modules-plugin.d.ts +5 -0
  180. package/src/lib/virtual-modules-plugin.js +23 -0
  181. package/src/lib/virtual-modules-plugin.js.map +1 -0
  182. package/src/test-setup.d.ts +2 -0
  183. package/setup-vitest.d.ts +0 -4
  184. package/setup-vitest.js +0 -215
  185. package/setup-vitest.js.map +0 -1
  186. package/src/lib/models.js +0 -1
  187. package/src/lib/models.js.map +0 -1
  188. package/src/lib/tools/README.md +0 -3
  189. package/src/lib/tools/src/index.d.ts +0 -0
  190. package/src/lib/tools/src/index.js.map +0 -1
  191. package/src/lib/utils/compiler-plugin-options.js +0 -1
  192. package/src/lib/utils/compiler-plugin-options.js.map +0 -1
  193. package/src/lib/utils/hmr-candidates.js +0 -272
  194. package/src/lib/utils/hmr-candidates.js.map +0 -1
@@ -1,1101 +1,1217 @@
1
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { basename, dirname, isAbsolute, join, relative, resolve, } from 'node:path';
3
- import * as compilerCli from '@angular/compiler-cli';
4
- import { createRequire } from 'node:module';
5
- import * as ngCompiler from '@angular/compiler';
6
- import { globSync } from 'tinyglobby';
7
- import { defaultClientConditions, normalizePath, preprocessCSS, } from 'vite';
8
- import { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';
9
- import { jitPlugin } from './angular-jit-plugin.js';
10
- import { createCompilerPlugin, createRolldownCompilerPlugin, } from './compiler-plugin.js';
11
- import { StyleUrlsResolver, TemplateUrlsResolver, } from './component-resolvers.js';
12
- import { augmentHostWithCaching, augmentHostWithResources, augmentProgramWithVersioning, mergeTransformers, } from './host.js';
13
- import { angularVitestPlugins } from './angular-vitest-plugin.js';
14
- import { createAngularCompilation, createJitResourceTransformer, SourceFileCache, angularFullVersion, } from './utils/devkit.js';
15
- import { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';
16
- const require = createRequire(import.meta.url);
17
- import { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';
18
- import { liveReloadPlugin } from './live-reload-plugin.js';
19
- import { nxFolderPlugin } from './nx-folder-plugin.js';
20
- import { replaceFiles, } from './plugins/file-replacements.plugin.js';
21
- import { routerPlugin } from './router-plugin.js';
22
- import { createHash } from 'node:crypto';
23
- export var DiagnosticModes;
24
- (function (DiagnosticModes) {
25
- DiagnosticModes[DiagnosticModes["None"] = 0] = "None";
26
- DiagnosticModes[DiagnosticModes["Option"] = 1] = "Option";
27
- DiagnosticModes[DiagnosticModes["Syntactic"] = 2] = "Syntactic";
28
- DiagnosticModes[DiagnosticModes["Semantic"] = 4] = "Semantic";
29
- DiagnosticModes[DiagnosticModes["All"] = 7] = "All";
30
- })(DiagnosticModes || (DiagnosticModes = {}));
31
- /**
32
- * TypeScript file extension regex
33
- * Match .(c or m)ts, .ts extensions with an optional ? for query params
34
- * Ignore .tsx extensions
35
- */
36
- const TS_EXT_REGEX = /\.[cm]?(ts)[^x]?\??/;
37
- const classNames = new Map();
38
- export function angular(options) {
39
- /**
40
- * Normalize plugin options so defaults
41
- * are used for values not provided.
42
- */
43
- const pluginOptions = {
44
- tsconfigGetter: createTsConfigGetter(options?.tsconfig),
45
- workspaceRoot: options?.workspaceRoot ?? process.cwd(),
46
- inlineStylesExtension: options?.inlineStylesExtension ?? 'css',
47
- advanced: {
48
- tsTransformers: {
49
- before: options?.advanced?.tsTransformers?.before ?? [],
50
- after: options?.advanced?.tsTransformers?.after ?? [],
51
- afterDeclarations: options?.advanced?.tsTransformers?.afterDeclarations ?? [],
52
- },
53
- },
54
- supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],
55
- jit: options?.jit,
56
- include: options?.include ?? [],
57
- additionalContentDirs: options?.additionalContentDirs ?? [],
58
- liveReload: options?.liveReload ?? false,
59
- disableTypeChecking: options?.disableTypeChecking ?? true,
60
- fileReplacements: options?.fileReplacements ?? [],
61
- useAngularCompilationAPI: options?.experimental?.useAngularCompilationAPI ?? false,
62
- };
63
- let resolvedConfig;
64
- // Store config context needed for getTsConfigPath resolution
65
- let tsConfigResolutionContext = null;
66
- const ts = require('typescript');
67
- let builder;
68
- let nextProgram;
69
- // Caches (always rebuild Angular program per user request)
70
- const tsconfigOptionsCache = new Map();
71
- let cachedHost;
72
- let cachedHostKey;
73
- let includeCache = [];
74
- function invalidateFsCaches() {
75
- includeCache = [];
76
- }
77
- function invalidateTsconfigCaches() {
78
- // `readConfiguration` caches the root file list, so hot-added pages can be
79
- // missing from Angular's compilation program until we clear this state.
80
- tsconfigOptionsCache.clear();
81
- cachedHost = undefined;
82
- cachedHostKey = undefined;
83
- }
84
- let watchMode = false;
85
- let testWatchMode = isTestWatchMode();
86
- let inlineComponentStyles;
87
- let externalComponentStyles;
88
- const sourceFileCache = new SourceFileCache();
89
- const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
90
- const isVitestVscode = !!process.env['VITEST_VSCODE'];
91
- const isStackBlitz = !!process.versions['webcontainer'];
92
- const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';
93
- const jit = typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;
94
- let viteServer;
95
- const styleUrlsResolver = new StyleUrlsResolver();
96
- const templateUrlsResolver = new TemplateUrlsResolver();
97
- let outputFile;
98
- const outputFiles = new Map();
99
- const fileEmitter = (file) => {
100
- outputFile?.(file);
101
- return outputFiles.get(normalizePath(file));
102
- };
103
- let initialCompilation = false;
104
- const declarationFiles = [];
105
- const fileTransformMap = new Map();
106
- let styleTransform;
107
- let pendingCompilation;
108
- let compilationLock = Promise.resolve();
109
- // Persistent Angular Compilation API instance. Kept alive across rebuilds so
110
- // Angular can diff previous state and emit `templateUpdates` for HMR.
111
- // Previously the compilation was recreated on every pass, which meant Angular
112
- // never had prior state and could never produce HMR payloads.
113
- let angularCompilation;
114
- function angularPlugin() {
115
- let isProd = false;
116
- if (angularFullVersion < 190000 || isTest) {
117
- pluginOptions.liveReload = false;
118
- }
119
- // liveReload and fileReplacements guards were previously here and forced
120
- // both options off when useAngularCompilationAPI was enabled. Those guards
121
- // have been removed because:
122
- // - liveReload: the persistent compilation instance (above) now gives
123
- // Angular the prior state it needs to emit `templateUpdates` for HMR
124
- // - fileReplacements: Angular's AngularHostOptions already accepts a
125
- // `fileReplacements` record — we now convert and pass it through in
126
- // `performAngularCompilation` via `toAngularCompilationFileReplacements`
127
- if (pluginOptions.useAngularCompilationAPI) {
128
- if (angularFullVersion < 200100) {
129
- pluginOptions.useAngularCompilationAPI = false;
130
- console.warn('[@analogjs/vite-plugin-angular]: The Angular Compilation API is only available with Angular v20.1 and later');
131
- }
132
- }
133
- return {
134
- name: '@analogjs/vite-plugin-angular',
135
- async config(config, { command }) {
136
- watchMode = command === 'serve';
137
- isProd =
138
- config.mode === 'production' ||
139
- process.env['NODE_ENV'] === 'production';
140
- // Store the config context for later resolution in configResolved
141
- tsConfigResolutionContext = {
142
- root: config.root || '.',
143
- isProd,
144
- isLib: !!config?.build?.lib,
145
- };
146
- // Do a preliminary resolution for esbuild plugin (before configResolved)
147
- const preliminaryTsConfigPath = resolveTsConfigPath();
148
- const esbuild = pluginOptions.useAngularCompilationAPI
149
- ? undefined
150
- : (config.esbuild ?? false);
151
- const oxc = pluginOptions.useAngularCompilationAPI
152
- ? undefined
153
- : (config.oxc ?? false);
154
- const defineOptions = {
155
- ngJitMode: 'false',
156
- ngI18nClosureMode: 'false',
157
- ...(watchMode ? {} : { ngDevMode: 'false' }),
158
- };
159
- const useRolldown = isRolldown();
160
- const jsTransformConfigKey = getJsTransformConfigKey();
161
- const jsTransformConfigValue = jsTransformConfigKey === 'oxc' ? oxc : esbuild;
162
- const rolldownOptions = {
163
- plugins: [
164
- createRolldownCompilerPlugin({
165
- tsconfig: preliminaryTsConfigPath,
166
- sourcemap: !isProd,
167
- advancedOptimizations: isProd,
168
- jit,
169
- incremental: watchMode,
170
- }),
171
- ],
172
- };
173
- const esbuildOptions = {
174
- plugins: [
175
- createCompilerPlugin({
176
- tsconfig: preliminaryTsConfigPath,
177
- sourcemap: !isProd,
178
- advancedOptimizations: isProd,
179
- jit,
180
- incremental: watchMode,
181
- }, isTest, !isAstroIntegration),
182
- ],
183
- define: defineOptions,
184
- };
185
- return {
186
- [jsTransformConfigKey]: jsTransformConfigValue,
187
- optimizeDeps: {
188
- include: ['rxjs/operators', 'rxjs'],
189
- exclude: ['@angular/platform-server'],
190
- ...(useRolldown ? { rolldownOptions } : { esbuildOptions }),
191
- },
192
- resolve: {
193
- conditions: [
194
- 'style',
195
- ...(config.resolve?.conditions || defaultClientConditions),
196
- ],
197
- },
198
- };
199
- },
200
- configResolved(config) {
201
- resolvedConfig = config;
202
- if (pluginOptions.useAngularCompilationAPI) {
203
- externalComponentStyles = new Map();
204
- inlineComponentStyles = new Map();
205
- }
206
- if (!jit) {
207
- styleTransform = (code, filename) => preprocessCSS(code, filename, config);
208
- }
209
- if (isTest) {
210
- // set test watch mode
211
- // - vite override from vitest-angular
212
- // - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)
213
- // - vite config for test.watch variable
214
- // - vitest watch mode detected from the command line
215
- testWatchMode =
216
- !(config.server.watch === null) ||
217
- config.test?.watch === true ||
218
- testWatchMode;
219
- }
220
- },
221
- configureServer(server) {
222
- viteServer = server;
223
- // Add/unlink changes the TypeScript program shape, not just file
224
- // contents, so we need to invalidate both include discovery and the
225
- // cached tsconfig root names before recompiling.
226
- const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, () => performCompilation(resolvedConfig));
227
- server.watcher.on('add', invalidateCompilationOnFsChange);
228
- server.watcher.on('unlink', invalidateCompilationOnFsChange);
229
- server.watcher.on('change', (file) => {
230
- if (file.includes('tsconfig')) {
231
- invalidateTsconfigCaches();
232
- }
233
- });
234
- },
235
- async buildStart() {
236
- // Defer the first compilation in test mode
237
- if (!isVitestVscode) {
238
- await performCompilation(resolvedConfig);
239
- pendingCompilation = null;
240
- initialCompilation = true;
241
- }
242
- },
243
- async handleHotUpdate(ctx) {
244
- if (TS_EXT_REGEX.test(ctx.file)) {
245
- const [fileId] = ctx.file.split('?');
246
- pendingCompilation = performCompilation(resolvedConfig, [fileId]);
247
- let result;
248
- if (pluginOptions.liveReload) {
249
- await pendingCompilation;
250
- pendingCompilation = null;
251
- result = fileEmitter(fileId);
252
- }
253
- if (pluginOptions.liveReload &&
254
- result?.hmrEligible &&
255
- classNames.get(fileId)) {
256
- const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
257
- sendHMRComponentUpdate(ctx.server, relativeFileId);
258
- return ctx.modules.map((mod) => {
259
- if (mod.id === ctx.file) {
260
- return markModuleSelfAccepting(mod);
261
- }
262
- return mod;
263
- });
264
- }
265
- }
266
- if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
267
- fileTransformMap.delete(ctx.file.split('?')[0]);
268
- /**
269
- * Check to see if this was a direct request
270
- * for an external resource (styles, html).
271
- */
272
- const isDirect = ctx.modules.find((mod) => ctx.file === mod.file && mod.id?.includes('?direct'));
273
- const isInline = ctx.modules.find((mod) => ctx.file === mod.file && mod.id?.includes('?inline'));
274
- if (isDirect || isInline) {
275
- if (pluginOptions.liveReload && isDirect?.id && isDirect.file) {
276
- const isComponentStyle = isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);
277
- if (isComponentStyle) {
278
- const { encapsulation } = getComponentStyleSheetMeta(isDirect.id);
279
- // Track if the component uses ShadowDOM encapsulation
280
- // Shadow DOM components currently require a full reload.
281
- // Vite's CSS hot replacement does not support shadow root searching.
282
- if (encapsulation !== 'shadow') {
283
- ctx.server.ws.send({
284
- type: 'update',
285
- updates: [
286
- {
287
- type: 'css-update',
288
- timestamp: Date.now(),
289
- path: isDirect.url,
290
- acceptedPath: isDirect.file,
291
- },
292
- ],
293
- });
294
- return ctx.modules
295
- .filter((mod) => {
296
- // Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)
297
- // We remove the module with the query params to prevent vite double logging the stylesheet name "hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x"
298
- return mod.file !== ctx.file || mod.id !== isDirect.id;
299
- })
300
- .map((mod) => {
301
- if (mod.file === ctx.file) {
302
- return markModuleSelfAccepting(mod);
303
- }
304
- return mod;
305
- });
306
- }
307
- }
308
- }
309
- return ctx.modules;
310
- }
311
- const mods = [];
312
- const updates = [];
313
- ctx.modules.forEach((mod) => {
314
- mod.importers.forEach((imp) => {
315
- ctx.server.moduleGraph.invalidateModule(imp);
316
- if (pluginOptions.liveReload && classNames.get(imp.id)) {
317
- updates.push(imp.id);
318
- }
319
- else {
320
- mods.push(imp);
321
- }
322
- });
323
- });
324
- pendingCompilation = performCompilation(resolvedConfig, [
325
- ...mods.map((mod) => mod.id),
326
- ...updates,
327
- ]);
328
- if (updates.length > 0) {
329
- await pendingCompilation;
330
- pendingCompilation = null;
331
- updates.forEach((updateId) => {
332
- const impRelativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
333
- sendHMRComponentUpdate(ctx.server, impRelativeFileId);
334
- });
335
- return ctx.modules.map((mod) => {
336
- if (mod.id === ctx.file) {
337
- return markModuleSelfAccepting(mod);
338
- }
339
- return mod;
340
- });
341
- }
342
- return mods;
343
- }
344
- // clear HMR updates with a full reload
345
- classNames.clear();
346
- return ctx.modules;
347
- },
348
- resolveId(id, importer) {
349
- if (jit && id.startsWith('angular:jit:')) {
350
- const path = id.split(';')[1];
351
- return `${normalizePath(resolve(dirname(importer), path))}?${id.includes(':style') ? 'inline' : 'raw'}`;
352
- }
353
- // Map angular external styleUrls to the source file
354
- if (isComponentStyleSheet(id)) {
355
- const componentStyles = externalComponentStyles?.get(getFilenameFromPath(id));
356
- if (componentStyles) {
357
- return componentStyles + new URL(id, 'http://localhost').search;
358
- }
359
- }
360
- return undefined;
361
- },
362
- async load(id) {
363
- // Map angular inline styles to the source text
364
- if (isComponentStyleSheet(id)) {
365
- const componentStyles = inlineComponentStyles?.get(getFilenameFromPath(id));
366
- if (componentStyles) {
367
- return componentStyles;
368
- }
369
- }
370
- return;
371
- },
372
- transform: {
373
- filter: {
374
- id: {
375
- include: [TS_EXT_REGEX],
376
- exclude: [/node_modules/, 'type=script', '@ng/component'],
377
- },
378
- },
379
- async handler(code, id) {
380
- /**
381
- * Check for options.transformFilter
382
- */
383
- if (options?.transformFilter &&
384
- !(options?.transformFilter(code, id) ?? true)) {
385
- return;
386
- }
387
- if (pluginOptions.useAngularCompilationAPI) {
388
- const isAngular = /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
389
- if (!isAngular) {
390
- return;
391
- }
392
- }
393
- /**
394
- * Skip transforming content files
395
- */
396
- if (id.includes('?') && id.includes('analog-content-')) {
397
- return;
398
- }
399
- /**
400
- * Encapsulate component stylesheets that use emulated encapsulation
401
- */
402
- if (pluginOptions.liveReload && isComponentStyleSheet(id)) {
403
- const { encapsulation, componentId } = getComponentStyleSheetMeta(id);
404
- if (encapsulation === 'emulated' && componentId) {
405
- const encapsulated = ngCompiler.encapsulateStyle(code, componentId);
406
- return {
407
- code: encapsulated,
408
- map: null,
409
- };
410
- }
411
- }
412
- if (id.includes('.ts?')) {
413
- // Strip the query string off the ID
414
- // in case of a dynamically loaded file
415
- id = id.replace(/\?(.*)/, '');
416
- }
417
- fileTransformMap.set(id, code);
418
- /**
419
- * Re-analyze on each transform
420
- * for test(Vitest)
421
- */
422
- if (isTest) {
423
- if (isVitestVscode && !initialCompilation) {
424
- // Do full initial compilation
425
- pendingCompilation = performCompilation(resolvedConfig);
426
- initialCompilation = true;
427
- }
428
- const tsMod = viteServer?.moduleGraph.getModuleById(id);
429
- if (tsMod) {
430
- const invalidated = tsMod.lastInvalidationTimestamp;
431
- if (testWatchMode && invalidated) {
432
- pendingCompilation = performCompilation(resolvedConfig, [id]);
433
- }
434
- }
435
- }
436
- const hasComponent = code.includes('@Component');
437
- const templateUrls = hasComponent
438
- ? templateUrlsResolver.resolve(code, id)
439
- : [];
440
- const styleUrls = hasComponent
441
- ? styleUrlsResolver.resolve(code, id)
442
- : [];
443
- if (hasComponent && watchMode) {
444
- for (const urlSet of [...templateUrls, ...styleUrls]) {
445
- // `urlSet` is a string where a relative path is joined with an
446
- // absolute path using the `|` symbol.
447
- // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.
448
- const [, absoluteFileUrl] = urlSet.split('|');
449
- this.addWatchFile(absoluteFileUrl);
450
- }
451
- }
452
- if (pendingCompilation) {
453
- await pendingCompilation;
454
- pendingCompilation = null;
455
- }
456
- const typescriptResult = fileEmitter(id);
457
- if (typescriptResult?.warnings &&
458
- typescriptResult?.warnings.length > 0) {
459
- this.warn(`${typescriptResult.warnings.join('\n')}`);
460
- }
461
- if (typescriptResult?.errors && typescriptResult?.errors.length > 0) {
462
- this.error(`${typescriptResult.errors.join('\n')}`);
463
- }
464
- // return fileEmitter
465
- let data = typescriptResult?.content ?? '';
466
- if (jit && data.includes('angular:jit:')) {
467
- data = data.replace(/angular:jit:style:inline;/g, 'virtual:angular:jit:style:inline;');
468
- templateUrls.forEach((templateUrlSet) => {
469
- const [templateFile, resolvedTemplateUrl] = templateUrlSet.split('|');
470
- data = data.replace(`angular:jit:template:file;${templateFile}`, `${resolvedTemplateUrl}?raw`);
471
- });
472
- styleUrls.forEach((styleUrlSet) => {
473
- const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');
474
- data = data.replace(`angular:jit:style:file;${styleFile}`, `${resolvedStyleUrl}?inline`);
475
- });
476
- }
477
- return {
478
- code: data,
479
- map: null,
480
- };
481
- },
482
- },
483
- closeBundle() {
484
- declarationFiles.forEach(({ declarationFileDir, declarationPath, data }) => {
485
- mkdirSync(declarationFileDir, { recursive: true });
486
- writeFileSync(declarationPath, data, 'utf-8');
487
- });
488
- // Tear down the persistent compilation instance at end of build so it
489
- // does not leak memory across unrelated Vite invocations.
490
- angularCompilation?.close?.();
491
- angularCompilation = undefined;
492
- },
493
- };
494
- }
495
- return [
496
- replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
497
- angularPlugin(),
498
- pluginOptions.liveReload && liveReloadPlugin({ classNames, fileEmitter }),
499
- ...(isTest && !isStackBlitz ? angularVitestPlugins() : []),
500
- (jit &&
501
- jitPlugin({
502
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
503
- })),
504
- buildOptimizerPlugin({
505
- supportedBrowsers: pluginOptions.supportedBrowsers,
506
- jit,
507
- }),
508
- routerPlugin(),
509
- angularFullVersion < 190004 && pendingTasksPlugin(),
510
- nxFolderPlugin(),
511
- ].filter(Boolean);
512
- function findIncludes() {
513
- const workspaceRoot = normalizePath(resolve(pluginOptions.workspaceRoot));
514
- // Map include patterns to absolute workspace paths
515
- const globs = [
516
- ...pluginOptions.include.map((glob) => `${workspaceRoot}${glob}`),
517
- ];
518
- // Discover TypeScript files using tinyglobby
519
- return globSync(globs, {
520
- dot: true,
521
- absolute: true,
522
- });
523
- }
524
- function createTsConfigGetter(tsconfigOrGetter) {
525
- if (typeof tsconfigOrGetter === 'function') {
526
- return tsconfigOrGetter;
527
- }
528
- return () => tsconfigOrGetter || '';
529
- }
530
- function getTsConfigPath(root, tsconfig, isProd, isTest, isLib) {
531
- if (tsconfig && isAbsolute(tsconfig)) {
532
- if (!existsSync(tsconfig)) {
533
- console.error(`[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${tsconfig}. This causes compilation issues. Check the path or set the "tsconfig" property with an absolute path.`);
534
- }
535
- return tsconfig;
536
- }
537
- let tsconfigFilePath = './tsconfig.app.json';
538
- if (isLib) {
539
- tsconfigFilePath = isProd
540
- ? './tsconfig.lib.prod.json'
541
- : './tsconfig.lib.json';
542
- }
543
- if (isTest) {
544
- tsconfigFilePath = './tsconfig.spec.json';
545
- }
546
- if (tsconfig) {
547
- tsconfigFilePath = tsconfig;
548
- }
549
- const resolvedPath = resolve(root, tsconfigFilePath);
550
- if (!existsSync(resolvedPath)) {
551
- console.error(`[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${resolvedPath}. This causes compilation issues. Check the path or set the "tsconfig" property with an absolute path.`);
552
- }
553
- return resolvedPath;
554
- }
555
- function resolveTsConfigPath() {
556
- const tsconfigValue = pluginOptions.tsconfigGetter();
557
- return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib);
558
- }
559
- /**
560
- * Perform compilation using Angular's private Compilation API.
561
- *
562
- * Key differences from the standard `performCompilation` path:
563
- * 1. The compilation instance is reused across rebuilds (nullish-coalescing
564
- * assignment below) so Angular retains prior state and can diff it to
565
- * produce `templateUpdates` for HMR.
566
- * 2. `ids` (modified files) are forwarded to both the source-file cache and
567
- * `angularCompilation.update()` so that incremental re-analysis is
568
- * scoped to what actually changed.
569
- * 3. `fileReplacements` are converted and passed into Angular's host via
570
- * `toAngularCompilationFileReplacements`.
571
- * 4. `templateUpdates` from the compilation result are mapped back to
572
- * file-level HMR metadata (`hmrUpdateCode`, `hmrEligible`, `classNames`).
573
- */
574
- async function performAngularCompilation(config, ids) {
575
- // Reuse the existing instance so Angular can diff against prior state.
576
- angularCompilation ??= await createAngularCompilation(!!pluginOptions.jit, false);
577
- const modifiedFiles = ids?.length
578
- ? new Set(ids.map((file) => normalizePath(file)))
579
- : undefined;
580
- if (modifiedFiles?.size) {
581
- sourceFileCache.invalidate(modifiedFiles);
582
- }
583
- // Notify Angular of modified files before re-initialization so it can
584
- // scope its incremental analysis.
585
- if (modifiedFiles?.size && angularCompilation.update) {
586
- await angularCompilation.update(modifiedFiles);
587
- }
588
- const resolvedTsConfigPath = resolveTsConfigPath();
589
- const compilationResult = await angularCompilation.initialize(resolvedTsConfigPath, {
590
- // Convert Analog's browser-style `{ replace, with }` entries into the
591
- // `Record<string, string>` shape that Angular's AngularHostOptions
592
- // expects. SSR-only replacements (`{ replace, ssr }`) are intentionally
593
- // excluded — they stay on the Vite runtime side.
594
- fileReplacements: toAngularCompilationFileReplacements(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
595
- modifiedFiles,
596
- async transformStylesheet(data, containingFile, resourceFile, order, className) {
597
- if (pluginOptions.liveReload) {
598
- const id = createHash('sha256')
599
- .update(containingFile)
600
- .update(className)
601
- .update(String(order))
602
- .update(data)
603
- .digest('hex');
604
- const filename = id + '.' + pluginOptions.inlineStylesExtension;
605
- inlineComponentStyles.set(filename, data);
606
- return filename;
607
- }
608
- const filename = resourceFile ??
609
- containingFile.replace('.ts', `.${options?.inlineStylesExtension}`);
610
- let stylesheetResult;
611
- try {
612
- stylesheetResult = await preprocessCSS(data, `${filename}?direct`, resolvedConfig);
613
- }
614
- catch (e) {
615
- console.error(`${e}`);
616
- }
617
- return stylesheetResult?.code || '';
618
- },
619
- processWebWorker(workerFile, containingFile) {
620
- return '';
621
- },
622
- }, (tsCompilerOptions) => {
623
- if (pluginOptions.liveReload && watchMode) {
624
- tsCompilerOptions['_enableHmr'] = true;
625
- tsCompilerOptions['externalRuntimeStyles'] = true;
626
- // Workaround for https://github.com/angular/angular/issues/59310
627
- // Force extra instructions to be generated for HMR w/defer
628
- tsCompilerOptions['supportTestBed'] = true;
629
- }
630
- if (tsCompilerOptions.compilationMode === 'partial') {
631
- // These options can't be false in partial mode
632
- tsCompilerOptions['supportTestBed'] = true;
633
- tsCompilerOptions['supportJitMode'] = true;
634
- }
635
- if (!isTest && config.build?.lib) {
636
- tsCompilerOptions['declaration'] = true;
637
- tsCompilerOptions['declarationMap'] = watchMode;
638
- tsCompilerOptions['inlineSources'] = true;
639
- }
640
- if (isTest) {
641
- // Allow `TestBed.overrideXXX()` APIs.
642
- tsCompilerOptions['supportTestBed'] = true;
643
- }
644
- return tsCompilerOptions;
645
- });
646
- compilationResult.externalStylesheets?.forEach((value, key) => {
647
- externalComponentStyles?.set(`${value}.css`, key);
648
- });
649
- const diagnostics = await angularCompilation.diagnoseFiles(pluginOptions.disableTypeChecking
650
- ? DiagnosticModes.All & ~DiagnosticModes.Semantic
651
- : DiagnosticModes.All);
652
- const errors = diagnostics.errors?.length ? diagnostics.errors : [];
653
- const warnings = diagnostics.warnings?.length ? diagnostics.warnings : [];
654
- // Angular encodes template updates as `encodedFilePath@ClassName` keys.
655
- // `mapTemplateUpdatesToFiles` decodes them back to absolute file paths so
656
- // we can attach HMR metadata to the correct `EmitFileResult` below.
657
- const templateUpdates = mapTemplateUpdatesToFiles(compilationResult.templateUpdates);
658
- for (const file of await angularCompilation.emitAffectedFiles()) {
659
- const normalizedFilename = normalizePath(file.filename);
660
- const templateUpdate = templateUpdates.get(normalizedFilename);
661
- if (templateUpdate) {
662
- classNames.set(normalizedFilename, templateUpdate.className);
663
- }
664
- // Surface Angular's HMR payloads into Analog's existing live-reload
665
- // flow via the `hmrUpdateCode` / `hmrEligible` fields.
666
- outputFiles.set(normalizedFilename, {
667
- content: file.contents,
668
- dependencies: [],
669
- errors: errors.map((error) => error.text || ''),
670
- warnings: warnings.map((warning) => warning.text || ''),
671
- hmrUpdateCode: templateUpdate?.code,
672
- hmrEligible: !!templateUpdate?.code,
673
- });
674
- }
675
- }
676
- async function performCompilation(config, ids) {
677
- let resolve;
678
- const previousLock = compilationLock;
679
- compilationLock = new Promise((r) => {
680
- resolve = r;
681
- });
682
- try {
683
- await previousLock;
684
- await _doPerformCompilation(config, ids);
685
- }
686
- finally {
687
- resolve();
688
- }
689
- }
690
- /**
691
- * This method share mutable state and performs the actual compilation work.
692
- * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.
693
- */
694
- async function _doPerformCompilation(config, ids) {
695
- // Forward `ids` (modified files) so the Compilation API path can do
696
- // incremental re-analysis instead of a full recompile on every change.
697
- if (pluginOptions.useAngularCompilationAPI) {
698
- await performAngularCompilation(config, ids);
699
- return;
700
- }
701
- const isProd = config.mode === 'production';
702
- const modifiedFiles = new Set(ids ?? []);
703
- sourceFileCache.invalidate(modifiedFiles);
704
- if (ids?.length) {
705
- for (const id of ids || []) {
706
- fileTransformMap.delete(id);
707
- }
708
- }
709
- // Cached include discovery (invalidated only on FS events)
710
- if (pluginOptions.include.length > 0 && includeCache.length === 0) {
711
- includeCache = findIncludes();
712
- }
713
- const resolvedTsConfigPath = resolveTsConfigPath();
714
- const tsconfigKey = [
715
- resolvedTsConfigPath,
716
- isProd ? 'prod' : 'dev',
717
- isTest ? 'test' : 'app',
718
- config.build?.lib ? 'lib' : 'nolib',
719
- ].join('|');
720
- let cached = tsconfigOptionsCache.get(tsconfigKey);
721
- if (!cached) {
722
- const read = compilerCli.readConfiguration(resolvedTsConfigPath, {
723
- suppressOutputPathCheck: true,
724
- outDir: undefined,
725
- sourceMap: false,
726
- inlineSourceMap: !isProd,
727
- inlineSources: !isProd,
728
- declaration: false,
729
- declarationMap: false,
730
- allowEmptyCodegenFiles: false,
731
- annotationsAs: 'decorators',
732
- enableResourceInlining: false,
733
- noEmitOnError: false,
734
- mapRoot: undefined,
735
- sourceRoot: undefined,
736
- supportTestBed: false,
737
- supportJitMode: false,
738
- });
739
- cached = { options: read.options, rootNames: read.rootNames };
740
- tsconfigOptionsCache.set(tsconfigKey, cached);
741
- }
742
- // Clone options before mutation (preserve cache purity)
743
- const tsCompilerOptions = { ...cached.options };
744
- let rootNames = [...cached.rootNames];
745
- if (pluginOptions.liveReload && watchMode) {
746
- tsCompilerOptions['_enableHmr'] = true;
747
- tsCompilerOptions['externalRuntimeStyles'] = true;
748
- // Workaround for https://github.com/angular/angular/issues/59310
749
- // Force extra instructions to be generated for HMR w/defer
750
- tsCompilerOptions['supportTestBed'] = true;
751
- }
752
- if (tsCompilerOptions['compilationMode'] === 'partial') {
753
- // These options can't be false in partial mode
754
- tsCompilerOptions['supportTestBed'] = true;
755
- tsCompilerOptions['supportJitMode'] = true;
756
- }
757
- if (!isTest && config.build?.lib) {
758
- tsCompilerOptions['declaration'] = true;
759
- tsCompilerOptions['declarationMap'] = watchMode;
760
- tsCompilerOptions['inlineSources'] = true;
761
- }
762
- if (isTest) {
763
- // Allow `TestBed.overrideXXX()` APIs.
764
- tsCompilerOptions['supportTestBed'] = true;
765
- }
766
- const replacements = pluginOptions.fileReplacements.map((rp) => join(pluginOptions.workspaceRoot, rp.ssr || rp.with));
767
- // Merge + dedupe root names
768
- rootNames = [...new Set([...rootNames, ...includeCache, ...replacements])];
769
- const hostKey = JSON.stringify(tsCompilerOptions);
770
- let host;
771
- if (cachedHost && cachedHostKey === hostKey) {
772
- host = cachedHost;
773
- }
774
- else {
775
- host = ts.createIncrementalCompilerHost(tsCompilerOptions, {
776
- ...ts.sys,
777
- readFile(path, encoding) {
778
- if (fileTransformMap.has(path)) {
779
- return fileTransformMap.get(path);
780
- }
781
- const file = ts.sys.readFile.call(null, path, encoding);
782
- if (file) {
783
- fileTransformMap.set(path, file);
784
- }
785
- return file;
786
- },
787
- });
788
- cachedHost = host;
789
- cachedHostKey = hostKey;
790
- // Only store cache if in watch mode
791
- if (watchMode) {
792
- augmentHostWithCaching(host, sourceFileCache);
793
- }
794
- }
795
- if (!jit) {
796
- inlineComponentStyles = tsCompilerOptions['externalRuntimeStyles']
797
- ? new Map()
798
- : undefined;
799
- externalComponentStyles = tsCompilerOptions['externalRuntimeStyles']
800
- ? new Map()
801
- : undefined;
802
- augmentHostWithResources(host, styleTransform, {
803
- inlineStylesExtension: pluginOptions.inlineStylesExtension,
804
- isProd,
805
- inlineComponentStyles,
806
- externalComponentStyles,
807
- sourceFileCache,
808
- });
809
- }
810
- /**
811
- * Creates a new NgtscProgram to analyze/re-analyze
812
- * the source files and create a file emitter.
813
- * This is shared between an initial build and a hot update.
814
- */
815
- let typeScriptProgram;
816
- let angularCompiler;
817
- const oldBuilder = builder ?? ts.readBuilderProgram(tsCompilerOptions, host);
818
- if (!jit) {
819
- // Create the Angular specific program that contains the Angular compiler
820
- const angularProgram = new compilerCli.NgtscProgram(rootNames, tsCompilerOptions, host, nextProgram);
821
- angularCompiler = angularProgram.compiler;
822
- typeScriptProgram = angularProgram.compiler.getCurrentProgram();
823
- augmentProgramWithVersioning(typeScriptProgram);
824
- builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, oldBuilder);
825
- nextProgram = angularProgram;
826
- }
827
- else {
828
- builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, tsCompilerOptions, host, oldBuilder);
829
- typeScriptProgram = builder.getProgram();
830
- }
831
- if (!watchMode) {
832
- // When not in watch mode, the startup cost of the incremental analysis can be avoided by
833
- // using an abstract builder that only wraps a TypeScript program.
834
- builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
835
- }
836
- if (angularCompiler) {
837
- await angularCompiler.analyzeAsync();
838
- }
839
- const beforeTransformers = jit
840
- ? [
841
- compilerCli.constructorParametersDownlevelTransform(builder.getProgram()),
842
- createJitResourceTransformer(() => builder.getProgram().getTypeChecker()),
843
- ]
844
- : [];
845
- const transformers = mergeTransformers({ before: beforeTransformers }, jit ? {} : angularCompiler.prepareEmit().transformers);
846
- const fileMetadata = getFileMetadata(builder, angularCompiler, pluginOptions.liveReload, pluginOptions.disableTypeChecking);
847
- const writeFileCallback = (_filename, content, _a, _b, sourceFiles) => {
848
- if (!sourceFiles?.length) {
849
- return;
850
- }
851
- const filename = normalizePath(sourceFiles[0].fileName);
852
- if (filename.includes('ngtypecheck.ts') || filename.includes('.d.')) {
853
- return;
854
- }
855
- const metadata = watchMode ? fileMetadata(filename) : {};
856
- outputFiles.set(filename, {
857
- content,
858
- dependencies: [],
859
- errors: metadata.errors,
860
- warnings: metadata.warnings,
861
- hmrUpdateCode: metadata.hmrUpdateCode,
862
- hmrEligible: metadata.hmrEligible,
863
- });
864
- };
865
- const writeOutputFile = (id) => {
866
- const sourceFile = builder.getSourceFile(id);
867
- if (!sourceFile) {
868
- return;
869
- }
870
- let content = '';
871
- builder.emit(sourceFile, (filename, data) => {
872
- if (/\.[cm]?js$/.test(filename)) {
873
- content = data;
874
- }
875
- if (!watchMode &&
876
- !isTest &&
877
- /\.d\.ts/.test(filename) &&
878
- !filename.includes('.ngtypecheck.')) {
879
- // output to library root instead /src
880
- const declarationPath = resolve(config.root, config.build.outDir, relative(config.root, filename)).replace('/src/', '/');
881
- const declarationFileDir = declarationPath
882
- .replace(basename(filename), '')
883
- .replace('/src/', '/');
884
- declarationFiles.push({
885
- declarationFileDir,
886
- declarationPath,
887
- data,
888
- });
889
- }
890
- }, undefined /* cancellationToken */, undefined /* emitOnlyDtsFiles */, transformers);
891
- writeFileCallback(id, content, false, undefined, [sourceFile]);
892
- if (angularCompiler) {
893
- angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
894
- }
895
- };
896
- if (watchMode) {
897
- if (ids && ids.length > 0) {
898
- ids.forEach((id) => writeOutputFile(id));
899
- }
900
- else {
901
- /**
902
- * Only block the server from starting up
903
- * during testing.
904
- */
905
- if (isTest) {
906
- // TypeScript will loop until there are no more affected files in the program
907
- while (builder.emitNextAffectedFile(writeFileCallback, undefined, undefined, transformers)) {
908
- /* empty */
909
- }
910
- }
911
- }
912
- }
913
- if (!isTest) {
914
- /**
915
- * Perf: Output files on demand so the dev server
916
- * isn't blocked when emitting files.
917
- */
918
- outputFile = writeOutputFile;
919
- }
920
- }
1
+ import { angularFullVersion, cjt, sourceFileCache } from "./utils/devkit.js";
2
+ import { createCompilerPlugin, createRolldownCompilerPlugin } from "./compiler-plugin.js";
3
+ import { TS_EXT_REGEX, createTsConfigGetter, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
4
+ import { getJsTransformConfigKey, isRolldown } from "./utils/rolldown.js";
5
+ import { buildOptimizerPlugin } from "./angular-build-optimizer-plugin.js";
6
+ import { toJitInlineStyleId } from "./utils/jit-inline-styles.js";
7
+ import { activateDeferredDebug, applyDebugOption, debugCompiler, debugCompilerV, debugEmit, debugEmitV, debugHmr, debugHmrV, debugStyles, debugStylesV } from "./utils/debug.js";
8
+ import { discoverAnalogIntegrations } from "./analog-plugin-interop.js";
9
+ import { AnalogStylesheetRegistry, preprocessStylesheet, rewriteRelativeCssImports } from "./stylesheet-registry.js";
10
+ import { jitPlugin } from "./angular-jit-plugin.js";
11
+ import { StyleUrlsResolver, TemplateUrlsResolver } from "./component-resolvers.js";
12
+ import { augmentHostWithCaching, augmentHostWithResources, augmentProgramWithVersioning, mergeTransformers } from "./host.js";
13
+ import { TsconfigResolver } from "./utils/tsconfig-resolver.js";
14
+ import { describeStylesheetContent, injectViteIgnoreForHmrMetadata, isIgnoredHmrFile, isTestWatchMode } from "./utils/compilation-shared.js";
15
+ import { toVirtualRawId } from "./utils/virtual-ids.js";
16
+ import { loadVirtualRawModule, rewriteHtmlRawImport } from "./utils/virtual-resources.js";
17
+ import { compilationAPIPlugin } from "./compilation-api/compilation-api-plugin.js";
18
+ import "./compilation-api/index.js";
19
+ import { ANGULAR_DECORATOR_CALL_RE } from "./compiler/constants.js";
20
+ import "./compiler/index.js";
21
+ import { markStylePathSafe } from "./utils/safe-module-paths.js";
22
+ import { fastCompilePlugin } from "./fast-compile-plugin.js";
23
+ import { encapsulationPlugin, getComponentStyleSheetMeta, isComponentStyleSheet } from "./encapsulation-plugin.js";
24
+ import { virtualModulesPlugin } from "./virtual-modules-plugin.js";
25
+ import { angularVitestPlugins } from "./angular-vitest-plugin.js";
26
+ import { cssExtensionStyleResolverPlugin } from "./utils/css-extension-resolver.js";
27
+ import { pendingTasksPlugin } from "./angular-pending-tasks.plugin.js";
28
+ import { liveReloadPlugin } from "./live-reload-plugin.js";
29
+ import { nxFolderPlugin } from "./nx-folder-plugin.js";
30
+ import { replaceFiles } from "./plugins/file-replacements.plugin.js";
31
+ import { routerPlugin } from "./router-plugin.js";
32
+ import { union } from "es-toolkit";
33
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
34
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
35
+ import * as compilerCli from "@angular/compiler-cli";
36
+ import { createRequire } from "node:module";
37
+ import { normalizePath, preprocessCSS } from "vite";
38
+ //#region packages/vite-plugin-angular/src/lib/angular-vite-plugin.ts
39
+ var require = createRequire(import.meta.url);
40
+ var classNames = /* @__PURE__ */ new Map();
41
+ function evictDeletedFileMetadata(file, { classNamesMap, fileTransformMap }) {
42
+ const normalizedFile = normalizePath(file.split("?")[0]);
43
+ classNamesMap.delete(normalizedFile);
44
+ fileTransformMap.delete(normalizedFile);
921
45
  }
922
- export function createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, performCompilation) {
923
- return async () => {
924
- invalidateFsCaches();
925
- invalidateTsconfigCaches();
926
- await performCompilation();
927
- };
46
+ function angular(options) {
47
+ applyDebugOption(options?.debug, options?.workspaceRoot);
48
+ const liveReload = options?.liveReload ?? true;
49
+ let externalizeStylesRequested = false;
50
+ let configureStylesheetRegistry;
51
+ let transformFilter;
52
+ /**
53
+ * Normalize plugin options so defaults
54
+ * are used for values not provided.
55
+ */
56
+ const pluginOptions = {
57
+ tsconfigGetter: createTsConfigGetter(options?.tsconfig),
58
+ workspaceRoot: options?.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd(),
59
+ inlineStylesExtension: options?.inlineStylesExtension ?? "css",
60
+ supportedBrowsers: options?.supportedBrowsers ?? ["safari 15"],
61
+ jit: options?.jit,
62
+ include: options?.include ?? [],
63
+ liveReload,
64
+ disableTypeChecking: options?.disableTypeChecking ?? true,
65
+ fileReplacements: options?.fileReplacements ?? [],
66
+ useAngularCompilationAPI: options?.experimental?.useAngularCompilationAPI ?? false,
67
+ fastCompile: options?.fastCompile ?? false,
68
+ fastCompileMode: options?.fastCompileMode ?? "full",
69
+ stylePreprocessor: void 0
70
+ };
71
+ let resolvedConfig;
72
+ let tsConfigResolutionContext = null;
73
+ const ts = require("typescript");
74
+ let builder;
75
+ let nextProgram;
76
+ let cachedHost;
77
+ let cachedHostKey;
78
+ const isTest = process.env.NODE_ENV === "test" || !!process.env["VITEST"];
79
+ const tsconfigResolver = new TsconfigResolver({
80
+ workspaceRoot: pluginOptions.workspaceRoot,
81
+ include: pluginOptions.include,
82
+ liveReload: pluginOptions.liveReload,
83
+ isTest
84
+ });
85
+ function invalidateFsCaches() {
86
+ tsconfigResolver.invalidateIncludeCache();
87
+ }
88
+ function invalidateTsconfigCaches() {
89
+ tsconfigResolver.invalidateTsconfigCaches();
90
+ cachedHost = void 0;
91
+ cachedHostKey = void 0;
92
+ }
93
+ let watchMode = false;
94
+ let testWatchMode = isTestWatchMode();
95
+ function hasViteHmrTransport() {
96
+ return resolvedConfig ? resolvedConfig.server.hmr !== false : true;
97
+ }
98
+ function shouldEnableLiveReload() {
99
+ return !!((isTest ? testWatchMode : watchMode) && pluginOptions.liveReload && hasViteHmrTransport());
100
+ }
101
+ /**
102
+ * Determines whether Angular should externalize component styles.
103
+ *
104
+ * When true, Angular emits style references (hash-based IDs) instead of
105
+ * inlining CSS strings. Vite's resolveId → load → transform pipeline
106
+ * then serves these virtual modules, allowing @tailwindcss/vite to
107
+ * process @reference directives.
108
+ *
109
+ * Required for TWO independent use-cases:
110
+ * 1. HMR — Vite needs external modules for hot replacement
111
+ * 2. A Vite plugin asked for it through `analog.setup()` so its styles
112
+ * pass through Vite's CSS pipeline (e.g. @tailwindcss/vite)
113
+ *
114
+ * In production builds (!watchMode), styles are NOT externalized — they
115
+ * are inlined after preprocessCSS runs eagerly in transformStylesheet.
116
+ */
117
+ function shouldExternalizeStyles() {
118
+ if (!(isTest ? testWatchMode : watchMode)) return false;
119
+ return !!(shouldEnableLiveReload() || externalizeStylesRequested);
120
+ }
121
+ let stylesheetRegistry;
122
+ const sourceFileCache$1 = new sourceFileCache();
123
+ const isVitestVscode = !!process.env["VITEST_VSCODE"];
124
+ const isStackBlitz = !!process.versions["webcontainer"];
125
+ const isAstroIntegration = process.env["ANALOG_ASTRO"] === "true";
126
+ const jit = typeof pluginOptions?.jit !== "undefined" ? pluginOptions.jit : isTest;
127
+ let viteServer;
128
+ const styleUrlsResolver = new StyleUrlsResolver();
129
+ const templateUrlsResolver = new TemplateUrlsResolver();
130
+ let outputFile;
131
+ const outputFiles = /* @__PURE__ */ new Map();
132
+ const normalizeEmitterLookupId = (file) => {
133
+ const normalizedFile = normalizePath(file);
134
+ if (!normalizedFile.startsWith("/@fs/")) return normalizedFile;
135
+ return normalizePath(normalizedFile.slice(4).replace(/^\/([A-Za-z]:\/)/, "$1"));
136
+ };
137
+ const describeEmitMarkers = (content) => ({
138
+ contentLength: content.length,
139
+ hasCmp: content.includes("ɵcmp"),
140
+ hasFac: content.includes("ɵfac"),
141
+ hasProv: content.includes("ɵprov"),
142
+ hasDecorate: content.includes("__decorate"),
143
+ hasMetadata: content.includes("__metadata")
144
+ });
145
+ const fileEmitter = (file) => {
146
+ const normalizedFile = normalizeEmitterLookupId(file);
147
+ const hadCachedEmit = outputFiles.has(normalizedFile);
148
+ outputFile?.(normalizedFile);
149
+ const emittedResult = outputFiles.get(normalizedFile);
150
+ debugEmitV("fileEmitter lookup", {
151
+ requestFile: file,
152
+ normalizedFile,
153
+ hadCachedEmit,
154
+ hasOutputFileHook: !!outputFile,
155
+ emitted: !!emittedResult,
156
+ knownOutputCount: outputFiles.size,
157
+ contentLength: emittedResult?.content?.length ?? 0,
158
+ errorCount: emittedResult?.errors?.length ?? 0,
159
+ warningCount: emittedResult?.warnings?.length ?? 0
160
+ });
161
+ return emittedResult;
162
+ };
163
+ let initialCompilation = false;
164
+ const declarationFiles = [];
165
+ const fileTransformMap = /* @__PURE__ */ new Map();
166
+ let styleTransform;
167
+ let pendingCompilation;
168
+ let compilationLock = Promise.resolve();
169
+ function angularPlugin() {
170
+ let isProd = false;
171
+ if (angularFullVersion < 19e4 && pluginOptions.liveReload) {
172
+ debugHmr("hmr disabled: Angular version does not support HMR APIs", {
173
+ angularVersion: angularFullVersion,
174
+ isTest
175
+ });
176
+ console.warn("[@analogjs/vite-plugin-angular]: HMR was disabled because Angular v19+ is required for externalRuntimeStyles/_enableHmr support. Detected Angular version: %s.", angularFullVersion);
177
+ pluginOptions.liveReload = false;
178
+ }
179
+ if (isTest) {
180
+ pluginOptions.liveReload = false;
181
+ debugHmr("hmr disabled", {
182
+ angularVersion: angularFullVersion,
183
+ isTest
184
+ });
185
+ }
186
+ return {
187
+ name: "@analogjs/vite-plugin-angular",
188
+ async config(config, { command }) {
189
+ activateDeferredDebug(command);
190
+ watchMode = command === "serve";
191
+ isProd = isProdMode(config.mode);
192
+ tsConfigResolutionContext = {
193
+ root: config.root || ".",
194
+ isProd,
195
+ isLib: !!config?.build?.lib
196
+ };
197
+ const preliminaryTsConfigPath = resolveTsConfigPath();
198
+ const esbuild = config.esbuild ?? false;
199
+ const oxc = config.oxc ?? false;
200
+ const defineOptions = {
201
+ ngJitMode: "false",
202
+ ngI18nClosureMode: "false",
203
+ ...watchMode ? {} : { ngDevMode: "false" }
204
+ };
205
+ const useRolldown = isRolldown();
206
+ const jsTransformConfigKey = getJsTransformConfigKey();
207
+ const jsTransformConfigValue = jsTransformConfigKey === "oxc" ? oxc : esbuild;
208
+ const rolldownOptions = { plugins: [createRolldownCompilerPlugin({
209
+ tsconfig: preliminaryTsConfigPath,
210
+ sourcemap: !isProd,
211
+ advancedOptimizations: isProd,
212
+ jit,
213
+ incremental: watchMode
214
+ }, !isAstroIntegration)] };
215
+ const esbuildOptions = {
216
+ plugins: [createCompilerPlugin({
217
+ tsconfig: preliminaryTsConfigPath,
218
+ sourcemap: !isProd,
219
+ advancedOptimizations: isProd,
220
+ jit,
221
+ incremental: watchMode
222
+ }, isTest, !isAstroIntegration)],
223
+ define: defineOptions
224
+ };
225
+ return {
226
+ [jsTransformConfigKey]: jsTransformConfigValue,
227
+ optimizeDeps: {
228
+ include: [
229
+ "rxjs/operators",
230
+ "rxjs",
231
+ "tslib"
232
+ ],
233
+ exclude: ["@angular/platform-server"],
234
+ ...useRolldown ? { rolldownOptions } : { esbuildOptions }
235
+ }
236
+ };
237
+ },
238
+ configResolved(config) {
239
+ resolvedConfig = config;
240
+ if (config.logger?.warnOnce) {
241
+ const originalWarnOnce = config.logger.warnOnce;
242
+ config.logger.warnOnce = (msg, options) => {
243
+ if (typeof msg === "string" && msg.includes("Sourcemap") && msg.includes("node_modules")) return;
244
+ originalWarnOnce(msg, options);
245
+ };
246
+ }
247
+ if (!jit) styleTransform = (code, filename) => preprocessCSS(code, filename, config);
248
+ if (isTest) testWatchMode = !(config.server.watch === null) || config.test?.watch === true || testWatchMode;
249
+ },
250
+ configureServer(server) {
251
+ viteServer = server;
252
+ const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, () => performCompilation(resolvedConfig));
253
+ server.watcher.on("add", invalidateCompilationOnFsChange);
254
+ server.watcher.on("unlink", (file) => {
255
+ evictDeletedFileMetadata(file, {
256
+ classNamesMap: classNames,
257
+ fileTransformMap
258
+ });
259
+ return invalidateCompilationOnFsChange();
260
+ });
261
+ server.watcher.on("change", (file) => {
262
+ if (file.includes("tsconfig")) invalidateTsconfigCaches();
263
+ });
264
+ },
265
+ async buildStart() {
266
+ if (!isVitestVscode) {
267
+ pendingCompilation = performCompilation(resolvedConfig);
268
+ await pendingCompilation;
269
+ pendingCompilation = null;
270
+ initialCompilation = true;
271
+ }
272
+ },
273
+ async handleHotUpdate(ctx) {
274
+ if (isIgnoredHmrFile(ctx.file)) {
275
+ debugHmr("ignored file change", { file: ctx.file });
276
+ return [];
277
+ }
278
+ if (TS_EXT_REGEX.test(ctx.file)) {
279
+ const [fileId] = ctx.file.split("?");
280
+ debugHmr("TS file changed", {
281
+ file: ctx.file,
282
+ fileId
283
+ });
284
+ pendingCompilation = performCompilation(resolvedConfig, [fileId]);
285
+ let result;
286
+ if (shouldEnableLiveReload()) {
287
+ await pendingCompilation;
288
+ pendingCompilation = null;
289
+ result = fileEmitter(fileId);
290
+ debugHmr("TS file emitted", {
291
+ fileId,
292
+ hmrEligible: !!result?.hmrEligible,
293
+ hasClassName: !!classNames.get(fileId)
294
+ });
295
+ debugHmrV("ts hmr evaluation", {
296
+ file: ctx.file,
297
+ fileId,
298
+ hasResult: !!result,
299
+ hmrEligible: !!result?.hmrEligible,
300
+ hasClassName: !!classNames.get(fileId),
301
+ className: classNames.get(fileId),
302
+ updateCode: result?.hmrUpdateCode ? describeStylesheetContent(result.hmrUpdateCode) : void 0,
303
+ errors: result?.errors?.length ?? 0,
304
+ warnings: result?.warnings?.length ?? 0,
305
+ hint: result?.hmrEligible ? "A TS-side component change, including inline template edits, produced an Angular HMR payload." : "No Angular HMR payload was emitted for this TS change; the change may not affect component template state."
306
+ });
307
+ }
308
+ if (shouldEnableLiveReload() && result?.hmrEligible && classNames.get(fileId)) {
309
+ const relativeFileId = `${normalizePath(relative(process.cwd(), fileId))}@${classNames.get(fileId)}`;
310
+ debugHmr("sending component update", { relativeFileId });
311
+ debugHmrV("ts hmr component update payload", {
312
+ file: ctx.file,
313
+ fileId,
314
+ relativeFileId,
315
+ className: classNames.get(fileId)
316
+ });
317
+ sendHMRComponentUpdate(ctx.server, relativeFileId);
318
+ return ctx.modules.map((mod) => {
319
+ if (mod.id === ctx.file) return markModuleSelfAccepting(mod);
320
+ return mod;
321
+ });
322
+ }
323
+ }
324
+ if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
325
+ debugHmr("resource file changed", { file: ctx.file });
326
+ fileTransformMap.delete(ctx.file.split("?")[0]);
327
+ const fileModules = await getModulesForChangedFile(ctx.server, ctx.file, ctx.modules, stylesheetRegistry);
328
+ /**
329
+ * Check to see if this was a direct request
330
+ * for an external resource (styles, html).
331
+ */
332
+ const isDirect = fileModules.find((mod) => !!mod.id && mod.id.includes("?direct") && isModuleForChangedResource(mod, ctx.file, stylesheetRegistry));
333
+ const isInline = fileModules.find((mod) => !!mod.id && mod.id.includes("?inline") && isModuleForChangedResource(mod, ctx.file, stylesheetRegistry));
334
+ debugHmrV("resource direct/inline detection", {
335
+ file: ctx.file,
336
+ hasDirect: !!isDirect,
337
+ directId: isDirect?.id,
338
+ hasInline: !!isInline,
339
+ inlineId: isInline?.id
340
+ });
341
+ if (isDirect || isInline) {
342
+ if (shouldExternalizeStyles() && isDirect?.id && isDirect.file) {
343
+ const isComponentStyle = isDirect.type === "css" && isComponentStyleSheet(isDirect.id);
344
+ debugHmrV("resource direct branch", {
345
+ file: ctx.file,
346
+ directId: isDirect.id,
347
+ directType: isDirect.type,
348
+ shouldExternalize: shouldExternalizeStyles(),
349
+ isComponentStyle
350
+ });
351
+ if (isComponentStyle) {
352
+ const { encapsulation } = getComponentStyleSheetMeta(isDirect.id);
353
+ const wrapperModules = await findComponentStylesheetWrapperModules(ctx.server, ctx.file, isDirect, fileModules, stylesheetRegistry);
354
+ const stylesheetDiagnosis = diagnoseComponentStylesheetPipeline(ctx.file, isDirect, stylesheetRegistry, wrapperModules, pluginOptions.stylePreprocessor);
355
+ debugStylesV("HMR: component stylesheet changed", {
356
+ file: isDirect.file,
357
+ encapsulation
358
+ });
359
+ debugHmrV("component stylesheet wrapper modules", {
360
+ file: ctx.file,
361
+ wrapperCount: wrapperModules.length,
362
+ wrapperIds: wrapperModules.map((mod) => mod.id),
363
+ availableModuleIds: fileModules.map((mod) => mod.id)
364
+ });
365
+ debugHmrV("component stylesheet pipeline diagnosis", stylesheetDiagnosis);
366
+ ctx.server.moduleGraph.invalidateModule(isDirect);
367
+ debugHmrV("component stylesheet direct module invalidated", {
368
+ file: ctx.file,
369
+ directModuleId: isDirect.id,
370
+ directModuleUrl: isDirect.url,
371
+ reason: "Ensure Vite drops stale direct CSS transform results before wrapper or fallback handling continues."
372
+ });
373
+ const trackedWrapperRequestIds = stylesheetDiagnosis.trackedRequestIds.filter((id) => id.includes("?ngcomp="));
374
+ if (encapsulation !== "shadow" && (wrapperModules.length > 0 || trackedWrapperRequestIds.length > 0)) {
375
+ wrapperModules.forEach((mod) => ctx.server.moduleGraph.invalidateModule(mod));
376
+ debugHmrV("sending css-update for component stylesheet", {
377
+ file: ctx.file,
378
+ path: isDirect.url,
379
+ acceptedPath: isDirect.file,
380
+ wrapperCount: wrapperModules.length,
381
+ trackedWrapperRequestIds,
382
+ hint: wrapperModules.length > 0 ? "Live wrapper modules were found and invalidated before sending the CSS update." : "No live wrapper ModuleNode was available, but the wrapper request id is already tracked, so Analog is trusting the browser-visible wrapper identity and patching the direct stylesheet instead of forcing a reload."
383
+ });
384
+ sendCssUpdate(ctx.server, {
385
+ path: isDirect.url,
386
+ acceptedPath: isDirect.file
387
+ });
388
+ logComponentStylesheetHmrOutcome({
389
+ file: ctx.file,
390
+ encapsulation,
391
+ diagnosis: stylesheetDiagnosis,
392
+ outcome: "css-update",
393
+ directModuleId: isDirect.id,
394
+ wrapperIds: wrapperModules.map((mod) => mod.id)
395
+ });
396
+ return union(fileModules.filter((mod) => {
397
+ return mod.file !== ctx.file || mod.id !== isDirect.id;
398
+ }).map((mod) => {
399
+ if (mod.file === ctx.file) return markModuleSelfAccepting(mod);
400
+ return mod;
401
+ }), wrapperModules.map((mod) => markModuleSelfAccepting(mod)));
402
+ }
403
+ debugHmrV("component stylesheet hmr fallback: full reload", {
404
+ file: ctx.file,
405
+ encapsulation,
406
+ reason: trackedWrapperRequestIds.length === 0 ? "missing-wrapper-module" : encapsulation === "shadow" ? "shadow-encapsulation" : "tracked-wrapper-still-not-patchable",
407
+ directId: isDirect.id,
408
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? []
409
+ });
410
+ logComponentStylesheetHmrOutcome({
411
+ file: ctx.file,
412
+ encapsulation,
413
+ diagnosis: stylesheetDiagnosis,
414
+ outcome: "full-reload",
415
+ directModuleId: isDirect.id,
416
+ wrapperIds: wrapperModules.map((mod) => mod.id)
417
+ });
418
+ sendFullReload(ctx.server, {
419
+ file: ctx.file,
420
+ encapsulation,
421
+ reason: wrapperModules.length === 0 ? "missing-wrapper-module" : "shadow-encapsulation",
422
+ directId: isDirect.id,
423
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(ctx.file) ?? []
424
+ });
425
+ return [];
426
+ }
427
+ }
428
+ return fileModules;
429
+ }
430
+ if (shouldEnableLiveReload() && /\.(html|htm)$/.test(ctx.file) && fileModules.length === 0) {
431
+ const ownerModules = findTemplateOwnerModules(ctx.server, ctx.file);
432
+ debugHmrV("template owner lookup", {
433
+ file: ctx.file,
434
+ ownerCount: ownerModules.length,
435
+ ownerIds: ownerModules.map((mod) => mod.id),
436
+ hint: ownerModules.length > 0 ? "The external template has candidate TS owner modules that can be recompiled for HMR." : "No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path."
437
+ });
438
+ if (ownerModules.length > 0) {
439
+ const ownerIds = ownerModules.map((mod) => mod.id).filter(Boolean);
440
+ ownerModules.forEach((mod) => ctx.server.moduleGraph.invalidateModule(mod));
441
+ pendingCompilation = performCompilation(resolvedConfig, ownerIds);
442
+ await pendingCompilation;
443
+ pendingCompilation = null;
444
+ const updates = ownerIds.filter((id) => classNames.get(id));
445
+ debugHmrV("template owner recompilation result", {
446
+ file: ctx.file,
447
+ ownerIds,
448
+ updates,
449
+ updateClassNames: updates.map((id) => ({
450
+ id,
451
+ className: classNames.get(id)
452
+ })),
453
+ hint: updates.length > 0 ? "External template recompilation produced Angular component update targets." : "External template recompilation completed, but no Angular component update targets were surfaced."
454
+ });
455
+ if (updates.length > 0) {
456
+ debugHmr("template owner module invalidation", {
457
+ file: ctx.file,
458
+ ownerIds,
459
+ updateCount: updates.length
460
+ });
461
+ updates.forEach((updateId) => {
462
+ const relativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
463
+ sendHMRComponentUpdate(ctx.server, relativeFileId);
464
+ });
465
+ return ownerModules.map((mod) => markModuleSelfAccepting(mod));
466
+ }
467
+ }
468
+ }
469
+ const mods = [];
470
+ const updates = [];
471
+ fileModules.forEach((mod) => {
472
+ mod.importers.forEach((imp) => {
473
+ ctx.server.moduleGraph.invalidateModule(imp);
474
+ if (shouldExternalizeStyles() && classNames.get(imp.id)) updates.push(imp.id);
475
+ else mods.push(imp);
476
+ });
477
+ });
478
+ debugHmrV("resource importer analysis", {
479
+ file: ctx.file,
480
+ fileModuleCount: fileModules.length,
481
+ importerCount: fileModules.reduce((count, mod) => count + mod.importers.size, 0),
482
+ updates,
483
+ mods: mods.map((mod) => mod.id)
484
+ });
485
+ pendingCompilation = performCompilation(resolvedConfig, [...mods.map((mod) => mod.id).filter(Boolean), ...updates]);
486
+ if (updates.length > 0) {
487
+ await pendingCompilation;
488
+ pendingCompilation = null;
489
+ debugHmr("resource importer component updates", {
490
+ file: ctx.file,
491
+ updateCount: updates.length
492
+ });
493
+ updates.forEach((updateId) => {
494
+ const impRelativeFileId = `${normalizePath(relative(process.cwd(), updateId))}@${classNames.get(updateId)}`;
495
+ sendHMRComponentUpdate(ctx.server, impRelativeFileId);
496
+ });
497
+ return fileModules.map((mod) => {
498
+ if (mod.id === ctx.file) return markModuleSelfAccepting(mod);
499
+ return mod;
500
+ });
501
+ }
502
+ return mods;
503
+ }
504
+ debugHmr("full reload — unrecognized file type", { file: ctx.file });
505
+ classNames.clear();
506
+ return ctx.modules;
507
+ },
508
+ resolveId(id, importer) {
509
+ if (id.startsWith("virtual:@analogjs/vite-plugin-angular:raw:")) return `\0${id}`;
510
+ if (jit && id.startsWith("angular:jit:")) {
511
+ const filePath = normalizePath(resolve(dirname(importer), id.split(";")[1]));
512
+ if (id.includes(":style")) {
513
+ markStylePathSafe(resolvedConfig, filePath);
514
+ return filePath + "?inline";
515
+ }
516
+ return toVirtualRawId(filePath);
517
+ }
518
+ const rawRewrite = rewriteHtmlRawImport(id, importer);
519
+ if (rawRewrite) return rawRewrite;
520
+ if (/\.(css|scss|sass|less)\?inline$/.test(id) && importer) {
521
+ const filePath = id.split("?")[0];
522
+ const resolved = isAbsolute(filePath) ? normalizePath(filePath) : normalizePath(resolve(dirname(importer), filePath));
523
+ markStylePathSafe(resolvedConfig, resolved);
524
+ return resolved + "?inline";
525
+ }
526
+ if (isComponentStyleSheet(id)) {
527
+ const filename = getFilenameFromPath(id);
528
+ const search = new URL(id, "http://localhost").search;
529
+ const servedSourcePath = stylesheetRegistry?.getServedSourcePath(filename);
530
+ if (servedSourcePath) {
531
+ debugStylesV("resolveId: mapped served stylesheet to source", {
532
+ filename,
533
+ resolvedPath: servedSourcePath
534
+ });
535
+ return servedSourcePath + search;
536
+ }
537
+ if (stylesheetRegistry?.hasServed(filename)) {
538
+ debugStylesV("resolveId: kept preprocessed ID", { filename });
539
+ return id;
540
+ }
541
+ const componentStyles = stylesheetRegistry?.resolveExternalSource(filename);
542
+ if (componentStyles) {
543
+ debugStylesV("resolveId: mapped external stylesheet", {
544
+ filename,
545
+ resolvedPath: componentStyles
546
+ });
547
+ return componentStyles + new URL(id, "http://localhost").search;
548
+ }
549
+ debugStyles("resolveId: component stylesheet NOT FOUND in either map", {
550
+ filename,
551
+ inlineMapSize: stylesheetRegistry?.servedCount ?? 0,
552
+ externalMapSize: stylesheetRegistry?.externalCount ?? 0
553
+ });
554
+ }
555
+ },
556
+ async load(id) {
557
+ const rawModule = await loadVirtualRawModule(this, id);
558
+ if (rawModule !== void 0) return rawModule;
559
+ if (/\.(css|scss|sass|less)\?inline$/.test(id)) markStylePathSafe(resolvedConfig, id.split("?")[0]);
560
+ if (isComponentStyleSheet(id)) {
561
+ const filename = getFilenameFromPath(id);
562
+ const componentStyles = stylesheetRegistry?.getServedContent(filename);
563
+ if (componentStyles) {
564
+ stylesheetRegistry?.registerActiveRequest(id);
565
+ debugHmrV("stylesheet active request registered", {
566
+ requestId: id,
567
+ filename,
568
+ sourcePath: stylesheetRegistry?.resolveExternalSource(filename) ?? stylesheetRegistry?.resolveExternalSource(filename.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(filename) ?? stylesheetRegistry?.getServedSourcePath(filename.replace(/^\//, "")),
569
+ trackedRequestIds: stylesheetRegistry?.getRequestIdsForSource(stylesheetRegistry?.resolveExternalSource(filename) ?? stylesheetRegistry?.resolveExternalSource(filename.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(filename) ?? stylesheetRegistry?.getServedSourcePath(filename.replace(/^\//, "")) ?? "") ?? []
570
+ });
571
+ debugStylesV("load: served inline component stylesheet", {
572
+ filename,
573
+ length: componentStyles.length,
574
+ requestId: id,
575
+ ...describeStylesheetContent(componentStyles)
576
+ });
577
+ return componentStyles;
578
+ }
579
+ }
580
+ },
581
+ transform: {
582
+ filter: { id: {
583
+ include: [TS_EXT_REGEX],
584
+ exclude: [
585
+ /node_modules/,
586
+ "type=script",
587
+ "@ng/component"
588
+ ]
589
+ } },
590
+ async handler(code, id) {
591
+ if (transformFilter && !transformFilter(code, id)) return;
592
+ if (pluginOptions.useAngularCompilationAPI) {
593
+ if (!ANGULAR_DECORATOR_CALL_RE.test(code)) return;
594
+ }
595
+ if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
596
+ fileTransformMap.set(id, code);
597
+ /**
598
+ * Re-analyze on each transform
599
+ * for test(Vitest)
600
+ */
601
+ if (isTest) {
602
+ if (isVitestVscode && !initialCompilation) {
603
+ pendingCompilation = performCompilation(resolvedConfig);
604
+ initialCompilation = true;
605
+ }
606
+ const tsMod = viteServer?.moduleGraph.getModuleById(id);
607
+ if (tsMod) {
608
+ const invalidated = tsMod.lastInvalidationTimestamp;
609
+ if (testWatchMode && invalidated) pendingCompilation = performCompilation(resolvedConfig, [id]);
610
+ }
611
+ }
612
+ const hasComponent = code.includes("@Component");
613
+ debugCompilerV("transform", {
614
+ id,
615
+ codeLength: code.length,
616
+ hasComponent
617
+ });
618
+ const resolveResourceUrls = hasComponent && (watchMode || jit);
619
+ const templateUrls = resolveResourceUrls ? templateUrlsResolver.resolve(code, id) : [];
620
+ const styleUrls = resolveResourceUrls ? styleUrlsResolver.resolve(code, id) : [];
621
+ if (resolveResourceUrls && watchMode) for (const urlSet of [...templateUrls, ...styleUrls]) {
622
+ const [, absoluteFileUrl] = urlSet.split("|");
623
+ this.addWatchFile(absoluteFileUrl);
624
+ }
625
+ if (pendingCompilation) {
626
+ await pendingCompilation;
627
+ pendingCompilation = null;
628
+ }
629
+ const typescriptResult = fileEmitter(id);
630
+ if (!typescriptResult) {
631
+ debugCompilerV("transform skip (file not emitted by Angular)", { id });
632
+ const isAngular = !id.includes("@ng/component") && /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
633
+ debugEmit("transform emit miss", {
634
+ id,
635
+ normalizedId: normalizeEmitterLookupId(id),
636
+ knownOutputCount: outputFiles.size,
637
+ hasOutputFileHook: !!outputFile,
638
+ isAngular
639
+ });
640
+ if (isAngular) this.warn(`[@analogjs/vite-plugin-angular]: "${id}" contains Angular decorators but is not in the TypeScript program. Ensure it is included in your tsconfig.`);
641
+ return;
642
+ }
643
+ if (typescriptResult.warnings && typescriptResult.warnings.length > 0) this.warn(`${typescriptResult.warnings.join("\n")}`);
644
+ if (typescriptResult.errors && typescriptResult.errors.length > 0) this.error(`${typescriptResult.errors.join("\n")}`);
645
+ let data = typescriptResult.content ?? "";
646
+ debugEmitV("transform emit hit", {
647
+ id,
648
+ normalizedId: normalizeEmitterLookupId(id),
649
+ ...describeEmitMarkers(data),
650
+ errorCount: typescriptResult.errors?.length ?? 0,
651
+ warningCount: typescriptResult.warnings?.length ?? 0
652
+ });
653
+ if (jit && data.includes("angular:jit:")) {
654
+ data = data.replace(/angular:jit:style:inline;([A-Za-z0-9+/=]*)/g, (_match, encodedStyles) => toJitInlineStyleId(encodedStyles));
655
+ templateUrls.forEach((templateUrlSet) => {
656
+ const [templateFile, resolvedTemplateUrl] = templateUrlSet.split("|");
657
+ data = data.replace(`angular:jit:template:file;${templateFile}`, toVirtualRawId(resolvedTemplateUrl));
658
+ });
659
+ styleUrls.forEach((styleUrlSet) => {
660
+ const [styleFile, resolvedStyleUrl] = styleUrlSet.split("|");
661
+ markStylePathSafe(resolvedConfig, resolvedStyleUrl);
662
+ data = data.replace(`angular:jit:style:file;${styleFile}`, resolvedStyleUrl + "?inline");
663
+ });
664
+ }
665
+ if (data.includes("HmrLoad")) {
666
+ const hasMetaUrl = data.includes("getReplaceMetadataURL");
667
+ debugHmrV("vite-ignore injection", {
668
+ id,
669
+ dataLength: data.length,
670
+ hasMetaUrl
671
+ });
672
+ if (hasMetaUrl) {
673
+ const patched = injectViteIgnoreForHmrMetadata(data);
674
+ if (patched !== data && !patched.includes("@vite-ignore")) debugHmrV("vite-ignore regex fallback", { id });
675
+ data = patched;
676
+ }
677
+ }
678
+ if (typescriptResult.map) data = data.replace(/\s*\/\/# sourceMappingURL=[^\r\n]*\s*$/, "");
679
+ return {
680
+ code: data,
681
+ map: typescriptResult.map ?? null
682
+ };
683
+ }
684
+ },
685
+ closeBundle() {
686
+ declarationFiles.forEach(({ declarationFileDir, declarationPath, data }) => {
687
+ mkdirSync(declarationFileDir, { recursive: true });
688
+ writeFileSync(declarationPath, data, "utf-8");
689
+ });
690
+ }
691
+ };
692
+ }
693
+ const compilationPlugin = pluginOptions.useAngularCompilationAPI ? compilationAPIPlugin({
694
+ tsconfigGetter: pluginOptions.tsconfigGetter,
695
+ workspaceRoot: pluginOptions.workspaceRoot,
696
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
697
+ jit,
698
+ liveReload: pluginOptions.liveReload,
699
+ disableTypeChecking: pluginOptions.disableTypeChecking,
700
+ supportedBrowsers: pluginOptions.supportedBrowsers,
701
+ fileReplacements: pluginOptions.fileReplacements,
702
+ isTest,
703
+ isAstroIntegration,
704
+ include: pluginOptions.include,
705
+ debug: options?.debug
706
+ }) : pluginOptions.fastCompile ? fastCompilePlugin({
707
+ tsconfigGetter: pluginOptions.tsconfigGetter,
708
+ workspaceRoot: pluginOptions.workspaceRoot,
709
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
710
+ jit,
711
+ liveReload: pluginOptions.liveReload,
712
+ supportedBrowsers: pluginOptions.supportedBrowsers,
713
+ isTest,
714
+ isAstroIntegration,
715
+ fastCompileMode: pluginOptions.fastCompileMode
716
+ }) : angularPlugin();
717
+ return [
718
+ cssExtensionStyleResolverPlugin(),
719
+ replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
720
+ virtualModulesPlugin({ jit }),
721
+ pluginOptions.liveReload && liveReloadPlugin({
722
+ classNames,
723
+ fileEmitter
724
+ }),
725
+ compilationPlugin,
726
+ !pluginOptions.fastCompile && pluginOptions.liveReload && liveReloadPlugin({
727
+ classNames,
728
+ fileEmitter
729
+ }),
730
+ ...isTest && !isStackBlitz ? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map) : [],
731
+ jit && jitPlugin({ inlineStylesExtension: pluginOptions.inlineStylesExtension }),
732
+ buildOptimizerPlugin({
733
+ supportedBrowsers: pluginOptions.supportedBrowsers,
734
+ jit
735
+ }),
736
+ routerPlugin(),
737
+ angularFullVersion < 190004 && pendingTasksPlugin(),
738
+ nxFolderPlugin(),
739
+ encapsulationPlugin()
740
+ ].filter(Boolean);
741
+ function resolveTsConfigPath() {
742
+ const tsconfigValue = pluginOptions.tsconfigGetter();
743
+ return getTsConfigPath(tsConfigResolutionContext.root, tsconfigValue, tsConfigResolutionContext.isProd, isTest, tsConfigResolutionContext.isLib, pluginOptions.workspaceRoot);
744
+ }
745
+ async function performCompilation(config, ids) {
746
+ let resolve;
747
+ const previousLock = compilationLock;
748
+ compilationLock = new Promise((r) => {
749
+ resolve = r;
750
+ });
751
+ try {
752
+ await previousLock;
753
+ const integrations = await discoverAnalogIntegrations(config);
754
+ pluginOptions.stylePreprocessor = integrations.stylePreprocessor;
755
+ externalizeStylesRequested = integrations.externalizeStyles;
756
+ configureStylesheetRegistry = integrations.configureStylesheetRegistry;
757
+ transformFilter = integrations.transformFilter;
758
+ tsconfigResolver.setIntegrationIncludes(integrations.include);
759
+ await _doPerformCompilation(config, ids);
760
+ } finally {
761
+ resolve();
762
+ }
763
+ }
764
+ /**
765
+ * This method share mutable state and performs the actual compilation work.
766
+ * It should not be called concurrently. Use `performCompilation` which wraps this method in a lock to ensure only one compilation runs at a time.
767
+ */
768
+ async function _doPerformCompilation(config, ids) {
769
+ const isProd = config.mode === "production";
770
+ const modifiedFiles = new Set(ids ?? []);
771
+ sourceFileCache$1.invalidate(modifiedFiles);
772
+ if (ids?.length) for (const id of ids || []) fileTransformMap.delete(id);
773
+ const resolvedTsConfigPath = resolveTsConfigPath();
774
+ const cached = tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
775
+ const tsCompilerOptions = { ...cached.options };
776
+ let rootNames = [...cached.rootNames];
777
+ if (shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
778
+ if (shouldEnableLiveReload()) {
779
+ tsCompilerOptions["_enableHmr"] = true;
780
+ tsCompilerOptions["supportTestBed"] = true;
781
+ }
782
+ debugCompiler("tsCompilerOptions (NgtscProgram path)", {
783
+ liveReload: pluginOptions.liveReload,
784
+ viteHmr: hasViteHmrTransport(),
785
+ externalizeStylesRequested,
786
+ shouldExternalize: shouldExternalizeStyles(),
787
+ externalRuntimeStyles: !!tsCompilerOptions["externalRuntimeStyles"],
788
+ hmrEnabled: !!tsCompilerOptions["_enableHmr"]
789
+ });
790
+ if (tsCompilerOptions["compilationMode"] === "partial") {
791
+ tsCompilerOptions["supportTestBed"] = true;
792
+ tsCompilerOptions["supportJitMode"] = true;
793
+ }
794
+ if (!isTest && config.build?.lib) {
795
+ tsCompilerOptions["declaration"] = true;
796
+ tsCompilerOptions["declarationMap"] = watchMode;
797
+ tsCompilerOptions["inlineSources"] = true;
798
+ }
799
+ if (isTest) tsCompilerOptions["supportTestBed"] = true;
800
+ const replacements = pluginOptions.fileReplacements.map((rp) => join(pluginOptions.workspaceRoot, rp.ssr || rp.with));
801
+ rootNames = union(rootNames, tsconfigResolver.ensureIncludeCache(), replacements);
802
+ const hostKey = JSON.stringify(tsCompilerOptions);
803
+ let host;
804
+ if (cachedHost && cachedHostKey === hostKey) host = cachedHost;
805
+ else {
806
+ host = ts.createIncrementalCompilerHost(tsCompilerOptions, {
807
+ ...ts.sys,
808
+ readFile(path, encoding) {
809
+ if (fileTransformMap.has(path)) return fileTransformMap.get(path);
810
+ const file = ts.sys.readFile.call(null, path, encoding);
811
+ if (file) fileTransformMap.set(path, file);
812
+ return file;
813
+ }
814
+ });
815
+ cachedHost = host;
816
+ cachedHostKey = hostKey;
817
+ if (watchMode) augmentHostWithCaching(host, sourceFileCache$1);
818
+ }
819
+ if (!jit) {
820
+ const externalizeStyles = !!tsCompilerOptions["externalRuntimeStyles"];
821
+ stylesheetRegistry = externalizeStyles ? new AnalogStylesheetRegistry() : void 0;
822
+ if (stylesheetRegistry) configureStylesheetRegistry?.(stylesheetRegistry, { workspaceRoot: pluginOptions.workspaceRoot });
823
+ debugStyles("stylesheet registry initialized (NgtscProgram path)", { externalizeStyles });
824
+ augmentHostWithResources(host, styleTransform, {
825
+ inlineStylesExtension: pluginOptions.inlineStylesExtension,
826
+ isProd,
827
+ stylesheetRegistry,
828
+ sourceFileCache: sourceFileCache$1,
829
+ stylePreprocessor: pluginOptions.stylePreprocessor
830
+ });
831
+ }
832
+ /**
833
+ * Creates a new NgtscProgram to analyze/re-analyze
834
+ * the source files and create a file emitter.
835
+ * This is shared between an initial build and a hot update.
836
+ */
837
+ let typeScriptProgram;
838
+ let angularCompiler;
839
+ const oldBuilder = builder ?? ts.readBuilderProgram(tsCompilerOptions, host);
840
+ if (!jit) {
841
+ const angularProgram = new compilerCli.NgtscProgram(rootNames, tsCompilerOptions, host, nextProgram);
842
+ angularCompiler = angularProgram.compiler;
843
+ typeScriptProgram = angularProgram.compiler.getCurrentProgram();
844
+ augmentProgramWithVersioning(typeScriptProgram);
845
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, oldBuilder);
846
+ nextProgram = angularProgram;
847
+ } else {
848
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, tsCompilerOptions, host, oldBuilder);
849
+ typeScriptProgram = builder.getProgram();
850
+ }
851
+ if (!watchMode) builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
852
+ if (angularCompiler) await angularCompiler.analyzeAsync();
853
+ const transformers = mergeTransformers({ before: jit ? [compilerCli.constructorParametersDownlevelTransform(builder.getProgram()), cjt(() => builder.getProgram().getTypeChecker())] : [] }, jit ? {} : angularCompiler.prepareEmit().transformers);
854
+ const fileMetadata = getFileMetadata(builder, angularCompiler, pluginOptions.liveReload, pluginOptions.disableTypeChecking);
855
+ const writeFileCallback = (_filename, content, _a, _b, sourceFiles) => {
856
+ if (!sourceFiles?.length) return;
857
+ const filename = normalizePath(sourceFiles[0].fileName);
858
+ if (filename.includes("ngtypecheck.ts") || filename.includes(".d.") || _filename.endsWith(".d.ts") || _filename.endsWith(".d.mts") || _filename.endsWith(".d.cts")) return;
859
+ if (/\.[cm]?js\.map$/.test(_filename)) {
860
+ const existing = outputFiles.get(filename);
861
+ outputFiles.set(filename, {
862
+ ...existing ?? { dependencies: [] },
863
+ map: content
864
+ });
865
+ return;
866
+ }
867
+ const metadata = watchMode ? fileMetadata(filename) : {};
868
+ const existing = outputFiles.get(filename);
869
+ outputFiles.set(filename, {
870
+ ...existing ?? {},
871
+ content,
872
+ dependencies: [],
873
+ errors: metadata.errors,
874
+ warnings: metadata.warnings,
875
+ hmrUpdateCode: metadata.hmrUpdateCode,
876
+ hmrEligible: metadata.hmrEligible
877
+ });
878
+ debugEmitV("registered ngtsc output", {
879
+ filename,
880
+ ...describeEmitMarkers(content),
881
+ errorCount: metadata.errors?.length ?? 0,
882
+ warningCount: metadata.warnings?.length ?? 0,
883
+ hmrEligible: !!metadata.hmrEligible,
884
+ knownOutputCount: outputFiles.size
885
+ });
886
+ };
887
+ const writeOutputFile = (id) => {
888
+ const sourceFile = builder.getSourceFile(id);
889
+ if (!sourceFile) return;
890
+ let content = "";
891
+ let map;
892
+ let mapFilename;
893
+ builder.emit(sourceFile, (filename, data) => {
894
+ if (/\.[cm]?js$/.test(filename)) content = data;
895
+ if (/\.[cm]?js\.map$/.test(filename)) {
896
+ map = data;
897
+ mapFilename = filename;
898
+ }
899
+ if (!watchMode && !isTest && /\.d\.ts/.test(filename) && !filename.includes(".ngtypecheck.")) {
900
+ const declarationPath = resolve(config.root, config.build.outDir, relative(config.root, filename)).replace("/src/", "/");
901
+ const declarationFileDir = declarationPath.replace(basename(filename), "").replace("/src/", "/");
902
+ declarationFiles.push({
903
+ declarationFileDir,
904
+ declarationPath,
905
+ data
906
+ });
907
+ }
908
+ }, void 0, void 0, transformers);
909
+ writeFileCallback(id, content, false, void 0, [sourceFile]);
910
+ if (map !== void 0 && mapFilename !== void 0) writeFileCallback(mapFilename, map, false, void 0, [sourceFile]);
911
+ if (angularCompiler) angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
912
+ };
913
+ if (watchMode) {
914
+ if (ids && ids.length > 0) ids.forEach((id) => writeOutputFile(id));
915
+ else if (isTest) while (builder.emitNextAffectedFile(writeFileCallback, void 0, void 0, transformers));
916
+ }
917
+ if (!isTest)
918
+ /**
919
+ * Perf: Output files on demand so the dev server
920
+ * isn't blocked when emitting files.
921
+ */
922
+ outputFile = writeOutputFile;
923
+ }
928
924
  }
929
- /**
930
- * Convert Analog/Angular CLI-style file replacements into the flat record
931
- * expected by `AngularHostOptions.fileReplacements`.
932
- *
933
- * Only browser replacements (`{ replace, with }`) are converted. SSR-only
934
- * replacements (`{ replace, ssr }`) are left for the Vite runtime plugin to
935
- * handle — they should not be baked into the Angular compilation host because
936
- * that would apply them to both browser and server builds.
937
- *
938
- * Relative paths are resolved against `workspaceRoot` so that the host
939
- * receives the same absolute paths it would get from the Angular CLI.
940
- */
941
- export function toAngularCompilationFileReplacements(replacements, workspaceRoot) {
942
- const mappedReplacements = replacements.flatMap((replacement) => {
943
- // Skip SSR-only entries — they use `ssr` instead of `with`.
944
- if (!('with' in replacement)) {
945
- return [];
946
- }
947
- return [
948
- [
949
- isAbsolute(replacement.replace)
950
- ? replacement.replace
951
- : resolve(workspaceRoot, replacement.replace),
952
- isAbsolute(replacement.with)
953
- ? replacement.with
954
- : resolve(workspaceRoot, replacement.with),
955
- ],
956
- ];
957
- });
958
- return mappedReplacements.length
959
- ? Object.fromEntries(mappedReplacements)
960
- : undefined;
925
+ function createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, performCompilation) {
926
+ return async () => {
927
+ invalidateFsCaches();
928
+ invalidateTsconfigCaches();
929
+ await performCompilation();
930
+ };
961
931
  }
962
932
  /**
963
- * Map Angular's `templateUpdates` (keyed by `encodedFilePath@ClassName`)
964
- * back to absolute file paths with their associated HMR code and component
965
- * class name.
966
- *
967
- * Angular's private Compilation API emits template update keys in the form
968
- * `encodeURIComponent(relativePath + '@' + className)`. We decode and resolve
969
- * them so the caller can look up updates by the same normalized absolute path
970
- * used elsewhere in the plugin (`outputFiles`, `classNames`, etc.).
971
- */
972
- export function mapTemplateUpdatesToFiles(templateUpdates) {
973
- const updatesByFile = new Map();
974
- templateUpdates?.forEach((code, encodedUpdateId) => {
975
- const [file, className = ''] = decodeURIComponent(encodedUpdateId).split('@');
976
- const resolvedFile = normalizePath(resolve(process.cwd(), file));
977
- updatesByFile.set(resolvedFile, {
978
- className,
979
- code,
980
- });
981
- });
982
- return updatesByFile;
933
+ * Returns every live Vite module that can legitimately represent a changed
934
+ * Angular resource file.
935
+ *
936
+ * For normal files, `getModulesByFile()` is enough. For Angular component
937
+ * stylesheets, it is not: the browser often holds virtual hashed requests
938
+ * (`/abc123.css?direct&ngcomp=...` and `/abc123.css?ngcomp=...`) that are no
939
+ * longer discoverable from the original source path alone. We therefore merge:
940
+ * - watcher event modules
941
+ * - module-graph modules by source file
942
+ * - registry-tracked live request ids resolved back through the module graph
943
+ */
944
+ async function getModulesForChangedFile(server, file, eventModules = [], stylesheetRegistry) {
945
+ const normalizedFile = normalizePath(file.split("?")[0]);
946
+ const modules = /* @__PURE__ */ new Map();
947
+ for (const mod of eventModules) if (mod.id) modules.set(mod.id, mod);
948
+ server.moduleGraph.getModulesByFile(normalizedFile)?.forEach((mod) => {
949
+ if (mod.id) modules.set(mod.id, mod);
950
+ });
951
+ const stylesheetRequestIds = stylesheetRegistry?.getRequestIdsForSource(normalizedFile) ?? [];
952
+ const requestIdHits = [];
953
+ for (const requestId of stylesheetRequestIds) {
954
+ const candidates = [requestId, requestId.startsWith("/") ? requestId : `/${requestId}`];
955
+ for (const candidate of candidates) {
956
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
957
+ requestIdHits.push({
958
+ requestId,
959
+ candidate,
960
+ via: mod?.url === candidate ? "url" : "id",
961
+ moduleId: mod?.id
962
+ });
963
+ if (mod?.id) modules.set(mod.id, mod);
964
+ }
965
+ }
966
+ debugHmrV("getModulesForChangedFile registry lookup", {
967
+ file: normalizedFile,
968
+ stylesheetRequestIds,
969
+ requestIdHits,
970
+ resolvedModuleIds: [...modules.keys()]
971
+ });
972
+ return [...modules.values()];
983
973
  }
984
- function sendHMRComponentUpdate(server, id) {
985
- server.ws.send('angular:component-update', {
986
- id: encodeURIComponent(id),
987
- timestamp: Date.now(),
988
- });
989
- classNames.delete(id);
974
+ function isModuleForChangedResource(mod, changedFile, stylesheetRegistry) {
975
+ const normalizedChangedFile = normalizePath(changedFile.split("?")[0]);
976
+ if (normalizePath((mod.file ?? "").split("?")[0]) === normalizedChangedFile) return true;
977
+ if (!mod.id) return false;
978
+ const requestPath = getFilenameFromPath(mod.id);
979
+ return normalizePath((stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, "")) ?? "").split("?")[0]) === normalizedChangedFile;
990
980
  }
991
- export function getFileMetadata(program, angularCompiler, liveReload, disableTypeChecking) {
992
- const ts = require('typescript');
993
- return (file) => {
994
- const sourceFile = program.getSourceFile(file);
995
- if (!sourceFile) {
996
- return {};
997
- }
998
- const diagnostics = getDiagnosticsForSourceFile(sourceFile, !!disableTypeChecking, program, angularCompiler);
999
- const errors = diagnostics
1000
- .filter((d) => d.category === ts.DiagnosticCategory?.Error)
1001
- .map((d) => typeof d.messageText === 'object'
1002
- ? d.messageText.messageText
1003
- : d.messageText);
1004
- const warnings = diagnostics
1005
- .filter((d) => d.category === ts.DiagnosticCategory?.Warning)
1006
- .map((d) => d.messageText);
1007
- let hmrUpdateCode = undefined;
1008
- let hmrEligible = false;
1009
- if (liveReload) {
1010
- for (const node of sourceFile.statements) {
1011
- if (ts.isClassDeclaration(node) && node.name != null) {
1012
- hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);
1013
- if (hmrUpdateCode) {
1014
- classNames.set(file, node.name.getText());
1015
- hmrEligible = true;
1016
- }
1017
- }
1018
- }
1019
- }
1020
- return { errors, warnings, hmrUpdateCode, hmrEligible };
1021
- };
981
+ function diagnoseComponentStylesheetPipeline(changedFile, directModule, stylesheetRegistry, wrapperModules, stylePreprocessor) {
982
+ const normalizedFile = normalizePath(changedFile.split("?")[0]);
983
+ const sourceExists = existsSync(normalizedFile);
984
+ const sourceCode = sourceExists ? readFileSync(normalizedFile, "utf-8") : void 0;
985
+ const directRequestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
986
+ const sourcePath = directRequestPath ? stylesheetRegistry?.resolveExternalSource(directRequestPath) ?? stylesheetRegistry?.resolveExternalSource(directRequestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath) ?? stylesheetRegistry?.getServedSourcePath(directRequestPath.replace(/^\//, "")) : normalizedFile;
987
+ const registryCode = directRequestPath ? stylesheetRegistry?.getServedContent(directRequestPath) : void 0;
988
+ const trackedRequestIds = stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? [];
989
+ const dependencies = stylesheetRegistry?.getDependenciesForSource(sourcePath ?? "") ?? [];
990
+ const diagnostics = stylesheetRegistry?.getDiagnosticsForSource(sourcePath ?? "") ?? [];
991
+ const tags = stylesheetRegistry?.getTagsForSource(sourcePath ?? "") ?? [];
992
+ const anomalies = [];
993
+ const hints = [];
994
+ if (!sourceExists) {
995
+ anomalies.push("source_file_missing");
996
+ hints.push("The stylesheet watcher fired for a file that no longer exists on disk.");
997
+ }
998
+ if (!registryCode) {
999
+ anomalies.push("registry_content_missing");
1000
+ hints.push("The stylesheet registry has no served content for the direct module request path.");
1001
+ }
1002
+ if (sourceCode && registryCode) {
1003
+ let expectedRegistryCode = preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor);
1004
+ expectedRegistryCode = rewriteRelativeCssImports(expectedRegistryCode, normalizedFile);
1005
+ if (describeStylesheetContent(expectedRegistryCode).digest !== describeStylesheetContent(registryCode).digest) {
1006
+ anomalies.push("source_registry_mismatch");
1007
+ hints.push("The source file changed, but the served stylesheet content in the registry is still stale.");
1008
+ }
1009
+ }
1010
+ if (trackedRequestIds.length === 0) {
1011
+ anomalies.push("no_tracked_requests");
1012
+ hints.push("No live stylesheet requests are tracked for this source file, so HMR has no browser-facing target.");
1013
+ }
1014
+ if (trackedRequestIds.some((id) => id.includes("?ngcomp=")) && wrapperModules.length === 0) {
1015
+ anomalies.push("tracked_wrapper_missing_from_module_graph");
1016
+ hints.push("A wrapper request id is known, but Vite did not expose a live wrapper module during this HMR pass.");
1017
+ }
1018
+ if (trackedRequestIds.every((id) => !id.includes("?ngcomp=")) && wrapperModules.length === 0) {
1019
+ anomalies.push("wrapper_not_yet_tracked");
1020
+ hints.push("Only direct stylesheet requests were tracked during this HMR pass; the wrapper request may be appearing too late.");
1021
+ }
1022
+ return {
1023
+ file: changedFile,
1024
+ sourcePath,
1025
+ source: sourceCode ? describeStylesheetContent(rewriteRelativeCssImports(preprocessStylesheet(sourceCode, normalizedFile, stylePreprocessor), normalizedFile)) : void 0,
1026
+ registry: registryCode ? describeStylesheetContent(registryCode) : void 0,
1027
+ dependencies,
1028
+ diagnostics,
1029
+ tags,
1030
+ directModuleId: directModule.id,
1031
+ directModuleUrl: directModule.url,
1032
+ trackedRequestIds,
1033
+ wrapperCount: wrapperModules.length,
1034
+ anomalies,
1035
+ hints
1036
+ };
1022
1037
  }
1023
- function getDiagnosticsForSourceFile(sourceFile, disableTypeChecking, program, angularCompiler) {
1024
- const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
1025
- if (disableTypeChecking) {
1026
- // Syntax errors are cheap to compute and the app will not run if there are any
1027
- // So always show these types of errors regardless if type checking is disabled
1028
- return syntacticDiagnostics;
1029
- }
1030
- const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
1031
- const angularDiagnostics = angularCompiler
1032
- ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)
1033
- : [];
1034
- return [
1035
- ...syntacticDiagnostics,
1036
- ...semanticDiagnostics,
1037
- ...angularDiagnostics,
1038
- ];
1038
+ async function findComponentStylesheetWrapperModules(server, changedFile, directModule, fileModules, stylesheetRegistry) {
1039
+ const wrapperModules = /* @__PURE__ */ new Map();
1040
+ for (const mod of fileModules) if (mod.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
1041
+ const directRequestIds = /* @__PURE__ */ new Set();
1042
+ if (directModule.id) directRequestIds.add(directModule.id);
1043
+ if (directModule.url) directRequestIds.add(directModule.url);
1044
+ const requestPath = directModule.id ? getFilenameFromPath(directModule.id) : void 0;
1045
+ const sourcePath = requestPath ? stylesheetRegistry?.resolveExternalSource(requestPath) ?? stylesheetRegistry?.resolveExternalSource(requestPath.replace(/^\//, "")) ?? stylesheetRegistry?.getServedSourcePath(requestPath) ?? stylesheetRegistry?.getServedSourcePath(requestPath.replace(/^\//, "")) : void 0;
1046
+ for (const requestId of stylesheetRegistry?.getRequestIdsForSource(sourcePath ?? "") ?? []) if (requestId.includes("?ngcomp=")) directRequestIds.add(requestId);
1047
+ const candidateWrapperIds = [...directRequestIds].filter((id) => id.includes("?direct&ngcomp=")).map((id) => id.replace("?direct&ngcomp=", "?ngcomp="));
1048
+ const lookupHits = [];
1049
+ for (const candidate of candidateWrapperIds) {
1050
+ const mod = await server.moduleGraph.getModuleByUrl(candidate) ?? server.moduleGraph.getModuleById(candidate);
1051
+ lookupHits.push({
1052
+ candidate,
1053
+ via: mod?.url === candidate ? "url" : mod ? "id" : void 0,
1054
+ moduleId: mod?.id,
1055
+ moduleType: mod?.type
1056
+ });
1057
+ if (mod?.id && mod.type === "js" && isComponentStyleSheet(mod.id) && isModuleForChangedResource(mod, changedFile, stylesheetRegistry)) wrapperModules.set(mod.id, mod);
1058
+ }
1059
+ debugHmrV("component stylesheet wrapper lookup", {
1060
+ file: changedFile,
1061
+ sourcePath,
1062
+ directModuleId: directModule.id,
1063
+ directModuleUrl: directModule.url,
1064
+ candidateWrapperIds,
1065
+ lookupHits
1066
+ });
1067
+ if (wrapperModules.size === 0) debugHmrV("component stylesheet wrapper lookup empty", {
1068
+ file: changedFile,
1069
+ sourcePath,
1070
+ directModuleId: directModule.id,
1071
+ directModuleUrl: directModule.url,
1072
+ candidateWrapperIds
1073
+ });
1074
+ return [...wrapperModules.values()];
1039
1075
  }
1040
- function markModuleSelfAccepting(mod) {
1041
- // support Vite 6
1042
- if ('_clientModule' in mod) {
1043
- mod['_clientModule'].isSelfAccepting = true;
1044
- }
1045
- return {
1046
- ...mod,
1047
- isSelfAccepting: true,
1048
- };
1076
+ function sendHMRComponentUpdate(server, id) {
1077
+ debugHmrV("ws send: angular component update", {
1078
+ id,
1079
+ timestamp: Date.now()
1080
+ });
1081
+ server.ws.send("angular:component-update", {
1082
+ id: encodeURIComponent(id),
1083
+ timestamp: Date.now()
1084
+ });
1085
+ classNames.delete(id);
1086
+ }
1087
+ function sendCssUpdate(server, update) {
1088
+ const timestamp = Date.now();
1089
+ debugHmrV("ws send: css-update", {
1090
+ ...update,
1091
+ timestamp
1092
+ });
1093
+ server.ws.send({
1094
+ type: "update",
1095
+ updates: [{
1096
+ type: "css-update",
1097
+ timestamp,
1098
+ path: update.path,
1099
+ acceptedPath: update.acceptedPath
1100
+ }]
1101
+ });
1049
1102
  }
1050
- function isComponentStyleSheet(id) {
1051
- return id.includes('ngcomp=');
1103
+ function sendFullReload(server, details) {
1104
+ debugHmrV("ws send: full-reload", details);
1105
+ server.ws.send("analog:debug-full-reload", details);
1106
+ server.ws.send({ type: "full-reload" });
1052
1107
  }
1053
- function getComponentStyleSheetMeta(id) {
1054
- const params = new URL(id, 'http://localhost').searchParams;
1055
- const encapsulationMapping = {
1056
- '0': 'emulated',
1057
- '2': 'none',
1058
- '3': 'shadow',
1059
- };
1060
- return {
1061
- componentId: params.get('ngcomp'),
1062
- encapsulation: encapsulationMapping[params.get('e')],
1063
- };
1108
+ function logComponentStylesheetHmrOutcome(details) {
1109
+ const pitfalls = [];
1110
+ const rejectedPreferredPaths = [];
1111
+ const hints = [];
1112
+ if (details.encapsulation === "shadow") {
1113
+ pitfalls.push("shadow-encapsulation");
1114
+ rejectedPreferredPaths.push("css-update");
1115
+ hints.push("Shadow DOM styles cannot rely on Vite CSS patching because Angular applies them inside a shadow root.");
1116
+ }
1117
+ if (details.diagnosis.anomalies.includes("wrapper_not_yet_tracked")) {
1118
+ pitfalls.push("wrapper-not-yet-tracked");
1119
+ rejectedPreferredPaths.push("css-update");
1120
+ hints.push("The direct stylesheet module exists, but the browser-visible Angular wrapper module was not available in the live graph during this HMR pass.");
1121
+ }
1122
+ if (details.diagnosis.anomalies.includes("tracked_wrapper_missing_from_module_graph")) {
1123
+ pitfalls.push("tracked-wrapper-missing-from-module-graph");
1124
+ rejectedPreferredPaths.push("css-update");
1125
+ hints.push("A wrapper request id is known, but Vite could not resolve a live wrapper module for targeted CSS HMR.");
1126
+ }
1127
+ debugHmrV("component stylesheet hmr outcome", {
1128
+ file: details.file,
1129
+ outcome: details.outcome,
1130
+ encapsulation: details.encapsulation,
1131
+ directModuleId: details.directModuleId,
1132
+ wrapperIds: details.wrapperIds ?? [],
1133
+ preferredPath: details.encapsulation === "shadow" ? "full-reload" : "css-update",
1134
+ rejectedPreferredPaths: [...new Set(rejectedPreferredPaths)],
1135
+ pitfalls: [...new Set(pitfalls)],
1136
+ anomalies: details.diagnosis.anomalies,
1137
+ hints: [...new Set([...details.diagnosis.hints, ...hints])]
1138
+ });
1139
+ }
1140
+ function findTemplateOwnerModules(server, resourceFile) {
1141
+ const candidateTsFiles = [normalizePath(resourceFile.split("?")[0]).replace(/\.(html|htm)$/i, ".ts")];
1142
+ const modules = /* @__PURE__ */ new Map();
1143
+ for (const candidate of candidateTsFiles) server.moduleGraph.getModulesByFile(candidate)?.forEach((mod) => {
1144
+ if (mod.id) modules.set(mod.id, mod);
1145
+ });
1146
+ return [...modules.values()];
1064
1147
  }
1065
1148
  /**
1066
- * Removes leading / and query string from a url path
1067
- * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss
1068
- * @param id
1069
- */
1070
- function getFilenameFromPath(id) {
1071
- return new URL(id, 'http://localhost').pathname.replace(/^\//, '');
1149
+ * @internal
1150
+ */
1151
+ function getFileMetadata(program, angularCompiler, hmrEnabled, disableTypeChecking) {
1152
+ const ts = require("typescript");
1153
+ return (file) => {
1154
+ const sourceFile = program.getSourceFile(file);
1155
+ if (!sourceFile) return {};
1156
+ const diagnostics = getDiagnosticsForSourceFile(sourceFile, !!disableTypeChecking, program, angularCompiler);
1157
+ const errors = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Error).map((d) => typeof d.messageText === "object" ? d.messageText.messageText : d.messageText);
1158
+ const warnings = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Warning).map((d) => d.messageText);
1159
+ let hmrUpdateCode = void 0;
1160
+ let hmrEligible = false;
1161
+ if (hmrEnabled) {
1162
+ for (const node of sourceFile.statements) if (ts.isClassDeclaration(node) && node.name != null) {
1163
+ hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);
1164
+ if (hmrUpdateCode) {
1165
+ const className = node.name.getText();
1166
+ classNames.set(file, className);
1167
+ hmrEligible = true;
1168
+ debugHmr("NgtscProgram emitHmrUpdateModule", {
1169
+ file,
1170
+ className
1171
+ });
1172
+ }
1173
+ }
1174
+ }
1175
+ return {
1176
+ errors,
1177
+ warnings,
1178
+ hmrUpdateCode,
1179
+ hmrEligible
1180
+ };
1181
+ };
1182
+ }
1183
+ function getDiagnosticsForSourceFile(sourceFile, disableTypeChecking, program, angularCompiler) {
1184
+ const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
1185
+ if (disableTypeChecking) return syntacticDiagnostics;
1186
+ const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
1187
+ const angularDiagnostics = angularCompiler ? angularCompiler.getDiagnosticsForFile(sourceFile, 1) : [];
1188
+ return [
1189
+ ...syntacticDiagnostics,
1190
+ ...semanticDiagnostics,
1191
+ ...angularDiagnostics
1192
+ ];
1193
+ }
1194
+ function markModuleSelfAccepting(mod) {
1195
+ if ("_clientModule" in mod) mod["_clientModule"].isSelfAccepting = true;
1196
+ return {
1197
+ ...mod,
1198
+ isSelfAccepting: true
1199
+ };
1072
1200
  }
1073
1201
  /**
1074
- * Checks for vitest run from the command line
1075
- * @returns boolean
1076
- */
1077
- export function isTestWatchMode(args = process.argv) {
1078
- // vitest --run
1079
- const hasRun = args.find((arg) => arg.includes('--run'));
1080
- if (hasRun) {
1081
- return false;
1082
- }
1083
- // vitest --no-run
1084
- const hasNoRun = args.find((arg) => arg.includes('--no-run'));
1085
- if (hasNoRun) {
1086
- return true;
1087
- }
1088
- // check for --watch=false or --no-watch
1089
- const hasWatch = args.find((arg) => arg.includes('watch'));
1090
- if (hasWatch && ['false', 'no'].some((neg) => hasWatch.includes(neg))) {
1091
- return false;
1092
- }
1093
- // check for --watch false
1094
- const watchIndex = args.findIndex((arg) => arg.includes('watch'));
1095
- const watchArg = args[watchIndex + 1];
1096
- if (watchArg && watchArg === 'false') {
1097
- return false;
1098
- }
1099
- return true;
1202
+ * Removes leading / and query string from a url path
1203
+ * e.g. /foo.scss?direct&ngcomp=ng-c3153525609&e=0 returns foo.scss
1204
+ * @param id
1205
+ */
1206
+ function getFilenameFromPath(id) {
1207
+ try {
1208
+ return new URL(id, "http://localhost").pathname.replace(/^\//, "");
1209
+ } catch {
1210
+ const queryIndex = id.indexOf("?");
1211
+ return (queryIndex >= 0 ? id.slice(0, queryIndex) : id).replace(/^\//, "");
1212
+ }
1100
1213
  }
1214
+ //#endregion
1215
+ export { angular };
1216
+
1101
1217
  //# sourceMappingURL=angular-vite-plugin.js.map