@analogjs/vite-plugin-angular 3.0.0-beta.2 → 3.0.0-beta.21
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 +40 -0
- package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +13 -2
- package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
- package/ngp/LICENSE +21 -0
- package/ngp/api.mjs +46048 -0
- package/ngp/build.json +4 -0
- package/ngp/ng_analyze.cjs +504 -0
- package/ngp/ng_analyze_bg.wasm +0 -0
- package/package.json +1 -14
- package/src/lib/angular-build-optimizer-plugin.js +6 -3
- package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
- package/src/lib/angular-vite-plugin.d.ts +20 -5
- package/src/lib/angular-vite-plugin.js +28 -13
- package/src/lib/angular-vite-plugin.js.map +1 -1
- package/src/lib/compiler/compile.js +5 -2
- package/src/lib/compiler/compile.js.map +1 -1
- package/src/lib/compiler/dts-reader.d.ts +5 -0
- package/src/lib/compiler/dts-reader.js +9 -3
- package/src/lib/compiler/dts-reader.js.map +1 -1
- package/src/lib/compiler/hmr.d.ts +4 -0
- package/src/lib/compiler/hmr.js +7 -2
- package/src/lib/compiler/hmr.js.map +1 -1
- package/src/lib/compiler/index.d.ts +2 -2
- package/src/lib/compiler/index.js +3 -3
- package/src/lib/compiler/jit-metadata.d.ts +3 -1
- package/src/lib/compiler/jit-metadata.js +10 -8
- package/src/lib/compiler/jit-metadata.js.map +1 -1
- package/src/lib/compiler/registry.d.ts +6 -0
- package/src/lib/compiler/registry.js +21 -1
- package/src/lib/compiler/registry.js.map +1 -1
- package/src/lib/fast-compile-plugin.d.ts +3 -0
- package/src/lib/fast-compile-plugin.js +97 -15
- package/src/lib/fast-compile-plugin.js.map +1 -1
- package/src/lib/live-reload-plugin.d.ts +4 -3
- package/src/lib/live-reload-plugin.js +4 -3
- package/src/lib/live-reload-plugin.js.map +1 -1
- package/src/lib/ngp-compile-plugin.d.ts +3 -0
- package/src/lib/ngp-compile-plugin.js +344 -0
- package/src/lib/ngp-compile-plugin.js.map +1 -0
- package/src/lib/tools/src/builders/vite/vite-build.impl.js +2 -1
- package/src/lib/tools/src/builders/vite/vite-build.impl.js.map +1 -1
- package/src/lib/utils/hmr-component-updates.d.ts +7 -0
- package/src/lib/utils/hmr-component-updates.js +87 -0
- package/src/lib/utils/hmr-component-updates.js.map +1 -0
- package/src/lib/utils/lsp-type-checker.d.ts +55 -0
- package/src/lib/utils/lsp-type-checker.js +502 -0
- package/src/lib/utils/lsp-type-checker.js.map +1 -0
- package/src/lib/utils/plugin-config.d.ts +9 -0
- package/src/lib/utils/plugin-config.js +10 -1
- package/src/lib/utils/plugin-config.js.map +1 -1
- package/migrations/migrations.json +0 -9
- package/migrations/update-3-0-0/migrate-setup-vitest.d.ts +0 -2
- package/migrations/update-3-0-0/migrate-setup-vitest.js +0 -37
- package/migrations/update-3-0-0/migrate-setup-vitest.js.map +0 -1
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { angularFullVersion } from "./utils/devkit.js";
|
|
2
|
+
import { TS_EXT_REGEX, createDepOptimizerConfig, getTsConfigPath, isProdMode } from "./utils/plugin-config.js";
|
|
3
|
+
import { discoverAnalogIntegrations } from "./analog-plugin-interop.js";
|
|
4
|
+
import { releaseCssPreprocessorWorkers } from "./utils/css-preprocessor-workers.js";
|
|
5
|
+
import { findHmrComponentUpdates } from "./utils/hmr-component-updates.js";
|
|
6
|
+
import { LspTypeChecker } from "./utils/lsp-type-checker.js";
|
|
7
|
+
import { resolve } from "node:path";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import * as vite from "vite";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
//#region packages/vite-plugin-angular/src/lib/ngp-compile-plugin.ts
|
|
12
|
+
var BUNDLED_NGP = new URL("../../ngp/", "" + import.meta.url);
|
|
13
|
+
async function loadNgp(tsconfig) {
|
|
14
|
+
const nativeBinding = process.env["ANALOG_NGP_NATIVE_BINDING"];
|
|
15
|
+
let modulePath = process.env["ANALOG_NGP_COMPILER"];
|
|
16
|
+
if (!modulePath) try {
|
|
17
|
+
modulePath = createRequire(tsconfig).resolve("@angular/ngp");
|
|
18
|
+
} catch {
|
|
19
|
+
if (angularFullVersion < 220200) throw new Error("[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.");
|
|
20
|
+
return {
|
|
21
|
+
api: await import(new URL("api.mjs", BUNDLED_NGP).href),
|
|
22
|
+
analyzerOptions: nativeBinding ? { nativeBinding } : {
|
|
23
|
+
backend: "wasm",
|
|
24
|
+
wasmBinding: fileURLToPath(new URL("ng_analyze.cjs", BUNDLED_NGP))
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
api: await import(pathToFileURL(resolve(modulePath)).href),
|
|
30
|
+
analyzerOptions: nativeBinding ? { nativeBinding } : {}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function transpile(source, filePath, map) {
|
|
34
|
+
return vite.transformWithOxc ? vite.transformWithOxc(source, filePath, {
|
|
35
|
+
lang: "ts",
|
|
36
|
+
sourcemap: true
|
|
37
|
+
}, map) : vite.transformWithEsbuild(source, filePath, {
|
|
38
|
+
loader: "ts",
|
|
39
|
+
sourcemap: true
|
|
40
|
+
}, map);
|
|
41
|
+
}
|
|
42
|
+
function ngpCompilePlugin(options) {
|
|
43
|
+
if (options.jit || options.fastCompileMode === "partial") throw new Error("compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.");
|
|
44
|
+
let configContext;
|
|
45
|
+
let resolvedConfig;
|
|
46
|
+
let transformFilter;
|
|
47
|
+
let watchMode = false;
|
|
48
|
+
let hmr = false;
|
|
49
|
+
let activeBuilds = 0;
|
|
50
|
+
let analyzer;
|
|
51
|
+
let compiler;
|
|
52
|
+
let typeChecker;
|
|
53
|
+
let api;
|
|
54
|
+
const filesByPath = /* @__PURE__ */ new Map();
|
|
55
|
+
const chunkContexts = /* @__PURE__ */ new Map();
|
|
56
|
+
const output = /* @__PURE__ */ new Map();
|
|
57
|
+
const sources = /* @__PURE__ */ new Map();
|
|
58
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
59
|
+
const hmrUpdateCode = /* @__PURE__ */ new Map();
|
|
60
|
+
const componentUpdates = {
|
|
61
|
+
classNames: /* @__PURE__ */ new Map(),
|
|
62
|
+
fileEmitter: (file, className) => ({ hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`) })
|
|
63
|
+
};
|
|
64
|
+
let pending = Promise.resolve();
|
|
65
|
+
const filter = vite.createFilter(TS_EXT_REGEX, [
|
|
66
|
+
/node_modules/,
|
|
67
|
+
/[?&]raw\b/,
|
|
68
|
+
/type=script/,
|
|
69
|
+
/@ng\/component/
|
|
70
|
+
]);
|
|
71
|
+
function resolveTsConfigPath() {
|
|
72
|
+
return getTsConfigPath(configContext.root, options.tsconfigGetter(), configContext.isProd, options.isTest, configContext.isLib, options.workspaceRoot);
|
|
73
|
+
}
|
|
74
|
+
async function prepareResources(file, watch) {
|
|
75
|
+
watch(file.filePath);
|
|
76
|
+
return {
|
|
77
|
+
...file,
|
|
78
|
+
classes: await Promise.all(file.classes.map(async (metadata, classIndex) => {
|
|
79
|
+
const component = metadata.component;
|
|
80
|
+
if (!component) return metadata;
|
|
81
|
+
if (component.templateUrl) watch(component.templateUrl.resolvedPath);
|
|
82
|
+
for (const style of component.styleUrls ?? []) watch(style.resolvedPath);
|
|
83
|
+
const preprocess = async (content, path) => {
|
|
84
|
+
const result = await vite.preprocessCSS(content, path, resolvedConfig);
|
|
85
|
+
result.deps?.forEach(watch);
|
|
86
|
+
return result.code;
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
...metadata,
|
|
90
|
+
component: {
|
|
91
|
+
...component,
|
|
92
|
+
styles: component.styles && await Promise.all(component.styles.map((style, index) => preprocess(style, `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`))),
|
|
93
|
+
stylesFromUrls: component.stylesFromUrls && await Promise.all(component.stylesFromUrls.map((style, index) => preprocess(style, component.styleUrls[index].resolvedPath)))
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}))
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function indexChunks(update) {
|
|
100
|
+
if (update) {
|
|
101
|
+
const invalidated = await update();
|
|
102
|
+
for (const filePath of invalidated) {
|
|
103
|
+
output.delete(vite.normalizePath(filePath));
|
|
104
|
+
compiler.fileCache.delete(filePath);
|
|
105
|
+
}
|
|
106
|
+
chunkContexts.clear();
|
|
107
|
+
} else {
|
|
108
|
+
filesByPath.clear();
|
|
109
|
+
chunkContexts.clear();
|
|
110
|
+
output.clear();
|
|
111
|
+
compiler = new api.HybridCompiler(analyzer, {
|
|
112
|
+
optimize: true,
|
|
113
|
+
enableHmr: hmr
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const chunks = update ? compiler.analyzeOptimizedDelta() : compiler.analyzeOptimized();
|
|
117
|
+
for await (const chunk of chunks) for (const file of chunk.files) {
|
|
118
|
+
const normPath = vite.normalizePath(file.filePath);
|
|
119
|
+
filesByPath.set(normPath, {
|
|
120
|
+
file,
|
|
121
|
+
chunk
|
|
122
|
+
});
|
|
123
|
+
output.delete(normPath);
|
|
124
|
+
compiler.fileCache.delete(file.filePath);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function enqueueIndex(update) {
|
|
128
|
+
pending = pending.catch(() => {}).then(() => indexChunks(update));
|
|
129
|
+
return pending;
|
|
130
|
+
}
|
|
131
|
+
function getChunkContext(chunk) {
|
|
132
|
+
let context = chunkContexts.get(chunk);
|
|
133
|
+
if (!context) {
|
|
134
|
+
context = compiler.prepareChunk(chunk);
|
|
135
|
+
chunkContexts.set(chunk, context);
|
|
136
|
+
}
|
|
137
|
+
return context;
|
|
138
|
+
}
|
|
139
|
+
async function checkTypes(filePath, sourceCode, tcbCode) {
|
|
140
|
+
typeChecker ??= new LspTypeChecker(resolveTsConfigPath(), options.typeChecker);
|
|
141
|
+
typeChecker.queueFile(filePath, sourceCode, tcbCode);
|
|
142
|
+
if (!watchMode) return;
|
|
143
|
+
const typeErrors = await typeChecker.flushQueue(true);
|
|
144
|
+
if (typeErrors.length) throw new Error(typeErrors.join("\n"));
|
|
145
|
+
}
|
|
146
|
+
async function processFile(normPath, activeCompiler, watch) {
|
|
147
|
+
const { file: analyzed, chunk } = filesByPath.get(normPath);
|
|
148
|
+
const [file, context, content] = await Promise.all([
|
|
149
|
+
prepareResources(analyzed, (path) => {
|
|
150
|
+
const key = vite.normalizePath(path);
|
|
151
|
+
dependents.set(key, (dependents.get(key) ?? /* @__PURE__ */ new Set()).add(normPath));
|
|
152
|
+
watch(path);
|
|
153
|
+
}),
|
|
154
|
+
getChunkContext(chunk),
|
|
155
|
+
analyzer.getFileContent(analyzed.filePath)
|
|
156
|
+
]);
|
|
157
|
+
sources.set(normPath, content);
|
|
158
|
+
return {
|
|
159
|
+
file,
|
|
160
|
+
content,
|
|
161
|
+
result: activeCompiler.processFile.length >= 5 ? await activeCompiler.processFile(file.filePath, content, void 0, file, context) : await activeCompiler.processFile(file.filePath, content, file, context)
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function compileFile(normPath, watch) {
|
|
165
|
+
if (!filesByPath.has(normPath)) return void 0;
|
|
166
|
+
let task = output.get(normPath);
|
|
167
|
+
if (!task) {
|
|
168
|
+
task = (async () => {
|
|
169
|
+
const { file, content, result } = await processFile(normPath, compiler, watch);
|
|
170
|
+
const errors = [...file.diagnostics ?? [], ...result.diagnostics ?? []].filter((diagnostic) => diagnostic.category === 1);
|
|
171
|
+
if (errors.length) throw new Error(`${file.filePath}: ${errors.map((error) => error.messageText).join("\n")}`);
|
|
172
|
+
if (options.disableTypeChecking !== true) await checkTypes(file.filePath, content, result.tcb?.code);
|
|
173
|
+
return result;
|
|
174
|
+
})();
|
|
175
|
+
output.set(normPath, task);
|
|
176
|
+
}
|
|
177
|
+
return task;
|
|
178
|
+
}
|
|
179
|
+
function componentNames(normPath) {
|
|
180
|
+
return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(({ className, component }) => component && className ? [className] : []);
|
|
181
|
+
}
|
|
182
|
+
async function findComponentUpdates(normPath, read) {
|
|
183
|
+
if (!TS_EXT_REGEX.test(normPath)) return [...dependents.get(normPath) ?? []].flatMap((file) => componentNames(file).map((className) => ({
|
|
184
|
+
file,
|
|
185
|
+
className
|
|
186
|
+
})));
|
|
187
|
+
const stale = sources.get(normPath);
|
|
188
|
+
if (stale === void 0) return [];
|
|
189
|
+
return (findHmrComponentUpdates(normPath, stale, await read(), new Set(componentNames(normPath))) ?? []).map((className) => ({
|
|
190
|
+
file: normPath,
|
|
191
|
+
className
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
async function emitHmrUpdate(file, className) {
|
|
195
|
+
const { result } = await processFile(file, Object.assign(Object.create(Object.getPrototypeOf(compiler)), compiler, { hmrUpdateTarget: className }), () => {});
|
|
196
|
+
return result.hmrUpdateModule && (await transpile(result.hmrUpdateModule, file)).code;
|
|
197
|
+
}
|
|
198
|
+
async function sendComponentUpdates(updates, server) {
|
|
199
|
+
try {
|
|
200
|
+
for (const file of new Set(updates.map((update) => update.file))) await compileFile(file, () => {});
|
|
201
|
+
const codes = await Promise.all(updates.map(({ file, className }) => emitHmrUpdate(file, className)));
|
|
202
|
+
if (codes.some((code) => !code)) return false;
|
|
203
|
+
updates.forEach(({ file, className }, index) => {
|
|
204
|
+
hmrUpdateCode.set(`${file}@${className}`, codes[index]);
|
|
205
|
+
componentUpdates.classNames.set(file, className);
|
|
206
|
+
server.moduleGraph.getModulesByFile(file)?.forEach((mod) => server.moduleGraph.invalidateModule(mod));
|
|
207
|
+
server.ws.send("angular:component-update", {
|
|
208
|
+
id: encodeURIComponent(`${filesByPath.get(file).file.filePath}@${className}`),
|
|
209
|
+
timestamp: Date.now()
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
return true;
|
|
213
|
+
} catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
name: "@analogjs/vite-plugin-angular-ngp",
|
|
219
|
+
enforce: "pre",
|
|
220
|
+
api: {
|
|
221
|
+
getTsConfigPath: resolveTsConfigPath,
|
|
222
|
+
output,
|
|
223
|
+
ready: () => pending,
|
|
224
|
+
componentUpdates
|
|
225
|
+
},
|
|
226
|
+
config(config, { command }) {
|
|
227
|
+
watchMode = command === "serve";
|
|
228
|
+
configContext = {
|
|
229
|
+
root: config.root || ".",
|
|
230
|
+
isProd: isProdMode(config.mode),
|
|
231
|
+
isLib: !!config.build?.lib
|
|
232
|
+
};
|
|
233
|
+
const depOptimizer = createDepOptimizerConfig({
|
|
234
|
+
tsconfig: resolveTsConfigPath(),
|
|
235
|
+
isProd: configContext.isProd,
|
|
236
|
+
jit: false,
|
|
237
|
+
watchMode,
|
|
238
|
+
isTest: options.isTest,
|
|
239
|
+
isAstroIntegration: options.isAstroIntegration
|
|
240
|
+
});
|
|
241
|
+
return {
|
|
242
|
+
...vite.rolldownVersion ? { oxc: {} } : { esbuild: false },
|
|
243
|
+
...depOptimizer
|
|
244
|
+
};
|
|
245
|
+
},
|
|
246
|
+
async configResolved(config) {
|
|
247
|
+
resolvedConfig = config;
|
|
248
|
+
hmr = watchMode && options.liveReload && !options.isTest && config.server.hmr !== false;
|
|
249
|
+
transformFilter = (await discoverAnalogIntegrations(config)).transformFilter;
|
|
250
|
+
},
|
|
251
|
+
configureServer(server) {
|
|
252
|
+
const changeTypes = {
|
|
253
|
+
add: 1,
|
|
254
|
+
change: 2,
|
|
255
|
+
unlink: 3
|
|
256
|
+
};
|
|
257
|
+
server.watcher.on("all", (event, path) => {
|
|
258
|
+
const type = changeTypes[event];
|
|
259
|
+
if (type) typeChecker?.notifyFileChanged(path, type);
|
|
260
|
+
});
|
|
261
|
+
server.httpServer?.on("close", () => {
|
|
262
|
+
typeChecker?.close();
|
|
263
|
+
typeChecker = void 0;
|
|
264
|
+
analyzer?.close();
|
|
265
|
+
analyzer = void 0;
|
|
266
|
+
compiler = void 0;
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
async buildStart() {
|
|
270
|
+
activeBuilds++;
|
|
271
|
+
if (!analyzer) {
|
|
272
|
+
const tsconfig = resolveTsConfigPath();
|
|
273
|
+
const ngp = await loadNgp(tsconfig);
|
|
274
|
+
api = ngp.api;
|
|
275
|
+
analyzer = await api.createAnalyzer(tsconfig, {
|
|
276
|
+
...ngp.analyzerOptions,
|
|
277
|
+
enableHmr: hmr
|
|
278
|
+
});
|
|
279
|
+
pending = indexChunks();
|
|
280
|
+
}
|
|
281
|
+
await pending;
|
|
282
|
+
for (const path of dependents.keys()) this.addWatchFile(path);
|
|
283
|
+
},
|
|
284
|
+
async transform(code, id) {
|
|
285
|
+
if (!filter(id) || transformFilter?.(code, id) === false) return;
|
|
286
|
+
const filePath = vite.normalizePath(id.split("?")[0]);
|
|
287
|
+
await pending;
|
|
288
|
+
let result = await compileFile(filePath, (path) => this.addWatchFile(path));
|
|
289
|
+
if (result && result.magicString.original !== code) {
|
|
290
|
+
await enqueueIndex(() => analyzer.updateFileContent([{
|
|
291
|
+
filePath,
|
|
292
|
+
content: code
|
|
293
|
+
}]));
|
|
294
|
+
result = await compileFile(filePath, (path) => this.addWatchFile(path));
|
|
295
|
+
} else if (!result && options.disableTypeChecking !== true) await checkTypes(filePath, code);
|
|
296
|
+
const source = result?.magicString.toString() ?? code;
|
|
297
|
+
const map = result?.magicString.generateMap({
|
|
298
|
+
source: filePath,
|
|
299
|
+
includeContent: true,
|
|
300
|
+
hires: true
|
|
301
|
+
});
|
|
302
|
+
return transpile(source, filePath, map);
|
|
303
|
+
},
|
|
304
|
+
async handleHotUpdate(ctx) {
|
|
305
|
+
const normPath = vite.normalizePath(ctx.file);
|
|
306
|
+
const updates = hmr ? await findComponentUpdates(normPath, ctx.read) : [];
|
|
307
|
+
await enqueueIndex(() => analyzer.invalidateFiles([{
|
|
308
|
+
filePath: ctx.file,
|
|
309
|
+
updateType: 2
|
|
310
|
+
}]));
|
|
311
|
+
if (updates.length && await sendComponentUpdates(updates, ctx.server)) return [];
|
|
312
|
+
hmrUpdateCode.clear();
|
|
313
|
+
componentUpdates.classNames.clear();
|
|
314
|
+
ctx.server.moduleGraph.invalidateAll();
|
|
315
|
+
ctx.server.ws.send({ type: "full-reload" });
|
|
316
|
+
return [];
|
|
317
|
+
},
|
|
318
|
+
async buildEnd(error) {
|
|
319
|
+
if (error || watchMode || !typeChecker) return;
|
|
320
|
+
const typeErrors = await typeChecker.flushQueue();
|
|
321
|
+
if (typeErrors.length) throw new Error(typeErrors.join("\n"));
|
|
322
|
+
},
|
|
323
|
+
async closeBundle() {
|
|
324
|
+
activeBuilds = Math.max(0, activeBuilds - 1);
|
|
325
|
+
if (watchMode || activeBuilds > 0) return;
|
|
326
|
+
await pending.catch(() => {});
|
|
327
|
+
typeChecker?.close();
|
|
328
|
+
typeChecker = void 0;
|
|
329
|
+
analyzer?.close();
|
|
330
|
+
analyzer = void 0;
|
|
331
|
+
compiler = void 0;
|
|
332
|
+
filesByPath.clear();
|
|
333
|
+
chunkContexts.clear();
|
|
334
|
+
output.clear();
|
|
335
|
+
sources.clear();
|
|
336
|
+
dependents.clear();
|
|
337
|
+
releaseCssPreprocessorWorkers();
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
342
|
+
export { ngpCompilePlugin };
|
|
343
|
+
|
|
344
|
+
//# sourceMappingURL=ngp-compile-plugin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ngp-compile-plugin.js","names":[],"sources":["../../../src/lib/ngp-compile-plugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type MagicString from 'magic-string';\nimport * as vite from 'vite';\nimport {\n discoverAnalogIntegrations,\n type TransformFilter,\n} from './analog-plugin-interop.js';\nimport type { FastCompilePluginOptions } from './fast-compile-plugin.js';\nimport {\n createDepOptimizerConfig,\n getTsConfigPath,\n isProdMode,\n TS_EXT_REGEX,\n type TsConfigResolutionContext,\n} from './utils/plugin-config.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport { angularFullVersion } from './utils/devkit.js';\nimport { findHmrComponentUpdates } from './utils/hmr-component-updates.js';\nimport {\n LspTypeChecker,\n type FileChangeType,\n} from './utils/lsp-type-checker.js';\nimport type { ComponentUpdates } from './live-reload-plugin.js';\n\n// The unpublished NGP API is loaded at runtime. Model only the surface we use.\ninterface NgpDiagnostic {\n category: number;\n messageText: string;\n}\n\ninterface NgpFile {\n filePath: string;\n diagnostics?: NgpDiagnostic[];\n classes: {\n className?: string;\n component?: {\n templateUrl?: { resolvedPath: string };\n styleUrls?: { resolvedPath: string }[];\n stylesFromUrls?: string[];\n styles?: string[];\n };\n }[];\n}\n\ninterface NgpChunk {\n files: NgpFile[];\n}\n\ninterface NgpResult {\n magicString: MagicString;\n diagnostics?: NgpDiagnostic[];\n tcb?: { code: string } | null;\n hmrUpdateModule?: string | null;\n}\n\ninterface NgpAnalyzer {\n getFileContent(path: string): Promise<string>;\n updateFileContent(\n updates: { filePath: string; content: string }[],\n ): Promise<string[]>;\n invalidateFiles(\n updates: { filePath: string; updateType: number }[],\n ): Promise<string[]>;\n close(): void;\n}\n\ninterface NgpCompiler {\n // Parsed templates by file, cleared by NGP's own update methods\n fileCache: Map<string, unknown>;\n analyzeOptimized(): AsyncIterable<NgpChunk>;\n analyzeOptimizedDelta(): AsyncIterable<NgpChunk>;\n prepareChunk(chunk: NgpChunk): Promise<unknown>;\n processFile(\n path: string,\n content: string,\n ...args: [undefined, NgpFile, unknown] | [NgpFile, unknown]\n ): Promise<NgpResult>;\n}\n\ninterface ComponentUpdate {\n file: string;\n className: string;\n}\n\ninterface NgpAnalyzerOptions {\n nativeBinding?: string;\n backend?: 'wasm';\n wasmBinding?: string;\n enableHmr?: boolean;\n}\n\ninterface NgpApi {\n createAnalyzer(\n tsconfig: string,\n options: NgpAnalyzerOptions,\n ): Promise<NgpAnalyzer>;\n HybridCompiler: new (\n analyzer: NgpAnalyzer,\n options: { optimize: boolean; enableHmr: boolean },\n ) => NgpCompiler;\n}\n\n// Interim NGP build bundled with this package until @angular/ngp is published\nconst BUNDLED_NGP = new URL('../../ngp/', import.meta.url);\n\nasync function loadNgp(\n tsconfig: string,\n): Promise<{ api: NgpApi; analyzerOptions: NgpAnalyzerOptions }> {\n const nativeBinding = process.env['ANALOG_NGP_NATIVE_BINDING'];\n let modulePath = process.env['ANALOG_NGP_COMPILER'];\n if (!modulePath) {\n try {\n modulePath = createRequire(tsconfig).resolve('@angular/ngp');\n } catch {\n if (angularFullVersion < 220200) {\n throw new Error(\n \"[@analogjs/vite-plugin-angular]: compilation: 'ngp' requires Angular v22.2 or later.\",\n );\n }\n return {\n api: await import(new URL('api.mjs', BUNDLED_NGP).href),\n analyzerOptions: nativeBinding\n ? { nativeBinding }\n : {\n backend: 'wasm',\n wasmBinding: fileURLToPath(\n new URL('ng_analyze.cjs', BUNDLED_NGP),\n ),\n },\n };\n }\n }\n return {\n api: await import(pathToFileURL(resolve(modulePath)).href),\n analyzerOptions: nativeBinding ? { nativeBinding } : {},\n };\n}\n\nfunction transpile(\n source: string,\n filePath: string,\n map?: Parameters<typeof vite.transformWithEsbuild>[3],\n) {\n return vite.transformWithOxc\n ? vite.transformWithOxc(\n source,\n filePath,\n { lang: 'ts', sourcemap: true },\n map,\n )\n : vite.transformWithEsbuild(\n source,\n filePath,\n { loader: 'ts', sourcemap: true },\n map,\n );\n}\n\nexport function ngpCompilePlugin(\n options: FastCompilePluginOptions,\n): vite.Plugin {\n if (options.jit || options.fastCompileMode === 'partial') {\n throw new Error(\n \"compilation: 'ngp' requires jit: false and fastCompileMode: 'full'.\",\n );\n }\n\n let configContext: TsConfigResolutionContext;\n let resolvedConfig: vite.ResolvedConfig;\n let transformFilter: TransformFilter | undefined;\n let watchMode = false;\n let hmr = false;\n let activeBuilds = 0;\n let analyzer: NgpAnalyzer | undefined;\n let compiler: NgpCompiler | undefined;\n let typeChecker: LspTypeChecker | undefined;\n let api: NgpApi;\n const filesByPath = new Map<string, { file: NgpFile; chunk: NgpChunk }>();\n const chunkContexts = new Map<NgpChunk, Promise<unknown>>();\n const output = new Map<string, Promise<NgpResult>>();\n // Last compiled source of each file, compared on edits for HMR\n const sources = new Map<string, string>();\n // Watched files mapped to the source files that depend on them\n const dependents = new Map<string, Set<string>>();\n const hmrUpdateCode = new Map<string, string>();\n const componentUpdates: ComponentUpdates = {\n classNames: new Map(),\n fileEmitter: (file, className) => ({\n hmrUpdateCode: hmrUpdateCode.get(`${file}@${className}`),\n }),\n };\n let pending = Promise.resolve();\n const filter = vite.createFilter(TS_EXT_REGEX, [\n /node_modules/,\n /[?&]raw\\b/,\n /type=script/,\n /@ng\\/component/,\n ]);\n\n function resolveTsConfigPath() {\n return getTsConfigPath(\n configContext.root,\n options.tsconfigGetter(),\n configContext.isProd,\n options.isTest,\n configContext.isLib,\n options.workspaceRoot,\n );\n }\n\n async function prepareResources(\n file: NgpFile,\n watch: (path: string) => void,\n ): Promise<NgpFile> {\n watch(file.filePath);\n return {\n ...file,\n classes: await Promise.all(\n file.classes.map(async (metadata, classIndex) => {\n const component = metadata.component;\n if (!component) return metadata;\n if (component.templateUrl) watch(component.templateUrl.resolvedPath);\n for (const style of component.styleUrls ?? [])\n watch(style.resolvedPath);\n const preprocess = async (content: string, path: string) => {\n const result = await vite.preprocessCSS(\n content,\n path,\n resolvedConfig,\n );\n result.deps?.forEach(watch);\n return result.code;\n };\n return {\n ...metadata,\n component: {\n ...component,\n styles:\n component.styles &&\n (await Promise.all(\n component.styles.map((style, index) =>\n preprocess(\n style,\n `${file.filePath}.inline-${classIndex}-${index}.${options.inlineStylesExtension}`,\n ),\n ),\n )),\n stylesFromUrls:\n component.stylesFromUrls &&\n (await Promise.all(\n component.stylesFromUrls.map((style, index) =>\n preprocess(style, component.styleUrls![index].resolvedPath),\n ),\n )),\n },\n };\n }),\n ),\n };\n }\n\n async function indexChunks(update?: () => Promise<string[]>) {\n if (update) {\n const invalidated = await update();\n for (const filePath of invalidated) {\n output.delete(vite.normalizePath(filePath));\n compiler!.fileCache.delete(filePath);\n }\n chunkContexts.clear();\n } else {\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n compiler = new api.HybridCompiler(analyzer!, {\n optimize: true,\n enableHmr: hmr,\n });\n }\n const chunks = update\n ? compiler!.analyzeOptimizedDelta()\n : compiler!.analyzeOptimized();\n for await (const chunk of chunks) {\n for (const file of chunk.files) {\n const normPath = vite.normalizePath(file.filePath);\n filesByPath.set(normPath, { file, chunk });\n output.delete(normPath);\n compiler!.fileCache.delete(file.filePath);\n }\n }\n }\n\n function enqueueIndex(update: () => Promise<string[]>) {\n pending = pending.catch(() => {}).then(() => indexChunks(update));\n return pending;\n }\n\n function getChunkContext(chunk: NgpChunk): Promise<unknown> {\n let context = chunkContexts.get(chunk);\n if (!context) {\n context = compiler!.prepareChunk(chunk);\n chunkContexts.set(chunk, context);\n }\n return context;\n }\n\n async function checkTypes(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n ) {\n typeChecker ??= new LspTypeChecker(\n resolveTsConfigPath(),\n options.typeChecker,\n );\n typeChecker.queueFile(filePath, sourceCode, tcbCode);\n if (!watchMode) return;\n const typeErrors = await typeChecker.flushQueue(true);\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n }\n\n async function processFile(\n normPath: string,\n activeCompiler: NgpCompiler,\n watch: (path: string) => void,\n ) {\n const { file: analyzed, chunk } = filesByPath.get(normPath)!;\n const [file, context, content] = await Promise.all([\n prepareResources(analyzed, (path) => {\n const key = vite.normalizePath(path);\n dependents.set(key, (dependents.get(key) ?? new Set()).add(normPath));\n watch(path);\n }),\n getChunkContext(chunk),\n analyzer!.getFileContent(analyzed.filePath),\n ]);\n sources.set(normPath, content);\n const result =\n activeCompiler.processFile.length >= 5\n ? await activeCompiler.processFile(\n file.filePath,\n content,\n undefined,\n file,\n context,\n )\n : await activeCompiler.processFile(\n file.filePath,\n content,\n file,\n context,\n );\n return { file, content, result };\n }\n\n function compileFile(\n normPath: string,\n watch: (path: string) => void,\n ): Promise<NgpResult> | undefined {\n if (!filesByPath.has(normPath)) return undefined;\n let task = output.get(normPath);\n if (!task) {\n task = (async () => {\n const { file, content, result } = await processFile(\n normPath,\n compiler!,\n watch,\n );\n const errors = [\n ...(file.diagnostics ?? []),\n ...(result.diagnostics ?? []),\n ].filter((diagnostic) => diagnostic.category === 1);\n if (errors.length) {\n throw new Error(\n `${file.filePath}: ${errors.map((error) => error.messageText).join('\\n')}`,\n );\n }\n if (options.disableTypeChecking !== true) {\n await checkTypes(file.filePath, content, result.tcb?.code);\n }\n return result;\n })();\n output.set(normPath, task);\n }\n return task;\n }\n\n function componentNames(normPath: string) {\n return (filesByPath.get(normPath)?.file.classes ?? []).flatMap(\n ({ className, component }) => (component && className ? [className] : []),\n );\n }\n\n // Components to update in place, following the Angular CLI's rule\n async function findComponentUpdates(\n normPath: string,\n read: () => string | Promise<string>,\n ): Promise<ComponentUpdate[]> {\n if (!TS_EXT_REGEX.test(normPath)) {\n return [...(dependents.get(normPath) ?? [])].flatMap((file) =>\n componentNames(file).map((className) => ({ file, className })),\n );\n }\n const stale = sources.get(normPath);\n if (stale === undefined) return [];\n const classNames = findHmrComponentUpdates(\n normPath,\n stale,\n await read(),\n new Set(componentNames(normPath)),\n );\n return (classNames ?? []).map((className) => ({\n file: normPath,\n className,\n }));\n }\n\n async function emitHmrUpdate(file: string, className: string) {\n // NGP emits only the update module of the class named by `hmrUpdateTarget`\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(compiler)),\n compiler,\n { hmrUpdateTarget: className },\n );\n const { result } = await processFile(file, target, () => {});\n return (\n result.hmrUpdateModule &&\n (await transpile(result.hmrUpdateModule, file)).code\n );\n }\n\n async function sendComponentUpdates(\n updates: ComponentUpdate[],\n server: vite.ViteDevServer,\n ) {\n try {\n for (const file of new Set(updates.map((update) => update.file))) {\n await compileFile(file, () => {});\n }\n const codes = await Promise.all(\n updates.map(({ file, className }) => emitHmrUpdate(file, className)),\n );\n if (codes.some((code) => !code)) return false;\n updates.forEach(({ file, className }, index) => {\n hmrUpdateCode.set(`${file}@${className}`, codes[index]!);\n componentUpdates.classNames.set(file, className);\n server.moduleGraph\n .getModulesByFile(file)\n ?.forEach((mod) => server.moduleGraph.invalidateModule(mod));\n server.ws.send('angular:component-update', {\n id: encodeURIComponent(\n `${filesByPath.get(file)!.file.filePath}@${className}`,\n ),\n timestamp: Date.now(),\n });\n });\n return true;\n } catch {\n // A full reload reports the compilation error\n return false;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular-ngp',\n enforce: 'pre',\n api: {\n getTsConfigPath: resolveTsConfigPath,\n output,\n ready: () => pending,\n componentUpdates,\n },\n config(config, { command }) {\n watchMode = command === 'serve';\n configContext = {\n root: config.root || '.',\n isProd: isProdMode(config.mode),\n isLib: !!config.build?.lib,\n };\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: resolveTsConfigPath(),\n isProd: configContext.isProd,\n jit: false,\n watchMode,\n isTest: options.isTest,\n isAstroIntegration: options.isAstroIntegration,\n });\n return {\n ...(vite.rolldownVersion ? { oxc: {} as any } : { esbuild: false }),\n ...depOptimizer,\n };\n },\n async configResolved(config) {\n resolvedConfig = config;\n hmr =\n watchMode &&\n options.liveReload &&\n !options.isTest &&\n config.server.hmr !== false;\n const integrations = await discoverAnalogIntegrations(config);\n transformFilter = integrations.transformFilter;\n },\n configureServer(server) {\n const changeTypes: Record<string, FileChangeType> = {\n add: 1,\n change: 2,\n unlink: 3,\n };\n server.watcher.on('all', (event, path) => {\n const type = changeTypes[event];\n if (type) typeChecker?.notifyFileChanged(path, type);\n });\n server.httpServer?.on('close', () => {\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n });\n },\n async buildStart() {\n activeBuilds++;\n if (!analyzer) {\n const tsconfig = resolveTsConfigPath();\n const ngp = await loadNgp(tsconfig);\n api = ngp.api;\n analyzer = await api.createAnalyzer(tsconfig, {\n ...ngp.analyzerOptions,\n enableHmr: hmr,\n });\n pending = indexChunks();\n }\n await pending;\n for (const path of dependents.keys()) {\n this.addWatchFile(path);\n }\n },\n async transform(code, id) {\n if (!filter(id) || transformFilter?.(code, id) === false) return;\n const filePath = vite.normalizePath(id.split('?')[0]);\n await pending;\n let result = await compileFile(filePath, (path) =>\n this.addWatchFile(path),\n );\n if (result && result.magicString.original !== code) {\n await enqueueIndex(() =>\n analyzer!.updateFileContent([{ filePath, content: code }]),\n );\n result = await compileFile(filePath, (path) => this.addWatchFile(path));\n } else if (!result && options.disableTypeChecking !== true) {\n await checkTypes(filePath, code);\n }\n const source = result?.magicString.toString() ?? code;\n const map = result?.magicString.generateMap({\n source: filePath,\n includeContent: true,\n hires: true,\n });\n return transpile(source, filePath, map);\n },\n async handleHotUpdate(ctx) {\n const normPath = vite.normalizePath(ctx.file);\n const updates = hmr ? await findComponentUpdates(normPath, ctx.read) : [];\n await enqueueIndex(() =>\n analyzer!.invalidateFiles([{ filePath: ctx.file, updateType: 2 }]),\n );\n if (updates.length && (await sendComponentUpdates(updates, ctx.server))) {\n return [];\n }\n hmrUpdateCode.clear();\n componentUpdates.classNames.clear();\n ctx.server.moduleGraph.invalidateAll();\n ctx.server.ws.send({ type: 'full-reload' });\n return [];\n },\n async buildEnd(error) {\n if (error || watchMode || !typeChecker) return;\n const typeErrors = await typeChecker.flushQueue();\n if (typeErrors.length) {\n throw new Error(typeErrors.join('\\n'));\n }\n },\n async closeBundle() {\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (watchMode || activeBuilds > 0) return;\n await pending.catch(() => {});\n typeChecker?.close();\n typeChecker = undefined;\n analyzer?.close();\n analyzer = undefined;\n compiler = undefined;\n filesByPath.clear();\n chunkContexts.clear();\n output.clear();\n sources.clear();\n dependents.clear();\n releaseCssPreprocessorWorkers();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAyGA,IAAM,cAAc,IAAA,IAAA,cAAA,KAAA,YAAA,GAAA;AAEpB,eAAe,QACb,UAC+D;CAC/D,MAAM,gBAAgB,QAAQ,IAAI;CAClC,IAAI,aAAa,QAAQ,IAAI;CAC7B,IAAI,CAAC,YACH,IAAI;EACF,aAAa,cAAc,QAAQ,CAAC,CAAC,QAAQ,cAAc;CAC7D,QAAQ;EACN,IAAI,qBAAqB,QACvB,MAAM,IAAI,MACR,sFACF;EAEF,OAAO;GACL,KAAK,MAAM,OAAO,IAAI,IAAI,WAAW,WAAW,CAAC,CAAC;GAClD,iBAAiB,gBACb,EAAE,cAAc,IAChB;IACE,SAAS;IACT,aAAa,cACX,IAAI,IAAI,kBAAkB,WAAW,CACvC;GACF;EACN;CACF;CAEF,OAAO;EACL,KAAK,MAAM,OAAO,cAAc,QAAQ,UAAU,CAAC,CAAC,CAAC;EACrD,iBAAiB,gBAAgB,EAAE,cAAc,IAAI,CAAC;CACxD;AACF;AAEA,SAAS,UACP,QACA,UACA,KACA;CACA,OAAO,KAAK,mBACR,KAAK,iBACH,QACA,UACA;EAAE,MAAM;EAAM,WAAW;CAAK,GAC9B,GACF,IACA,KAAK,qBACH,QACA,UACA;EAAE,QAAQ;EAAM,WAAW;CAAK,GAChC,GACF;AACN;AAEA,SAAgB,iBACd,SACa;CACb,IAAI,QAAQ,OAAO,QAAQ,oBAAoB,WAC7C,MAAM,IAAI,MACR,qEACF;CAGF,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,YAAY;CAChB,IAAI,MAAM;CACV,IAAI,eAAe;CACnB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,8BAAc,IAAI,IAAgD;CACxE,MAAM,gCAA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AI;GAC5C,MAAM,UAAU,MAAM,MAAM,qBAAqB,UAAU,IAAI,IAAI,IAAI,CAAC;GACxE,MAAM,mBACJ,SAAU,gBAAgB,CAAC;IAAE,UAAU,IAAI;IAAM,YAAY;GAAE,CAAC,CAAC,CACnE;GACA,IAAI,QAAQ,UAAW,MAAM,qBAAqB,SAAS,IAAI,MAAM,GACnE,OAAO,CAAC;GAEV,cAAc,MAAM;GACpB,iBAAiB,WAAW,MAAM;GAClC,IAAI,OAAO,YAAY,cAAc;GACrC,IAAI,OAAO,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;GAC1C,OAAO,CAAC;EACV;EACA,MAAM,SAAS,OAAO;GACpB,IAAI,SAAS,aAAa,CAAC,aAAa;GACxC,MAAM,aAAa,MAAM,YAAY,WAAW;GAChD,IAAI,WAAW,QACb,MAAM,IAAI,MAAM,WAAW,KAAK,IAAI,CAAC;EAEzC;EACA,MAAM,cAAc;GAClB,eAAe,KAAK,IAAI,GAAG,eAAe,CAAC;GAC3C,IAAI,aAAa,eAAe,GAAG;GACnC,MAAM,QAAQ,YAAY,CAAC,CAAC;GAC5B,aAAa,MAAM;GACnB,cAAc,KAAA;GACd,UAAU,MAAM;GAChB,WAAW,KAAA;GACX,WAAW,KAAA;GACX,YAAY,MAAM;GAClB,cAAc,MAAM;GACpB,OAAO,MAAM;GACb,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,8BAA8B;EAChC;CACF;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
let _angular_devkit_architect = require("@angular-devkit/architect");
|
|
2
|
+
let node_path = require("node:path");
|
|
2
3
|
//#region packages/vite-plugin-angular-tools/src/builders/vite/vite-build.impl.ts
|
|
3
4
|
async function viteBuilder(options, context) {
|
|
4
5
|
const { createBuilder } = await Function("return import(\"vite\")")();
|
|
@@ -18,7 +19,7 @@ async function viteBuilder(options, context) {
|
|
|
18
19
|
root: projectConfig.root,
|
|
19
20
|
mode,
|
|
20
21
|
build: {
|
|
21
|
-
outDir: options.outputPath,
|
|
22
|
+
outDir: options.outputPath ? (0, node_path.resolve)(context.workspaceRoot, options.outputPath) : void 0,
|
|
22
23
|
sourcemap: !!buildOptions.sourcemap
|
|
23
24
|
}
|
|
24
25
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-build.impl.js","names":[],"sources":["../../../../../../../../vite-plugin-angular-tools/src/builders/vite/vite-build.impl.ts"],"sourcesContent":["import {\n BuilderContext,\n BuilderOutput,\n createBuilder,\n targetFromTargetString,\n} from '@angular-devkit/architect';\nimport type { InlineConfig } from 'vite';\nimport { ViteBuildSchema } from './schema';\n\nasync function viteBuilder(\n options: ViteBuildSchema,\n context: BuilderContext,\n): Promise<BuilderOutput> {\n const { createBuilder } = await Function('return import(\"vite\")')();\n if (!context.target) {\n throw new Error('Builder must be executed with a target');\n }\n const projectConfig = await context.getProjectMetadata(context.target);\n const projectName = context.target.project;\n const configuration = context.target.configuration || 'production';\n const buildTargetSpecifier = `::${configuration}`;\n const buildTarget = targetFromTargetString(\n buildTargetSpecifier,\n projectName,\n 'build',\n );\n\n const browserBuilderName = await context.getBuilderNameForTarget(buildTarget);\n const rawBuildOptions = await context.getTargetOptions(buildTarget);\n const buildOptions = await context.validateOptions(\n rawBuildOptions,\n browserBuilderName,\n );\n\n // Explicit build options and the requested configuration win over an\n // ambient NODE_ENV, so `build:production` cannot silently produce a\n // development build when NODE_ENV happens to be set. See #2458.\n const mode = (buildOptions.mode ?? configuration) as string;\n\n if (process.env.NODE_ENV && process.env.NODE_ENV !== mode) {\n context.logger.warn(\n `NODE_ENV is set to \"${process.env.NODE_ENV}\" but is ignored because the build resolved mode \"${mode}\" from the build options and configuration.`,\n );\n }\n\n const buildConfig: InlineConfig = {\n configFile: options.configFile,\n root: projectConfig.root as string,\n mode,\n build: {\n outDir: options.outputPath,\n sourcemap: !!buildOptions.sourcemap,\n },\n };\n\n try {\n const builder = await createBuilder(buildConfig, false);\n await builder.buildApp();\n\n return {\n success: true,\n };\n } catch (e) {\n console.error(e);\n return {\n success: false,\n };\n }\n}\n\nexport default createBuilder(viteBuilder) as any;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"vite-build.impl.js","names":[],"sources":["../../../../../../../../vite-plugin-angular-tools/src/builders/vite/vite-build.impl.ts"],"sourcesContent":["import {\n BuilderContext,\n BuilderOutput,\n createBuilder,\n targetFromTargetString,\n} from '@angular-devkit/architect';\nimport { resolve } from 'node:path';\nimport type { InlineConfig } from 'vite';\nimport { ViteBuildSchema } from './schema';\n\nasync function viteBuilder(\n options: ViteBuildSchema,\n context: BuilderContext,\n): Promise<BuilderOutput> {\n const { createBuilder } = await Function('return import(\"vite\")')();\n if (!context.target) {\n throw new Error('Builder must be executed with a target');\n }\n const projectConfig = await context.getProjectMetadata(context.target);\n const projectName = context.target.project;\n const configuration = context.target.configuration || 'production';\n const buildTargetSpecifier = `::${configuration}`;\n const buildTarget = targetFromTargetString(\n buildTargetSpecifier,\n projectName,\n 'build',\n );\n\n const browserBuilderName = await context.getBuilderNameForTarget(buildTarget);\n const rawBuildOptions = await context.getTargetOptions(buildTarget);\n const buildOptions = await context.validateOptions(\n rawBuildOptions,\n browserBuilderName,\n );\n\n // Explicit build options and the requested configuration win over an\n // ambient NODE_ENV, so `build:production` cannot silently produce a\n // development build when NODE_ENV happens to be set. See #2458.\n const mode = (buildOptions.mode ?? configuration) as string;\n\n if (process.env.NODE_ENV && process.env.NODE_ENV !== mode) {\n context.logger.warn(\n `NODE_ENV is set to \"${process.env.NODE_ENV}\" but is ignored because the build resolved mode \"${mode}\" from the build options and configuration.`,\n );\n }\n\n const buildConfig: InlineConfig = {\n configFile: options.configFile,\n root: projectConfig.root as string,\n mode,\n build: {\n // outputPath is workspace-relative; Vite resolves a relative outDir\n // against the project root.\n outDir: options.outputPath\n ? resolve(context.workspaceRoot, options.outputPath)\n : undefined,\n sourcemap: !!buildOptions.sourcemap,\n },\n };\n\n try {\n const builder = await createBuilder(buildConfig, false);\n await builder.buildApp();\n\n return {\n success: true,\n };\n } catch (e) {\n console.error(e);\n return {\n success: false,\n };\n }\n}\n\nexport default createBuilder(viteBuilder) as any;\n"],"mappings":";;;AAUA,eAAe,YACb,SACA,SACwB;CACxB,MAAM,EAAE,kBAAkB,MAAM,SAAS,yBAAuB,CAAC,CAAC;CAClE,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MAAM,wCAAwC;CAE1D,MAAM,gBAAgB,MAAM,QAAQ,mBAAmB,QAAQ,MAAM;CACrE,MAAM,cAAc,QAAQ,OAAO;CACnC,MAAM,gBAAgB,QAAQ,OAAO,iBAAiB;CACtD,MAAM,uBAAuB,KAAK;CAClC,MAAM,eAAA,GAAc,0BAAA,uBAAA,CAClB,sBACA,aACA,OACF;CAEA,MAAM,qBAAqB,MAAM,QAAQ,wBAAwB,WAAW;CAC5E,MAAM,kBAAkB,MAAM,QAAQ,iBAAiB,WAAW;CAClE,MAAM,eAAe,MAAM,QAAQ,gBACjC,iBACA,kBACF;CAKA,MAAM,OAAQ,aAAa,QAAQ;CAEnC,IAAA,QAAA,IAAA,YAAA,QAAA,IAAA,aAAqD,MACnD,QAAQ,OAAO,KACb,uBAAA,QAAA,IAAA,SAA4C,oDAAoD,KAAK,4CACvG;CAGF,MAAM,cAA4B;EAChC,YAAY,QAAQ;EACpB,MAAM,cAAc;EACpB;EACA,OAAO;GAGL,QAAQ,QAAQ,cAAA,GACZ,UAAA,QAAA,CAAQ,QAAQ,eAAe,QAAQ,UAAU,IACjD,KAAA;GACJ,WAAW,CAAC,CAAC,aAAa;EAC5B;CACF;CAEA,IAAI;EAEF,OAAM,MADgB,cAAc,aAAa,KAAK,EAAA,CACxC,SAAS;EAEvB,OAAO,EACL,SAAS,KACX;CACF,SAAS,GAAG;EACV,QAAQ,MAAM,CAAC;EACf,OAAO,EACL,SAAS,MACX;CACF;AACF;AAEA,IAAA,2BAAA,GAAe,0BAAA,cAAA,CAAc,WAAW"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applies the Angular CLI's HMR rule to an edited file. Returns the
|
|
3
|
+
* components whose `template`, `templateUrl`, `styles`, `styleUrl` or
|
|
4
|
+
* `stylesUrl` fields are the only changes, or `null` when the edit
|
|
5
|
+
* needs a full reload.
|
|
6
|
+
*/
|
|
7
|
+
export declare function findHmrComponentUpdates(filename: string, staleText: string, updatedText: string, components: ReadonlySet<string>): string[] | null;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { parseSync } from "oxc-parser";
|
|
2
|
+
//#region packages/vite-plugin-angular/src/lib/utils/hmr-component-updates.ts
|
|
3
|
+
var HMR_FIELDS = /* @__PURE__ */ new Set([
|
|
4
|
+
"template",
|
|
5
|
+
"templateUrl",
|
|
6
|
+
"styles",
|
|
7
|
+
"styleUrl",
|
|
8
|
+
"stylesUrl"
|
|
9
|
+
]);
|
|
10
|
+
function parse(filename, text) {
|
|
11
|
+
const { program, errors } = parseSync(filename, text);
|
|
12
|
+
return errors.length ? null : {
|
|
13
|
+
text,
|
|
14
|
+
body: program.body
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function classOf(statement) {
|
|
18
|
+
if (statement.type === "ClassDeclaration") return statement;
|
|
19
|
+
return statement.declaration?.type === "ClassDeclaration" ? statement.declaration : void 0;
|
|
20
|
+
}
|
|
21
|
+
function statementStart(statement) {
|
|
22
|
+
return Math.min(statement.start, classOf(statement)?.decorators[0]?.start ?? statement.start);
|
|
23
|
+
}
|
|
24
|
+
function statementText(source, statement) {
|
|
25
|
+
return source.text.slice(statementStart(statement), statement.end);
|
|
26
|
+
}
|
|
27
|
+
function classHeader(source, statement, cls) {
|
|
28
|
+
const [decorator] = cls.decorators;
|
|
29
|
+
return source.text.slice(statementStart(statement), decorator.start) + source.text.slice(decorator.end, cls.body.start) + source.text.slice(cls.body.end, statement.end);
|
|
30
|
+
}
|
|
31
|
+
function decoratorMetadata(source, decorator) {
|
|
32
|
+
const call = decorator.expression;
|
|
33
|
+
const metadata = call.arguments?.[0];
|
|
34
|
+
if (call.arguments?.length !== 1 || metadata.type !== "ObjectExpression") return null;
|
|
35
|
+
const fields = [];
|
|
36
|
+
for (const property of metadata.properties) {
|
|
37
|
+
if (property.type !== "Property" || property.kind !== "init" || property.computed || property.shorthand || property.method) return null;
|
|
38
|
+
fields.push([String(property.key.name ?? property.key.value), source.text.slice(property.value.start, property.value.end)]);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
callee: source.text.slice(call.callee.start, call.callee.end),
|
|
42
|
+
fields
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function fieldsText(fields, hmr) {
|
|
46
|
+
const selected = fields.filter(([name]) => HMR_FIELDS.has(name) === hmr);
|
|
47
|
+
if (hmr) selected.sort(([a], [b]) => a.localeCompare(b));
|
|
48
|
+
return JSON.stringify(selected);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether a component changed only in its HMR fields, or `null` when
|
|
52
|
+
* anything else in the statement changed.
|
|
53
|
+
*/
|
|
54
|
+
function componentChanged(stale, staleStatement, updated, updatedStatement) {
|
|
55
|
+
const staleClass = classOf(staleStatement);
|
|
56
|
+
const updatedClass = classOf(updatedStatement);
|
|
57
|
+
if (staleStatement.type !== updatedStatement.type || staleClass?.decorators.length !== 1 || updatedClass.decorators.length !== 1 || classHeader(stale, staleStatement, staleClass) !== classHeader(updated, updatedStatement, updatedClass) || stale.text.slice(staleClass.body.start, staleClass.body.end) !== updated.text.slice(updatedClass.body.start, updatedClass.body.end)) return null;
|
|
58
|
+
const staleMeta = decoratorMetadata(stale, staleClass.decorators[0]);
|
|
59
|
+
const updatedMeta = decoratorMetadata(updated, updatedClass.decorators[0]);
|
|
60
|
+
if (!staleMeta || !updatedMeta || staleMeta.callee !== updatedMeta.callee || fieldsText(staleMeta.fields, false) !== fieldsText(updatedMeta.fields, false)) return null;
|
|
61
|
+
return fieldsText(staleMeta.fields, true) !== fieldsText(updatedMeta.fields, true);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Applies the Angular CLI's HMR rule to an edited file. Returns the
|
|
65
|
+
* components whose `template`, `templateUrl`, `styles`, `styleUrl` or
|
|
66
|
+
* `stylesUrl` fields are the only changes, or `null` when the edit
|
|
67
|
+
* needs a full reload.
|
|
68
|
+
*/
|
|
69
|
+
function findHmrComponentUpdates(filename, staleText, updatedText, components) {
|
|
70
|
+
const stale = parse(filename, staleText);
|
|
71
|
+
const updated = parse(filename, updatedText);
|
|
72
|
+
if (!stale || !updated || stale.body.length !== updated.body.length) return null;
|
|
73
|
+
const changed = [];
|
|
74
|
+
for (let i = 0; i < updated.body.length; i++) {
|
|
75
|
+
const name = classOf(updated.body[i])?.id?.name;
|
|
76
|
+
if (name && components.has(name)) {
|
|
77
|
+
const result = componentChanged(stale, stale.body[i], updated, updated.body[i]);
|
|
78
|
+
if (result === null) return null;
|
|
79
|
+
if (result) changed.push(name);
|
|
80
|
+
} else if (statementText(stale, stale.body[i]) !== statementText(updated, updated.body[i])) return null;
|
|
81
|
+
}
|
|
82
|
+
return changed.length ? changed : null;
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { findHmrComponentUpdates };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=hmr-component-updates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hmr-component-updates.js","names":[],"sources":["../../../../src/lib/utils/hmr-component-updates.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\n\n// Component metadata fields the Angular CLI updates in place\nconst HMR_FIELDS = new Set([\n 'template',\n 'templateUrl',\n 'styles',\n 'styleUrl',\n 'stylesUrl',\n]);\n\ninterface Source {\n text: string;\n body: any[];\n}\n\ntype Fields = [name: string, value: string][];\n\nfunction parse(filename: string, text: string): Source | null {\n const { program, errors } = parseSync(filename, text);\n return errors.length ? null : { text, body: program.body };\n}\n\nfunction classOf(statement: any) {\n if (statement.type === 'ClassDeclaration') return statement;\n return statement.declaration?.type === 'ClassDeclaration'\n ? statement.declaration\n : undefined;\n}\n\n// Decorators written before `export` fall outside the statement span\nfunction statementStart(statement: any) {\n return Math.min(\n statement.start,\n classOf(statement)?.decorators[0]?.start ?? statement.start,\n );\n}\n\nfunction statementText(source: Source, statement: any) {\n return source.text.slice(statementStart(statement), statement.end);\n}\n\n// The statement without its decorator and class body\nfunction classHeader(source: Source, statement: any, cls: any) {\n const [decorator] = cls.decorators;\n return (\n source.text.slice(statementStart(statement), decorator.start) +\n source.text.slice(decorator.end, cls.body.start) +\n source.text.slice(cls.body.end, statement.end)\n );\n}\n\nfunction decoratorMetadata(source: Source, decorator: any) {\n const call = decorator.expression;\n const metadata = call.arguments?.[0];\n if (call.arguments?.length !== 1 || metadata.type !== 'ObjectExpression') {\n return null;\n }\n const fields: Fields = [];\n for (const property of metadata.properties) {\n if (\n property.type !== 'Property' ||\n property.kind !== 'init' ||\n property.computed ||\n property.shorthand ||\n property.method\n ) {\n return null;\n }\n fields.push([\n String(property.key.name ?? property.key.value),\n source.text.slice(property.value.start, property.value.end),\n ]);\n }\n return {\n callee: source.text.slice(call.callee.start, call.callee.end),\n fields,\n };\n}\n\nfunction fieldsText(fields: Fields, hmr: boolean) {\n const selected = fields.filter(([name]) => HMR_FIELDS.has(name) === hmr);\n // HMR fields can move; other fields must keep their order\n if (hmr) selected.sort(([a], [b]) => a.localeCompare(b));\n return JSON.stringify(selected);\n}\n\n/**\n * Whether a component changed only in its HMR fields, or `null` when\n * anything else in the statement changed.\n */\nfunction componentChanged(\n stale: Source,\n staleStatement: any,\n updated: Source,\n updatedStatement: any,\n): boolean | null {\n const staleClass = classOf(staleStatement);\n const updatedClass = classOf(updatedStatement);\n if (\n staleStatement.type !== updatedStatement.type ||\n staleClass?.decorators.length !== 1 ||\n updatedClass.decorators.length !== 1 ||\n classHeader(stale, staleStatement, staleClass) !==\n classHeader(updated, updatedStatement, updatedClass) ||\n stale.text.slice(staleClass.body.start, staleClass.body.end) !==\n updated.text.slice(updatedClass.body.start, updatedClass.body.end)\n ) {\n return null;\n }\n const staleMeta = decoratorMetadata(stale, staleClass.decorators[0]);\n const updatedMeta = decoratorMetadata(updated, updatedClass.decorators[0]);\n if (\n !staleMeta ||\n !updatedMeta ||\n staleMeta.callee !== updatedMeta.callee ||\n fieldsText(staleMeta.fields, false) !==\n fieldsText(updatedMeta.fields, false)\n ) {\n return null;\n }\n return (\n fieldsText(staleMeta.fields, true) !== fieldsText(updatedMeta.fields, true)\n );\n}\n\n/**\n * Applies the Angular CLI's HMR rule to an edited file. Returns the\n * components whose `template`, `templateUrl`, `styles`, `styleUrl` or\n * `stylesUrl` fields are the only changes, or `null` when the edit\n * needs a full reload.\n */\nexport function findHmrComponentUpdates(\n filename: string,\n staleText: string,\n updatedText: string,\n components: ReadonlySet<string>,\n): string[] | null {\n const stale = parse(filename, staleText);\n const updated = parse(filename, updatedText);\n if (!stale || !updated || stale.body.length !== updated.body.length) {\n return null;\n }\n const changed: string[] = [];\n for (let i = 0; i < updated.body.length; i++) {\n const name = classOf(updated.body[i])?.id?.name;\n if (name && components.has(name)) {\n const result = componentChanged(\n stale,\n stale.body[i],\n updated,\n updated.body[i],\n );\n if (result === null) return null;\n if (result) changed.push(name);\n } else if (\n statementText(stale, stale.body[i]) !==\n statementText(updated, updated.body[i])\n ) {\n return null;\n }\n }\n return changed.length ? changed : null;\n}\n"],"mappings":";;AAGA,IAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;AACF,CAAC;AASD,SAAS,MAAM,UAAkB,MAA6B;CAC5D,MAAM,EAAE,SAAS,WAAW,UAAU,UAAU,IAAI;CACpD,OAAO,OAAO,SAAS,OAAO;EAAE;EAAM,MAAM,QAAQ;CAAK;AAC3D;AAEA,SAAS,QAAQ,WAAgB;CAC/B,IAAI,UAAU,SAAS,oBAAoB,OAAO;CAClD,OAAO,UAAU,aAAa,SAAS,qBACnC,UAAU,cACV,KAAA;AACN;AAGA,SAAS,eA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OAAO,MAAM,KAAK,EAAE,MAClC,cAAc,SAAS,QAAQ,KAAK,EAAE,GAEtC,OAAO;CAEX;CACA,OAAO,QAAQ,SAAS,UAAU;AACpC"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export interface TcbTemplateSource {
|
|
2
|
+
templateFile?: string;
|
|
3
|
+
templateExpression?: {
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
type TemplateSources = Record<string, TcbTemplateSource>;
|
|
9
|
+
interface TcbLineRange {
|
|
10
|
+
startLine: number;
|
|
11
|
+
endLine: number;
|
|
12
|
+
filePath: string;
|
|
13
|
+
sourceCode: string;
|
|
14
|
+
templateSources: TemplateSources;
|
|
15
|
+
}
|
|
16
|
+
/** NGP's footer comment mapping TCB ids to the template they were generated from. */
|
|
17
|
+
export declare const TCB_TEMPLATE_SOURCES_PREFIX = "ngp-tcb-template-sources:";
|
|
18
|
+
export declare function readSpanComment(value: string): {
|
|
19
|
+
start: number;
|
|
20
|
+
end: number;
|
|
21
|
+
} | null;
|
|
22
|
+
export type TypeCheckerOption = "tsgo" | "tsrs" | {
|
|
23
|
+
command: string;
|
|
24
|
+
args?: string[];
|
|
25
|
+
};
|
|
26
|
+
interface TypeCheckerCommand {
|
|
27
|
+
command: string;
|
|
28
|
+
args: string[];
|
|
29
|
+
}
|
|
30
|
+
/** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */
|
|
31
|
+
export type FileChangeType = 1 | 2 | 3;
|
|
32
|
+
export declare function resolveTypeChecker(tsconfig: string, option: TypeCheckerOption): TypeCheckerCommand;
|
|
33
|
+
export declare class LspTypeChecker {
|
|
34
|
+
private proc;
|
|
35
|
+
private seq;
|
|
36
|
+
private pending;
|
|
37
|
+
private versions;
|
|
38
|
+
private queued;
|
|
39
|
+
private buffer;
|
|
40
|
+
private exitError;
|
|
41
|
+
readonly ready: Promise<void>;
|
|
42
|
+
constructor(tsconfig: string, option?: TypeCheckerOption);
|
|
43
|
+
private onData;
|
|
44
|
+
private send;
|
|
45
|
+
private notify;
|
|
46
|
+
private request;
|
|
47
|
+
updateDocument(filePath: string, text: string);
|
|
48
|
+
checkFile(filePath: string, sourceLineCount?: number, lines?: string[], tcbRanges?: TcbLineRange[]): Promise<string[]>;
|
|
49
|
+
/** Reports a change on disk; an open copy is closed so the checker rereads the file. */
|
|
50
|
+
notifyFileChanged(filePath: string, type: FileChangeType);
|
|
51
|
+
queueFile(filePath: string, sourceCode: string, tcbCode?: string | null);
|
|
52
|
+
flushQueue(watchMode?: boolean): Promise<string[]>;
|
|
53
|
+
close();
|
|
54
|
+
}
|
|
55
|
+
export {};
|