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