@analogjs/vite-plugin-angular 3.0.0-beta.2 → 3.0.0-beta.20
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,502 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, relative, resolve } from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { parseSync } from "oxc-parser";
|
|
5
|
+
import MagicString from "magic-string";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
//#region packages/vite-plugin-angular/src/lib/utils/lsp-type-checker.ts
|
|
9
|
+
/** NGP's footer comment mapping TCB ids to the template they were generated from. */
|
|
10
|
+
var TCB_TEMPLATE_SOURCES_PREFIX = "ngp-tcb-template-sources:";
|
|
11
|
+
var IGNORED_TCB_CODES = /* @__PURE__ */ new Set([
|
|
12
|
+
6133,
|
|
13
|
+
6199,
|
|
14
|
+
2695,
|
|
15
|
+
7006
|
|
16
|
+
]);
|
|
17
|
+
var BATCH_SIZE = 32;
|
|
18
|
+
var TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\d+$/;
|
|
19
|
+
var TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\d+$/;
|
|
20
|
+
var SPAN_COMMENT = /^(\d+),(\d+)$/;
|
|
21
|
+
function readSpanComment(value) {
|
|
22
|
+
const match = SPAN_COMMENT.exec(value);
|
|
23
|
+
return match ? {
|
|
24
|
+
start: Number(match[1]),
|
|
25
|
+
end: Number(match[2])
|
|
26
|
+
} : null;
|
|
27
|
+
}
|
|
28
|
+
function walk(node, visit) {
|
|
29
|
+
if (Array.isArray(node)) {
|
|
30
|
+
for (const child of node) walk(child, visit);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (!node || typeof node.type !== "string") return;
|
|
34
|
+
visit(node);
|
|
35
|
+
for (const key in node) {
|
|
36
|
+
const value = node[key];
|
|
37
|
+
if (value && typeof value === "object") walk(value, visit);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function declaredName(stmt) {
|
|
41
|
+
if (stmt.type === "VariableDeclaration") return stmt.declarations[0]?.id?.name;
|
|
42
|
+
if (stmt.type === "FunctionDeclaration" || stmt.type === "TSDeclareFunction") return stmt.id?.name;
|
|
43
|
+
}
|
|
44
|
+
function isTcbImport(stmt) {
|
|
45
|
+
const ns = stmt.type === "ImportDeclaration" && stmt.specifiers[0];
|
|
46
|
+
return ns?.type === "ImportNamespaceSpecifier" && TCB_IMPORT_ALIAS.test(ns.local.name);
|
|
47
|
+
}
|
|
48
|
+
function splitTcb(tcbCode) {
|
|
49
|
+
if (!tcbCode.includes("/*tcb")) return null;
|
|
50
|
+
const { program, comments, errors } = parseSync("tcb.ts", tcbCode);
|
|
51
|
+
if (errors.length > 0) return null;
|
|
52
|
+
const parts = {
|
|
53
|
+
source: [],
|
|
54
|
+
imports: [],
|
|
55
|
+
blocks: [],
|
|
56
|
+
templateSources: {}
|
|
57
|
+
};
|
|
58
|
+
const footer = comments.find((c) => c.value.startsWith(TCB_TEMPLATE_SOURCES_PREFIX));
|
|
59
|
+
if (footer) parts.templateSources = JSON.parse(footer.value.slice(25));
|
|
60
|
+
for (const stmt of program.body) if (TCB_LOCAL_NAME.test(declaredName(stmt) ?? "")) parts.blocks.push(stmt);
|
|
61
|
+
else {
|
|
62
|
+
parts.source.push(stmt);
|
|
63
|
+
if (isTcbImport(stmt)) parts.imports.push(stmt);
|
|
64
|
+
}
|
|
65
|
+
return parts.blocks.length > 0 ? parts : null;
|
|
66
|
+
}
|
|
67
|
+
function inPlaceDocument(filePath, sourceCode, tcbCode) {
|
|
68
|
+
const lines = sourceCode.split("\n");
|
|
69
|
+
const sourceLineCount = lines.length;
|
|
70
|
+
if (!tcbCode) return {
|
|
71
|
+
text: sourceCode,
|
|
72
|
+
meta: {
|
|
73
|
+
filePath,
|
|
74
|
+
sourceLineCount
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const parts = splitTcb(tcbCode);
|
|
78
|
+
const suffix = parts ? [...parts.imports, ...parts.blocks].map((stmt) => tcbCode.slice(stmt.start, stmt.end)).join("\n") : tcbCode;
|
|
79
|
+
lines.push(...suffix.split("\n"));
|
|
80
|
+
const range = {
|
|
81
|
+
startLine: sourceLineCount,
|
|
82
|
+
endLine: lines.length,
|
|
83
|
+
filePath,
|
|
84
|
+
sourceCode,
|
|
85
|
+
templateSources: parts?.templateSources ?? {}
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
text: lines.join("\n"),
|
|
89
|
+
meta: {
|
|
90
|
+
filePath,
|
|
91
|
+
sourceLineCount,
|
|
92
|
+
lines,
|
|
93
|
+
tcbRanges: [range]
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function trailingSpan(text, pos, commentsByStart) {
|
|
98
|
+
while (true) {
|
|
99
|
+
while (pos < text.length && /\s/.test(text[pos])) pos++;
|
|
100
|
+
const comment = commentsByStart.get(pos);
|
|
101
|
+
if (!comment) return null;
|
|
102
|
+
const span = readSpanComment(comment.value);
|
|
103
|
+
if (span) return span;
|
|
104
|
+
pos = comment.end;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function lineAndCharacter(text, offset) {
|
|
108
|
+
const before = text.slice(0, offset).split("\n");
|
|
109
|
+
return {
|
|
110
|
+
line: before.length,
|
|
111
|
+
character: before[before.length - 1].length + 1
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function templateLocation(range, lines, position) {
|
|
115
|
+
const chunk = lines.slice(range.startLine, range.endLine).join("\n");
|
|
116
|
+
let offset = position.character;
|
|
117
|
+
for (let i = range.startLine; i < position.line; i++) offset += lines[i].length + 1;
|
|
118
|
+
const { program, comments } = parseSync("tcb.ts", chunk);
|
|
119
|
+
const commentsByStart = new Map(comments.map((c) => [c.start, c]));
|
|
120
|
+
const ancestors = [];
|
|
121
|
+
walk(program.body, (node) => {
|
|
122
|
+
if (node.start <= offset && offset < node.end) ancestors.push(node);
|
|
123
|
+
});
|
|
124
|
+
const tcbFunction = ancestors.find((node) => node.type === "FunctionDeclaration" && /_tcb\d+$/.test(node.id?.name));
|
|
125
|
+
let span = null;
|
|
126
|
+
for (let i = ancestors.length - 1; i >= 0 && !span; i--) span = trailingSpan(chunk, ancestors[i].end, commentsByStart);
|
|
127
|
+
if (!tcbFunction || !span) return null;
|
|
128
|
+
const id = /(tcb\d+)$/.exec(tcbFunction.id.name)[1];
|
|
129
|
+
const source = range.templateSources[id];
|
|
130
|
+
const file = source?.templateFile ?? range.filePath;
|
|
131
|
+
let content = range.sourceCode;
|
|
132
|
+
if (source?.templateFile) try {
|
|
133
|
+
content = readFileSync(source.templateFile, "utf-8");
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const start = source?.templateExpression?.start ?? span.start;
|
|
138
|
+
return {
|
|
139
|
+
file,
|
|
140
|
+
...lineAndCharacter(content, start)
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function isBareTypeReference(type) {
|
|
144
|
+
return type?.type === "TSTypeReference" && type.typeName.type === "Identifier";
|
|
145
|
+
}
|
|
146
|
+
function collectExportedClasses(header) {
|
|
147
|
+
const exported = /* @__PURE__ */ new Map();
|
|
148
|
+
for (const stmt of header) {
|
|
149
|
+
const cls = stmt.declaration;
|
|
150
|
+
if (cls?.type !== "ClassDeclaration" || !cls.id) continue;
|
|
151
|
+
if (stmt.type === "ExportDefaultDeclaration") exported.set(cls.id.name, "default");
|
|
152
|
+
else if (stmt.type === "ExportNamedDeclaration") exported.set(cls.id.name, cls.id.name);
|
|
153
|
+
}
|
|
154
|
+
return exported;
|
|
155
|
+
}
|
|
156
|
+
function hostRelativeSpecifier(absPath, hostDir) {
|
|
157
|
+
const spec = relative(hostDir, absPath).replace(/\\/g, "/");
|
|
158
|
+
return spec.startsWith(".") ? spec : "./" + spec;
|
|
159
|
+
}
|
|
160
|
+
function sharedAliasFor(spec, sharedImports) {
|
|
161
|
+
let alias = sharedImports.get(spec);
|
|
162
|
+
if (!alias) {
|
|
163
|
+
alias = `_si${sharedImports.size}`;
|
|
164
|
+
sharedImports.set(spec, alias);
|
|
165
|
+
}
|
|
166
|
+
return alias;
|
|
167
|
+
}
|
|
168
|
+
function relocateTcb(filePath, tcbCode, hostDir, fileIdx, sharedImports) {
|
|
169
|
+
const parts = splitTcb(tcbCode);
|
|
170
|
+
if (!parts) return null;
|
|
171
|
+
const aliasSpecs = /* @__PURE__ */ new Map();
|
|
172
|
+
for (const stmt of parts.imports) aliasSpecs.set(stmt.specifiers[0].local.name, stmt.source.value);
|
|
173
|
+
const exportedClasses = collectExportedClasses(parts.source);
|
|
174
|
+
const identifiers = [];
|
|
175
|
+
const thisTypes = [];
|
|
176
|
+
let relocatable = true;
|
|
177
|
+
walk(parts.blocks, (node) => {
|
|
178
|
+
if (node.type === "Identifier") {
|
|
179
|
+
identifiers.push(node);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (node.type === "VariableDeclarator" && /^_pipe\d+$/.test(node.id.name) && isBareTypeReference(node.init?.typeAnnotation) || node.type === "TSFunctionType" && node.params[0]?.name === "init" && isBareTypeReference(node.returnType?.typeAnnotation)) {
|
|
183
|
+
relocatable = false;
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (node.type !== "FunctionDeclaration" || !/^_tcb\d+$/.test(node.id?.name)) return;
|
|
187
|
+
const thisType = node.params[0]?.typeAnnotation?.typeAnnotation;
|
|
188
|
+
if (node.params[0]?.name !== "this" || !isBareTypeReference(thisType)) return;
|
|
189
|
+
const exportProp = exportedClasses.get(thisType.typeName.name);
|
|
190
|
+
if (node.typeParameters || !exportProp) {
|
|
191
|
+
relocatable = false;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
thisTypes.push({
|
|
195
|
+
node: thisType.typeName,
|
|
196
|
+
exportProp
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
if (!relocatable) return null;
|
|
200
|
+
const fileDir = dirname(resolve(filePath));
|
|
201
|
+
const aliasMap = /* @__PURE__ */ new Map();
|
|
202
|
+
for (const [alias, rawSpec] of aliasSpecs) {
|
|
203
|
+
const spec = rawSpec.startsWith(".") ? hostRelativeSpecifier(resolve(fileDir, rawSpec), hostDir) : rawSpec;
|
|
204
|
+
aliasMap.set(alias, sharedAliasFor(spec, sharedImports));
|
|
205
|
+
}
|
|
206
|
+
const ms = new MagicString(tcbCode);
|
|
207
|
+
for (const node of identifiers) if (TCB_LOCAL_NAME.test(node.name)) ms.overwrite(node.start, node.end, `_f${fileIdx}_${node.name}`);
|
|
208
|
+
else if (aliasMap.has(node.name)) ms.overwrite(node.start, node.end, aliasMap.get(node.name));
|
|
209
|
+
if (thisTypes.length > 0) {
|
|
210
|
+
const selfAlias = sharedAliasFor(hostRelativeSpecifier(resolve(filePath).replace(/\.[cm]?tsx?$/, ""), hostDir), sharedImports);
|
|
211
|
+
for (const { node, exportProp } of thisTypes) ms.overwrite(node.start, node.end, `${selfAlias}.${exportProp}`);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
body: parts.blocks.map((stmt) => ms.slice(stmt.start, stmt.end)).join("\n"),
|
|
215
|
+
templateSources: parts.templateSources
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
var LSP_ARGS = ["--lsp", "--stdio"];
|
|
219
|
+
function resolveTsgoBinary(tsconfig) {
|
|
220
|
+
if (process.env["TSNATIVE_BINARY_PATH"]) return process.env["TSNATIVE_BINARY_PATH"];
|
|
221
|
+
const ext = process.platform === "win32" ? ".exe" : "";
|
|
222
|
+
const candidates = [{
|
|
223
|
+
parent: "typescript/package.json",
|
|
224
|
+
platform: `@typescript/typescript-${process.platform}-${process.arch}/package.json`,
|
|
225
|
+
bin: `tsc${ext}`
|
|
226
|
+
}, {
|
|
227
|
+
parent: "@typescript/native-preview/package.json",
|
|
228
|
+
platform: `@typescript/native-preview-${process.platform}-${process.arch}/package.json`,
|
|
229
|
+
bin: `tsgo${ext}`
|
|
230
|
+
}];
|
|
231
|
+
for (const base of [tsconfig, import.meta.url]) {
|
|
232
|
+
const req = createRequire(base);
|
|
233
|
+
for (const candidate of candidates) try {
|
|
234
|
+
const parentPkg = req.resolve(candidate.parent);
|
|
235
|
+
const platformPkg = createRequire(parentPkg).resolve(candidate.platform);
|
|
236
|
+
return resolve(dirname(platformPkg), "lib", candidate.bin);
|
|
237
|
+
} catch {}
|
|
238
|
+
}
|
|
239
|
+
throw new Error("disableTypeChecking: false requires TypeScript 7 (typescript@^7.0.0), @typescript/native-preview, or TSNATIVE_BINARY_PATH.");
|
|
240
|
+
}
|
|
241
|
+
function resolveTsrs(tsconfig) {
|
|
242
|
+
for (const base of [tsconfig, import.meta.url]) try {
|
|
243
|
+
const pkg = createRequire(base).resolve("tsrs/package.json");
|
|
244
|
+
return {
|
|
245
|
+
command: process.execPath,
|
|
246
|
+
args: [resolve(dirname(pkg), "bin", "tsrs"), ...LSP_ARGS]
|
|
247
|
+
};
|
|
248
|
+
} catch {}
|
|
249
|
+
throw new Error("typeChecker: 'tsrs' requires the tsrs package.");
|
|
250
|
+
}
|
|
251
|
+
function resolveTypeChecker(tsconfig, option) {
|
|
252
|
+
if (typeof option === "object") return {
|
|
253
|
+
command: option.command,
|
|
254
|
+
args: option.args ?? LSP_ARGS
|
|
255
|
+
};
|
|
256
|
+
if (option === "tsrs") return resolveTsrs(tsconfig);
|
|
257
|
+
return {
|
|
258
|
+
command: resolveTsgoBinary(tsconfig),
|
|
259
|
+
args: LSP_ARGS
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
var LspTypeChecker = class {
|
|
263
|
+
proc;
|
|
264
|
+
seq = 1;
|
|
265
|
+
pending = /* @__PURE__ */ new Map();
|
|
266
|
+
versions = /* @__PURE__ */ new Map();
|
|
267
|
+
queued = /* @__PURE__ */ new Map();
|
|
268
|
+
buffer = Buffer.alloc(0);
|
|
269
|
+
exitError;
|
|
270
|
+
ready;
|
|
271
|
+
constructor(tsconfig, option = "tsgo") {
|
|
272
|
+
const cwd = dirname(tsconfig);
|
|
273
|
+
const { command, args } = resolveTypeChecker(tsconfig, option);
|
|
274
|
+
this.proc = spawn(command, args, {
|
|
275
|
+
cwd,
|
|
276
|
+
stdio: [
|
|
277
|
+
"pipe",
|
|
278
|
+
"pipe",
|
|
279
|
+
"ignore"
|
|
280
|
+
]
|
|
281
|
+
});
|
|
282
|
+
this.proc.stdout.on("data", (chunk) => this.onData(chunk));
|
|
283
|
+
const fail = (error) => {
|
|
284
|
+
this.exitError ??= error;
|
|
285
|
+
for (const { reject } of this.pending.values()) reject(this.exitError);
|
|
286
|
+
this.pending.clear();
|
|
287
|
+
};
|
|
288
|
+
this.proc.on("error", fail);
|
|
289
|
+
this.proc.stdin.on("error", fail);
|
|
290
|
+
this.proc.on("exit", (code) => fail(/* @__PURE__ */ new Error(`type checker exited with code ${code}`)));
|
|
291
|
+
const rootUri = pathToFileURL(cwd).href;
|
|
292
|
+
this.ready = this.request("initialize", {
|
|
293
|
+
processId: process.pid,
|
|
294
|
+
rootUri,
|
|
295
|
+
capabilities: { textDocument: { diagnostic: {} } },
|
|
296
|
+
workspaceFolders: [{
|
|
297
|
+
uri: rootUri,
|
|
298
|
+
name: "root"
|
|
299
|
+
}]
|
|
300
|
+
}).then(() => this.notify("initialized", {}));
|
|
301
|
+
this.ready.catch(() => {});
|
|
302
|
+
}
|
|
303
|
+
onData(chunk) {
|
|
304
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
305
|
+
while (true) {
|
|
306
|
+
const headerEnd = this.buffer.indexOf("\r\n\r\n");
|
|
307
|
+
if (headerEnd === -1) break;
|
|
308
|
+
const match = /Content-Length: (\d+)/i.exec(this.buffer.subarray(0, headerEnd).toString("utf8"));
|
|
309
|
+
if (!match) break;
|
|
310
|
+
const bodyStart = headerEnd + 4;
|
|
311
|
+
const bodyEnd = bodyStart + Number(match[1]);
|
|
312
|
+
if (this.buffer.length < bodyEnd) break;
|
|
313
|
+
const msg = JSON.parse(this.buffer.subarray(bodyStart, bodyEnd).toString("utf8"));
|
|
314
|
+
this.buffer = this.buffer.subarray(bodyEnd);
|
|
315
|
+
if (msg.id !== void 0 && msg.method !== void 0) this.send({
|
|
316
|
+
jsonrpc: "2.0",
|
|
317
|
+
id: msg.id,
|
|
318
|
+
result: null
|
|
319
|
+
});
|
|
320
|
+
else if (msg.id !== void 0 && this.pending.has(msg.id)) {
|
|
321
|
+
const entry = this.pending.get(msg.id);
|
|
322
|
+
this.pending.delete(msg.id);
|
|
323
|
+
if (msg.error) entry.reject(new Error(msg.error.message));
|
|
324
|
+
else entry.resolve(msg.result);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
send(payload) {
|
|
329
|
+
const json = JSON.stringify(payload);
|
|
330
|
+
this.proc.stdin.write(`Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`);
|
|
331
|
+
}
|
|
332
|
+
notify(method, params) {
|
|
333
|
+
this.send({
|
|
334
|
+
jsonrpc: "2.0",
|
|
335
|
+
method,
|
|
336
|
+
params
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
request(method, params) {
|
|
340
|
+
if (this.exitError) return Promise.reject(this.exitError);
|
|
341
|
+
const id = this.seq++;
|
|
342
|
+
return new Promise((resolve, reject) => {
|
|
343
|
+
this.pending.set(id, {
|
|
344
|
+
resolve,
|
|
345
|
+
reject
|
|
346
|
+
});
|
|
347
|
+
this.send({
|
|
348
|
+
jsonrpc: "2.0",
|
|
349
|
+
id,
|
|
350
|
+
method,
|
|
351
|
+
params
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
updateDocument(filePath, text) {
|
|
356
|
+
const uri = pathToFileURL(resolve(filePath)).href;
|
|
357
|
+
if (!this.versions.has(uri)) {
|
|
358
|
+
this.versions.set(uri, 1);
|
|
359
|
+
this.notify("textDocument/didOpen", { textDocument: {
|
|
360
|
+
uri,
|
|
361
|
+
languageId: "typescript",
|
|
362
|
+
version: 1,
|
|
363
|
+
text
|
|
364
|
+
} });
|
|
365
|
+
}
|
|
366
|
+
const version = this.versions.get(uri) + 1;
|
|
367
|
+
this.versions.set(uri, version);
|
|
368
|
+
this.notify("textDocument/didChange", {
|
|
369
|
+
textDocument: {
|
|
370
|
+
uri,
|
|
371
|
+
version
|
|
372
|
+
},
|
|
373
|
+
contentChanges: [{ text }]
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
async checkFile(filePath, sourceLineCount, lines, tcbRanges) {
|
|
377
|
+
const resolvedPath = resolve(filePath);
|
|
378
|
+
const errors = [];
|
|
379
|
+
const diag = await this.request("textDocument/diagnostic", { textDocument: { uri: pathToFileURL(resolvedPath).href } });
|
|
380
|
+
for (const item of diag?.items ?? []) {
|
|
381
|
+
if (item.severity !== 1) continue;
|
|
382
|
+
const line = item.range.start.line;
|
|
383
|
+
if (sourceLineCount !== void 0 && line >= sourceLineCount) {
|
|
384
|
+
if (!IGNORED_TCB_CODES.has(Number(item.code)) && !lines?.[line]?.includes("/*D:ignore*/")) {
|
|
385
|
+
const range = tcbRanges?.find((r) => line >= r.startLine && line < r.endLine);
|
|
386
|
+
const location = range && lines && templateLocation(range, lines, item.range.start);
|
|
387
|
+
errors.push(location ? `${location.file}:${location.line}:${location.character} - error TS${item.code}: ${item.message}` : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`);
|
|
388
|
+
}
|
|
389
|
+
} else errors.push(`${filePath}:${line + 1}:${item.range.start.character + 1} - error TS${item.code}: ${item.message}`);
|
|
390
|
+
}
|
|
391
|
+
return errors;
|
|
392
|
+
}
|
|
393
|
+
/** Reports a change on disk; an open copy is closed so the checker rereads the file. */
|
|
394
|
+
notifyFileChanged(filePath, type) {
|
|
395
|
+
const uri = pathToFileURL(resolve(filePath)).href;
|
|
396
|
+
const wasOpen = this.versions.delete(uri);
|
|
397
|
+
this.ready.then(() => {
|
|
398
|
+
if (wasOpen) this.notify("textDocument/didClose", { textDocument: { uri } });
|
|
399
|
+
this.notify("workspace/didChangeWatchedFiles", { changes: [{
|
|
400
|
+
uri,
|
|
401
|
+
type
|
|
402
|
+
}] });
|
|
403
|
+
}, () => {});
|
|
404
|
+
}
|
|
405
|
+
queueFile(filePath, sourceCode, tcbCode) {
|
|
406
|
+
this.queued.set(filePath, {
|
|
407
|
+
sourceCode,
|
|
408
|
+
tcbCode
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
async flushQueue(watchMode = false) {
|
|
412
|
+
if (this.queued.size === 0) return [];
|
|
413
|
+
const entries = Array.from(this.queued.entries());
|
|
414
|
+
this.queued.clear();
|
|
415
|
+
await this.ready;
|
|
416
|
+
const metas = [];
|
|
417
|
+
let updatesCount = 0;
|
|
418
|
+
const update = async (filePath, text) => {
|
|
419
|
+
this.updateDocument(filePath, text);
|
|
420
|
+
updatesCount++;
|
|
421
|
+
if (updatesCount % BATCH_SIZE === 0) await new Promise((r) => setTimeout(r, 5));
|
|
422
|
+
};
|
|
423
|
+
if (!watchMode && entries.length > 1) {
|
|
424
|
+
const [hostFilePath, hostItem] = entries[0];
|
|
425
|
+
const hostDir = dirname(resolve(hostFilePath));
|
|
426
|
+
const hostUri = pathToFileURL(resolve(hostFilePath)).href;
|
|
427
|
+
const sharedImports = /* @__PURE__ */ new Map();
|
|
428
|
+
const relocatedChunks = [];
|
|
429
|
+
let hostRelocated = false;
|
|
430
|
+
for (let i = 0; i < entries.length; i++) {
|
|
431
|
+
const [filePath, { sourceCode, tcbCode }] = entries[i];
|
|
432
|
+
const uri = pathToFileURL(resolve(filePath)).href;
|
|
433
|
+
if (tcbCode && !this.versions.has(uri)) {
|
|
434
|
+
const relocated = relocateTcb(filePath, tcbCode, hostDir, i, sharedImports);
|
|
435
|
+
if (relocated !== null) {
|
|
436
|
+
relocatedChunks.push({
|
|
437
|
+
filePath,
|
|
438
|
+
sourceCode,
|
|
439
|
+
...relocated
|
|
440
|
+
});
|
|
441
|
+
if (i === 0) hostRelocated = true;
|
|
442
|
+
else metas.push({
|
|
443
|
+
filePath,
|
|
444
|
+
sourceLineCount: sourceCode.split("\n").length
|
|
445
|
+
});
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
if (i === 0) continue;
|
|
450
|
+
const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
|
|
451
|
+
if (tcbCode || this.versions.has(uri)) await update(filePath, text);
|
|
452
|
+
metas.push(meta);
|
|
453
|
+
}
|
|
454
|
+
const { meta: hostMeta } = inPlaceDocument(hostFilePath, hostItem.sourceCode, hostRelocated ? null : hostItem.tcbCode);
|
|
455
|
+
const hostLines = hostMeta.lines ?? hostItem.sourceCode.split("\n");
|
|
456
|
+
const hostTcbRanges = hostMeta.tcbRanges ?? [];
|
|
457
|
+
if (relocatedChunks.length > 0) {
|
|
458
|
+
for (const [spec, alias] of sharedImports) hostLines.push(`import * as ${alias} from '${spec}';`);
|
|
459
|
+
for (const { filePath, sourceCode, body, templateSources } of relocatedChunks) {
|
|
460
|
+
const startLine = hostLines.length;
|
|
461
|
+
hostLines.push(...body.split("\n"));
|
|
462
|
+
hostTcbRanges.push({
|
|
463
|
+
startLine,
|
|
464
|
+
endLine: hostLines.length,
|
|
465
|
+
filePath,
|
|
466
|
+
sourceCode,
|
|
467
|
+
templateSources
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const hasHostTcb = hostTcbRanges.length > 0;
|
|
472
|
+
if (hasHostTcb || this.versions.has(hostUri)) this.updateDocument(hostFilePath, hostLines.join("\n"));
|
|
473
|
+
metas.unshift({
|
|
474
|
+
filePath: hostFilePath,
|
|
475
|
+
sourceLineCount: hostMeta.sourceLineCount,
|
|
476
|
+
lines: hasHostTcb ? hostLines : void 0,
|
|
477
|
+
tcbRanges: hasHostTcb ? hostTcbRanges : void 0
|
|
478
|
+
});
|
|
479
|
+
} else for (const [filePath, { sourceCode, tcbCode }] of entries) {
|
|
480
|
+
const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
|
|
481
|
+
const uri = pathToFileURL(resolve(filePath)).href;
|
|
482
|
+
if (tcbCode || watchMode || this.versions.has(uri)) await update(filePath, text);
|
|
483
|
+
metas.push(meta);
|
|
484
|
+
}
|
|
485
|
+
const errors = [];
|
|
486
|
+
const first = metas[0];
|
|
487
|
+
errors.push(...await this.checkFile(first.filePath, first.sourceLineCount, first.lines, first.tcbRanges));
|
|
488
|
+
for (let i = 1; i < metas.length; i += BATCH_SIZE) {
|
|
489
|
+
const slice = metas.slice(i, i + BATCH_SIZE);
|
|
490
|
+
const batchResults = await Promise.all(slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) => this.checkFile(filePath, sourceLineCount, lines, tcbRanges)));
|
|
491
|
+
for (const res of batchResults) errors.push(...res);
|
|
492
|
+
}
|
|
493
|
+
return errors;
|
|
494
|
+
}
|
|
495
|
+
close() {
|
|
496
|
+
this.proc.kill();
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
//#endregion
|
|
500
|
+
export { LspTypeChecker, TCB_TEMPLATE_SOURCES_PREFIX, readSpanComment, resolveTypeChecker };
|
|
501
|
+
|
|
502
|
+
//# sourceMappingURL=lsp-type-checker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lsp-type-checker.js","names":[],"sources":["../../../../src/lib/utils/lsp-type-checker.ts"],"sourcesContent":["import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport { dirname, relative, resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport MagicString from 'magic-string';\nimport { parseSync } from 'oxc-parser';\n\ninterface LspDiagnostic {\n range: { start: { line: number; character: number } };\n severity?: number;\n code?: number | string;\n message: string;\n}\n\n// Same shape as NGP's `TcbTemplateSource`\nexport interface TcbTemplateSource {\n templateFile?: string;\n templateExpression?: { start: number; end: number };\n}\n\ntype TemplateSources = Record<string, TcbTemplateSource>;\n\ninterface TcbLineRange {\n startLine: number;\n endLine: number;\n filePath: string;\n sourceCode: string;\n templateSources: TemplateSources;\n}\n\ninterface FileMeta {\n filePath: string;\n sourceLineCount: number;\n lines?: string[];\n tcbRanges?: TcbLineRange[];\n}\n\n/** NGP's footer comment mapping TCB ids to the template they were generated from. */\nexport const TCB_TEMPLATE_SOURCES_PREFIX = 'ngp-tcb-template-sources:';\n\nconst IGNORED_TCB_CODES = new Set([6133, 6199, 2695, 7006]);\nconst BATCH_SIZE = 32;\n\nconst TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\\d+$/;\nconst TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\\d+$/;\nconst SPAN_COMMENT = /^(\\d+),(\\d+)$/;\n\nexport function readSpanComment(\n value: string,\n): { start: number; end: number } | null {\n const match = SPAN_COMMENT.exec(value);\n return match ? { start: Number(match[1]), end: Number(match[2]) } : null;\n}\n\nfunction walk(node: any, visit: (node: any) => void): void {\n if (Array.isArray(node)) {\n for (const child of node) walk(child, visit);\n return;\n }\n if (!node || typeof node.type !== 'string') return;\n visit(node);\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === 'object') walk(value, visit);\n }\n}\n\nfunction declaredName(stmt: any): string | undefined {\n if (stmt.type === 'VariableDeclaration')\n return stmt.declarations[0]?.id?.name;\n if (stmt.type === 'FunctionDeclaration' || stmt.type === 'TSDeclareFunction')\n return stmt.id?.name;\n return undefined;\n}\n\nfunction isTcbImport(stmt: any): boolean {\n const ns = stmt.type === 'ImportDeclaration' && stmt.specifiers[0];\n return (\n ns?.type === 'ImportNamespaceSpecifier' &&\n TCB_IMPORT_ALIAS.test(ns.local.name)\n );\n}\n\ninterface TcbParts {\n source: any[];\n imports: any[];\n blocks: any[];\n templateSources: TemplateSources;\n}\n\n// NGP places each block right after its class, so source can follow a block\nfunction splitTcb(tcbCode: string): TcbParts | null {\n if (!tcbCode.includes('/*tcb')) return null;\n const { program, comments, errors } = parseSync('tcb.ts', tcbCode);\n if (errors.length > 0) return null;\n const parts: TcbParts = {\n source: [],\n imports: [],\n blocks: [],\n templateSources: {},\n };\n const footer = comments.find((c) =>\n c.value.startsWith(TCB_TEMPLATE_SOURCES_PREFIX),\n );\n if (footer) {\n parts.templateSources = JSON.parse(\n footer.value.slice(TCB_TEMPLATE_SOURCES_PREFIX.length),\n );\n }\n for (const stmt of program.body) {\n if (TCB_LOCAL_NAME.test(declaredName(stmt) ?? '')) {\n parts.blocks.push(stmt);\n } else {\n parts.source.push(stmt);\n if (isTcbImport(stmt)) parts.imports.push(stmt);\n }\n }\n return parts.blocks.length > 0 ? parts : null;\n}\n\nfunction inPlaceDocument(\n filePath: string,\n sourceCode: string,\n tcbCode?: string | null,\n): { text: string; meta: FileMeta } {\n const lines = sourceCode.split('\\n');\n const sourceLineCount = lines.length;\n if (!tcbCode)\n return { text: sourceCode, meta: { filePath, sourceLineCount } };\n const parts = splitTcb(tcbCode);\n const suffix = parts\n ? [...parts.imports, ...parts.blocks]\n .map((stmt) => tcbCode.slice(stmt.start, stmt.end))\n .join('\\n')\n : tcbCode;\n lines.push(...suffix.split('\\n'));\n const range: TcbLineRange = {\n startLine: sourceLineCount,\n endLine: lines.length,\n filePath,\n sourceCode,\n templateSources: parts?.templateSources ?? {},\n };\n return {\n text: lines.join('\\n'),\n meta: { filePath, sourceLineCount, lines, tcbRanges: [range] },\n };\n}\n\nfunction trailingSpan(\n text: string,\n pos: number,\n commentsByStart: Map<number, any>,\n): { start: number; end: number } | null {\n while (true) {\n while (pos < text.length && /\\s/.test(text[pos])) pos++;\n const comment = commentsByStart.get(pos);\n if (!comment) return null;\n const span = readSpanComment(comment.value);\n if (span) return span;\n pos = comment.end;\n }\n}\n\nfunction lineAndCharacter(text: string, offset: number) {\n const before = text.slice(0, offset).split('\\n');\n return {\n line: before.length,\n character: before[before.length - 1].length + 1,\n };\n}\n\n// Mirrors ngtsc: the span comment trailing the innermost node at the diagnostic\nfunction templateLocation(\n range: TcbLineRange,\n lines: string[],\n position: { line: number; character: number },\n): { file: string; line: number; character: number } | null {\n const chunk = lines.slice(range.startLine, range.endLine).join('\\n');\n let offset = position.character;\n for (let i = range.startLine; i < position.line; i++) {\n offset += lines[i].length + 1;\n }\n const { program, comments } = parseSync('tcb.ts', chunk);\n const commentsByStart = new Map(comments.map((c) => [c.start, c]));\n const ancestors: any[] = [];\n walk(program.body, (node) => {\n if (node.start <= offset && offset < node.end) ancestors.push(node);\n });\n const tcbFunction = ancestors.find(\n (node) =>\n node.type === 'FunctionDeclaration' && /_tcb\\d+$/.test(node.id?.name),\n );\n let span: { start: number; end: number } | null = null;\n for (let i = ancestors.length - 1; i >= 0 && !span; i--) {\n span = trailingSpan(chunk, ancestors[i].end, commentsByStart);\n }\n if (!tcbFunction || !span) return null;\n\n const id = /(tcb\\d+)$/.exec(tcbFunction.id.name)![1];\n const source = range.templateSources[id];\n const file = source?.templateFile ?? range.filePath;\n let content = range.sourceCode;\n if (source?.templateFile) {\n try {\n content = readFileSync(source.templateFile, 'utf-8');\n } catch {\n return null;\n }\n }\n const start = source?.templateExpression?.start ?? span.start;\n return { file, ...lineAndCharacter(content, start) };\n}\n\nfunction isBareTypeReference(type: any): boolean {\n return (\n type?.type === 'TSTypeReference' && type.typeName.type === 'Identifier'\n );\n}\n\nfunction collectExportedClasses(header: any[]): Map<string, string> {\n const exported = new Map<string, string>();\n for (const stmt of header) {\n const cls = stmt.declaration;\n if (cls?.type !== 'ClassDeclaration' || !cls.id) continue;\n if (stmt.type === 'ExportDefaultDeclaration') {\n exported.set(cls.id.name, 'default');\n } else if (stmt.type === 'ExportNamedDeclaration') {\n exported.set(cls.id.name, cls.id.name);\n }\n }\n return exported;\n}\n\nfunction hostRelativeSpecifier(absPath: string, hostDir: string): string {\n const spec = relative(hostDir, absPath).replace(/\\\\/g, '/');\n return spec.startsWith('.') ? spec : './' + spec;\n}\n\nfunction sharedAliasFor(spec: string, sharedImports: Map<string, string>) {\n let alias = sharedImports.get(spec);\n if (!alias) {\n alias = `_si${sharedImports.size}`;\n sharedImports.set(spec, alias);\n }\n return alias;\n}\n\nfunction relocateTcb(\n filePath: string,\n tcbCode: string,\n hostDir: string,\n fileIdx: number,\n sharedImports: Map<string, string>,\n): { body: string; templateSources: TemplateSources } | null {\n const parts = splitTcb(tcbCode);\n if (!parts) return null;\n\n const aliasSpecs = new Map<string, string>();\n for (const stmt of parts.imports) {\n aliasSpecs.set(stmt.specifiers[0].local.name, stmt.source.value);\n }\n\n const exportedClasses = collectExportedClasses(parts.source);\n const identifiers: any[] = [];\n const thisTypes: Array<{ node: any; exportProp: string }> = [];\n let relocatable = true;\n\n walk(parts.blocks, (node) => {\n if (node.type === 'Identifier') {\n identifiers.push(node);\n return;\n }\n // Same-file directives or pipes have no namespace import to relocate\n if (\n (node.type === 'VariableDeclarator' &&\n /^_pipe\\d+$/.test(node.id.name) &&\n isBareTypeReference(node.init?.typeAnnotation)) ||\n (node.type === 'TSFunctionType' &&\n node.params[0]?.name === 'init' &&\n isBareTypeReference(node.returnType?.typeAnnotation))\n ) {\n relocatable = false;\n return;\n }\n if (node.type !== 'FunctionDeclaration' || !/^_tcb\\d+$/.test(node.id?.name))\n return;\n const thisType = node.params[0]?.typeAnnotation?.typeAnnotation;\n if (node.params[0]?.name !== 'this' || !isBareTypeReference(thisType))\n return;\n const exportProp = exportedClasses.get(thisType.typeName.name);\n if (node.typeParameters || !exportProp) {\n relocatable = false;\n return;\n }\n thisTypes.push({ node: thisType.typeName, exportProp });\n });\n if (!relocatable) return null;\n\n const fileDir = dirname(resolve(filePath));\n const aliasMap = new Map<string, string>();\n for (const [alias, rawSpec] of aliasSpecs) {\n const spec = rawSpec.startsWith('.')\n ? hostRelativeSpecifier(resolve(fileDir, rawSpec), hostDir)\n : rawSpec;\n aliasMap.set(alias, sharedAliasFor(spec, sharedImports));\n }\n\n const ms = new MagicString(tcbCode);\n for (const node of identifiers) {\n if (TCB_LOCAL_NAME.test(node.name)) {\n ms.overwrite(node.start, node.end, `_f${fileIdx}_${node.name}`);\n } else if (aliasMap.has(node.name)) {\n ms.overwrite(node.start, node.end, aliasMap.get(node.name)!);\n }\n }\n if (thisTypes.length > 0) {\n const selfSpec = hostRelativeSpecifier(\n resolve(filePath).replace(/\\.[cm]?tsx?$/, ''),\n hostDir,\n );\n const selfAlias = sharedAliasFor(selfSpec, sharedImports);\n for (const { node, exportProp } of thisTypes) {\n ms.overwrite(node.start, node.end, `${selfAlias}.${exportProp}`);\n }\n }\n\n return {\n body: parts.blocks.map((stmt) => ms.slice(stmt.start, stmt.end)).join('\\n'),\n templateSources: parts.templateSources,\n };\n}\n\nexport type TypeCheckerOption =\n | 'tsgo'\n | 'tsrs'\n | { command: string; args?: string[] };\n\ninterface TypeCheckerCommand {\n command: string;\n args: string[];\n}\n\nconst LSP_ARGS = ['--lsp', '--stdio'];\n\n/** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */\nexport type FileChangeType = 1 | 2 | 3;\n\nfunction resolveTsgoBinary(tsconfig: string): string {\n if (process.env['TSNATIVE_BINARY_PATH'])\n return process.env['TSNATIVE_BINARY_PATH'];\n const ext = process.platform === 'win32' ? '.exe' : '';\n const candidates = [\n {\n parent: 'typescript/package.json',\n platform: `@typescript/typescript-${process.platform}-${process.arch}/package.json`,\n bin: `tsc${ext}`,\n },\n {\n parent: '@typescript/native-preview/package.json',\n platform: `@typescript/native-preview-${process.platform}-${process.arch}/package.json`,\n bin: `tsgo${ext}`,\n },\n ];\n for (const base of [tsconfig, import.meta.url]) {\n const req = createRequire(base);\n for (const candidate of candidates) {\n try {\n const parentPkg = req.resolve(candidate.parent);\n const platformPkg = createRequire(parentPkg).resolve(\n candidate.platform,\n );\n return resolve(dirname(platformPkg), 'lib', candidate.bin);\n } catch {\n // try next candidate\n }\n }\n }\n throw new Error(\n 'disableTypeChecking: false requires TypeScript 7 (typescript@^7.0.0), @typescript/native-preview, or TSNATIVE_BINARY_PATH.',\n );\n}\n\n// Run tsrs through its launcher, which selects the platform binary.\nfunction resolveTsrs(tsconfig: string): TypeCheckerCommand {\n for (const base of [tsconfig, import.meta.url]) {\n try {\n const pkg = createRequire(base).resolve('tsrs/package.json');\n return {\n command: process.execPath,\n args: [resolve(dirname(pkg), 'bin', 'tsrs'), ...LSP_ARGS],\n };\n } catch {\n // try next base\n }\n }\n throw new Error(\"typeChecker: 'tsrs' requires the tsrs package.\");\n}\n\nexport function resolveTypeChecker(\n tsconfig: string,\n option: TypeCheckerOption,\n): TypeCheckerCommand {\n if (typeof option === 'object') {\n return { command: option.command, args: option.args ?? LSP_ARGS };\n }\n if (option === 'tsrs') return resolveTsrs(tsconfig);\n return { command: resolveTsgoBinary(tsconfig), args: LSP_ARGS };\n}\n\nexport class LspTypeChecker {\n private proc: ChildProcessWithoutNullStreams;\n private seq = 1;\n private pending = new Map<\n number,\n { resolve: (value: any) => void; reject: (error: Error) => void }\n >();\n private versions = new Map<string, number>();\n private queued = new Map<\n string,\n { sourceCode: string; tcbCode?: string | null }\n >();\n private buffer = Buffer.alloc(0);\n private exitError: Error | undefined;\n readonly ready: Promise<void>;\n\n constructor(tsconfig: string, option: TypeCheckerOption = 'tsgo') {\n const cwd = dirname(tsconfig);\n const { command, args } = resolveTypeChecker(tsconfig, option);\n this.proc = spawn(command, args, {\n cwd,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n this.proc.stdout.on('data', (chunk: Buffer) => this.onData(chunk));\n const fail = (error: Error) => {\n this.exitError ??= error;\n for (const { reject } of this.pending.values()) reject(this.exitError);\n this.pending.clear();\n };\n this.proc.on('error', fail);\n this.proc.stdin.on('error', fail);\n this.proc.on('exit', (code) =>\n fail(new Error(`type checker exited with code ${code}`)),\n );\n const rootUri = pathToFileURL(cwd).href;\n this.ready = this.request('initialize', {\n processId: process.pid,\n rootUri,\n capabilities: { textDocument: { diagnostic: {} } },\n workspaceFolders: [{ uri: rootUri, name: 'root' }],\n }).then(() => this.notify('initialized', {}));\n this.ready.catch(() => {});\n }\n\n private onData(chunk: Buffer) {\n this.buffer = Buffer.concat([this.buffer, chunk]);\n while (true) {\n const headerEnd = this.buffer.indexOf('\\r\\n\\r\\n');\n if (headerEnd === -1) break;\n const match = /Content-Length: (\\d+)/i.exec(\n this.buffer.subarray(0, headerEnd).toString('utf8'),\n );\n if (!match) break;\n const bodyStart = headerEnd + 4;\n const bodyEnd = bodyStart + Number(match[1]);\n if (this.buffer.length < bodyEnd) break;\n const msg = JSON.parse(\n this.buffer.subarray(bodyStart, bodyEnd).toString('utf8'),\n );\n this.buffer = this.buffer.subarray(bodyEnd);\n if (msg.id !== undefined && msg.method !== undefined) {\n this.send({ jsonrpc: '2.0', id: msg.id, result: null });\n } else if (msg.id !== undefined && this.pending.has(msg.id)) {\n const entry = this.pending.get(msg.id)!;\n this.pending.delete(msg.id);\n if (msg.error) entry.reject(new Error(msg.error.message));\n else entry.resolve(msg.result);\n }\n }\n }\n\n private send(payload: unknown) {\n const json = JSON.stringify(payload);\n this.proc.stdin.write(\n `Content-Length: ${Buffer.byteLength(json, 'utf8')}\\r\\n\\r\\n${json}`,\n );\n }\n\n private notify(method: string, params: unknown) {\n this.send({ jsonrpc: '2.0', method, params });\n }\n\n private request(method: string, params: unknown): Promise<any> {\n if (this.exitError) return Promise.reject(this.exitError);\n const id = this.seq++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.send({ jsonrpc: '2.0', id, method, params });\n });\n }\n\n updateDocument(filePath: string, text: string) {\n const uri = pathToFileURL(resolve(filePath)).href;\n if (!this.versions.has(uri)) {\n // tsgo 7.0.0-dev.20260412 ignores didOpen text once other documents are open\n this.versions.set(uri, 1);\n this.notify('textDocument/didOpen', {\n textDocument: { uri, languageId: 'typescript', version: 1, text },\n });\n }\n const version = this.versions.get(uri)! + 1;\n this.versions.set(uri, version);\n this.notify('textDocument/didChange', {\n textDocument: { uri, version },\n contentChanges: [{ text }],\n });\n }\n\n async checkFile(\n filePath: string,\n sourceLineCount?: number,\n lines?: string[],\n tcbRanges?: TcbLineRange[],\n ): Promise<string[]> {\n const resolvedPath = resolve(filePath);\n const errors: string[] = [];\n const diag = await this.request('textDocument/diagnostic', {\n textDocument: { uri: pathToFileURL(resolvedPath).href },\n });\n for (const item of (diag?.items ?? []) as LspDiagnostic[]) {\n if (item.severity !== 1) continue;\n const line = item.range.start.line;\n if (sourceLineCount !== undefined && line >= sourceLineCount) {\n if (\n !IGNORED_TCB_CODES.has(Number(item.code)) &&\n !lines?.[line]?.includes('/*D:ignore*/')\n ) {\n const range = tcbRanges?.find(\n (r) => line >= r.startLine && line < r.endLine,\n );\n const location =\n range && lines && templateLocation(range, lines, item.range.start);\n errors.push(\n location\n ? `${location.file}:${location.line}:${location.character} - error TS${item.code}: ${item.message}`\n : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`,\n );\n }\n } else {\n errors.push(\n `${filePath}:${line + 1}:${item.range.start.character + 1} - error TS${item.code}: ${item.message}`,\n );\n }\n }\n return errors;\n }\n\n /** Reports a change on disk; an open copy is closed so the checker rereads the file. */\n notifyFileChanged(filePath: string, type: FileChangeType) {\n const uri = pathToFileURL(resolve(filePath)).href;\n const wasOpen = this.versions.delete(uri);\n this.ready.then(\n () => {\n if (wasOpen)\n this.notify('textDocument/didClose', { textDocument: { uri } });\n this.notify('workspace/didChangeWatchedFiles', {\n changes: [{ uri, type }],\n });\n },\n () => {},\n );\n }\n\n queueFile(filePath: string, sourceCode: string, tcbCode?: string | null) {\n this.queued.set(filePath, { sourceCode, tcbCode });\n }\n\n async flushQueue(watchMode = false): Promise<string[]> {\n if (this.queued.size === 0) return [];\n const entries = Array.from(this.queued.entries());\n this.queued.clear();\n await this.ready;\n\n const metas: FileMeta[] = [];\n let updatesCount = 0;\n const update = async (filePath: string, text: string) => {\n this.updateDocument(filePath, text);\n updatesCount++;\n if (updatesCount % BATCH_SIZE === 0) {\n await new Promise((r) => setTimeout(r, 5));\n }\n };\n\n if (!watchMode && entries.length > 1) {\n const [hostFilePath, hostItem] = entries[0];\n const hostDir = dirname(resolve(hostFilePath));\n const hostUri = pathToFileURL(resolve(hostFilePath)).href;\n const sharedImports = new Map<string, string>();\n const relocatedChunks: Array<{\n filePath: string;\n sourceCode: string;\n body: string;\n templateSources: TemplateSources;\n }> = [];\n let hostRelocated = false;\n\n for (let i = 0; i < entries.length; i++) {\n const [filePath, { sourceCode, tcbCode }] = entries[i];\n const uri = pathToFileURL(resolve(filePath)).href;\n if (tcbCode && !this.versions.has(uri)) {\n const relocated = relocateTcb(\n filePath,\n tcbCode,\n hostDir,\n i,\n sharedImports,\n );\n if (relocated !== null) {\n relocatedChunks.push({ filePath, sourceCode, ...relocated });\n if (i === 0) {\n hostRelocated = true;\n } else {\n metas.push({\n filePath,\n sourceLineCount: sourceCode.split('\\n').length,\n });\n }\n continue;\n }\n }\n if (i === 0) continue;\n\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n if (tcbCode || this.versions.has(uri)) await update(filePath, text);\n metas.push(meta);\n }\n\n const { meta: hostMeta } = inPlaceDocument(\n hostFilePath,\n hostItem.sourceCode,\n hostRelocated ? null : hostItem.tcbCode,\n );\n const hostLines = hostMeta.lines ?? hostItem.sourceCode.split('\\n');\n const hostTcbRanges = hostMeta.tcbRanges ?? [];\n\n if (relocatedChunks.length > 0) {\n for (const [spec, alias] of sharedImports) {\n hostLines.push(`import * as ${alias} from '${spec}';`);\n }\n for (const {\n filePath,\n sourceCode,\n body,\n templateSources,\n } of relocatedChunks) {\n const startLine = hostLines.length;\n hostLines.push(...body.split('\\n'));\n hostTcbRanges.push({\n startLine,\n endLine: hostLines.length,\n filePath,\n sourceCode,\n templateSources,\n });\n }\n }\n\n const hasHostTcb = hostTcbRanges.length > 0;\n if (hasHostTcb || this.versions.has(hostUri)) {\n this.updateDocument(hostFilePath, hostLines.join('\\n'));\n }\n metas.unshift({\n filePath: hostFilePath,\n sourceLineCount: hostMeta.sourceLineCount,\n lines: hasHostTcb ? hostLines : undefined,\n tcbRanges: hasHostTcb ? hostTcbRanges : undefined,\n });\n } else {\n for (const [filePath, { sourceCode, tcbCode }] of entries) {\n const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);\n const uri = pathToFileURL(resolve(filePath)).href;\n if (tcbCode || watchMode || this.versions.has(uri)) {\n await update(filePath, text);\n }\n metas.push(meta);\n }\n }\n\n const errors: string[] = [];\n const first = metas[0];\n errors.push(\n ...(await this.checkFile(\n first.filePath,\n first.sourceLineCount,\n first.lines,\n first.tcbRanges,\n )),\n );\n\n for (let i = 1; i < metas.length; i += BATCH_SIZE) {\n const slice = metas.slice(i, i + BATCH_SIZE);\n const batchResults = await Promise.all(\n slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) =>\n this.checkFile(filePath, sourceLineCount, lines, tcbRanges),\n ),\n );\n for (const res of batchResults) {\n errors.push(...res);\n }\n }\n return errors;\n }\n\n close() {\n this.proc.kill();\n }\n}\n"],"mappings":";;;;;;;;;AAuCA,IAAa,8BAA8B;AAE3C,IAAM,oCAAoB,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;AAAI,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iB,OAAO,gBAC7C,KAAK,UAAU,UAAU,iBAAiB,OAAO,SAAS,CAC5D,CACF;GACA,KAAK,MAAM,OAAO,cAChB,OAAO,KAAK,GAAG,GAAG;EAEtB;EACA,OAAO;CACT;CAEA,QAAQ;EACN,KAAK,KAAK,KAAK;CACjB;AACF"}
|
|
@@ -19,6 +19,15 @@ export declare const EXCLUDED_TS_EXT_REGEX: unknown;
|
|
|
19
19
|
* development compilation. See #2458 and #2462.
|
|
20
20
|
*/
|
|
21
21
|
export declare function isProdMode(mode: string | undefined): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Whether a Vite environment runs on the server. `configEnvironment` sees the
|
|
24
|
+
* environment's options before Vite resolves them, so an unset `consumer`
|
|
25
|
+
* falls back to Vite's own default: every environment except `client` is a
|
|
26
|
+
* server environment.
|
|
27
|
+
*/
|
|
28
|
+
export declare function isServerEnvironment(name: string, config: {
|
|
29
|
+
consumer?: string;
|
|
30
|
+
}): boolean;
|
|
22
31
|
export interface TsConfigResolutionContext {
|
|
23
32
|
root: string;
|
|
24
33
|
isProd: boolean;
|
|
@@ -28,6 +28,15 @@ function isProdMode(mode) {
|
|
|
28
28
|
if (mode === "development") return false;
|
|
29
29
|
return mode === "production" || process.env.NODE_ENV === "production";
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Whether a Vite environment runs on the server. `configEnvironment` sees the
|
|
33
|
+
* environment's options before Vite resolves them, so an unset `consumer`
|
|
34
|
+
* falls back to Vite's own default: every environment except `client` is a
|
|
35
|
+
* server environment.
|
|
36
|
+
*/
|
|
37
|
+
function isServerEnvironment(name, config) {
|
|
38
|
+
return (config.consumer ?? (name === "client" ? "client" : "server")) === "server";
|
|
39
|
+
}
|
|
31
40
|
function getTsConfigPath(root, tsconfig, isProd, isTest, isLib, workspaceRoot) {
|
|
32
41
|
if (tsconfig && isAbsolute(tsconfig)) {
|
|
33
42
|
if (!existsSync(tsconfig)) 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.`);
|
|
@@ -81,6 +90,6 @@ function createDepOptimizerConfig(opts) {
|
|
|
81
90
|
} };
|
|
82
91
|
}
|
|
83
92
|
//#endregion
|
|
84
|
-
export { EXCLUDED_TS_EXT_REGEX, TS_EXT_REGEX, createDepOptimizerConfig, createTsConfigGetter, getTsConfigPath, isProdMode };
|
|
93
|
+
export { EXCLUDED_TS_EXT_REGEX, TS_EXT_REGEX, createDepOptimizerConfig, createTsConfigGetter, getTsConfigPath, isProdMode, isServerEnvironment };
|
|
85
94
|
|
|
86
95
|
//# sourceMappingURL=plugin-config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-config.js","names":[],"sources":["../../../../src/lib/utils/plugin-config.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport * as vite from 'vite';\n\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\nimport {\n createPersistentTransformCache,\n resolveTransformCacheDir,\n} from './transform-cache.js';\n\n/**\n * TypeScript file extension regex\n * Match .ts / .cts / .mts extensions with an optional ?query suffix.\n * Reject .tsx — and any other `.ts<letter>…` extension like .tsrx — via\n * a negative-lookahead on a following ASCII letter, so only genuine TS\n * files pass.\n *\n * Previous form `/\\.[cm]?(ts)[^x]?\\??/` was intended to exclude `.tsx`\n * specifically (`[^x]?` = not-an-x), but the `?` quantifier also allows\n * zero characters, and any non-`x` letter was admitted — so `.tsrx`\n * and similar extensions matched by accident.\n */\nexport const TS_EXT_REGEX = /\\.[cm]?ts(?![a-z])/;\n\n// Spec files stay included — a newly added spec must join the program's\n// root names in Vitest watch mode.\nexport const EXCLUDED_TS_EXT_REGEX = /\\.d\\.[cm]?ts$/;\n\n/**\n * Resolves whether Angular should be compiled for production. An explicit\n * `development` mode wins over an ambient production `NODE_ENV` (e.g. set by\n * `storybook build` at CLI entry), so a build can opt into Angular's\n * development compilation. See #2458 and #2462.\n */\nexport function isProdMode(mode: string | undefined): boolean {\n if (mode === 'development') {\n return false;\n }\n\n return mode === 'production' || process.env['NODE_ENV'] === 'production';\n}\n\nexport interface TsConfigResolutionContext {\n root: string;\n isProd: boolean;\n isLib: boolean;\n}\n\nexport function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n workspaceRoot?: string,\n) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@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.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n\n // Callers such as Storybook's Angular builder document their `tsConfig` as\n // workspace-relative while setting the Vite root to the project directory,\n // so the path joins onto the project root twice. Fall back to the workspace\n // root before failing.\n const workspacePath = workspaceRoot\n ? resolve(workspaceRoot, tsconfigFilePath)\n : undefined;\n\n if (workspacePath && existsSync(workspacePath)) {\n return workspacePath;\n }\n\n const attemptedPaths =\n workspacePath && workspacePath !== resolvedPath\n ? `${resolvedPath} or ${workspacePath}`\n : resolvedPath;\n\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${attemptedPaths}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n\n return resolvedPath;\n}\n\nexport function createTsConfigGetter(\n tsconfigOrGetter?: string | (() => string),\n) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n}\n\nexport interface DepOptimizerOptions {\n tsconfig: string;\n isProd: boolean;\n jit: boolean;\n watchMode: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n}\n\nexport function createDepOptimizerConfig(opts: DepOptimizerOptions) {\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(opts.watchMode ? {} : { ngDevMode: 'false' }),\n };\n\n // Persist linked dependency output across dep-optimizer runs. The\n // transformer's own key covers file bytes + options, and the directory\n // is namespaced by Angular version, so entries never go stale.\n const transformCacheDir = resolveTransformCacheDir(dirname(opts.tsconfig));\n const transformCache = transformCacheDir\n ? createPersistentTransformCache(transformCacheDir)\n : undefined;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] = {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n transformCache,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n transformCache,\n ),\n ],\n define: defineOptions,\n };\n\n // No top-level `resolve` block: the `style` package-export condition\n // is now scoped to `.css`-extension requests via\n // `cssExtensionStyleResolverPlugin`, so this dep optimizer config no\n // longer needs to leak it into Vite's global `resolve.conditions`.\n return {\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs'],\n exclude: ['@angular/platform-server'],\n ...(vite.rolldownVersion ? { rolldownOptions } : { esbuildOptions }),\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAe;AAI5B,IAAa,wBAAwB;;;;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ACF,EACF;CAEA,MAAM,iBAAgE;EACpE,SAAS,CACP,qBACE;GACE,UAAU,KAAK;GACf,WAAW,CAAC,KAAK;GACjB,uBAAuB,KAAK;GAC5B,KAAK,KAAK;GACV,aAAa,KAAK;EACpB,GACA,KAAK,QACL,CAAC,KAAK,oBACN,cACF,CACF;EACA,QAAQ;CACV;CAMA,OAAO,EACL,cAAc;EACZ,SAAS,CAAC,kBAAkB,MAAM;EAClC,SAAS,CAAC,0BAA0B;EACpC,GAAI,KAAK,kBAAkB,EAAE,gBAAgB,IAAI,EAAE,eAAe;CACpE,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"plugin-config.js","names":[],"sources":["../../../../src/lib/utils/plugin-config.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport * as vite from 'vite';\n\nimport {\n createCompilerPlugin,\n createRolldownCompilerPlugin,\n} from '../compiler-plugin.js';\nimport {\n createPersistentTransformCache,\n resolveTransformCacheDir,\n} from './transform-cache.js';\n\n/**\n * TypeScript file extension regex\n * Match .ts / .cts / .mts extensions with an optional ?query suffix.\n * Reject .tsx — and any other `.ts<letter>…` extension like .tsrx — via\n * a negative-lookahead on a following ASCII letter, so only genuine TS\n * files pass.\n *\n * Previous form `/\\.[cm]?(ts)[^x]?\\??/` was intended to exclude `.tsx`\n * specifically (`[^x]?` = not-an-x), but the `?` quantifier also allows\n * zero characters, and any non-`x` letter was admitted — so `.tsrx`\n * and similar extensions matched by accident.\n */\nexport const TS_EXT_REGEX = /\\.[cm]?ts(?![a-z])/;\n\n// Spec files stay included — a newly added spec must join the program's\n// root names in Vitest watch mode.\nexport const EXCLUDED_TS_EXT_REGEX = /\\.d\\.[cm]?ts$/;\n\n/**\n * Resolves whether Angular should be compiled for production. An explicit\n * `development` mode wins over an ambient production `NODE_ENV` (e.g. set by\n * `storybook build` at CLI entry), so a build can opt into Angular's\n * development compilation. See #2458 and #2462.\n */\nexport function isProdMode(mode: string | undefined): boolean {\n if (mode === 'development') {\n return false;\n }\n\n return mode === 'production' || process.env['NODE_ENV'] === 'production';\n}\n\n/**\n * Whether a Vite environment runs on the server. `configEnvironment` sees the\n * environment's options before Vite resolves them, so an unset `consumer`\n * falls back to Vite's own default: every environment except `client` is a\n * server environment.\n */\nexport function isServerEnvironment(\n name: string,\n config: { consumer?: string },\n): boolean {\n return (\n (config.consumer ?? (name === 'client' ? 'client' : 'server')) === 'server'\n );\n}\n\nexport interface TsConfigResolutionContext {\n root: string;\n isProd: boolean;\n isLib: boolean;\n}\n\nexport function getTsConfigPath(\n root: string,\n tsconfig: string,\n isProd: boolean,\n isTest: boolean,\n isLib: boolean,\n workspaceRoot?: string,\n) {\n if (tsconfig && isAbsolute(tsconfig)) {\n if (!existsSync(tsconfig)) {\n console.error(\n `[@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.`,\n );\n }\n\n return tsconfig;\n }\n\n let tsconfigFilePath = './tsconfig.app.json';\n\n if (isLib) {\n tsconfigFilePath = isProd\n ? './tsconfig.lib.prod.json'\n : './tsconfig.lib.json';\n }\n\n if (isTest) {\n tsconfigFilePath = './tsconfig.spec.json';\n }\n\n if (tsconfig) {\n tsconfigFilePath = tsconfig;\n }\n\n const resolvedPath = resolve(root, tsconfigFilePath);\n\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n\n // Callers such as Storybook's Angular builder document their `tsConfig` as\n // workspace-relative while setting the Vite root to the project directory,\n // so the path joins onto the project root twice. Fall back to the workspace\n // root before failing.\n const workspacePath = workspaceRoot\n ? resolve(workspaceRoot, tsconfigFilePath)\n : undefined;\n\n if (workspacePath && existsSync(workspacePath)) {\n return workspacePath;\n }\n\n const attemptedPaths =\n workspacePath && workspacePath !== resolvedPath\n ? `${resolvedPath} or ${workspacePath}`\n : resolvedPath;\n\n console.error(\n `[@analogjs/vite-plugin-angular]: Unable to resolve tsconfig at ${attemptedPaths}. This causes compilation issues. Check the path or set the \"tsconfig\" property with an absolute path.`,\n );\n\n return resolvedPath;\n}\n\nexport function createTsConfigGetter(\n tsconfigOrGetter?: string | (() => string),\n) {\n if (typeof tsconfigOrGetter === 'function') {\n return tsconfigOrGetter;\n }\n\n return () => tsconfigOrGetter || '';\n}\n\nexport interface DepOptimizerOptions {\n tsconfig: string;\n isProd: boolean;\n jit: boolean;\n watchMode: boolean;\n isTest: boolean;\n isAstroIntegration: boolean;\n}\n\nexport function createDepOptimizerConfig(opts: DepOptimizerOptions) {\n const defineOptions = {\n ngJitMode: 'false',\n ngI18nClosureMode: 'false',\n ...(opts.watchMode ? {} : { ngDevMode: 'false' }),\n };\n\n // Persist linked dependency output across dep-optimizer runs. The\n // transformer's own key covers file bytes + options, and the directory\n // is namespaced by Angular version, so entries never go stale.\n const transformCacheDir = resolveTransformCacheDir(dirname(opts.tsconfig));\n const transformCache = transformCacheDir\n ? createPersistentTransformCache(transformCacheDir)\n : undefined;\n\n const rolldownOptions: vite.DepOptimizationOptions['rolldownOptions'] = {\n plugins: [\n createRolldownCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n transformCache,\n ),\n ],\n };\n\n const esbuildOptions: vite.DepOptimizationOptions['esbuildOptions'] = {\n plugins: [\n createCompilerPlugin(\n {\n tsconfig: opts.tsconfig,\n sourcemap: !opts.isProd,\n advancedOptimizations: opts.isProd,\n jit: opts.jit,\n incremental: opts.watchMode,\n },\n opts.isTest,\n !opts.isAstroIntegration,\n transformCache,\n ),\n ],\n define: defineOptions,\n };\n\n // No top-level `resolve` block: the `style` package-export condition\n // is now scoped to `.css`-extension requests via\n // `cssExtensionStyleResolverPlugin`, so this dep optimizer config no\n // longer needs to leak it into Vite's global `resolve.conditions`.\n return {\n optimizeDeps: {\n include: ['rxjs/operators', 'rxjs'],\n ex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