@analogjs/vite-plugin-angular 3.0.0-beta.38 → 3.0.0-beta.39

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 (64) hide show
  1. package/package.json +1 -1
  2. package/src/lib/analog-plugin-interop.js +1 -1
  3. package/src/lib/angular-build-context.d.ts +215 -0
  4. package/src/lib/angular-build-context.js +361 -0
  5. package/src/lib/angular-build-context.js.map +1 -0
  6. package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
  7. package/src/lib/angular-build-optimizer-plugin.js +4 -2
  8. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  9. package/src/lib/angular-jit-plugin.d.ts +5 -3
  10. package/src/lib/angular-jit-plugin.js +14 -6
  11. package/src/lib/angular-jit-plugin.js.map +1 -1
  12. package/src/lib/angular-vite-plugin.d.ts +6 -124
  13. package/src/lib/angular-vite-plugin.js +8 -1276
  14. package/src/lib/angular-vite-plugin.js.map +1 -1
  15. package/src/lib/angular-vitest-plugin.d.ts +3 -2
  16. package/src/lib/angular-vitest-plugin.js +5 -3
  17. package/src/lib/angular-vitest-plugin.js.map +1 -1
  18. package/src/lib/companion-plugins.d.ts +7 -0
  19. package/src/lib/companion-plugins.js +38 -0
  20. package/src/lib/companion-plugins.js.map +1 -0
  21. package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
  22. package/src/lib/compilation-api/compilation-api-plugin.js +154 -285
  23. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  24. package/src/lib/component-styles-plugin.d.ts +52 -0
  25. package/src/lib/component-styles-plugin.js +353 -0
  26. package/src/lib/component-styles-plugin.js.map +1 -0
  27. package/src/lib/compose-angular-plugins.d.ts +12 -0
  28. package/src/lib/compose-angular-plugins.js +31 -0
  29. package/src/lib/compose-angular-plugins.js.map +1 -0
  30. package/src/lib/dev-server-mode-plugin.d.ts +7 -0
  31. package/src/lib/dev-server-mode-plugin.js +23 -0
  32. package/src/lib/dev-server-mode-plugin.js.map +1 -0
  33. package/src/lib/fast-compile-plugin.d.ts +3 -1
  34. package/src/lib/fast-compile-plugin.js +93 -49
  35. package/src/lib/fast-compile-plugin.js.map +1 -1
  36. package/src/lib/host.js +3 -3
  37. package/src/lib/live-reload-plugin.d.ts +3 -1
  38. package/src/lib/live-reload-plugin.js +11 -5
  39. package/src/lib/live-reload-plugin.js.map +1 -1
  40. package/src/lib/ngp-compile-plugin.d.ts +2 -1
  41. package/src/lib/ngp-compile-plugin.js +90 -24
  42. package/src/lib/ngp-compile-plugin.js.map +1 -1
  43. package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
  44. package/src/lib/ngtsc-compile-plugin.js +762 -0
  45. package/src/lib/ngtsc-compile-plugin.js.map +1 -0
  46. package/src/lib/nx-folder-plugin.d.ts +6 -5
  47. package/src/lib/nx-folder-plugin.js +12 -7
  48. package/src/lib/nx-folder-plugin.js.map +1 -1
  49. package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
  50. package/src/lib/plugins/file-replacements.plugin.js +1 -0
  51. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  52. package/src/lib/router-plugin.d.ts +5 -1
  53. package/src/lib/router-plugin.js +13 -4
  54. package/src/lib/router-plugin.js.map +1 -1
  55. package/src/lib/utils/compilation-shared.js +1 -1
  56. package/src/lib/utils/devkit.js +1 -1
  57. package/src/lib/utils/lsp-type-checker.js +1 -1
  58. package/src/lib/utils/plugin-config.d.ts +6 -8
  59. package/src/lib/utils/plugin-config.js +8 -4
  60. package/src/lib/utils/plugin-config.js.map +1 -1
  61. package/src/lib/utils/tsconfig-resolver.js +1 -1
  62. package/src/lib/virtual-modules-plugin.d.ts +11 -3
  63. package/src/lib/virtual-modules-plugin.js +43 -12
  64. package/src/lib/virtual-modules-plugin.js.map +1 -1
@@ -0,0 +1,762 @@
1
+ import { activateDeferredDebug, debugCompiler, debugCompilerV, debugEmit, debugEmitV, debugHmr, debugHmrV, debugStyles } from "./utils/debug.js";
2
+ import { isComponentStyleSheet } from "./encapsulation-plugin.js";
3
+ import { describeStylesheetContent, injectViteIgnoreForHmrMetadata } from "./utils/compilation-shared.js";
4
+ import { SourceFileCache, createJitResourceTransformer } from "./utils/devkit.js";
5
+ import { getJsTransformConfigKey } from "./utils/rolldown.js";
6
+ import { EXCLUDED_TS_EXT_REGEX, TS_EXT_REGEX, createDepOptimizerConfig } from "./utils/plugin-config.js";
7
+ import { createAngularBuildContext, isAngularBuildContext } from "./angular-build-context.js";
8
+ import { releaseCssPreprocessorWorkers } from "./utils/css-preprocessor-workers.js";
9
+ import { toJitInlineStyleId } from "./utils/jit-inline-styles.js";
10
+ import { findTemplateOwnerModules, getModulesForChangedFile, handleDirectComponentStyleHmr, isModuleForChangedResource, markModuleSelfAccepting } from "./component-styles-plugin.js";
11
+ import { markStylePathSafe } from "./utils/safe-module-paths.js";
12
+ import { toVirtualRawId } from "./utils/virtual-ids.js";
13
+ import { loadAngularVirtualModule, resolveAngularVirtualId } from "./virtual-modules-plugin.js";
14
+ import { createHotUpdateBatcher } from "./hot-update-batch.js";
15
+ import { StyleUrlsResolver, TemplateUrlsResolver } from "./component-resolvers.js";
16
+ import { augmentHostWithCaching, augmentHostWithModuleResolution, augmentHostWithResources, augmentProgramWithVersioning, mergeTransformers } from "./host.js";
17
+ import { union } from "es-toolkit";
18
+ import { mkdirSync, writeFileSync } from "node:fs";
19
+ import { createRequire } from "node:module";
20
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
21
+ import { normalizePath, preprocessCSS } from "vite";
22
+ import * as compilerCli from "@angular/compiler-cli";
23
+ //#region packages/vite-plugin-angular/src/lib/ngtsc-compile-plugin.ts
24
+ var require = createRequire(import.meta.url);
25
+ function evictDeletedFileMetadata(file, { classNamesMap, fileTransformMap }) {
26
+ const normalizedFile = normalizePath(file.split("?")[0]);
27
+ classNamesMap.delete(normalizedFile);
28
+ fileTransformMap.delete(normalizedFile);
29
+ }
30
+ function createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, performCompilation) {
31
+ return async () => {
32
+ invalidateFsCaches();
33
+ invalidateTsconfigCaches();
34
+ await performCompilation();
35
+ };
36
+ }
37
+ /**
38
+ * Compiles Angular TypeScript sources using `@angular/compiler-cli` (`NgtscProgram`).
39
+ */
40
+ function ngtscCompilePlugin(ctxOrOptions) {
41
+ const ctx = isAngularBuildContext(ctxOrOptions) ? ctxOrOptions : createAngularBuildContext({
42
+ ...ctxOrOptions,
43
+ compilationBackend: "ngtsc"
44
+ });
45
+ const ts = require("typescript");
46
+ let cachedBuilder;
47
+ let nextProgram;
48
+ let cachedHost;
49
+ let cachedHostKey;
50
+ function invalidateFsCaches() {
51
+ ctx.tsconfigResolver.invalidateIncludeCache();
52
+ }
53
+ function invalidateTsconfigCaches() {
54
+ ctx.tsconfigResolver.invalidateTsconfigCaches();
55
+ cachedHost = void 0;
56
+ cachedHostKey = void 0;
57
+ }
58
+ const sourceFileCache = new SourceFileCache();
59
+ const tsSourceFileCache = /* @__PURE__ */ new Map();
60
+ function invalidateSourceFiles(files) {
61
+ for (const file of files) tsSourceFileCache.delete(normalizePath(file));
62
+ sourceFileCache.invalidate(files);
63
+ }
64
+ const { jit, isTest } = ctx.options;
65
+ let viteServer;
66
+ const styleUrlsResolver = new StyleUrlsResolver();
67
+ const templateUrlsResolver = new TemplateUrlsResolver();
68
+ let outputFile;
69
+ const outputFiles = /* @__PURE__ */ new Map();
70
+ const normalizeEmitterLookupId = (file) => {
71
+ const normalizedFile = normalizePath(file);
72
+ if (!normalizedFile.startsWith("/@fs/")) return normalizedFile;
73
+ const fsPath = normalizedFile.slice(4).replace(/^\/([A-Za-z]:\/)/, "$1");
74
+ return normalizePath(fsPath);
75
+ };
76
+ const describeEmitMarkers = (content) => ({
77
+ contentLength: content.length,
78
+ hasCmp: content.includes("ɵcmp"),
79
+ hasFac: content.includes("ɵfac"),
80
+ hasProv: content.includes("ɵprov"),
81
+ hasDecorate: content.includes("__decorate"),
82
+ hasMetadata: content.includes("__metadata")
83
+ });
84
+ const fileEmitter = (file) => {
85
+ const normalizedFile = normalizeEmitterLookupId(file);
86
+ const hadCachedEmit = outputFiles.has(normalizedFile);
87
+ outputFile?.(normalizedFile);
88
+ const emittedResult = outputFiles.get(normalizedFile);
89
+ debugEmitV("fileEmitter lookup", {
90
+ requestFile: file,
91
+ normalizedFile,
92
+ hadCachedEmit,
93
+ hasOutputFileHook: !!outputFile,
94
+ emitted: !!emittedResult,
95
+ knownOutputCount: outputFiles.size,
96
+ contentLength: emittedResult?.content?.length ?? 0,
97
+ errorCount: emittedResult?.errors?.length ?? 0,
98
+ warningCount: emittedResult?.warnings?.length ?? 0
99
+ });
100
+ return emittedResult;
101
+ };
102
+ ctx.hmr.setFileEmitter((file) => fileEmitter(file));
103
+ const compilerApi = {
104
+ angularCompiler: true,
105
+ getTsConfigPath: () => ctx.resolveTsConfigPath(),
106
+ getSourceMap: (id) => outputFiles.get(normalizeEmitterLookupId(id))?.map,
107
+ hasEmitted: (id) => outputFiles.has(normalizeEmitterLookupId(id))
108
+ };
109
+ ctx.registerCompiler({
110
+ name: "@analogjs/vite-plugin-angular",
111
+ getTsConfigPath: compilerApi.getTsConfigPath,
112
+ getSourceMap: compilerApi.getSourceMap,
113
+ hasEmitted: compilerApi.hasEmitted
114
+ });
115
+ let initialCompilation = false;
116
+ let activeBuilds = 0;
117
+ let closeRequested = false;
118
+ const declarationFiles = [];
119
+ const fileTransformMap = /* @__PURE__ */ new Map();
120
+ let styleTransform;
121
+ let pendingCompilation = null;
122
+ let compilationLock = Promise.resolve();
123
+ const hotUpdates = createHotUpdateBatcher((ids) => performCompilation(ctx.resolvedConfig, ids));
124
+ function releaseCompilation() {
125
+ cachedBuilder = void 0;
126
+ nextProgram = void 0;
127
+ cachedHost = void 0;
128
+ cachedHostKey = void 0;
129
+ outputFile = void 0;
130
+ outputFiles.clear();
131
+ fileTransformMap.clear();
132
+ tsSourceFileCache.clear();
133
+ sourceFileCache.clear();
134
+ sourceFileCache.modifiedFiles.clear();
135
+ sourceFileCache.babelFileCache?.clear();
136
+ sourceFileCache.typeScriptFileCache?.clear();
137
+ sourceFileCache.referencedFiles = void 0;
138
+ ctx.tsconfigResolver.invalidateAll();
139
+ releaseCssPreprocessorWorkers();
140
+ ctx.styles.clear();
141
+ }
142
+ async function closeCompilation() {
143
+ closeRequested = false;
144
+ hotUpdates.close();
145
+ await compilationLock;
146
+ declarationFiles.forEach(({ declarationFileDir, declarationPath, data }) => {
147
+ mkdirSync(declarationFileDir, { recursive: true });
148
+ writeFileSync(declarationPath, data, "utf-8");
149
+ });
150
+ declarationFiles.length = 0;
151
+ releaseCompilation();
152
+ }
153
+ function normalizeSourceMapSources(map, id) {
154
+ const sourceMap = JSON.parse(map);
155
+ const sourceDirectory = dirname(id);
156
+ const sourceRoot = sourceMap.sourceRoot ?? "";
157
+ sourceMap.sources = sourceMap.sources?.map((source) => {
158
+ if (isAbsolute(source) || /^[a-z][a-z\d+.-]*:/i.test(source)) return normalizePath(source);
159
+ return normalizePath(resolve(sourceDirectory, sourceRoot, source));
160
+ });
161
+ delete sourceMap.sourceRoot;
162
+ return JSON.stringify(sourceMap);
163
+ }
164
+ async function performCompilation(config, ids) {
165
+ let releaseLock;
166
+ const previousLock = compilationLock;
167
+ compilationLock = new Promise((r) => {
168
+ releaseLock = r;
169
+ });
170
+ try {
171
+ await previousLock;
172
+ await ctx.refreshIntegrations(config);
173
+ await _doPerformCompilation(config, ids);
174
+ } finally {
175
+ releaseLock();
176
+ }
177
+ }
178
+ /**
179
+ * This method shares mutable state and performs the actual compilation work.
180
+ * It should not be called concurrently. Use `performCompilation` which wraps
181
+ * this method in a lock to ensure only one compilation runs at a time.
182
+ */
183
+ async function _doPerformCompilation(config, ids) {
184
+ const isProd = config.mode === "production";
185
+ invalidateSourceFiles(new Set(ids ?? []));
186
+ if (ids?.length) for (const id of ids) fileTransformMap.delete(id);
187
+ const resolvedTsConfigPath = ctx.resolveTsConfigPath();
188
+ const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(resolvedTsConfigPath, config);
189
+ const tsCompilerOptions = { ...cached.options };
190
+ let rootNames = [...cached.rootNames];
191
+ if (ctx.shouldExternalizeStyles()) tsCompilerOptions["externalRuntimeStyles"] = true;
192
+ if (ctx.shouldEnableLiveReload()) {
193
+ tsCompilerOptions["_enableHmr"] = true;
194
+ tsCompilerOptions["supportTestBed"] = true;
195
+ }
196
+ debugCompiler("tsCompilerOptions (NgtscProgram path)", {
197
+ liveReload: ctx.options.liveReload,
198
+ viteHmr: ctx.hasViteHmrTransport(),
199
+ externalizeStylesRequested: ctx.externalizeStylesRequested,
200
+ shouldExternalize: ctx.shouldExternalizeStyles(),
201
+ externalRuntimeStyles: !!tsCompilerOptions["externalRuntimeStyles"],
202
+ hmrEnabled: !!tsCompilerOptions["_enableHmr"]
203
+ });
204
+ if (tsCompilerOptions["compilationMode"] === "partial") {
205
+ tsCompilerOptions["supportTestBed"] = true;
206
+ tsCompilerOptions["supportJitMode"] = true;
207
+ }
208
+ if (!isTest && config.build?.lib) {
209
+ tsCompilerOptions["declaration"] = true;
210
+ tsCompilerOptions["declarationMap"] = ctx.watchMode;
211
+ tsCompilerOptions["inlineSources"] = true;
212
+ }
213
+ if (isTest) tsCompilerOptions["supportTestBed"] = true;
214
+ const replacements = ctx.options.fileReplacements.map((rp) => join(ctx.options.workspaceRoot, rp.ssr || rp.with));
215
+ rootNames = union(union(rootNames, ctx.tsconfigResolver.ensureIncludeCache()), replacements);
216
+ const hostKey = JSON.stringify(tsCompilerOptions);
217
+ let host;
218
+ if (cachedHost && cachedHostKey === hostKey) host = cachedHost;
219
+ else {
220
+ host = ts.createIncrementalCompilerHost(tsCompilerOptions, {
221
+ ...ts.sys,
222
+ readFile(path, encoding) {
223
+ if (fileTransformMap.has(path)) return fileTransformMap.get(path);
224
+ const file = ts.sys.readFile.call(null, path, encoding);
225
+ if (file) fileTransformMap.set(path, file);
226
+ return file;
227
+ }
228
+ });
229
+ augmentHostWithModuleResolution(host, tsCompilerOptions);
230
+ cachedHost = host;
231
+ cachedHostKey = hostKey;
232
+ if (ctx.watchMode) augmentHostWithCaching(host, tsSourceFileCache);
233
+ }
234
+ if (!jit) {
235
+ const externalizeStyles = !!tsCompilerOptions["externalRuntimeStyles"];
236
+ const stylesheetRegistry = ctx.styles.resetRegistry(externalizeStyles);
237
+ debugStyles("stylesheet registry initialized (NgtscProgram path)", { externalizeStyles });
238
+ augmentHostWithResources(host, styleTransform, {
239
+ inlineStylesExtension: ctx.options.inlineStylesExtension,
240
+ isProd,
241
+ stylesheetRegistry,
242
+ sourceFileCache,
243
+ stylePreprocessor: ctx.stylePreprocessor,
244
+ logger: ctx.resolvedConfig?.logger
245
+ });
246
+ }
247
+ /**
248
+ * Creates a new NgtscProgram to analyze/re-analyze
249
+ * the source files and create a file emitter.
250
+ * This is shared between an initial build and a hot update.
251
+ */
252
+ let typeScriptProgram;
253
+ let angularCompiler;
254
+ let builder;
255
+ const oldBuilder = ids?.some((id) => EXCLUDED_TS_EXT_REGEX.test(id)) ? void 0 : cachedBuilder ?? ts.readBuilderProgram(tsCompilerOptions, host);
256
+ if (!jit) {
257
+ const angularProgram = new compilerCli.NgtscProgram(rootNames, tsCompilerOptions, host, nextProgram);
258
+ angularCompiler = angularProgram.compiler;
259
+ typeScriptProgram = angularProgram.compiler.getCurrentProgram();
260
+ augmentProgramWithVersioning(typeScriptProgram);
261
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, oldBuilder);
262
+ nextProgram = angularProgram;
263
+ } else {
264
+ builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, tsCompilerOptions, host, oldBuilder);
265
+ typeScriptProgram = builder.getProgram();
266
+ }
267
+ if (!ctx.watchMode) builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);
268
+ cachedBuilder = builder;
269
+ if (angularCompiler) {
270
+ await angularCompiler.analyzeAsync();
271
+ if (!ctx.options.disableTypeChecking) typeScriptProgram.getOptionsDiagnostics();
272
+ }
273
+ const beforeTransformers = jit ? [compilerCli.constructorParametersDownlevelTransform(builder.getProgram()), createJitResourceTransformer(() => builder.getProgram().getTypeChecker())] : [];
274
+ const transformers = mergeTransformers({ before: beforeTransformers }, jit ? {} : angularCompiler.prepareEmit().transformers);
275
+ const fileMetadata = getFileMetadata(builder, angularCompiler, ctx.options.liveReload, ctx.options.disableTypeChecking, ctx.hmr.classNames);
276
+ const writeFileCallback = (_filename, content, _a, _b, sourceFiles) => {
277
+ if (!sourceFiles?.length) return;
278
+ const filename = normalizePath(sourceFiles[0].fileName);
279
+ if (filename.includes("ngtypecheck.ts") || filename.includes(".d.") || _filename.endsWith(".d.ts") || _filename.endsWith(".d.mts") || _filename.endsWith(".d.cts")) return;
280
+ if (/\.[cm]?js\.map$/.test(_filename)) {
281
+ const existing = outputFiles.get(filename);
282
+ outputFiles.set(filename, {
283
+ ...existing ?? { dependencies: [] },
284
+ map: content
285
+ });
286
+ return;
287
+ }
288
+ const metadata = ctx.watchMode ? fileMetadata(filename) : {};
289
+ const existing = outputFiles.get(filename);
290
+ outputFiles.set(filename, {
291
+ ...existing ?? {},
292
+ content,
293
+ dependencies: [],
294
+ errors: metadata.errors,
295
+ warnings: metadata.warnings,
296
+ hmrUpdateCode: metadata.hmrUpdateCode,
297
+ hmrEligible: metadata.hmrEligible
298
+ });
299
+ debugEmitV("registered ngtsc output", {
300
+ filename,
301
+ ...describeEmitMarkers(content),
302
+ errorCount: metadata.errors?.length ?? 0,
303
+ warningCount: metadata.warnings?.length ?? 0,
304
+ hmrEligible: !!metadata.hmrEligible,
305
+ knownOutputCount: outputFiles.size
306
+ });
307
+ };
308
+ const writeOutputFile = (id) => {
309
+ const sourceFile = builder.getSourceFile(id);
310
+ if (!sourceFile) return;
311
+ let content = "";
312
+ let map;
313
+ let mapFilename;
314
+ builder.emit(sourceFile, (filename, data) => {
315
+ if (/\.[cm]?js$/.test(filename)) content = data;
316
+ if (/\.[cm]?js\.map$/.test(filename)) {
317
+ map = data;
318
+ mapFilename = filename;
319
+ }
320
+ if (!ctx.watchMode && !isTest && /\.d\.ts/.test(filename) && !filename.includes(".ngtypecheck.")) {
321
+ const declarationPath = resolve(config.root, config.build.outDir, relative(config.root, filename)).replace("/src/", "/");
322
+ const declarationFileDir = declarationPath.replace(basename(filename), "").replace("/src/", "/");
323
+ declarationFiles.push({
324
+ declarationFileDir,
325
+ declarationPath,
326
+ data
327
+ });
328
+ }
329
+ }, void 0, void 0, transformers);
330
+ writeFileCallback(id, content, false, void 0, [sourceFile]);
331
+ if (map !== void 0 && mapFilename !== void 0) writeFileCallback(mapFilename, map, false, void 0, [sourceFile]);
332
+ if (angularCompiler) angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
333
+ };
334
+ if (ctx.watchMode) {
335
+ if (ids && ids.length > 0) ids.forEach((id) => writeOutputFile(id));
336
+ else if (isTest)
337
+ /**
338
+ * Only block the server from starting up
339
+ * during testing.
340
+ */
341
+ while (builder.emitNextAffectedFile(writeFileCallback, void 0, void 0, transformers));
342
+ }
343
+ if (!isTest)
344
+ /**
345
+ * Perf: Output files on demand so the dev server
346
+ * isn't blocked when emitting files.
347
+ */
348
+ outputFile = writeOutputFile;
349
+ }
350
+ return {
351
+ name: "@analogjs/vite-plugin-angular",
352
+ api: compilerApi,
353
+ async config(config, { command, mode }) {
354
+ activateDeferredDebug(command);
355
+ const resolution = ctx.initConfig(config, {
356
+ command,
357
+ mode
358
+ });
359
+ const preliminaryTsConfigPath = ctx.resolveTsConfigPath();
360
+ const esbuild = config.esbuild ?? false;
361
+ const oxc = config.oxc ?? false;
362
+ const jsTransformConfigKey = getJsTransformConfigKey();
363
+ const jsTransformConfigValue = jsTransformConfigKey === "oxc" ? oxc : esbuild;
364
+ const depOptimizer = createDepOptimizerConfig({
365
+ tsconfig: preliminaryTsConfigPath,
366
+ isProd: resolution.isProd,
367
+ jit: ctx.options.jit,
368
+ watchMode: ctx.watchMode,
369
+ isTest: ctx.options.isTest,
370
+ isAstroIntegration: ctx.options.isAstroIntegration
371
+ });
372
+ return {
373
+ [jsTransformConfigKey]: jsTransformConfigValue,
374
+ ...depOptimizer
375
+ };
376
+ },
377
+ configResolved(config) {
378
+ ctx.setResolvedConfig(config);
379
+ if (!jit) styleTransform = (code, filename) => preprocessCSS(code, filename, config);
380
+ },
381
+ configureServer(server) {
382
+ viteServer = server;
383
+ hotUpdates.configureServer(server);
384
+ const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(invalidateFsCaches, invalidateTsconfigCaches, () => performCompilation(ctx.resolvedConfig));
385
+ server.watcher.on("add", (file) => {
386
+ if (EXCLUDED_TS_EXT_REGEX.test(file)) invalidateSourceFiles(/* @__PURE__ */ new Set([normalizePath(file)]));
387
+ return invalidateCompilationOnFsChange();
388
+ });
389
+ server.watcher.on("unlink", (file) => {
390
+ const id = normalizePath(file);
391
+ outputFiles.delete(id);
392
+ tsSourceFileCache.delete(id);
393
+ sourceFileCache.invalidate(/* @__PURE__ */ new Set([id]));
394
+ evictDeletedFileMetadata(file, {
395
+ classNamesMap: ctx.hmr.classNames,
396
+ fileTransformMap
397
+ });
398
+ return invalidateCompilationOnFsChange();
399
+ });
400
+ server.watcher.on("change", (file) => {
401
+ if (file.includes("tsconfig")) invalidateTsconfigCaches();
402
+ });
403
+ },
404
+ async buildStart() {
405
+ activeBuilds++;
406
+ if (!jit) styleTransform = (code, filename) => preprocessCSS(code, filename, ctx.resolvedConfig);
407
+ if (!ctx.deferInitialCompilation) {
408
+ pendingCompilation = performCompilation(this.environment?.config ?? ctx.resolvedConfig);
409
+ await pendingCompilation;
410
+ pendingCompilation = null;
411
+ initialCompilation = true;
412
+ }
413
+ },
414
+ async buildEnd() {
415
+ activeBuilds = Math.max(0, activeBuilds - 1);
416
+ if (activeBuilds > 0) return;
417
+ if (closeRequested) {
418
+ await closeCompilation();
419
+ return;
420
+ }
421
+ if (!ctx.watchMode) releaseCompilation();
422
+ },
423
+ async handleHotUpdate(hmrCtx) {
424
+ if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {
425
+ debugHmr("ignored file change", { file: hmrCtx.file });
426
+ return [];
427
+ }
428
+ if (TS_EXT_REGEX.test(hmrCtx.file)) {
429
+ const [fileId] = hmrCtx.file.split("?");
430
+ debugHmr("TS file changed", {
431
+ file: hmrCtx.file,
432
+ fileId
433
+ });
434
+ await hotUpdates.schedule(hmrCtx.file, [fileId]);
435
+ if (EXCLUDED_TS_EXT_REGEX.test(fileId)) {
436
+ hmrCtx.server.moduleGraph.invalidateAll();
437
+ hmrCtx.server.ws.send({
438
+ type: "full-reload",
439
+ triggeredBy: fileId
440
+ });
441
+ return [];
442
+ }
443
+ let result;
444
+ if (ctx.shouldEnableLiveReload()) {
445
+ result = fileEmitter(fileId);
446
+ debugHmr("TS file emitted", {
447
+ fileId,
448
+ hmrEligible: !!result?.hmrEligible,
449
+ hasClassName: !!ctx.hmr.classNames.get(fileId)
450
+ });
451
+ debugHmrV("ts hmr evaluation", {
452
+ file: hmrCtx.file,
453
+ fileId,
454
+ hasResult: !!result,
455
+ hmrEligible: !!result?.hmrEligible,
456
+ hasClassName: !!ctx.hmr.classNames.get(fileId),
457
+ className: ctx.hmr.classNames.get(fileId),
458
+ updateCode: result?.hmrUpdateCode ? describeStylesheetContent(result.hmrUpdateCode) : void 0,
459
+ errors: result?.errors?.length ?? 0,
460
+ warnings: result?.warnings?.length ?? 0,
461
+ 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."
462
+ });
463
+ }
464
+ if (ctx.shouldEnableLiveReload() && result?.hmrEligible && ctx.hmr.classNames.get(fileId)) {
465
+ const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);
466
+ debugHmr("sending component update", { relativeFileId });
467
+ debugHmrV("ts hmr component update payload", {
468
+ file: hmrCtx.file,
469
+ fileId,
470
+ relativeFileId,
471
+ className: ctx.hmr.classNames.get(fileId)
472
+ });
473
+ ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);
474
+ return hmrCtx.modules.map((mod) => {
475
+ if (mod.id === hmrCtx.file) return markModuleSelfAccepting(mod);
476
+ return mod;
477
+ });
478
+ }
479
+ }
480
+ if (/\.(html|htm|css|less|sass|scss)$/.test(hmrCtx.file)) {
481
+ debugHmr("resource file changed", { file: hmrCtx.file });
482
+ fileTransformMap.delete(hmrCtx.file.split("?")[0]);
483
+ const stylesheetRegistry = ctx.styles.registry;
484
+ const fileModules = await getModulesForChangedFile(hmrCtx.server, hmrCtx.file, hmrCtx.modules, stylesheetRegistry);
485
+ /**
486
+ * Check to see if this was a direct request
487
+ * for an external resource (styles, html).
488
+ */
489
+ const isDirect = fileModules.find((mod) => !!mod.id && mod.id.includes("?direct") && isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry));
490
+ const isInline = fileModules.find((mod) => !!mod.id && mod.id.includes("?inline") && isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry));
491
+ debugHmrV("resource direct/inline detection", {
492
+ file: hmrCtx.file,
493
+ hasDirect: !!isDirect,
494
+ directId: isDirect?.id,
495
+ hasInline: !!isInline,
496
+ inlineId: isInline?.id
497
+ });
498
+ if (isDirect || isInline) {
499
+ if (ctx.shouldExternalizeStyles() && isDirect?.id && isDirect.file) {
500
+ const isComponentStyle = isDirect.type === "css" && isComponentStyleSheet(isDirect.id);
501
+ debugHmrV("resource direct branch", {
502
+ file: hmrCtx.file,
503
+ directId: isDirect.id,
504
+ directType: isDirect.type,
505
+ shouldExternalize: ctx.shouldExternalizeStyles(),
506
+ isComponentStyle
507
+ });
508
+ if (isComponentStyle) return handleDirectComponentStyleHmr({
509
+ server: hmrCtx.server,
510
+ file: hmrCtx.file,
511
+ directModule: isDirect,
512
+ fileModules,
513
+ stylesheetRegistry,
514
+ stylePreprocessor: ctx.stylePreprocessor
515
+ });
516
+ }
517
+ return fileModules;
518
+ }
519
+ if (ctx.shouldEnableLiveReload() && /\.(html|htm)$/.test(hmrCtx.file) && fileModules.length === 0) {
520
+ const ownerModules = findTemplateOwnerModules(hmrCtx.server, hmrCtx.file);
521
+ debugHmrV("template owner lookup", {
522
+ file: hmrCtx.file,
523
+ ownerCount: ownerModules.length,
524
+ ownerIds: ownerModules.map((mod) => mod.id),
525
+ 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."
526
+ });
527
+ if (ownerModules.length > 0) {
528
+ const ownerIds = ownerModules.map((mod) => mod.id).filter(Boolean);
529
+ ownerModules.forEach((mod) => hmrCtx.server.moduleGraph.invalidateModule(mod));
530
+ await hotUpdates.schedule(hmrCtx.file, ownerIds);
531
+ const updates = ownerIds.filter((id) => ctx.hmr.classNames.get(id));
532
+ debugHmrV("template owner recompilation result", {
533
+ file: hmrCtx.file,
534
+ ownerIds,
535
+ updates,
536
+ updateClassNames: updates.map((id) => ({
537
+ id,
538
+ className: ctx.hmr.classNames.get(id)
539
+ })),
540
+ hint: updates.length > 0 ? "External template recompilation produced Angular component update targets." : "External template recompilation completed, but no Angular component update targets were surfaced."
541
+ });
542
+ if (updates.length > 0) {
543
+ debugHmr("template owner module invalidation", {
544
+ file: hmrCtx.file,
545
+ ownerIds,
546
+ updateCount: updates.length
547
+ });
548
+ updates.forEach((updateId) => {
549
+ ctx.hmr.sendComponentUpdate(hmrCtx.server, ctx.hmr.toComponentUpdateId(updateId));
550
+ });
551
+ return ownerModules.map((mod) => markModuleSelfAccepting(mod));
552
+ }
553
+ }
554
+ }
555
+ const mods = [];
556
+ const updates = [];
557
+ fileModules.forEach((mod) => {
558
+ mod.importers.forEach((imp) => {
559
+ hmrCtx.server.moduleGraph.invalidateModule(imp);
560
+ if (ctx.shouldExternalizeStyles() && imp.id && ctx.hmr.classNames.get(imp.id)) updates.push(imp.id);
561
+ else mods.push(imp);
562
+ });
563
+ });
564
+ debugHmrV("resource importer analysis", {
565
+ file: hmrCtx.file,
566
+ fileModuleCount: fileModules.length,
567
+ importerCount: fileModules.reduce((count, mod) => count + mod.importers.size, 0),
568
+ updates,
569
+ mods: mods.map((mod) => mod.id)
570
+ });
571
+ if (mods.length === 0 && updates.length === 0) return mods;
572
+ await hotUpdates.schedule(hmrCtx.file, [...mods.map((mod) => mod.id), ...updates]);
573
+ if (updates.length > 0) {
574
+ debugHmr("resource importer component updates", {
575
+ file: hmrCtx.file,
576
+ updateCount: updates.length
577
+ });
578
+ updates.forEach((updateId) => {
579
+ ctx.hmr.sendComponentUpdate(hmrCtx.server, ctx.hmr.toComponentUpdateId(updateId));
580
+ });
581
+ return fileModules.map((mod) => {
582
+ if (mod.id === hmrCtx.file) return markModuleSelfAccepting(mod);
583
+ return mod;
584
+ });
585
+ }
586
+ return mods;
587
+ }
588
+ debugHmr("full reload — unrecognized file type", { file: hmrCtx.file });
589
+ ctx.hmr.clear();
590
+ return hmrCtx.modules;
591
+ },
592
+ resolveId(id, importer) {
593
+ const virtualId = resolveAngularVirtualId(id, importer, {
594
+ jit,
595
+ resolvedConfig: ctx.resolvedConfig
596
+ });
597
+ if (virtualId !== void 0) return virtualId;
598
+ return ctx.styles.resolveComponentStyleId(id);
599
+ },
600
+ async load(id) {
601
+ const virtualModule = await loadAngularVirtualModule(this, id, ctx.resolvedConfig);
602
+ if (virtualModule !== void 0) return virtualModule;
603
+ return ctx.styles.loadComponentStyle(id);
604
+ },
605
+ transform: {
606
+ filter: { id: {
607
+ include: [TS_EXT_REGEX],
608
+ exclude: [
609
+ /node_modules/,
610
+ "type=script",
611
+ "@ng/component"
612
+ ]
613
+ } },
614
+ async handler(code, id) {
615
+ if (ctx.transformFilter && !ctx.transformFilter(code, id)) return;
616
+ if (id.includes(".ts?")) id = id.replace(/\?(.*)/, "");
617
+ fileTransformMap.set(id, code);
618
+ /**
619
+ * Re-analyze on each transform
620
+ * for test(Vitest)
621
+ */
622
+ if (isTest) {
623
+ if (ctx.deferInitialCompilation && !initialCompilation) {
624
+ pendingCompilation = performCompilation(this.environment?.config ?? ctx.resolvedConfig);
625
+ initialCompilation = true;
626
+ }
627
+ const tsMod = viteServer?.moduleGraph.getModuleById(id);
628
+ if (tsMod) {
629
+ const invalidated = tsMod.lastInvalidationTimestamp;
630
+ if (ctx.testWatchMode && invalidated) pendingCompilation = performCompilation(this.environment?.config ?? ctx.resolvedConfig, [id]);
631
+ }
632
+ }
633
+ const hasComponent = code.includes("@Component");
634
+ debugCompilerV("transform", {
635
+ id,
636
+ codeLength: code.length,
637
+ hasComponent
638
+ });
639
+ const resolveResourceUrls = hasComponent && (ctx.watchMode || jit);
640
+ const templateUrls = resolveResourceUrls ? templateUrlsResolver.resolve(code, id) : [];
641
+ const styleUrls = resolveResourceUrls ? styleUrlsResolver.resolve(code, id) : [];
642
+ if (resolveResourceUrls && ctx.watchMode) for (const urlSet of [...templateUrls, ...styleUrls]) {
643
+ const [, absoluteFileUrl] = urlSet.split("|");
644
+ this.addWatchFile(absoluteFileUrl);
645
+ }
646
+ if (pendingCompilation) {
647
+ await pendingCompilation;
648
+ pendingCompilation = null;
649
+ }
650
+ await hotUpdates.wait();
651
+ const typescriptResult = fileEmitter(id);
652
+ if (!typescriptResult) {
653
+ debugCompilerV("transform skip (file not emitted by Angular)", { id });
654
+ const isAngular = !id.includes("@ng/component") && /(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
655
+ debugEmit("transform emit miss", {
656
+ id,
657
+ normalizedId: normalizeEmitterLookupId(id),
658
+ knownOutputCount: outputFiles.size,
659
+ hasOutputFileHook: !!outputFile,
660
+ isAngular
661
+ });
662
+ 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.`);
663
+ return;
664
+ }
665
+ if (typescriptResult.warnings && typescriptResult.warnings.length > 0) this.warn(`${typescriptResult.warnings.join("\n")}`);
666
+ if (typescriptResult.errors && typescriptResult.errors.length > 0) this.error(`${typescriptResult.errors.join("\n")}`);
667
+ let data = typescriptResult.content ?? "";
668
+ debugEmitV("transform emit hit", {
669
+ id,
670
+ normalizedId: normalizeEmitterLookupId(id),
671
+ ...describeEmitMarkers(data),
672
+ errorCount: typescriptResult.errors?.length ?? 0,
673
+ warningCount: typescriptResult.warnings?.length ?? 0
674
+ });
675
+ if (jit && data.includes("angular:jit:")) {
676
+ data = data.replace(/angular:jit:style:inline;([A-Za-z0-9+/=]*)/g, (_match, encodedStyles) => toJitInlineStyleId(encodedStyles, isTest));
677
+ templateUrls.forEach((templateUrlSet) => {
678
+ const [templateFile, resolvedTemplateUrl] = templateUrlSet.split("|");
679
+ data = data.replace(`angular:jit:template:file;${templateFile}`, toVirtualRawId(resolvedTemplateUrl));
680
+ });
681
+ styleUrls.forEach((styleUrlSet) => {
682
+ const [styleFile, resolvedStyleUrl] = styleUrlSet.split("|");
683
+ markStylePathSafe(ctx.resolvedConfig, resolvedStyleUrl);
684
+ data = data.replace(`angular:jit:style:file;${styleFile}`, resolvedStyleUrl + "?inline");
685
+ });
686
+ }
687
+ if (data.includes("HmrLoad")) {
688
+ const hasMetaUrl = data.includes("getReplaceMetadataURL");
689
+ debugHmrV("vite-ignore injection", {
690
+ id,
691
+ dataLength: data.length,
692
+ hasMetaUrl
693
+ });
694
+ if (hasMetaUrl) {
695
+ const patched = injectViteIgnoreForHmrMetadata(data);
696
+ if (patched !== data && !patched.includes("@vite-ignore")) debugHmrV("vite-ignore regex fallback", { id });
697
+ data = patched;
698
+ }
699
+ }
700
+ if (typescriptResult.map) data = data.replace(/\s*\/\/# sourceMappingURL=[^\r\n]*\s*$/, "");
701
+ return {
702
+ code: data,
703
+ map: typescriptResult.map ? normalizeSourceMapSources(typescriptResult.map, id) : null
704
+ };
705
+ }
706
+ },
707
+ async closeBundle() {
708
+ closeRequested = true;
709
+ if (activeBuilds === 0) await closeCompilation();
710
+ }
711
+ };
712
+ }
713
+ /**
714
+ * @internal
715
+ */
716
+ function getFileMetadata(program, angularCompiler, hmrEnabled, disableTypeChecking, classNamesMap = /* @__PURE__ */ new Map()) {
717
+ const ts = require("typescript");
718
+ return (file) => {
719
+ const sourceFile = program.getSourceFile(file);
720
+ if (!sourceFile) return {};
721
+ const diagnostics = getDiagnosticsForSourceFile(sourceFile, !!disableTypeChecking, program, angularCompiler);
722
+ const errors = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Error).map((d) => typeof d.messageText === "object" ? d.messageText.messageText : d.messageText);
723
+ const warnings = diagnostics.filter((d) => d.category === ts.DiagnosticCategory?.Warning).map((d) => d.messageText);
724
+ let hmrUpdateCode = void 0;
725
+ let hmrEligible = false;
726
+ if (hmrEnabled) {
727
+ for (const node of sourceFile.statements) if (ts.isClassDeclaration(node) && node.name != null) {
728
+ hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);
729
+ if (hmrUpdateCode) {
730
+ const className = node.name.getText();
731
+ classNamesMap.set(file, className);
732
+ hmrEligible = true;
733
+ debugHmr("NgtscProgram emitHmrUpdateModule", {
734
+ file,
735
+ className
736
+ });
737
+ }
738
+ }
739
+ }
740
+ return {
741
+ errors,
742
+ warnings,
743
+ hmrUpdateCode,
744
+ hmrEligible
745
+ };
746
+ };
747
+ }
748
+ function getDiagnosticsForSourceFile(sourceFile, disableTypeChecking, program, angularCompiler) {
749
+ const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
750
+ if (disableTypeChecking) return syntacticDiagnostics;
751
+ const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
752
+ const angularDiagnostics = angularCompiler ? angularCompiler.getDiagnosticsForFile(sourceFile, 1) : [];
753
+ return [
754
+ ...syntacticDiagnostics,
755
+ ...semanticDiagnostics,
756
+ ...angularDiagnostics
757
+ ];
758
+ }
759
+ //#endregion
760
+ export { createFsWatcherCacheInvalidator, evictDeletedFileMetadata, getFileMetadata, ngtscCompilePlugin };
761
+
762
+ //# sourceMappingURL=ngtsc-compile-plugin.js.map