@analogjs/vite-plugin-angular 3.0.0-beta.5 → 3.0.0-beta.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js +2 -1
  2. package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
  3. package/ngp/LICENSE +21 -0
  4. package/ngp/api.mjs +46806 -0
  5. package/ngp/build.json +4 -0
  6. package/ngp/ng_analyze.cjs +601 -0
  7. package/ngp/ng_analyze_bg.wasm +0 -0
  8. package/package.json +4 -1
  9. package/src/index.d.ts +2 -0
  10. package/src/index.js +3 -1
  11. package/src/index.js.map +1 -1
  12. package/src/lib/analog-plugin-interop.js +1 -1
  13. package/src/lib/angular-build-context.d.ts +215 -0
  14. package/src/lib/angular-build-context.js +361 -0
  15. package/src/lib/angular-build-context.js.map +1 -0
  16. package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
  17. package/src/lib/angular-build-optimizer-plugin.js +24 -9
  18. package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
  19. package/src/lib/angular-jit-plugin.d.ts +5 -3
  20. package/src/lib/angular-jit-plugin.js +14 -6
  21. package/src/lib/angular-jit-plugin.js.map +1 -1
  22. package/src/lib/angular-vite-plugin.d.ts +6 -109
  23. package/src/lib/angular-vite-plugin.js +8 -1249
  24. package/src/lib/angular-vite-plugin.js.map +1 -1
  25. package/src/lib/angular-vitest-plugin.d.ts +3 -2
  26. package/src/lib/angular-vitest-plugin.js +6 -3
  27. package/src/lib/angular-vitest-plugin.js.map +1 -1
  28. package/src/lib/companion-plugins.d.ts +7 -0
  29. package/src/lib/companion-plugins.js +38 -0
  30. package/src/lib/companion-plugins.js.map +1 -0
  31. package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
  32. package/src/lib/compilation-api/compilation-api-plugin.js +154 -282
  33. package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
  34. package/src/lib/compiler/compile.d.ts +1 -1
  35. package/src/lib/compiler/compile.js +190 -145
  36. package/src/lib/compiler/compile.js.map +1 -1
  37. package/src/lib/compiler/defer.d.ts +2 -3
  38. package/src/lib/compiler/defer.js +12 -14
  39. package/src/lib/compiler/defer.js.map +1 -1
  40. package/src/lib/compiler/dts-reader.d.ts +6 -1
  41. package/src/lib/compiler/dts-reader.js +19 -10
  42. package/src/lib/compiler/dts-reader.js.map +1 -1
  43. package/src/lib/compiler/hmr.d.ts +4 -0
  44. package/src/lib/compiler/hmr.js +7 -2
  45. package/src/lib/compiler/hmr.js.map +1 -1
  46. package/src/lib/compiler/index.d.ts +2 -2
  47. package/src/lib/compiler/index.js +4 -4
  48. package/src/lib/compiler/jit-metadata.d.ts +3 -1
  49. package/src/lib/compiler/jit-metadata.js +10 -8
  50. package/src/lib/compiler/jit-metadata.js.map +1 -1
  51. package/src/lib/compiler/jit-transform.js +2 -2
  52. package/src/lib/compiler/jit-transform.js.map +1 -1
  53. package/src/lib/compiler/js-emitter.d.ts +0 -3
  54. package/src/lib/compiler/js-emitter.js +3 -21
  55. package/src/lib/compiler/js-emitter.js.map +1 -1
  56. package/src/lib/compiler/registry.d.ts +7 -1
  57. package/src/lib/compiler/registry.js +23 -3
  58. package/src/lib/compiler/registry.js.map +1 -1
  59. package/src/lib/compiler/resource-inliner.d.ts +8 -9
  60. package/src/lib/compiler/resource-inliner.js +10 -18
  61. package/src/lib/compiler/resource-inliner.js.map +1 -1
  62. package/src/lib/compiler/style-ast.d.ts +9 -1
  63. package/src/lib/compiler/style-ast.js +26 -5
  64. package/src/lib/compiler/style-ast.js.map +1 -1
  65. package/src/lib/compiler/type-elision.d.ts +4 -3
  66. package/src/lib/compiler/type-elision.js +10 -11
  67. package/src/lib/compiler/type-elision.js.map +1 -1
  68. package/src/lib/compiler/utils.d.ts +9 -7
  69. package/src/lib/compiler/utils.js +49 -9
  70. package/src/lib/compiler/utils.js.map +1 -1
  71. package/src/lib/component-scanner.d.ts +74 -0
  72. package/src/lib/component-scanner.js +178 -0
  73. package/src/lib/component-scanner.js.map +1 -0
  74. package/src/lib/component-styles-plugin.d.ts +52 -0
  75. package/src/lib/component-styles-plugin.js +353 -0
  76. package/src/lib/component-styles-plugin.js.map +1 -0
  77. package/src/lib/compose-angular-plugins.d.ts +12 -0
  78. package/src/lib/compose-angular-plugins.js +31 -0
  79. package/src/lib/compose-angular-plugins.js.map +1 -0
  80. package/src/lib/dev-server-mode-plugin.d.ts +7 -0
  81. package/src/lib/dev-server-mode-plugin.js +23 -0
  82. package/src/lib/dev-server-mode-plugin.js.map +1 -0
  83. package/src/lib/fast-compile-api.d.ts +62 -0
  84. package/src/lib/fast-compile-api.js +12 -0
  85. package/src/lib/fast-compile-api.js.map +1 -0
  86. package/src/lib/fast-compile-plugin.d.ts +6 -1
  87. package/src/lib/fast-compile-plugin.js +167 -107
  88. package/src/lib/fast-compile-plugin.js.map +1 -1
  89. package/src/lib/host.d.ts +3 -0
  90. package/src/lib/host.js +4 -2
  91. package/src/lib/host.js.map +1 -1
  92. package/src/lib/live-reload-plugin.d.ts +6 -3
  93. package/src/lib/live-reload-plugin.js +13 -6
  94. package/src/lib/live-reload-plugin.js.map +1 -1
  95. package/src/lib/ngp-compile-api.d.ts +55 -0
  96. package/src/lib/ngp-compile-api.js +12 -0
  97. package/src/lib/ngp-compile-api.js.map +1 -0
  98. package/src/lib/ngp-compile-plugin.d.ts +4 -0
  99. package/src/lib/ngp-compile-plugin.js +662 -0
  100. package/src/lib/ngp-compile-plugin.js.map +1 -0
  101. package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
  102. package/src/lib/ngtsc-compile-plugin.js +778 -0
  103. package/src/lib/ngtsc-compile-plugin.js.map +1 -0
  104. package/src/lib/nx-folder-plugin.d.ts +6 -5
  105. package/src/lib/nx-folder-plugin.js +12 -7
  106. package/src/lib/nx-folder-plugin.js.map +1 -1
  107. package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
  108. package/src/lib/plugins/file-replacements.plugin.js +1 -0
  109. package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
  110. package/src/lib/router-plugin.d.ts +5 -1
  111. package/src/lib/router-plugin.js +13 -4
  112. package/src/lib/router-plugin.js.map +1 -1
  113. package/src/lib/utils/compilation-shared.js +1 -1
  114. package/src/lib/utils/devkit.js +1 -1
  115. package/src/lib/utils/hmr-component-updates.d.ts +7 -0
  116. package/src/lib/utils/hmr-component-updates.js +87 -0
  117. package/src/lib/utils/hmr-component-updates.js.map +1 -0
  118. package/src/lib/utils/lsp-type-checker.d.ts +75 -0
  119. package/src/lib/utils/lsp-type-checker.js +531 -0
  120. package/src/lib/utils/lsp-type-checker.js.map +1 -0
  121. package/src/lib/utils/ngp-host-fs.d.ts +32 -0
  122. package/src/lib/utils/ngp-host-fs.js +104 -0
  123. package/src/lib/utils/ngp-host-fs.js.map +1 -0
  124. package/src/lib/utils/plugin-config.d.ts +15 -8
  125. package/src/lib/utils/plugin-config.js +18 -5
  126. package/src/lib/utils/plugin-config.js.map +1 -1
  127. package/src/lib/utils/stylesheet-warning.d.ts +2 -0
  128. package/src/lib/utils/stylesheet-warning.js +11 -0
  129. package/src/lib/utils/stylesheet-warning.js.map +1 -0
  130. package/src/lib/utils/tsconfig-resolver.js +1 -1
  131. package/src/lib/virtual-modules-plugin.d.ts +11 -3
  132. package/src/lib/virtual-modules-plugin.js +43 -12
  133. package/src/lib/virtual-modules-plugin.js.map +1 -1
@@ -0,0 +1,531 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, relative, resolve } from "node:path";
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 IGNORED_IN_MEMORY_CODES = /* @__PURE__ */ new Set([2742, 2883]);
18
+ var BATCH_SIZE = 32;
19
+ var TCB_IMPORT_ALIAS = /^(?:_tcb_)?_?i\d+$/;
20
+ var TCB_LOCAL_NAME = /^(?:_tcb|_ctor|_pipe)\d+$/;
21
+ var SPAN_COMMENT = /^(\d+),(\d+)$/;
22
+ function readSpanComment(value) {
23
+ const match = SPAN_COMMENT.exec(value);
24
+ return match ? {
25
+ start: Number(match[1]),
26
+ end: Number(match[2])
27
+ } : null;
28
+ }
29
+ function walk(node, visit) {
30
+ if (Array.isArray(node)) {
31
+ for (const child of node) walk(child, visit);
32
+ return;
33
+ }
34
+ if (!node || typeof node.type !== "string") return;
35
+ visit(node);
36
+ for (const key in node) {
37
+ const value = node[key];
38
+ if (value && typeof value === "object") walk(value, visit);
39
+ }
40
+ }
41
+ function declaredName(stmt) {
42
+ if (stmt.type === "VariableDeclaration") return stmt.declarations[0]?.id?.name;
43
+ if (stmt.type === "FunctionDeclaration" || stmt.type === "TSDeclareFunction") return stmt.id?.name;
44
+ }
45
+ function isTcbImport(stmt) {
46
+ const ns = stmt.type === "ImportDeclaration" && stmt.specifiers[0];
47
+ return ns?.type === "ImportNamespaceSpecifier" && TCB_IMPORT_ALIAS.test(ns.local.name);
48
+ }
49
+ function splitTcb(tcbCode) {
50
+ if (!tcbCode.includes("/*tcb")) return null;
51
+ const { program, comments, errors } = parseSync("tcb.ts", tcbCode);
52
+ if (errors.length > 0) return null;
53
+ const parts = {
54
+ source: [],
55
+ imports: [],
56
+ blocks: [],
57
+ templateSources: {}
58
+ };
59
+ const footer = comments.find((c) => c.value.startsWith(TCB_TEMPLATE_SOURCES_PREFIX));
60
+ if (footer) parts.templateSources = JSON.parse(footer.value.slice(25));
61
+ for (const stmt of program.body) if (TCB_LOCAL_NAME.test(declaredName(stmt) ?? "")) parts.blocks.push(stmt);
62
+ else {
63
+ parts.source.push(stmt);
64
+ if (isTcbImport(stmt)) parts.imports.push(stmt);
65
+ }
66
+ return parts.blocks.length > 0 ? parts : null;
67
+ }
68
+ function inPlaceDocument(filePath, sourceCode, tcbCode) {
69
+ const lines = sourceCode.split("\n");
70
+ const sourceLineCount = lines.length;
71
+ if (!tcbCode) return {
72
+ text: sourceCode,
73
+ meta: {
74
+ filePath,
75
+ sourceLineCount
76
+ }
77
+ };
78
+ const parts = splitTcb(tcbCode);
79
+ const suffix = parts ? [...parts.imports, ...parts.blocks].map((stmt) => tcbCode.slice(stmt.start, stmt.end)).join("\n") : tcbCode;
80
+ lines.push(...suffix.split("\n"));
81
+ const range = {
82
+ startLine: sourceLineCount,
83
+ endLine: lines.length,
84
+ filePath,
85
+ sourceCode,
86
+ templateSources: parts?.templateSources ?? {}
87
+ };
88
+ return {
89
+ text: lines.join("\n"),
90
+ meta: {
91
+ filePath,
92
+ sourceLineCount,
93
+ lines,
94
+ tcbRanges: [range]
95
+ }
96
+ };
97
+ }
98
+ function trailingSpan(text, pos, commentsByStart) {
99
+ while (true) {
100
+ while (pos < text.length && /\s/.test(text[pos])) pos++;
101
+ const comment = commentsByStart.get(pos);
102
+ if (!comment) return null;
103
+ const span = readSpanComment(comment.value);
104
+ if (span) return span;
105
+ pos = comment.end;
106
+ }
107
+ }
108
+ function lineAndCharacter(text, offset) {
109
+ const before = text.slice(0, offset).split("\n");
110
+ return {
111
+ line: before.length,
112
+ character: before[before.length - 1].length + 1
113
+ };
114
+ }
115
+ function templateLocation(range, lines, position) {
116
+ const chunk = lines.slice(range.startLine, range.endLine).join("\n");
117
+ let offset = position.character;
118
+ for (let i = range.startLine; i < position.line; i++) offset += lines[i].length + 1;
119
+ const { program, comments } = parseSync("tcb.ts", chunk);
120
+ const commentsByStart = new Map(comments.map((c) => [c.start, c]));
121
+ const ancestors = [];
122
+ walk(program.body, (node) => {
123
+ if (node.start <= offset && offset < node.end) ancestors.push(node);
124
+ });
125
+ const tcbFunction = ancestors.find((node) => node.type === "FunctionDeclaration" && /_tcb\d+$/.test(node.id?.name));
126
+ let span = null;
127
+ for (let i = ancestors.length - 1; i >= 0 && !span; i--) span = trailingSpan(chunk, ancestors[i].end, commentsByStart);
128
+ if (!tcbFunction || !span) return null;
129
+ const id = /(tcb\d+)$/.exec(tcbFunction.id.name)[1];
130
+ const source = range.templateSources[id];
131
+ const file = source?.templateFile ?? range.filePath;
132
+ let content = range.sourceCode;
133
+ if (source?.templateFile) try {
134
+ content = readFileSync(source.templateFile, "utf-8");
135
+ } catch {
136
+ return null;
137
+ }
138
+ const start = source?.templateExpression?.start ?? span.start;
139
+ return {
140
+ file,
141
+ ...lineAndCharacter(content, start)
142
+ };
143
+ }
144
+ function isBareTypeReference(type) {
145
+ return type?.type === "TSTypeReference" && type.typeName.type === "Identifier";
146
+ }
147
+ function collectExportedClasses(header) {
148
+ const exported = /* @__PURE__ */ new Map();
149
+ for (const stmt of header) {
150
+ const cls = stmt.declaration;
151
+ if (cls?.type !== "ClassDeclaration" || !cls.id) continue;
152
+ if (stmt.type === "ExportDefaultDeclaration") exported.set(cls.id.name, "default");
153
+ else if (stmt.type === "ExportNamedDeclaration") exported.set(cls.id.name, cls.id.name);
154
+ }
155
+ return exported;
156
+ }
157
+ function hostRelativeSpecifier(absPath, hostDir) {
158
+ const spec = relative(hostDir, absPath).replace(/\\/g, "/");
159
+ return spec.startsWith(".") ? spec : "./" + spec;
160
+ }
161
+ function sharedAliasFor(spec, sharedImports) {
162
+ let alias = sharedImports.get(spec);
163
+ if (!alias) {
164
+ alias = `_si${sharedImports.size}`;
165
+ sharedImports.set(spec, alias);
166
+ }
167
+ return alias;
168
+ }
169
+ function relocateTcb(filePath, tcbCode, hostDir, fileIdx, sharedImports) {
170
+ const parts = splitTcb(tcbCode);
171
+ if (!parts) return null;
172
+ const aliasSpecs = /* @__PURE__ */ new Map();
173
+ for (const stmt of parts.imports) aliasSpecs.set(stmt.specifiers[0].local.name, stmt.source.value);
174
+ const exportedClasses = collectExportedClasses(parts.source);
175
+ const identifiers = [];
176
+ const thisTypes = [];
177
+ let relocatable = true;
178
+ walk(parts.blocks, (node) => {
179
+ if (node.type === "Identifier") {
180
+ identifiers.push(node);
181
+ return;
182
+ }
183
+ 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)) {
184
+ relocatable = false;
185
+ return;
186
+ }
187
+ if (node.type !== "FunctionDeclaration" || !/^_tcb\d+$/.test(node.id?.name)) return;
188
+ const thisType = node.params[0]?.typeAnnotation?.typeAnnotation;
189
+ if (node.params[0]?.name !== "this" || !isBareTypeReference(thisType)) return;
190
+ const exportProp = exportedClasses.get(thisType.typeName.name);
191
+ if (node.typeParameters || !exportProp) {
192
+ relocatable = false;
193
+ return;
194
+ }
195
+ thisTypes.push({
196
+ node: thisType.typeName,
197
+ exportProp
198
+ });
199
+ });
200
+ if (!relocatable) return null;
201
+ const fileDir = dirname(resolve(filePath));
202
+ const aliasMap = /* @__PURE__ */ new Map();
203
+ for (const [alias, rawSpec] of aliasSpecs) {
204
+ const spec = rawSpec.startsWith(".") ? hostRelativeSpecifier(resolve(fileDir, rawSpec), hostDir) : rawSpec;
205
+ aliasMap.set(alias, sharedAliasFor(spec, sharedImports));
206
+ }
207
+ const ms = new MagicString(tcbCode);
208
+ for (const node of identifiers) if (TCB_LOCAL_NAME.test(node.name)) ms.overwrite(node.start, node.end, `_f${fileIdx}_${node.name}`);
209
+ else if (aliasMap.has(node.name)) ms.overwrite(node.start, node.end, aliasMap.get(node.name));
210
+ if (thisTypes.length > 0) {
211
+ const selfAlias = sharedAliasFor(hostRelativeSpecifier(resolve(filePath).replace(/\.[cm]?tsx?$/, ""), hostDir), sharedImports);
212
+ for (const { node, exportProp } of thisTypes) ms.overwrite(node.start, node.end, `${selfAlias}.${exportProp}`);
213
+ }
214
+ return {
215
+ body: parts.blocks.map((stmt) => ms.slice(stmt.start, stmt.end)).join("\n"),
216
+ templateSources: parts.templateSources
217
+ };
218
+ }
219
+ var LSP_ARGS = ["--lsp", "--stdio"];
220
+ function resolveTsgoBinary(tsconfig) {
221
+ if (process.env["TSNATIVE_BINARY_PATH"]) return process.env["TSNATIVE_BINARY_PATH"];
222
+ const ext = process.platform === "win32" ? ".exe" : "";
223
+ const candidates = [{
224
+ parent: "typescript/package.json",
225
+ platform: `@typescript/typescript-${process.platform}-${process.arch}/package.json`,
226
+ bin: `tsc${ext}`
227
+ }, {
228
+ parent: "@typescript/native-preview/package.json",
229
+ platform: `@typescript/native-preview-${process.platform}-${process.arch}/package.json`,
230
+ bin: `tsgo${ext}`
231
+ }];
232
+ for (const base of [tsconfig, import.meta.url]) {
233
+ const req = createRequire(base);
234
+ for (const candidate of candidates) try {
235
+ const parentPkg = req.resolve(candidate.parent);
236
+ const platformPkg = createRequire(parentPkg).resolve(candidate.platform);
237
+ return resolve(dirname(platformPkg), "lib", candidate.bin);
238
+ } catch {}
239
+ }
240
+ throw new Error("disableTypeChecking: false requires TypeScript 7 (typescript@^7.0.0), @typescript/native-preview, or TSNATIVE_BINARY_PATH.");
241
+ }
242
+ function resolveTsrs(tsconfig) {
243
+ for (const base of [tsconfig, import.meta.url]) try {
244
+ const pkg = createRequire(base).resolve("tsrs/package.json");
245
+ return {
246
+ command: process.execPath,
247
+ args: [resolve(dirname(pkg), "bin", "tsrs"), ...LSP_ARGS]
248
+ };
249
+ } catch {}
250
+ throw new Error("typeChecker: 'tsrs' requires the tsrs package.");
251
+ }
252
+ function resolveTypeChecker(tsconfig, option) {
253
+ if (typeof option === "object") return {
254
+ command: option.command,
255
+ args: option.args ?? LSP_ARGS
256
+ };
257
+ if (option === "tsrs") return resolveTsrs(tsconfig);
258
+ return {
259
+ command: resolveTsgoBinary(tsconfig),
260
+ args: LSP_ARGS
261
+ };
262
+ }
263
+ var LspTypeChecker = class {
264
+ host;
265
+ proc;
266
+ seq = 1;
267
+ pending = /* @__PURE__ */ new Map();
268
+ versions = /* @__PURE__ */ new Map();
269
+ queued = /* @__PURE__ */ new Map();
270
+ /** The text last sent for each open in-memory file. */
271
+ inMemoryText = /* @__PURE__ */ new Map();
272
+ buffer = Buffer.alloc(0);
273
+ exitError;
274
+ ready;
275
+ constructor(tsconfig, option = "tsgo", host) {
276
+ this.host = host;
277
+ const cwd = dirname(tsconfig);
278
+ const { command, args } = resolveTypeChecker(tsconfig, option);
279
+ this.proc = spawn(command, args, {
280
+ cwd,
281
+ stdio: [
282
+ "pipe",
283
+ "pipe",
284
+ "ignore"
285
+ ]
286
+ });
287
+ this.proc.stdout.on("data", (chunk) => this.onData(chunk));
288
+ const fail = (error) => {
289
+ this.exitError ??= error;
290
+ for (const { reject } of this.pending.values()) reject(this.exitError);
291
+ this.pending.clear();
292
+ };
293
+ this.proc.on("error", fail);
294
+ this.proc.stdin.on("error", fail);
295
+ this.proc.on("exit", (code) => fail(/* @__PURE__ */ new Error(`type checker exited with code ${code}`)));
296
+ const rootUri = pathToFileURL(cwd).href;
297
+ this.ready = this.request("initialize", {
298
+ processId: process.pid,
299
+ rootUri,
300
+ capabilities: { textDocument: { diagnostic: {} } },
301
+ workspaceFolders: [{
302
+ uri: rootUri,
303
+ name: "root"
304
+ }]
305
+ }).then(() => this.notify("initialized", {}));
306
+ this.ready.catch(() => {});
307
+ }
308
+ onData(chunk) {
309
+ this.buffer = Buffer.concat([this.buffer, chunk]);
310
+ while (true) {
311
+ const headerEnd = this.buffer.indexOf("\r\n\r\n");
312
+ if (headerEnd === -1) break;
313
+ const match = /Content-Length: (\d+)/i.exec(this.buffer.subarray(0, headerEnd).toString("utf8"));
314
+ if (!match) break;
315
+ const bodyStart = headerEnd + 4;
316
+ const bodyEnd = bodyStart + Number(match[1]);
317
+ if (this.buffer.length < bodyEnd) break;
318
+ const msg = JSON.parse(this.buffer.subarray(bodyStart, bodyEnd).toString("utf8"));
319
+ this.buffer = this.buffer.subarray(bodyEnd);
320
+ if (msg.id !== void 0 && msg.method !== void 0) this.send({
321
+ jsonrpc: "2.0",
322
+ id: msg.id,
323
+ result: null
324
+ });
325
+ else if (msg.id !== void 0 && this.pending.has(msg.id)) {
326
+ const entry = this.pending.get(msg.id);
327
+ this.pending.delete(msg.id);
328
+ if (msg.error) entry.reject(new Error(msg.error.message));
329
+ else entry.resolve(msg.result);
330
+ }
331
+ }
332
+ }
333
+ send(payload) {
334
+ const json = JSON.stringify(payload);
335
+ this.proc.stdin.write(`Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`);
336
+ }
337
+ notify(method, params) {
338
+ this.send({
339
+ jsonrpc: "2.0",
340
+ method,
341
+ params
342
+ });
343
+ }
344
+ request(method, params) {
345
+ if (this.exitError) return Promise.reject(this.exitError);
346
+ const id = this.seq++;
347
+ return new Promise((resolve, reject) => {
348
+ this.pending.set(id, {
349
+ resolve,
350
+ reject
351
+ });
352
+ this.send({
353
+ jsonrpc: "2.0",
354
+ id,
355
+ method,
356
+ params
357
+ });
358
+ });
359
+ }
360
+ updateDocument(filePath, text) {
361
+ const uri = pathToFileURL(resolve(filePath)).href;
362
+ if (!this.versions.has(uri)) {
363
+ this.versions.set(uri, 1);
364
+ this.notify("textDocument/didOpen", { textDocument: {
365
+ uri,
366
+ languageId: "typescript",
367
+ version: 1,
368
+ text
369
+ } });
370
+ }
371
+ const version = this.versions.get(uri) + 1;
372
+ this.versions.set(uri, version);
373
+ this.notify("textDocument/didChange", {
374
+ textDocument: {
375
+ uri,
376
+ version
377
+ },
378
+ contentChanges: [{ text }]
379
+ });
380
+ }
381
+ async checkFile(filePath, sourceLineCount, lines, tcbRanges, inMemory = false) {
382
+ const resolvedPath = resolve(filePath);
383
+ const errors = [];
384
+ const diag = await this.request("textDocument/diagnostic", { textDocument: { uri: pathToFileURL(resolvedPath).href } });
385
+ for (const item of diag?.items ?? []) {
386
+ if (item.severity !== 1) continue;
387
+ if (inMemory && IGNORED_IN_MEMORY_CODES.has(Number(item.code))) continue;
388
+ const line = item.range.start.line;
389
+ if (sourceLineCount !== void 0 && line >= sourceLineCount) {
390
+ if (!IGNORED_TCB_CODES.has(Number(item.code)) && !lines?.[line]?.includes("/*D:ignore*/")) {
391
+ const range = tcbRanges?.find((r) => line >= r.startLine && line < r.endLine);
392
+ const location = range && lines && templateLocation(range, lines, item.range.start);
393
+ errors.push(location ? `${this.formatLocation(location)} - error TS${item.code}: ${item.message}` : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`);
394
+ }
395
+ } else {
396
+ const location = {
397
+ file: filePath,
398
+ line: line + 1,
399
+ character: item.range.start.character + 1
400
+ };
401
+ errors.push(`${this.formatLocation(location)} - error TS${item.code}: ${item.message}`);
402
+ }
403
+ }
404
+ return errors;
405
+ }
406
+ formatLocation(location) {
407
+ const { file, line, character } = this.host?.mapLocation(location) ?? location;
408
+ return `${file}:${line}:${character}`;
409
+ }
410
+ /** Reports a change on disk; an open copy is closed so the checker rereads the file. */
411
+ notifyFileChanged(filePath, type) {
412
+ const uri = pathToFileURL(resolve(filePath)).href;
413
+ const wasOpen = this.versions.delete(uri);
414
+ this.ready.then(() => {
415
+ if (wasOpen) this.notify("textDocument/didClose", { textDocument: { uri } });
416
+ this.notify("workspace/didChangeWatchedFiles", { changes: [{
417
+ uri,
418
+ type
419
+ }] });
420
+ }, () => {});
421
+ }
422
+ queueFile(filePath, sourceCode, tcbCode) {
423
+ this.queued.set(filePath, {
424
+ sourceCode,
425
+ tcbCode
426
+ });
427
+ }
428
+ async flushQueue(watchMode = false) {
429
+ if (this.queued.size === 0) return [];
430
+ const entries = Array.from(this.queued.entries());
431
+ this.queued.clear();
432
+ await this.ready;
433
+ const toKey = (filePath) => filePath.replace(/\\/g, "/");
434
+ const inMemoryFiles = new Map([...this.host?.inMemoryFiles() ?? []].map(([filePath, text]) => [toKey(filePath), text]));
435
+ const isInMemory = (filePath) => inMemoryFiles.has(toKey(filePath));
436
+ for (const filePath of this.inMemoryText.keys()) if (!inMemoryFiles.has(filePath)) {
437
+ this.inMemoryText.delete(filePath);
438
+ const uri = pathToFileURL(resolve(filePath)).href;
439
+ if (this.versions.delete(uri)) this.notify("textDocument/didClose", { textDocument: { uri } });
440
+ }
441
+ for (const [filePath, text] of inMemoryFiles) if (this.inMemoryText.get(filePath) !== text) {
442
+ this.inMemoryText.set(filePath, text);
443
+ this.updateDocument(filePath, text);
444
+ }
445
+ const metas = [];
446
+ let updatesCount = 0;
447
+ const update = async (filePath, text) => {
448
+ this.updateDocument(filePath, text);
449
+ updatesCount++;
450
+ if (updatesCount % BATCH_SIZE === 0) await new Promise((r) => setTimeout(r, 5));
451
+ };
452
+ if (!watchMode && entries.length > 1) {
453
+ const [hostFilePath, hostItem] = entries[0];
454
+ const hostDir = dirname(resolve(hostFilePath));
455
+ const hostUri = pathToFileURL(resolve(hostFilePath)).href;
456
+ const sharedImports = /* @__PURE__ */ new Map();
457
+ const relocatedChunks = [];
458
+ let hostRelocated = false;
459
+ for (let i = 0; i < entries.length; i++) {
460
+ const [filePath, { sourceCode, tcbCode }] = entries[i];
461
+ const uri = pathToFileURL(resolve(filePath)).href;
462
+ if (tcbCode && !this.versions.has(uri) && !isInMemory(filePath)) {
463
+ const relocated = relocateTcb(filePath, tcbCode, hostDir, i, sharedImports);
464
+ if (relocated !== null) {
465
+ relocatedChunks.push({
466
+ filePath,
467
+ sourceCode,
468
+ ...relocated
469
+ });
470
+ if (i === 0) hostRelocated = true;
471
+ else metas.push({
472
+ filePath,
473
+ sourceLineCount: sourceCode.split("\n").length
474
+ });
475
+ continue;
476
+ }
477
+ }
478
+ if (i === 0) continue;
479
+ const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
480
+ if (tcbCode || this.versions.has(uri) || isInMemory(filePath)) await update(filePath, text);
481
+ metas.push(meta);
482
+ }
483
+ const { meta: hostMeta } = inPlaceDocument(hostFilePath, hostItem.sourceCode, hostRelocated ? null : hostItem.tcbCode);
484
+ const hostLines = hostMeta.lines ?? hostItem.sourceCode.split("\n");
485
+ const hostTcbRanges = hostMeta.tcbRanges ?? [];
486
+ if (relocatedChunks.length > 0) {
487
+ for (const [spec, alias] of sharedImports) hostLines.push(`import * as ${alias} from '${spec}';`);
488
+ for (const { filePath, sourceCode, body, templateSources } of relocatedChunks) {
489
+ const startLine = hostLines.length;
490
+ hostLines.push(...body.split("\n"));
491
+ hostTcbRanges.push({
492
+ startLine,
493
+ endLine: hostLines.length,
494
+ filePath,
495
+ sourceCode,
496
+ templateSources
497
+ });
498
+ }
499
+ }
500
+ const hasHostTcb = hostTcbRanges.length > 0;
501
+ if (hasHostTcb || this.versions.has(hostUri) || isInMemory(hostFilePath)) this.updateDocument(hostFilePath, hostLines.join("\n"));
502
+ metas.unshift({
503
+ filePath: hostFilePath,
504
+ sourceLineCount: hostMeta.sourceLineCount,
505
+ lines: hasHostTcb ? hostLines : void 0,
506
+ tcbRanges: hasHostTcb ? hostTcbRanges : void 0
507
+ });
508
+ } else for (const [filePath, { sourceCode, tcbCode }] of entries) {
509
+ const { text, meta } = inPlaceDocument(filePath, sourceCode, tcbCode);
510
+ const uri = pathToFileURL(resolve(filePath)).href;
511
+ if (tcbCode || watchMode || this.versions.has(uri) || isInMemory(filePath)) await update(filePath, text);
512
+ metas.push(meta);
513
+ }
514
+ const errors = [];
515
+ const first = metas[0];
516
+ errors.push(...await this.checkFile(first.filePath, first.sourceLineCount, first.lines, first.tcbRanges, isInMemory(first.filePath)));
517
+ for (let i = 1; i < metas.length; i += BATCH_SIZE) {
518
+ const slice = metas.slice(i, i + BATCH_SIZE);
519
+ const batchResults = await Promise.all(slice.map(({ filePath, sourceLineCount, lines, tcbRanges }) => this.checkFile(filePath, sourceLineCount, lines, tcbRanges, isInMemory(filePath))));
520
+ for (const res of batchResults) errors.push(...res);
521
+ }
522
+ return errors;
523
+ }
524
+ close() {
525
+ this.proc.kill();
526
+ }
527
+ };
528
+ //#endregion
529
+ export { LspTypeChecker, TCB_TEMPLATE_SOURCES_PREFIX, readSpanComment, resolveTypeChecker };
530
+
531
+ //# 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]);\n// \"The inferred type of 'x' cannot be named\": in-memory files are never emitted\nconst IGNORED_IN_MEMORY_CODES = new Set([2742, 2883]);\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\n/** A reported location, with a one-based line and character. */\nexport interface SourceLocation {\n file: string;\n line: number;\n character: number;\n}\n\n/** Hooks for checking files that don't exist on disk. */\nexport interface LspTypeCheckerHost {\n /**\n * The text of files that exist only in memory, by normalized path. They're\n * opened before any check, so imports of them resolve.\n */\n inMemoryFiles(): ReadonlyMap<string, string>;\n /** Maps a reported location to the source it was generated from. */\n mapLocation(location: SourceLocation): SourceLocation;\n}\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 /** The text last sent for each open in-memory file. */\n private inMemoryText = new Map<string, string>();\n private buffer = Buffer.alloc(0);\n private exitError: Error | undefined;\n readonly ready: Promise<void>;\n\n constructor(\n tsconfig: string,\n option: TypeCheckerOption = 'tsgo',\n private readonly host?: LspTypeCheckerHost,\n ) {\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 inMemory = false,\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 if (inMemory && IGNORED_IN_MEMORY_CODES.has(Number(item.code))) 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 ? `${this.formatLocation(location)} - error TS${item.code}: ${item.message}`\n : `${range?.filePath ?? filePath} (template): error TS${item.code}: ${item.message}`,\n );\n }\n } else {\n const location = {\n file: filePath,\n line: line + 1,\n character: item.range.start.character + 1,\n };\n errors.push(\n `${this.formatLocation(location)} - error TS${item.code}: ${item.message}`,\n );\n }\n }\n return errors;\n }\n\n private formatLocation(location: SourceLocation): string {\n const { file, line, character } =\n this.host?.mapLocation(location) ?? location;\n return `${file}:${line}:${character}`;\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 toKey = (filePath: string) => filePath.replace(/\\\\/g, '/');\n const inMemoryFiles = new Map(\n [...(this.host?.inMemoryFiles() ?? [])].map(([filePath, text]) => [\n toKey(filePath),\n text,\n ]),\n );\n const isInMemory = (filePath: string) => inMemoryFiles.has(toKey(filePath));\n // Keep the checker's in-memory files in step with the host's\n for (const filePath of this.inMemoryText.keys()) {\n if (!inMemoryFiles.has(filePath)) {\n this.inMemoryText.delete(filePath);\n const uri = pathToFileURL(resolve(filePath)).href;\n if (this.versions.delete(uri)) {\n this.notify('textDocument/didClose', { textDocument: { uri } });\n }\n }\n }\n for (const [filePath, text] of inMemoryFiles) {\n if (this.inMemoryText.get(filePath) !== text) {\n this.inMemoryText.set(filePath, text);\n this.updateDocument(filePath, text);\n }\n }\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) && !isInMemory(filePath)) {\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) || isInMemory(filePath)) {\n await update(filePath, text);\n }\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 (\n hasHostTcb ||\n this.versions.has(hostUri) ||\n isInMemory(hostFilePath)\n ) {\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 (\n tcbCode ||\n watchMode ||\n this.versions.has(uri) ||\n isInMemory(filePath)\n ) {\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 isInMemory(first.filePath),\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(\n filePath,\n sourceLineCount,\n lines,\n tcbRanges,\n isInMemory(filePath),\n ),\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,CAAC;AAE1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CACF,CACF;GACA,KAAK,MAAM,OAAO,cAChB,OAAO,KAAK,GAAG,GAAG;EAEtB;EACA,OAAO;CACT;CAEA,QAAQ;EACN,KAAK,KAAK,KAAK;CACjB;AACF"}
@@ -0,0 +1,32 @@
1
+ interface HostStat {
2
+ isFile: boolean;
3
+ isDir: boolean;
4
+ isSymlink: boolean;
5
+ }
6
+ interface HostDirEntry extends HostStat {
7
+ name: string;
8
+ }
9
+ /** The file system NGP's WebAssembly backend reads through (`hostFs`). */
10
+ export interface NgpHostFs {
11
+ read(path: string): Uint8Array | null;
12
+ metadata(path: string): HostStat | null;
13
+ symlinkMetadata(path: string): HostStat | null;
14
+ readLink(path: string): string | null;
15
+ canonicalize(path: string): string | null;
16
+ readDir(path: string): HostDirEntry[] | null;
17
+ }
18
+ /**
19
+ * `path`, normalized, with the symlinks of its directory resolved. Lowered
20
+ * modules are keyed by these paths, whichever path a file is reached by.
21
+ */
22
+ export declare function canonicalPath(path: string): string;
23
+ /**
24
+ * The disk, with each module of a source format served as a TypeScript file
25
+ * named after it (`x.tsrx` as `x.tsrx.ts`) and the module itself hidden, so an
26
+ * import of `./x.tsrx` resolves to its TypeScript.
27
+ *
28
+ * @param programCode The TypeScript of a module's program file, by the file's
29
+ * normalized, canonical path.
30
+ */
31
+ export declare function createNgpHostFs(programCode: (path: string) => string | undefined): NgpHostFs;
32
+ export {};