@tsrx/content-mapper 0.1.0 → 0.1.2

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.
@@ -0,0 +1,3366 @@
1
+ import { DiagnosticDirectivePolicy, SpanMapFeature, SpanMapKind } from "./protocol.js";
2
+ import { createRequire } from "node:module";
3
+ import { createHash } from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { createRequire as createRequire$1 } from "module";
8
+ import path$1 from "path";
9
+ import { parse, printParseErrorCode } from "jsonc-parser";
10
+ import fs$1 from "fs";
11
+ import { fileURLToPath as fileURLToPath$1 } from "url";
12
+
13
+ //#region \0rolldown/runtime.js
14
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
15
+
16
+ //#endregion
17
+ //#region ../typescript-plugin/src/config-host.js
18
+ /**
19
+ * The file-system host the TSRX tooling reads `tsconfig.json` files and
20
+ * package manifests through when no TypeScript `sys` is supplied. It covers
21
+ * the subset of `ts.sys` that `tsconfig-resolution.js` and
22
+ * `consumer-compiler.js` use, on `node:fs`, so the native TypeScript 7 path
23
+ * (whose `typescript` package has no JavaScript API) needs no TypeScript at
24
+ * all. `ts.sys` still satisfies the same interface for the classic path.
25
+ */
26
+ /**
27
+ * @typedef {object} ConfigHost
28
+ * @property {(file_name: string) => boolean} fileExists
29
+ * @property {(file_name: string) => string | undefined} readFile
30
+ * @property {(directory_name: string) => boolean} [directoryExists]
31
+ * @property {boolean | (() => boolean)} useCaseSensitiveFileNames
32
+ * @property {(file_name: string) => Date | undefined} [getModifiedTime]
33
+ * @property {(path_name: string) => string} [realpath]
34
+ */
35
+ /**
36
+ * Whether the file system distinguishes letter case, probed the way
37
+ * TypeScript's `sys` does: this module's own path with its case swapped exists
38
+ * only on a case-insensitive file system.
39
+ * @returns {boolean}
40
+ */
41
+ function detect_case_sensitive_file_names() {
42
+ const own_path = fileURLToPath(import.meta.url);
43
+ const swapped = own_path.replace(/[a-zA-Z]/g, (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase());
44
+ if (swapped === own_path) return true;
45
+ return !fs.existsSync(swapped);
46
+ }
47
+ /** @type {boolean | undefined} */
48
+ let case_sensitive_file_names;
49
+ /** @returns {boolean} */
50
+ function use_case_sensitive_file_names() {
51
+ case_sensitive_file_names ??= detect_case_sensitive_file_names();
52
+ return case_sensitive_file_names;
53
+ }
54
+ /**
55
+ * @param {string} file_name
56
+ * @returns {fs.Stats | undefined}
57
+ */
58
+ function stat(file_name) {
59
+ try {
60
+ return fs.statSync(file_name, { throwIfNoEntry: false });
61
+ } catch {
62
+ return;
63
+ }
64
+ }
65
+ /** @returns {ConfigHost} */
66
+ function create_config_host() {
67
+ return {
68
+ fileExists: (file_name) => stat(file_name)?.isFile() === true,
69
+ directoryExists: (directory_name) => stat(directory_name)?.isDirectory() === true,
70
+ readFile: (file_name) => {
71
+ try {
72
+ return fs.readFileSync(file_name, "utf8");
73
+ } catch {
74
+ return;
75
+ }
76
+ },
77
+ useCaseSensitiveFileNames: use_case_sensitive_file_names,
78
+ getModifiedTime: (file_name) => stat(file_name)?.mtime,
79
+ realpath: (path_name) => {
80
+ try {
81
+ return fs.realpathSync(path_name);
82
+ } catch {
83
+ return path_name;
84
+ }
85
+ }
86
+ };
87
+ }
88
+ /** The shared default host; one instance so per-host caches are reused. */
89
+ const NODE_CONFIG_HOST = create_config_host();
90
+
91
+ //#endregion
92
+ //#region ../../node_modules/.pnpm/resolve-pkg-maps@1.0.0/node_modules/resolve-pkg-maps/dist/index.mjs
93
+ const A = (r) => r !== null && typeof r == "object";
94
+ const a = (r, t) => Object.assign(/* @__PURE__ */ new Error(`[${r}]: ${t}`), { code: r });
95
+ const _ = "ERR_INVALID_PACKAGE_CONFIG";
96
+ const E = "ERR_INVALID_PACKAGE_TARGET";
97
+ const I = "ERR_PACKAGE_PATH_NOT_EXPORTED";
98
+ const R = /^\d+$/;
99
+ const O = /^(\.{1,2}|node_modules)$/i;
100
+ const w = /\/|\\/;
101
+ var h = ((r) => (r.Export = "exports", r.Import = "imports", r))(h || {});
102
+ const f = (r, t, e, o, c) => {
103
+ if (t == null) return [];
104
+ if (typeof t == "string") {
105
+ const [n, ...i] = t.split(w);
106
+ if (n === ".." || i.some((l) => O.test(l))) throw a(E, `Invalid "${r}" target "${t}" defined in the package config`);
107
+ return [c ? t.replace(/\*/g, c) : t];
108
+ }
109
+ if (Array.isArray(t)) return t.flatMap((n) => f(r, n, e, o, c));
110
+ if (A(t)) {
111
+ for (const n of Object.keys(t)) {
112
+ if (R.test(n)) throw a(_, "Cannot contain numeric property keys");
113
+ if (n === "default" || o.includes(n)) return f(r, t[n], e, o, c);
114
+ }
115
+ return [];
116
+ }
117
+ throw a(E, `Invalid "${r}" target "${t}"`);
118
+ };
119
+ const s = "*";
120
+ const m = (r, t) => {
121
+ const e = r.indexOf(s), o = t.indexOf(s);
122
+ return e === o ? t.length > r.length : o > e;
123
+ };
124
+ function d(r, t) {
125
+ if (!t.includes(s) && r.hasOwnProperty(t)) return [t];
126
+ let e, o;
127
+ for (const c of Object.keys(r)) if (c.includes(s)) {
128
+ const [n, i, l] = c.split(s);
129
+ if (l === void 0 && t.startsWith(n) && t.endsWith(i)) {
130
+ const g = t.slice(n.length, -i.length || void 0);
131
+ g && (!e || m(e, c)) && (e = c, o = g);
132
+ }
133
+ }
134
+ return [e, o];
135
+ }
136
+ const p = (r) => Object.keys(r).reduce((t, e) => {
137
+ const o = e === "" || e[0] !== ".";
138
+ if (t === void 0 || t === o) return o;
139
+ throw a(_, "\"exports\" cannot contain some keys starting with \".\" and some not");
140
+ }, void 0);
141
+ const u = /^\w+:/;
142
+ const v = (r, t, e) => {
143
+ if (!r) throw new Error("\"exports\" is required");
144
+ t = t === "" ? "." : `./${t}`, (typeof r == "string" || Array.isArray(r) || A(r) && p(r)) && (r = { ".": r });
145
+ const [o, c] = d(r, t), n = f(h.Export, r[o], t, e, c);
146
+ if (n.length === 0) throw a(I, t === "." ? "No \"exports\" main defined" : `Package subpath '${t}' is not defined by "exports"`);
147
+ for (const i of n) if (!i.startsWith("./") && !u.test(i)) throw a(E, `Invalid "exports" target "${i}" defined in the package config`);
148
+ return n;
149
+ };
150
+
151
+ //#endregion
152
+ //#region ../typescript-plugin/src/package-resolution.js
153
+ /**
154
+ * Package lookups without TypeScript's module resolver: the runtime entry of a
155
+ * TSRX compiler package, and the file a `tsconfig.json` `extends` entry names.
156
+ * Both walk `node_modules` directories upwards from a starting directory and
157
+ * read every `package.json` fresh, so they also serve as the retry path when
158
+ * Node's own `require.resolve` keeps a negative lookup after a package is
159
+ * installed.
160
+ */
161
+ /** @typedef {import('./config-host.js').ConfigHost} ConfigHost */
162
+ /**
163
+ * @typedef {object} ParsedSpecifier
164
+ * @property {string} name `pkg` or `@scope/pkg`.
165
+ * @property {string} subpath The part after the package name, without a leading slash; empty for the package root.
166
+ */
167
+ /**
168
+ * @param {string} specifier
169
+ * @returns {ParsedSpecifier | undefined} `undefined` for relative, absolute or empty specifiers.
170
+ */
171
+ function parse_bare_specifier(specifier) {
172
+ if (specifier === "" || specifier.startsWith(".") || path.isAbsolute(specifier)) return;
173
+ const segments = specifier.split("/");
174
+ const name_segments = specifier.startsWith("@") ? 2 : 1;
175
+ if (segments.length < name_segments || segments.slice(0, name_segments).some((s) => s === "")) return;
176
+ return {
177
+ name: segments.slice(0, name_segments).join("/"),
178
+ subpath: segments.slice(name_segments).join("/")
179
+ };
180
+ }
181
+ /**
182
+ * A directory exists when the host says so, or (for hosts without
183
+ * `directoryExists`) when it holds a `package.json`.
184
+ * @param {ConfigHost} host
185
+ * @param {string} directory_name
186
+ * @returns {boolean}
187
+ */
188
+ function is_directory(host, directory_name) {
189
+ return host.directoryExists ? host.directoryExists(directory_name) : host.fileExists(path.join(directory_name, "package.json"));
190
+ }
191
+ /**
192
+ * Read a package manifest through the host, never through Node's cached reader.
193
+ * @param {ConfigHost} host
194
+ * @param {string} package_dir
195
+ * @returns {Record<string, unknown> | undefined}
196
+ */
197
+ function read_package_manifest(host, package_dir) {
198
+ const text = host.readFile(path.join(package_dir, "package.json"));
199
+ if (text === void 0) return;
200
+ try {
201
+ const parsed = JSON.parse(text);
202
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
203
+ } catch {
204
+ return;
205
+ }
206
+ }
207
+ /**
208
+ * Every `node_modules/<name>` directory that exists on the way up from `from_dir`.
209
+ * @param {ConfigHost} host
210
+ * @param {string} from_dir
211
+ * @param {string} name
212
+ * @returns {string[]}
213
+ */
214
+ function package_directories(host, from_dir, name) {
215
+ /** @type {string[]} */
216
+ const directories = [];
217
+ let current = path.resolve(from_dir);
218
+ while (true) {
219
+ if (path.basename(current) !== "node_modules") {
220
+ const candidate = path.join(current, "node_modules", name);
221
+ if (is_directory(host, candidate)) directories.push(candidate);
222
+ }
223
+ const parent = path.dirname(current);
224
+ if (parent === current) return directories;
225
+ current = parent;
226
+ }
227
+ }
228
+ /**
229
+ * Targets of `exports` for a subpath under the given conditions, in order;
230
+ * empty when the package has no `exports` or does not export the subpath.
231
+ * @param {Record<string, unknown> | undefined} manifest
232
+ * @param {string} subpath
233
+ * @param {readonly string[]} conditions
234
+ * @returns {string[]}
235
+ */
236
+ function exports_targets(manifest, subpath, conditions) {
237
+ const exports = manifest?.exports;
238
+ if (exports === void 0 || exports === null) return [];
239
+ try {
240
+ return v(exports, subpath, conditions);
241
+ } catch {
242
+ return [];
243
+ }
244
+ }
245
+ /**
246
+ * The file a bare specifier loads at runtime: the package's `exports` (under
247
+ * `conditions`), else its `main`, else `index.js`, with the extension probing
248
+ * Node's CommonJS loader applies; a subpath is resolved the same way.
249
+ * @param {string} specifier
250
+ * @param {string} from_dir
251
+ * @param {{ conditions?: readonly string[], host?: ConfigHost }} [options]
252
+ * @returns {string | undefined}
253
+ */
254
+ function resolve_package_entry(specifier, from_dir, options = {}) {
255
+ const parsed = parse_bare_specifier(specifier);
256
+ if (!parsed) return;
257
+ const host = options.host ?? NODE_CONFIG_HOST;
258
+ const conditions = options.conditions ?? [
259
+ "node",
260
+ "require",
261
+ "default"
262
+ ];
263
+ for (const package_dir of package_directories(host, from_dir, parsed.name)) {
264
+ const manifest = read_package_manifest(host, package_dir);
265
+ for (const target of exports_targets(manifest, parsed.subpath, conditions)) {
266
+ const resolved = path.resolve(package_dir, target);
267
+ if (host.fileExists(resolved)) return resolved;
268
+ }
269
+ if (manifest?.exports !== void 0 && manifest.exports !== null) continue;
270
+ const main = typeof manifest?.main === "string" ? manifest.main : void 0;
271
+ const targets = parsed.subpath !== "" ? [parsed.subpath] : main !== void 0 ? [main, "index"] : ["index"];
272
+ for (const target of targets) {
273
+ const base = path.resolve(package_dir, target);
274
+ for (const candidate of [
275
+ base,
276
+ `${base}.js`,
277
+ `${base}.cjs`,
278
+ `${base}.mjs`,
279
+ `${base}.json`,
280
+ path.join(base, "index.js")
281
+ ]) if (host.fileExists(candidate)) return candidate;
282
+ }
283
+ }
284
+ }
285
+ /**
286
+ * The config a package directory stands for: its `package.json` `tsconfig`
287
+ * field (with `.json` appended when the file is missing without it, as
288
+ * TypeScript's file loader does) or its `tsconfig.json`.
289
+ * @param {ConfigHost} host
290
+ * @param {string} directory
291
+ * @param {Record<string, unknown> | undefined} manifest
292
+ * @returns {string | undefined}
293
+ */
294
+ function tsconfig_field_target(host, directory, manifest) {
295
+ const field = typeof manifest?.tsconfig === "string" ? manifest.tsconfig : "tsconfig.json";
296
+ let resolved = path.resolve(directory, field);
297
+ if (!host.fileExists(resolved) && !resolved.endsWith(".json")) resolved = `${resolved}.json`;
298
+ return host.fileExists(resolved) ? resolved : void 0;
299
+ }
300
+ /**
301
+ * The JSON file a `tsconfig.json` `extends` entry names. The rules and their
302
+ * order are those of get-tsconfig's `resolveExtendsPath` (MIT, privatenumber),
303
+ * which are tested against `tsc`:
304
+ *
305
+ * 1. `..` means `../tsconfig.json`; an entry starting with `.` is relative to
306
+ * the config's directory; an absolute path is used as is. A missing path
307
+ * without a `.json` extension gets one appended.
308
+ * 2. Otherwise the entry names a package (`name` or `@scope/name`, plus an
309
+ * optional subpath) found by walking `node_modules` upwards. A package with
310
+ * `exports` is resolved only through them (conditions `require`, `types`);
311
+ * an unexported subpath is a hard stop. Without `exports`, the package
312
+ * root's `tsconfig` field or its `tsconfig.json` is used; a subpath is tried
313
+ * with `.json` appended, as a `.json` file, then as a directory whose
314
+ * `package.json` `tsconfig` field or `tsconfig.json` is the target.
315
+ *
316
+ * @param {string} extends_value
317
+ * @param {string} config_dir
318
+ * @param {ConfigHost} [host]
319
+ * @returns {{ path: string, candidate?: string } | { path?: undefined, candidate?: string }}
320
+ * `path` when found; `candidate` is the location TypeScript would have read
321
+ * for a path entry, whether or not it exists (so a watcher can wait for it).
322
+ */
323
+ function resolve_extends_target(extends_value, config_dir, host = NODE_CONFIG_HOST) {
324
+ let file_path = extends_value === ".." ? path.join("..", "tsconfig.json") : extends_value;
325
+ if (file_path.startsWith(".")) file_path = path.resolve(config_dir, file_path);
326
+ if (path.isAbsolute(file_path)) {
327
+ if (host.fileExists(file_path)) return {
328
+ path: file_path,
329
+ candidate: file_path
330
+ };
331
+ const candidate = file_path.endsWith(".json") ? file_path : `${file_path}.json`;
332
+ return host.fileExists(candidate) ? {
333
+ path: candidate,
334
+ candidate
335
+ } : { candidate };
336
+ }
337
+ const parsed = parse_bare_specifier(extends_value);
338
+ if (!parsed) return {};
339
+ for (const found_dir of package_directories(host, config_dir, parsed.name)) {
340
+ const package_dir = host.realpath ? host.realpath(found_dir) : found_dir;
341
+ const manifest = read_package_manifest(host, package_dir);
342
+ if (manifest?.exports !== void 0 && manifest.exports !== null) {
343
+ const [target] = exports_targets(manifest, parsed.subpath, ["require", "types"]);
344
+ if (target === void 0) return {};
345
+ const resolved = path.resolve(package_dir, target);
346
+ return host.fileExists(resolved) ? { path: resolved } : {};
347
+ }
348
+ if (parsed.subpath === "") {
349
+ const resolved = tsconfig_field_target(host, package_dir, manifest);
350
+ if (resolved !== void 0) return { path: resolved };
351
+ }
352
+ const full_path = path.join(package_dir, parsed.subpath);
353
+ if (!full_path.endsWith(".json") && host.fileExists(`${full_path}.json`)) return { path: `${full_path}.json` };
354
+ if (is_directory(host, full_path)) {
355
+ const resolved = tsconfig_field_target(host, full_path, read_package_manifest(host, full_path));
356
+ if (resolved !== void 0) return { path: resolved };
357
+ } else if (full_path.endsWith(".json") && host.fileExists(full_path)) return { path: full_path };
358
+ }
359
+ return {};
360
+ }
361
+
362
+ //#endregion
363
+ //#region ../typescript-plugin/src/jsonc.js
364
+ /**
365
+ * A JSON-with-comments reader for `tsconfig.json` and package manifests:
366
+ * comments and trailing commas are allowed, as TypeScript allows them. The
367
+ * parsing is Microsoft's `jsonc-parser` (the same scanner VS Code and
368
+ * get-tsconfig use), so what parses here parses there.
369
+ */
370
+ /**
371
+ * @typedef {object} JsoncParseResult
372
+ * @property {unknown} value `undefined` when the text does not parse.
373
+ * @property {{ message: string, offset: number }} [error] The first parse error.
374
+ */
375
+ /**
376
+ * @param {string} text
377
+ * @returns {JsoncParseResult}
378
+ */
379
+ function parse_jsonc(text) {
380
+ const source = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
381
+ if (source.trim() === "") return { value: {} };
382
+ /** @type {import('jsonc-parser').ParseError[]} */
383
+ const errors = [];
384
+ const value = parse(source, errors, {
385
+ allowTrailingComma: true,
386
+ disallowComments: false
387
+ });
388
+ if (errors.length > 0) {
389
+ const [first] = errors;
390
+ return {
391
+ value: void 0,
392
+ error: {
393
+ message: `${printParseErrorCode(first.error)} at offset ${first.offset}`,
394
+ offset: first.offset
395
+ }
396
+ };
397
+ }
398
+ return { value };
399
+ }
400
+
401
+ //#endregion
402
+ //#region ../typescript-plugin/src/tsconfig-resolution.js
403
+ /**
404
+ * What the tooling needs from a file system to read tsconfig files: the
405
+ * subset of TypeScript's `sys` that `config-host.js` also provides on
406
+ * `node:fs`, so no TypeScript is needed to resolve a config chain.
407
+ * @typedef {object} TsconfigHost
408
+ * @property {(file_name: string) => boolean} fileExists
409
+ * @property {(file_name: string) => string | undefined} readFile
410
+ * @property {boolean | (() => boolean)} useCaseSensitiveFileNames
411
+ * @property {(file_name: string) => Date | undefined} [getModifiedTime]
412
+ */
413
+ /**
414
+ * A problem reading or resolving a config file. `code` follows TypeScript's
415
+ * numbering for the cases it has one for (5024 invalid `extends` entry,
416
+ * 6053 file not found, 18000 circular `extends`), so callers that filter on
417
+ * codes keep working on both paths.
418
+ * @typedef {object} TsconfigDiagnostic
419
+ * @property {number} code
420
+ * @property {string} message
421
+ * @property {string} [file] The config file the problem is in.
422
+ */
423
+ /**
424
+ * @typedef {object} TsconfigLayer
425
+ * @property {string} path
426
+ * @property {string} dir
427
+ * @property {Record<string, unknown>} config
428
+ * @property {string | undefined} raw_source
429
+ * @property {TsconfigDiagnostic[]} parse_diagnostics
430
+ */
431
+ /** @typedef {TsconfigLayer & { extends_values: unknown[] }} ParsedTsconfigLayer */
432
+ /**
433
+ * @typedef {object} TsconfigExtendsFailure
434
+ * @property {string} config_path
435
+ * @property {unknown} extends_value
436
+ * @property {string | undefined} resolved_path
437
+ * @property {TsconfigDiagnostic[]} diagnostics
438
+ */
439
+ /**
440
+ * @typedef {object} ResolvedTsconfigLayers
441
+ * @property {TsconfigLayer[]} layers
442
+ * @property {string[]} dependencies
443
+ * @property {TsconfigDiagnostic[]} diagnostics
444
+ * @property {TsconfigExtendsFailure[]} extends_failures
445
+ */
446
+ /**
447
+ * @template TValue
448
+ * @typedef {{state: 'absent'} | {state: 'found', value: TValue}} ConfigValueResult
449
+ */
450
+ /** @typedef {{config_path: string, config_dir: string}} TsconfigValueOrigin */
451
+ const INVALID_EXTENDS_DIAGNOSTIC_CODE = 5024;
452
+ const FILE_NOT_FOUND_DIAGNOSTIC_CODE = 6053;
453
+ const CIRCULARITY_DIAGNOSTIC_CODE = 18e3;
454
+ const PARSE_ERROR_DIAGNOSTIC_CODE = 1005;
455
+ /**
456
+ * Load a tsconfig and its explicit inheritance graph from lowest to highest
457
+ * precedence. Parsed files are cached, but traversal intentionally does not
458
+ * deduplicate layers because a shared base must be reapplied in every branch.
459
+ * `extends` entries follow TypeScript's rules (see `resolve_extends_target`).
460
+ *
461
+ * @param {TsconfigHost} host
462
+ * @param {string} config_file_name
463
+ * @returns {ResolvedTsconfigLayers}
464
+ */
465
+ function load_tsconfig_layers(host, config_file_name) {
466
+ /** @type {Map<string, ParsedTsconfigLayer>} */
467
+ const parsed_file_cache = /* @__PURE__ */ new Map();
468
+ /** @type {TsconfigLayer[]} */
469
+ const layers = [];
470
+ /** @type {string[]} */
471
+ const dependencies = [];
472
+ const dependency_keys = /* @__PURE__ */ new Set();
473
+ /** @type {TsconfigDiagnostic[]} */
474
+ const diagnostics = [];
475
+ /** @type {TsconfigExtendsFailure[]} */
476
+ const extends_failures = [];
477
+ const diagnostic_keys = /* @__PURE__ */ new Set();
478
+ /** The chain of configs being visited, root first, for cycle reporting. */
479
+ /** @type {string[]} */
480
+ const active_stack = [];
481
+ const active_keys = /* @__PURE__ */ new Set();
482
+ const use_case_sensitive_file_names = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
483
+ /** @param {string} file_name */
484
+ function normalize_path(file_name) {
485
+ return path.normalize(path.resolve(file_name));
486
+ }
487
+ /** @param {string} file_name */
488
+ function get_path_key(file_name) {
489
+ const normalized_path = normalize_path(file_name);
490
+ return use_case_sensitive_file_names ? normalized_path : normalized_path.toLowerCase();
491
+ }
492
+ /** @param {TsconfigDiagnostic[]} next_diagnostics */
493
+ function add_diagnostics(next_diagnostics) {
494
+ for (const diagnostic of next_diagnostics) {
495
+ const key = `${diagnostic.code}\0${diagnostic.file ?? ""}\0${diagnostic.message}`;
496
+ if (!diagnostic_keys.has(key)) {
497
+ diagnostic_keys.add(key);
498
+ diagnostics.push(diagnostic);
499
+ }
500
+ }
501
+ }
502
+ /** @param {string} file_name */
503
+ function add_dependency(file_name) {
504
+ const normalized_path = normalize_path(file_name);
505
+ const key = get_path_key(normalized_path);
506
+ if (!dependency_keys.has(key)) {
507
+ dependency_keys.add(key);
508
+ dependencies.push(normalized_path);
509
+ }
510
+ }
511
+ /** @param {string} file_name */
512
+ function parse_file(file_name) {
513
+ const normalized_path = normalize_path(file_name);
514
+ const key = get_path_key(normalized_path);
515
+ const cached = parsed_file_cache.get(key);
516
+ if (cached) return cached;
517
+ const raw_source = host.readFile(normalized_path);
518
+ /** @type {TsconfigDiagnostic[]} */
519
+ const parse_diagnostics = [];
520
+ /** @type {Record<string, unknown>} */
521
+ let config = {};
522
+ if (raw_source !== void 0) {
523
+ const parsed = parse_jsonc(raw_source);
524
+ if (parsed.error) parse_diagnostics.push({
525
+ code: PARSE_ERROR_DIAGNOSTIC_CODE,
526
+ message: `Failed to parse ${normalized_path}: ${parsed.error.message}`,
527
+ file: normalized_path
528
+ });
529
+ else if (parsed.value !== null && typeof parsed.value === "object" && !Array.isArray(parsed.value)) config = parsed.value;
530
+ else parse_diagnostics.push({
531
+ code: PARSE_ERROR_DIAGNOSTIC_CODE,
532
+ message: `The root value of ${normalized_path} must be an object.`,
533
+ file: normalized_path
534
+ });
535
+ }
536
+ const extends_value = config.extends;
537
+ const extends_values = Array.isArray(extends_value) ? extends_value : extends_value !== void 0 ? [extends_value] : [];
538
+ const parsed = {
539
+ path: normalized_path,
540
+ dir: path.dirname(normalized_path),
541
+ config,
542
+ raw_source,
543
+ parse_diagnostics,
544
+ extends_values
545
+ };
546
+ parsed_file_cache.set(key, parsed);
547
+ add_diagnostics(parse_diagnostics);
548
+ return parsed;
549
+ }
550
+ /**
551
+ * Resolve one immediate extends entry. The conventional JSON candidate of an
552
+ * unresolved relative entry is still recorded as a dependency so creating it
553
+ * later invalidates caches and language-server projects.
554
+ * @param {ParsedTsconfigLayer} parsed
555
+ * @param {unknown} extends_value
556
+ */
557
+ function resolve_extends_path(parsed, extends_value) {
558
+ if (typeof extends_value !== "string") {
559
+ const diagnostic = {
560
+ code: INVALID_EXTENDS_DIAGNOSTIC_CODE,
561
+ message: `Compiler option 'extends' requires a value of type string.`,
562
+ file: parsed.path
563
+ };
564
+ add_diagnostics([diagnostic]);
565
+ extends_failures.push({
566
+ config_path: parsed.path,
567
+ extends_value,
568
+ resolved_path: void 0,
569
+ diagnostics: [diagnostic]
570
+ });
571
+ return;
572
+ }
573
+ const target = resolve_extends_target(extends_value, parsed.dir, host);
574
+ const dependency_path = target.path ?? target.candidate;
575
+ if (dependency_path !== void 0) add_dependency(dependency_path);
576
+ if (target.path === void 0) {
577
+ const diagnostic = {
578
+ code: FILE_NOT_FOUND_DIAGNOSTIC_CODE,
579
+ message: `File '${target.candidate ?? extends_value}' not found.`,
580
+ file: parsed.path
581
+ };
582
+ add_diagnostics([diagnostic]);
583
+ extends_failures.push({
584
+ config_path: parsed.path,
585
+ extends_value,
586
+ resolved_path: dependency_path,
587
+ diagnostics: [diagnostic]
588
+ });
589
+ return;
590
+ }
591
+ if (active_keys.has(get_path_key(target.path))) {
592
+ const chain = [...active_stack, normalize_path(target.path)];
593
+ const diagnostic = {
594
+ code: CIRCULARITY_DIAGNOSTIC_CODE,
595
+ message: `Circularity detected while resolving configuration: ${chain.join(" -> ")}`,
596
+ file: parsed.path
597
+ };
598
+ add_diagnostics([diagnostic]);
599
+ extends_failures.push({
600
+ config_path: parsed.path,
601
+ extends_value,
602
+ resolved_path: dependency_path,
603
+ diagnostics: [diagnostic]
604
+ });
605
+ return;
606
+ }
607
+ return target.path;
608
+ }
609
+ /** @param {string} file_name */
610
+ function visit(file_name) {
611
+ const normalized_path = normalize_path(file_name);
612
+ const key = get_path_key(normalized_path);
613
+ active_keys.add(key);
614
+ active_stack.push(normalized_path);
615
+ add_dependency(normalized_path);
616
+ const parsed = parse_file(normalized_path);
617
+ for (const extends_value of parsed.extends_values) {
618
+ const extended_path = resolve_extends_path(parsed, extends_value);
619
+ if (extended_path !== void 0) visit(extended_path);
620
+ }
621
+ layers.push({
622
+ path: parsed.path,
623
+ dir: parsed.dir,
624
+ config: parsed.config,
625
+ raw_source: parsed.raw_source,
626
+ parse_diagnostics: parsed.parse_diagnostics
627
+ });
628
+ active_stack.pop();
629
+ active_keys.delete(key);
630
+ }
631
+ visit(config_file_name);
632
+ return {
633
+ layers,
634
+ dependencies,
635
+ diagnostics,
636
+ extends_failures
637
+ };
638
+ }
639
+ /**
640
+ * Read a nested config value only when every segment is an own property.
641
+ *
642
+ * @param {unknown} config
643
+ * @param {readonly PropertyKey[]} path_parts
644
+ * @returns {ConfigValueResult<unknown>}
645
+ */
646
+ function get_own_config_value(config, path_parts) {
647
+ let current = config;
648
+ for (const path_part of path_parts) {
649
+ if (current === null || typeof current !== "object" && typeof current !== "function" || !Object.prototype.hasOwnProperty.call(current, path_part)) return { state: "absent" };
650
+ current = current[path_part];
651
+ }
652
+ return {
653
+ state: "found",
654
+ value: current
655
+ };
656
+ }
657
+ /**
658
+ * Resolve a caller-defined value across layers. The last result whose state is
659
+ * not absent wins and is annotated with the config that declared it.
660
+ *
661
+ * @template {{state: string}} TResult
662
+ * @param {readonly TsconfigLayer[]} layers
663
+ * @param {(layer: TsconfigLayer) => TResult} read_layer
664
+ * @returns {{state: 'absent'} | (TResult & TsconfigValueOrigin)}
665
+ */
666
+ function resolve_inherited_config_value(layers, read_layer) {
667
+ /** @type {{state: 'absent'} | (TResult & TsconfigValueOrigin)} */
668
+ let resolved = { state: "absent" };
669
+ for (const layer of layers) {
670
+ const value = read_layer(layer);
671
+ if (value.state !== "absent") resolved = {
672
+ ...value,
673
+ config_path: layer.path,
674
+ config_dir: layer.dir
675
+ };
676
+ }
677
+ return resolved;
678
+ }
679
+
680
+ //#endregion
681
+ //#region ../typescript-plugin/src/utils.js
682
+ const DEBUG = process.env.TSRX_DEBUG === "true";
683
+ /**
684
+ * Create a logging utility with a specific label
685
+ * @param {string} label
686
+ * @returns {{
687
+ * log: (...args: unknown[]) => void,
688
+ * logError: (...args: unknown[]) => void,
689
+ * logWarning: (...args: unknown[]) => void,
690
+ * }}
691
+ */
692
+ function createLogging(label) {
693
+ return {
694
+ log(...args) {
695
+ if (DEBUG) console.log(label, ...args);
696
+ },
697
+ logError(...args) {
698
+ if (DEBUG) console.error(label, ...args);
699
+ },
700
+ logWarning(...args) {
701
+ if (DEBUG) console.warn(label, ...args);
702
+ }
703
+ };
704
+ }
705
+
706
+ //#endregion
707
+ //#region ../typescript-plugin/src/consumer-compiler.js
708
+ /** @typedef {{actual_type: string, actual_value: string}} InvalidConfigValueDetails */
709
+ /** @typedef {'web' | 'ios' | 'android'} Platform */
710
+ /**
711
+ * @typedef {
712
+ * | {state: 'absent'}
713
+ * | {state: 'declared', value: string}
714
+ * | ({state: 'invalid', target: 'tsrx' | 'compiler'} & InvalidConfigValueDetails)
715
+ * } CompilerDeclaration
716
+ */
717
+ /**
718
+ * @typedef {
719
+ * | {state: 'absent'}
720
+ * | {state: 'declared', value: Platform}
721
+ * | ({state: 'invalid', target: 'tsrx' | 'platform'} & InvalidConfigValueDetails)
722
+ * } PlatformDeclaration
723
+ */
724
+ /**
725
+ * @typedef {object} CompilerResolutionOptions
726
+ * @property {typeof import('typescript')} [ts] Accepted for the classic callers; config resolution no longer uses it.
727
+ * @property {string} [configFileName]
728
+ * @property {import('./tsconfig-resolution.js').TsconfigHost} [configHost]
729
+ * @property {Set<string>} [dependencies]
730
+ * @property {boolean} [requirePlatformResolution]
731
+ */
732
+ /**
733
+ * @typedef {object} ConfigHostResolutionCache
734
+ * @property {Map<string, string | null>} nearest_config_paths
735
+ * @property {Map<string, CachedTsconfigLayers>} resolved_config_layers
736
+ */
737
+ /**
738
+ * @typedef {object} CachedTsconfigLayers
739
+ * @property {import('./tsconfig-resolution.js').ResolvedTsconfigLayers} value
740
+ * @property {Map<string, number | undefined> | undefined} dependency_modified_times
741
+ */
742
+ const { log: log$1, logError: logError$1, logWarning: logWarning$1 } = createLogging("[TSRX Language]");
743
+ const bare_package_specifier_pattern$1 = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/;
744
+ const tsrx_key_pattern = /["']tsrx["']\s*:/;
745
+ /** @type {WeakMap<object, ConfigHostResolutionCache>} */
746
+ let config_host_to_resolution_cache = /* @__PURE__ */ new WeakMap();
747
+ /** @type {Map<string, string | null>} */
748
+ const declared_compiler_path_map = /* @__PURE__ */ new Map();
749
+ /**
750
+ * @param {unknown} value
751
+ * @returns {{ actual_type: string, actual_value: string }}
752
+ */
753
+ function describe_config_value(value) {
754
+ return {
755
+ actual_type: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
756
+ actual_value: JSON.stringify(value) ?? String(value)
757
+ };
758
+ }
759
+ /**
760
+ * Keep filesystem-derived config caches isolated per TypeScript/Volar host.
761
+ * Different hosts can expose different snapshots for the same absolute path.
762
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
763
+ */
764
+ function get_config_host_cache(host) {
765
+ let cache = config_host_to_resolution_cache.get(host);
766
+ if (!cache) {
767
+ cache = {
768
+ nearest_config_paths: /* @__PURE__ */ new Map(),
769
+ resolved_config_layers: /* @__PURE__ */ new Map()
770
+ };
771
+ config_host_to_resolution_cache.set(host, cache);
772
+ }
773
+ return cache;
774
+ }
775
+ /**
776
+ * @param {string} file_name
777
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
778
+ */
779
+ function get_config_cache_key(file_name, host) {
780
+ const normalized_path = path$1.normalize(path$1.resolve(file_name));
781
+ return (typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames) ? normalized_path : normalized_path.toLowerCase();
782
+ }
783
+ /**
784
+ * @param {unknown} config
785
+ * @returns {CompilerDeclaration}
786
+ */
787
+ function get_compiler_declaration(config) {
788
+ const tsrx_result = get_own_config_value(config, ["tsrx"]);
789
+ if (tsrx_result.state === "absent") return { state: "absent" };
790
+ const tsrx_value = tsrx_result.value;
791
+ if (tsrx_value === null || typeof tsrx_value !== "object" || Array.isArray(tsrx_value)) return {
792
+ state: "invalid",
793
+ target: "tsrx",
794
+ ...describe_config_value(tsrx_value)
795
+ };
796
+ const compiler_result = get_own_config_value(tsrx_value, ["compiler"]);
797
+ if (compiler_result.state === "absent") return { state: "absent" };
798
+ const compiler = compiler_result.value;
799
+ if (typeof compiler === "string" && compiler.trim() !== "") return {
800
+ state: "declared",
801
+ value: compiler.trim()
802
+ };
803
+ return {
804
+ state: "invalid",
805
+ target: "compiler",
806
+ ...describe_config_value(compiler)
807
+ };
808
+ }
809
+ /**
810
+ * @param {unknown} config
811
+ * @returns {PlatformDeclaration}
812
+ */
813
+ function get_platform_declaration(config) {
814
+ const tsrx_result = get_own_config_value(config, ["tsrx"]);
815
+ if (tsrx_result.state === "absent") return { state: "absent" };
816
+ const tsrx_value = tsrx_result.value;
817
+ if (tsrx_value === null || typeof tsrx_value !== "object" || Array.isArray(tsrx_value)) return {
818
+ state: "invalid",
819
+ target: "tsrx",
820
+ ...describe_config_value(tsrx_value)
821
+ };
822
+ const platform_result = get_own_config_value(tsrx_value, ["platform"]);
823
+ if (platform_result.state === "absent") return { state: "absent" };
824
+ const platform = platform_result.value;
825
+ if (platform === "web" || platform === "ios" || platform === "android") return {
826
+ state: "declared",
827
+ value: platform
828
+ };
829
+ return {
830
+ state: "invalid",
831
+ target: "platform",
832
+ ...describe_config_value(platform)
833
+ };
834
+ }
835
+ /**
836
+ * Find the nearest tsconfig.json to use as the root of inheritance resolution.
837
+ * @param {string} start_dir
838
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
839
+ * @param {ConfigHostResolutionCache} cache
840
+ * @returns {string | null}
841
+ */
842
+ function get_nearest_root_tsconfig(start_dir, host, cache) {
843
+ let current_dir = start_dir;
844
+ /** @type {string[]} */
845
+ const visited_dir_keys = [];
846
+ while (current_dir) {
847
+ const current_dir_key = get_config_cache_key(current_dir, host);
848
+ if (cache.nearest_config_paths.has(current_dir_key)) {
849
+ const cached_tsconfig = cache.nearest_config_paths.get(current_dir_key) ?? null;
850
+ for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, cached_tsconfig);
851
+ return cached_tsconfig;
852
+ }
853
+ visited_dir_keys.push(current_dir_key);
854
+ const tsconfig_path = path$1.join(current_dir, "tsconfig.json");
855
+ if (host.fileExists(tsconfig_path)) {
856
+ for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, tsconfig_path);
857
+ return tsconfig_path;
858
+ }
859
+ const parent_dir = path$1.dirname(current_dir);
860
+ if (parent_dir === current_dir) break;
861
+ current_dir = parent_dir;
862
+ }
863
+ for (const visited_dir_key of visited_dir_keys) cache.nearest_config_paths.set(visited_dir_key, null);
864
+ return null;
865
+ }
866
+ /**
867
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
868
+ * @param {string} root_config_path
869
+ * @param {ConfigHostResolutionCache} cache
870
+ */
871
+ function get_tsconfig_layers(host, root_config_path, cache) {
872
+ const cache_key = get_config_cache_key(root_config_path, host);
873
+ const cached = cache.resolved_config_layers.get(cache_key);
874
+ if (cached && (cached.dependency_modified_times === void 0 || [...cached.dependency_modified_times].every(([dependency, modified_time]) => host.getModifiedTime?.(dependency)?.valueOf() === modified_time))) return cached.value;
875
+ const value = load_tsconfig_layers(host, root_config_path);
876
+ const dependency_modified_times = host.getModifiedTime ? new Map(value.dependencies.map((dependency) => [dependency, host.getModifiedTime?.(dependency)?.valueOf()])) : void 0;
877
+ cache.resolved_config_layers.set(cache_key, {
878
+ value,
879
+ dependency_modified_times
880
+ });
881
+ return value;
882
+ }
883
+ /**
884
+ * A declaration in the config that owns a failed extends entry, or in a child
885
+ * config above it, has higher precedence than anything the missing base could
886
+ * have declared and therefore makes that failure irrelevant to this value.
887
+ * @param {readonly import('./tsconfig-resolution.js').TsconfigLayer[]} layers
888
+ * @param {import('./tsconfig-resolution.js').TsconfigExtendsFailure} failure
889
+ * @param {string} declaration_config_path
890
+ */
891
+ function is_extends_failure_overridden(layers, failure, declaration_config_path) {
892
+ const failure_owner_index = layers.findLastIndex((layer) => layer.path === failure.config_path);
893
+ const declaration_index = layers.findLastIndex((layer) => layer.path === declaration_config_path);
894
+ return failure_owner_index >= 0 && declaration_index >= failure_owner_index;
895
+ }
896
+ /**
897
+ * Resolve without a module-resolution cache. This is the recovery path when
898
+ * Node retains a negative package lookup after a dependency is installed: the
899
+ * package walk reads every manifest fresh and resolves the runtime entry.
900
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
901
+ * @param {string} config_path
902
+ * @param {string} specifier
903
+ */
904
+ function resolve_uncached_declared_compiler(host, config_path, specifier) {
905
+ return resolve_package_entry(specifier, path$1.dirname(config_path), { host });
906
+ }
907
+ /**
908
+ * Resolve the compiler explicitly selected by a consumer tsconfig. Invalid
909
+ * specifiers are stable and cached, while missing packages are retried so
910
+ * tsserver can recover after the dependency is installed.
911
+ * @param {import('./tsconfig-resolution.js').TsconfigHost} host
912
+ * @param {string} config_path
913
+ * @param {string} specifier
914
+ * @returns {string | null}
915
+ */
916
+ function resolve_declared_compiler(host, config_path, specifier) {
917
+ const cache_key = `${config_path}\0${specifier}`;
918
+ if (declared_compiler_path_map.has(cache_key)) return declared_compiler_path_map.get(cache_key) ?? null;
919
+ if (!bare_package_specifier_pattern$1.test(specifier)) {
920
+ declared_compiler_path_map.set(cache_key, null);
921
+ logError$1("Declared TSRX compiler must be a bare package specifier:", specifier, `in ${config_path}`);
922
+ return null;
923
+ }
924
+ try {
925
+ const compiler_path = createRequire$1(config_path).resolve(specifier);
926
+ declared_compiler_path_map.set(cache_key, compiler_path);
927
+ log$1("Found declared tsrx compiler at:", compiler_path, "from tsconfig:", config_path);
928
+ return compiler_path;
929
+ } catch {
930
+ const compiler_path = resolve_uncached_declared_compiler(host, config_path, specifier);
931
+ if (compiler_path !== void 0) {
932
+ declared_compiler_path_map.set(cache_key, compiler_path);
933
+ log$1("Found declared tsrx compiler after uncached retry at:", compiler_path, "from tsconfig:", config_path);
934
+ return compiler_path;
935
+ }
936
+ logError$1(`Unable to resolve declared TSRX compiler "${specifier}" from tsconfig`, config_path);
937
+ return null;
938
+ }
939
+ }
940
+ /**
941
+ * Return undefined when there is no consumer declaration, null for a declared
942
+ * hard stop, or the resolved compiler path for a valid declaration.
943
+ * @param {string} normalized_file_name
944
+ * @param {CompilerResolutionOptions} [options]
945
+ * @returns {string | null | undefined}
946
+ */
947
+ function resolve_consumer_compiler_for_file(normalized_file_name, options = {}) {
948
+ const config_host = options.configHost ?? NODE_CONFIG_HOST;
949
+ const host_cache = get_config_host_cache(config_host);
950
+ const root_config_path = options.configFileName ?? get_nearest_root_tsconfig(path$1.dirname(normalized_file_name), config_host, host_cache);
951
+ if (root_config_path === null) return;
952
+ const resolved_layers = get_tsconfig_layers(config_host, root_config_path, host_cache);
953
+ for (const dependency of resolved_layers.dependencies) options.dependencies?.add(dependency);
954
+ const unreadable_layers = resolved_layers.layers.filter((layer) => layer.raw_source === void 0);
955
+ if (unreadable_layers.length > 0) {
956
+ for (const layer of unreadable_layers) logError$1("Unable to read tsconfig layer:", layer.path);
957
+ return null;
958
+ }
959
+ const malformed_layers = resolved_layers.layers.filter((layer) => layer.parse_diagnostics.length > 0);
960
+ if (malformed_layers.length > 0) {
961
+ const has_tsrx_intent = resolved_layers.layers.some((layer) => {
962
+ if (get_own_config_value(layer.config, ["tsrx"]).state === "found") return true;
963
+ if (layer.parse_diagnostics.length === 0 || layer.raw_source === void 0) return false;
964
+ return tsrx_key_pattern.test(layer.raw_source);
965
+ });
966
+ const log_parse_error = has_tsrx_intent ? logError$1 : logWarning$1;
967
+ for (const layer of malformed_layers) for (const diagnostic of layer.parse_diagnostics) log_parse_error("Unable to parse tsconfig layer:", layer.path, diagnostic.message);
968
+ return has_tsrx_intent ? null : void 0;
969
+ }
970
+ const declaration = resolve_inherited_config_value(resolved_layers.layers, (layer) => get_compiler_declaration(layer.config));
971
+ if (declaration.state === "invalid") {
972
+ logError$1(`Invalid TSRX ${declaration.target} declaration:`, declaration.actual_type, declaration.actual_value, `in ${declaration.config_path}`);
973
+ return null;
974
+ }
975
+ const effective_extends_failures = resolved_layers.extends_failures.filter((failure) => declaration.state !== "declared" || !is_extends_failure_overridden(resolved_layers.layers, failure, declaration.config_path));
976
+ if (effective_extends_failures.length > 0) {
977
+ for (const failure of effective_extends_failures) {
978
+ if (failure.diagnostics.length === 0) {
979
+ logError$1("Unable to resolve tsconfig extends entry:", JSON.stringify(failure.extends_value), `in ${failure.config_path}`);
980
+ continue;
981
+ }
982
+ for (const diagnostic of failure.diagnostics) logError$1("Unable to resolve tsconfig extends entry:", JSON.stringify(failure.extends_value), `in ${failure.config_path}`, diagnostic.message);
983
+ }
984
+ return null;
985
+ }
986
+ if (declaration.state === "declared") return resolve_declared_compiler(config_host, declaration.config_path, declaration.value);
987
+ }
988
+ /**
989
+ * Resolve the compile-time platform selected by the active TypeScript project.
990
+ * The same inheritance graph and dependency tracking as compiler selection are
991
+ * used so nested projects and config edits cannot silently drift.
992
+ *
993
+ * @param {string} normalized_file_name
994
+ * @param {CompilerResolutionOptions} [options]
995
+ * @returns {Platform | undefined}
996
+ */
997
+ function resolve_consumer_platform_for_file(normalized_file_name, options = {}) {
998
+ const config_host = options.configHost ?? NODE_CONFIG_HOST;
999
+ const host_cache = get_config_host_cache(config_host);
1000
+ const root_config_path = options.configFileName ?? get_nearest_root_tsconfig(path$1.dirname(normalized_file_name), config_host, host_cache);
1001
+ if (root_config_path === null) return;
1002
+ const resolved_layers = get_tsconfig_layers(config_host, root_config_path, host_cache);
1003
+ for (const dependency of resolved_layers.dependencies) options.dependencies?.add(dependency);
1004
+ const unreadable_layer = resolved_layers.layers.find((layer) => layer.raw_source === void 0);
1005
+ if (unreadable_layer) {
1006
+ const message = `Unable to read tsconfig layer while resolving TSRX platform: ${unreadable_layer.path}`;
1007
+ logError$1(message);
1008
+ throw new Error(message);
1009
+ }
1010
+ const malformed_layers = resolved_layers.layers.filter((layer) => layer.parse_diagnostics.length > 0);
1011
+ if (malformed_layers.length > 0) {
1012
+ if (!resolved_layers.layers.some((layer) => {
1013
+ if (get_own_config_value(layer.config, ["tsrx"]).state === "found") return true;
1014
+ return layer.parse_diagnostics.length > 0 && layer.raw_source !== void 0 && tsrx_key_pattern.test(layer.raw_source);
1015
+ })) return void 0;
1016
+ const layer = malformed_layers[0];
1017
+ const detail = layer.parse_diagnostics[0].message;
1018
+ const message = `Unable to parse tsconfig layer while resolving TSRX platform: ${layer.path}: ${detail}`;
1019
+ logError$1(message);
1020
+ throw new Error(message);
1021
+ }
1022
+ const declaration = resolve_inherited_config_value(resolved_layers.layers, (layer) => get_platform_declaration(layer.config));
1023
+ if (declaration.state === "invalid") {
1024
+ const expected = declaration.target === "platform" ? " Expected \"web\", \"ios\", or \"android\"." : "";
1025
+ const message = `Invalid TSRX ${declaration.target} declaration: ${declaration.actual_type} ${declaration.actual_value} in ${declaration.config_path}.${expected}`;
1026
+ logError$1(message);
1027
+ throw new TypeError(message);
1028
+ }
1029
+ const effective_extends_failures = resolved_layers.extends_failures.filter((failure) => declaration.state !== "declared" || !is_extends_failure_overridden(resolved_layers.layers, failure, declaration.config_path));
1030
+ if (effective_extends_failures.length > 0) {
1031
+ if (!options.requirePlatformResolution) return declaration.state === "declared" ? declaration.value : void 0;
1032
+ const failure = effective_extends_failures[0];
1033
+ const detail = failure.diagnostics.length > 0 ? `: ${failure.diagnostics[0].message}` : "";
1034
+ const message = `Unable to resolve tsconfig extends entry ${JSON.stringify(failure.extends_value)} in ${failure.config_path} while resolving TSRX platform${detail}`;
1035
+ logError$1(message);
1036
+ throw new Error(message);
1037
+ }
1038
+ return declaration.state === "declared" ? declaration.value : void 0;
1039
+ }
1040
+ /** Drop all filesystem-derived consumer compiler resolution state. */
1041
+ function reset_consumer_compiler_resolution_caches() {
1042
+ config_host_to_resolution_cache = /* @__PURE__ */ new WeakMap();
1043
+ declared_compiler_path_map.clear();
1044
+ }
1045
+
1046
+ //#endregion
1047
+ //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/binarySearch.js
1048
+ var require_binarySearch = /* @__PURE__ */ __commonJSMin(((exports) => {
1049
+ Object.defineProperty(exports, "__esModule", { value: true });
1050
+ exports.binarySearch = binarySearch;
1051
+ function binarySearch(values, searchValue) {
1052
+ let low = 0;
1053
+ let high = values.length - 1;
1054
+ let match;
1055
+ while (low <= high) {
1056
+ const mid = Math.floor((low + high) / 2);
1057
+ const midValue = values[mid];
1058
+ if (midValue < searchValue) low = mid + 1;
1059
+ else if (midValue > searchValue) high = mid - 1;
1060
+ else {
1061
+ low = mid;
1062
+ high = mid;
1063
+ match = mid;
1064
+ break;
1065
+ }
1066
+ }
1067
+ return {
1068
+ low: Math.max(Math.min(low, high, values.length - 1), 0),
1069
+ high: Math.min(Math.max(low, high, 0), values.length - 1),
1070
+ match
1071
+ };
1072
+ }
1073
+ }));
1074
+
1075
+ //#endregion
1076
+ //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/translateOffset.js
1077
+ var require_translateOffset = /* @__PURE__ */ __commonJSMin(((exports) => {
1078
+ Object.defineProperty(exports, "__esModule", { value: true });
1079
+ exports.translateOffset = translateOffset;
1080
+ let warned = false;
1081
+ function translateOffset(start, fromOffsets, toOffsets, fromLengths, toLengths = fromLengths, preferEnd = false) {
1082
+ if (!fromOffsets.every((value, index) => index === 0 || fromOffsets[index - 1] <= value)) {
1083
+ for (let i = 0; i < fromOffsets.length; i++) {
1084
+ const fromOffset = fromOffsets[i];
1085
+ const fromLength = fromLengths[i];
1086
+ if (start >= fromOffset && start <= fromOffset + fromLength) {
1087
+ const toLength = toLengths[i];
1088
+ const toOffset = toOffsets[i];
1089
+ let rangeOffset;
1090
+ const relativePos = start - fromOffset;
1091
+ if (preferEnd && toLength > fromLength && relativePos === fromLength) rangeOffset = toLength;
1092
+ else rangeOffset = Math.min(relativePos, toLength);
1093
+ return toOffset + rangeOffset;
1094
+ }
1095
+ }
1096
+ if (!warned) {
1097
+ warned = true;
1098
+ console.warn("fromOffsets should be sorted in ascending order");
1099
+ }
1100
+ }
1101
+ let low = 0;
1102
+ let high = fromOffsets.length - 1;
1103
+ while (low <= high) {
1104
+ const mid = Math.floor((low + high) / 2);
1105
+ const fromOffset = fromOffsets[mid];
1106
+ const fromLength = fromLengths[mid];
1107
+ if (start >= fromOffset && start <= fromOffset + fromLength) {
1108
+ const toLength = toLengths[mid];
1109
+ const toOffset = toOffsets[mid];
1110
+ let rangeOffset;
1111
+ const relativePos = start - fromOffset;
1112
+ if (preferEnd && toLength > fromLength && relativePos === fromLength) rangeOffset = toLength;
1113
+ else rangeOffset = Math.min(relativePos, toLength);
1114
+ return toOffset + rangeOffset;
1115
+ } else if (start < fromOffset) high = mid - 1;
1116
+ else low = mid + 1;
1117
+ }
1118
+ }
1119
+ }));
1120
+
1121
+ //#endregion
1122
+ //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/lib/sourceMap.js
1123
+ var require_sourceMap = /* @__PURE__ */ __commonJSMin(((exports) => {
1124
+ Object.defineProperty(exports, "__esModule", { value: true });
1125
+ exports.SourceMap = void 0;
1126
+ const binarySearch_1 = require_binarySearch();
1127
+ const translateOffset_1 = require_translateOffset();
1128
+ var SourceMap = class {
1129
+ constructor(mappings) {
1130
+ this.mappings = mappings;
1131
+ }
1132
+ toSourceRange(generatedStart, generatedEnd, fallbackToAnyMatch, filter) {
1133
+ return this.findMatchingStartEnd(generatedStart, generatedEnd, fallbackToAnyMatch, "generatedOffsets", filter);
1134
+ }
1135
+ toGeneratedRange(sourceStart, sourceEnd, fallbackToAnyMatch, filter) {
1136
+ return this.findMatchingStartEnd(sourceStart, sourceEnd, fallbackToAnyMatch, "sourceOffsets", filter);
1137
+ }
1138
+ toSourceLocation(generatedOffset, filter) {
1139
+ return this.findMatchingOffsets(generatedOffset, "generatedOffsets", filter);
1140
+ }
1141
+ toGeneratedLocation(sourceOffset, filter) {
1142
+ return this.findMatchingOffsets(sourceOffset, "sourceOffsets", filter);
1143
+ }
1144
+ *findMatchingOffsets(offset, fromRange, filter, preferEnd = false) {
1145
+ const memo = this.getMemoBasedOnRange(fromRange);
1146
+ if (memo.offsets.length === 0) return;
1147
+ const { low: start, high: end } = (0, binarySearch_1.binarySearch)(memo.offsets, offset);
1148
+ const skip = /* @__PURE__ */ new Set();
1149
+ const toRange = fromRange === "sourceOffsets" ? "generatedOffsets" : "sourceOffsets";
1150
+ for (let i = start; i <= end; i++) for (const mapping of memo.mappings[i]) {
1151
+ if (skip.has(mapping)) continue;
1152
+ skip.add(mapping);
1153
+ if (filter && !filter(mapping.data)) continue;
1154
+ const mapped = (0, translateOffset_1.translateOffset)(offset, mapping[fromRange], mapping[toRange], getLengths(mapping, fromRange), getLengths(mapping, toRange), preferEnd);
1155
+ if (mapped !== void 0) yield [mapped, mapping];
1156
+ }
1157
+ }
1158
+ *findMatchingStartEnd(start, end, fallbackToAnyMatch, fromRange, filter) {
1159
+ const toRange = fromRange === "sourceOffsets" ? "generatedOffsets" : "sourceOffsets";
1160
+ const preferEnd = toRange === "sourceOffsets";
1161
+ const mappedStarts = [];
1162
+ let hadMatch = false;
1163
+ for (const [mappedStart, mapping] of this.findMatchingOffsets(start, fromRange)) {
1164
+ if (filter && !filter(mapping.data)) continue;
1165
+ mappedStarts.push([mappedStart, mapping]);
1166
+ const mappedEnd = (0, translateOffset_1.translateOffset)(end, mapping[fromRange], mapping[toRange], getLengths(mapping, fromRange), getLengths(mapping, toRange), preferEnd);
1167
+ if (mappedEnd !== void 0) {
1168
+ hadMatch = true;
1169
+ yield [
1170
+ mappedStart,
1171
+ mappedEnd,
1172
+ mapping,
1173
+ mapping
1174
+ ];
1175
+ }
1176
+ }
1177
+ if (!hadMatch && fallbackToAnyMatch) for (const [mappedStart, mappingStart] of mappedStarts) for (const [mappedEnd, mappingEnd] of this.findMatchingOffsets(end, fromRange, void 0, preferEnd)) {
1178
+ if (filter && !filter(mappingEnd.data) || mappedEnd < mappedStart) continue;
1179
+ yield [
1180
+ mappedStart,
1181
+ mappedEnd,
1182
+ mappingStart,
1183
+ mappingEnd
1184
+ ];
1185
+ break;
1186
+ }
1187
+ }
1188
+ getMemoBasedOnRange(fromRange) {
1189
+ return fromRange === "sourceOffsets" ? this.sourceCodeOffsetsMemo ??= this.createMemo("sourceOffsets") : this.generatedCodeOffsetsMemo ??= this.createMemo("generatedOffsets");
1190
+ }
1191
+ createMemo(key) {
1192
+ const offsetsSet = /* @__PURE__ */ new Set();
1193
+ for (const mapping of this.mappings) for (let i = 0; i < mapping[key].length; i++) {
1194
+ offsetsSet.add(mapping[key][i]);
1195
+ offsetsSet.add(mapping[key][i] + getLengths(mapping, key)[i]);
1196
+ }
1197
+ const offsets = [...offsetsSet].sort((a, b) => a - b);
1198
+ const mappings = offsets.map(() => /* @__PURE__ */ new Set());
1199
+ for (const mapping of this.mappings) for (let i = 0; i < mapping[key].length; i++) {
1200
+ const startIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i]).match;
1201
+ const endIndex = (0, binarySearch_1.binarySearch)(offsets, mapping[key][i] + getLengths(mapping, key)[i]).match;
1202
+ for (let i = startIndex; i <= endIndex; i++) mappings[i].add(mapping);
1203
+ }
1204
+ return {
1205
+ offsets,
1206
+ mappings
1207
+ };
1208
+ }
1209
+ };
1210
+ exports.SourceMap = SourceMap;
1211
+ function getLengths(mapping, key) {
1212
+ return key === "sourceOffsets" ? mapping.lengths : mapping.generatedLengths ?? mapping.lengths;
1213
+ }
1214
+ }));
1215
+
1216
+ //#endregion
1217
+ //#region ../../node_modules/.pnpm/@volar+source-map@2.4.28/node_modules/@volar/source-map/index.js
1218
+ var require_source_map = /* @__PURE__ */ __commonJSMin(((exports) => {
1219
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
1220
+ if (k2 === void 0) k2 = k;
1221
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1222
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
1223
+ enumerable: true,
1224
+ get: function() {
1225
+ return m[k];
1226
+ }
1227
+ };
1228
+ Object.defineProperty(o, k2, desc);
1229
+ }) : (function(o, m, k, k2) {
1230
+ if (k2 === void 0) k2 = k;
1231
+ o[k2] = m[k];
1232
+ }));
1233
+ var __exportStar = exports && exports.__exportStar || function(m, exports$2) {
1234
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p);
1235
+ };
1236
+ Object.defineProperty(exports, "__esModule", { value: true });
1237
+ __exportStar(require_sourceMap(), exports);
1238
+ __exportStar(require_translateOffset(), exports);
1239
+ }));
1240
+
1241
+ //#endregion
1242
+ //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/editor.js
1243
+ var require_editor = /* @__PURE__ */ __commonJSMin(((exports) => {
1244
+ Object.defineProperty(exports, "__esModule", { value: true });
1245
+ exports.isHoverEnabled = isHoverEnabled;
1246
+ exports.isInlayHintsEnabled = isInlayHintsEnabled;
1247
+ exports.isCodeLensEnabled = isCodeLensEnabled;
1248
+ exports.isMonikerEnabled = isMonikerEnabled;
1249
+ exports.isInlineValueEnabled = isInlineValueEnabled;
1250
+ exports.isSemanticTokensEnabled = isSemanticTokensEnabled;
1251
+ exports.isCallHierarchyEnabled = isCallHierarchyEnabled;
1252
+ exports.isTypeHierarchyEnabled = isTypeHierarchyEnabled;
1253
+ exports.isRenameEnabled = isRenameEnabled;
1254
+ exports.isDefinitionEnabled = isDefinitionEnabled;
1255
+ exports.isTypeDefinitionEnabled = isTypeDefinitionEnabled;
1256
+ exports.isReferencesEnabled = isReferencesEnabled;
1257
+ exports.isImplementationEnabled = isImplementationEnabled;
1258
+ exports.isHighlightEnabled = isHighlightEnabled;
1259
+ exports.isSymbolsEnabled = isSymbolsEnabled;
1260
+ exports.isFoldingRangesEnabled = isFoldingRangesEnabled;
1261
+ exports.isSelectionRangesEnabled = isSelectionRangesEnabled;
1262
+ exports.isLinkedEditingEnabled = isLinkedEditingEnabled;
1263
+ exports.isColorEnabled = isColorEnabled;
1264
+ exports.isDocumentLinkEnabled = isDocumentLinkEnabled;
1265
+ exports.isDiagnosticsEnabled = isDiagnosticsEnabled;
1266
+ exports.isCodeActionsEnabled = isCodeActionsEnabled;
1267
+ exports.isFormattingEnabled = isFormattingEnabled;
1268
+ exports.isCompletionEnabled = isCompletionEnabled;
1269
+ exports.isAutoInsertEnabled = isAutoInsertEnabled;
1270
+ exports.isSignatureHelpEnabled = isSignatureHelpEnabled;
1271
+ exports.shouldReportDiagnostics = shouldReportDiagnostics;
1272
+ exports.resolveRenameNewName = resolveRenameNewName;
1273
+ exports.resolveRenameEditText = resolveRenameEditText;
1274
+ exports.findOverlapCodeRange = findOverlapCodeRange;
1275
+ function isHoverEnabled(info) {
1276
+ return !!info.semantic;
1277
+ }
1278
+ function isInlayHintsEnabled(info) {
1279
+ return !!info.semantic;
1280
+ }
1281
+ function isCodeLensEnabled(info) {
1282
+ return !!info.semantic;
1283
+ }
1284
+ function isMonikerEnabled(info) {
1285
+ return !!info.semantic;
1286
+ }
1287
+ function isInlineValueEnabled(info) {
1288
+ return !!info.semantic;
1289
+ }
1290
+ function isSemanticTokensEnabled(info) {
1291
+ return typeof info.semantic === "object" ? info.semantic.shouldHighlight?.() ?? true : !!info.semantic;
1292
+ }
1293
+ function isCallHierarchyEnabled(info) {
1294
+ return !!info.navigation;
1295
+ }
1296
+ function isTypeHierarchyEnabled(info) {
1297
+ return !!info.navigation;
1298
+ }
1299
+ function isRenameEnabled(info) {
1300
+ return typeof info.navigation === "object" ? info.navigation.shouldRename?.() ?? true : !!info.navigation;
1301
+ }
1302
+ function isDefinitionEnabled(info) {
1303
+ return !!info.navigation;
1304
+ }
1305
+ function isTypeDefinitionEnabled(info) {
1306
+ return !!info.navigation;
1307
+ }
1308
+ function isReferencesEnabled(info) {
1309
+ return !!info.navigation;
1310
+ }
1311
+ function isImplementationEnabled(info) {
1312
+ return !!info.navigation;
1313
+ }
1314
+ function isHighlightEnabled(info) {
1315
+ return typeof info.navigation === "object" ? info.navigation.shouldHighlight?.() ?? true : !!info.navigation;
1316
+ }
1317
+ function isSymbolsEnabled(info) {
1318
+ return !!info.structure;
1319
+ }
1320
+ function isFoldingRangesEnabled(info) {
1321
+ return !!info.structure;
1322
+ }
1323
+ function isSelectionRangesEnabled(info) {
1324
+ return !!info.structure;
1325
+ }
1326
+ function isLinkedEditingEnabled(info) {
1327
+ return !!info.structure;
1328
+ }
1329
+ function isColorEnabled(info) {
1330
+ return !!info.structure;
1331
+ }
1332
+ function isDocumentLinkEnabled(info) {
1333
+ return !!info.structure;
1334
+ }
1335
+ function isDiagnosticsEnabled(info) {
1336
+ return !!info.verification;
1337
+ }
1338
+ function isCodeActionsEnabled(info) {
1339
+ return !!info.verification;
1340
+ }
1341
+ function isFormattingEnabled(info) {
1342
+ return !!info.format;
1343
+ }
1344
+ function isCompletionEnabled(info) {
1345
+ return !!info.completion;
1346
+ }
1347
+ function isAutoInsertEnabled(info) {
1348
+ return !!info.completion;
1349
+ }
1350
+ function isSignatureHelpEnabled(info) {
1351
+ return !!info.completion;
1352
+ }
1353
+ function shouldReportDiagnostics(info, source, code) {
1354
+ return typeof info.verification === "object" ? info.verification.shouldReport?.(source, code) ?? true : !!info.verification;
1355
+ }
1356
+ function resolveRenameNewName(newName, info) {
1357
+ return typeof info.navigation === "object" ? info.navigation.resolveRenameNewName?.(newName) ?? newName : newName;
1358
+ }
1359
+ function resolveRenameEditText(text, info) {
1360
+ return typeof info.navigation === "object" ? info.navigation.resolveRenameEditText?.(text) ?? text : text;
1361
+ }
1362
+ function findOverlapCodeRange(start, end, map, filter) {
1363
+ let mappedStart;
1364
+ let mappedEnd;
1365
+ for (const [mapped, mapping] of map.toGeneratedLocation(start)) if (filter(mapping.data)) {
1366
+ mappedStart = mapped;
1367
+ break;
1368
+ }
1369
+ for (const [mapped, mapping] of map.toGeneratedLocation(end)) if (filter(mapping.data)) {
1370
+ mappedEnd = mapped;
1371
+ break;
1372
+ }
1373
+ if (mappedStart === void 0 || mappedEnd === void 0) {
1374
+ for (const mapping of map.mappings) if (filter(mapping.data)) {
1375
+ const mappingStart = mapping.sourceOffsets[0];
1376
+ const overlap = getOverlapRange(start, end, mappingStart, mapping.sourceOffsets[mapping.sourceOffsets.length - 1] + mapping.lengths[mapping.lengths.length - 1]);
1377
+ if (overlap) {
1378
+ const curMappedStart = overlap.start - mappingStart + mapping.generatedOffsets[0];
1379
+ const lastGeneratedLength = (mapping.generatedLengths ?? mapping.lengths)[mapping.generatedOffsets.length - 1];
1380
+ const curMappedEndOffset = Math.min(overlap.end - mapping.sourceOffsets[mapping.sourceOffsets.length - 1], lastGeneratedLength);
1381
+ const curMappedEnd = mapping.generatedOffsets[mapping.generatedOffsets.length - 1] + curMappedEndOffset;
1382
+ mappedStart = mappedStart === void 0 ? curMappedStart : Math.min(mappedStart, curMappedStart);
1383
+ mappedEnd = mappedEnd === void 0 ? curMappedEnd : Math.max(mappedEnd, curMappedEnd);
1384
+ }
1385
+ }
1386
+ }
1387
+ if (mappedStart !== void 0 && mappedEnd !== void 0) return {
1388
+ start: mappedStart,
1389
+ end: mappedEnd
1390
+ };
1391
+ }
1392
+ function getOverlapRange(range1Start, range1End, range2Start, range2End) {
1393
+ const start = Math.max(range1Start, range2Start);
1394
+ const end = Math.min(range1End, range2End);
1395
+ if (start > end) return;
1396
+ return {
1397
+ start,
1398
+ end
1399
+ };
1400
+ }
1401
+ }));
1402
+
1403
+ //#endregion
1404
+ //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/linkedCodeMap.js
1405
+ var require_linkedCodeMap = /* @__PURE__ */ __commonJSMin(((exports) => {
1406
+ Object.defineProperty(exports, "__esModule", { value: true });
1407
+ exports.LinkedCodeMap = void 0;
1408
+ const source_map_1 = require_source_map();
1409
+ var LinkedCodeMap = class extends source_map_1.SourceMap {
1410
+ *getLinkedOffsets(start) {
1411
+ for (const mapped of this.toGeneratedLocation(start)) yield mapped[0];
1412
+ for (const mapped of this.toSourceLocation(start)) yield mapped[0];
1413
+ }
1414
+ };
1415
+ exports.LinkedCodeMap = LinkedCodeMap;
1416
+ }));
1417
+
1418
+ //#endregion
1419
+ //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/types.js
1420
+ var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
1421
+ Object.defineProperty(exports, "__esModule", { value: true });
1422
+ }));
1423
+
1424
+ //#endregion
1425
+ //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/lib/utils.js
1426
+ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
1427
+ Object.defineProperty(exports, "__esModule", { value: true });
1428
+ exports.FileMap = void 0;
1429
+ var FileMap = class extends Map {
1430
+ constructor(caseSensitive) {
1431
+ super();
1432
+ this.caseSensitive = caseSensitive;
1433
+ this.originalFileNames = /* @__PURE__ */ new Map();
1434
+ }
1435
+ keys() {
1436
+ return this.originalFileNames.values();
1437
+ }
1438
+ get(key) {
1439
+ return super.get(this.normalizeId(key));
1440
+ }
1441
+ has(key) {
1442
+ return super.has(this.normalizeId(key));
1443
+ }
1444
+ set(key, value) {
1445
+ this.originalFileNames.set(this.normalizeId(key), key);
1446
+ return super.set(this.normalizeId(key), value);
1447
+ }
1448
+ delete(key) {
1449
+ this.originalFileNames.delete(this.normalizeId(key));
1450
+ return super.delete(this.normalizeId(key));
1451
+ }
1452
+ clear() {
1453
+ this.originalFileNames.clear();
1454
+ return super.clear();
1455
+ }
1456
+ normalizeId(id) {
1457
+ return this.caseSensitive ? id : id.toLowerCase();
1458
+ }
1459
+ };
1460
+ exports.FileMap = FileMap;
1461
+ }));
1462
+
1463
+ //#endregion
1464
+ //#region ../../node_modules/.pnpm/@volar+language-core@2.4.28/node_modules/@volar/language-core/index.js
1465
+ var require_language_core = /* @__PURE__ */ __commonJSMin(((exports) => {
1466
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
1467
+ if (k2 === void 0) k2 = k;
1468
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1469
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
1470
+ enumerable: true,
1471
+ get: function() {
1472
+ return m[k];
1473
+ }
1474
+ };
1475
+ Object.defineProperty(o, k2, desc);
1476
+ }) : (function(o, m, k, k2) {
1477
+ if (k2 === void 0) k2 = k;
1478
+ o[k2] = m[k];
1479
+ }));
1480
+ var __exportStar = exports && exports.__exportStar || function(m, exports$1) {
1481
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
1482
+ };
1483
+ Object.defineProperty(exports, "__esModule", { value: true });
1484
+ exports.defaultMapperFactory = exports.SourceMap = void 0;
1485
+ exports.createLanguage = createLanguage;
1486
+ exports.forEachEmbeddedCode = forEachEmbeddedCode;
1487
+ var source_map_1 = require_source_map();
1488
+ Object.defineProperty(exports, "SourceMap", {
1489
+ enumerable: true,
1490
+ get: function() {
1491
+ return source_map_1.SourceMap;
1492
+ }
1493
+ });
1494
+ __exportStar(require_editor(), exports);
1495
+ __exportStar(require_linkedCodeMap(), exports);
1496
+ __exportStar(require_types(), exports);
1497
+ __exportStar(require_utils(), exports);
1498
+ const source_map_2 = require_source_map();
1499
+ const linkedCodeMap_1 = require_linkedCodeMap();
1500
+ const defaultMapperFactory = (mappings) => new source_map_2.SourceMap(mappings);
1501
+ exports.defaultMapperFactory = defaultMapperFactory;
1502
+ function createLanguage(plugins, scriptRegistry, sync, onAssociationDirty) {
1503
+ const virtualCodeToSourceScriptMap = /* @__PURE__ */ new WeakMap();
1504
+ const virtualCodeToSourceMap = /* @__PURE__ */ new WeakMap();
1505
+ const virtualCodeToLinkedCodeMap = /* @__PURE__ */ new WeakMap();
1506
+ const language = {
1507
+ mapperFactory: exports.defaultMapperFactory,
1508
+ plugins,
1509
+ scripts: {
1510
+ fromVirtualCode(virtualCode) {
1511
+ return virtualCodeToSourceScriptMap.get(virtualCode);
1512
+ },
1513
+ get(id, includeFsFiles = true, shouldRegister = false) {
1514
+ sync(id, includeFsFiles, shouldRegister);
1515
+ const result = scriptRegistry.get(id);
1516
+ if (result?.isAssociationDirty) this.set(id, result.snapshot, result.languageId);
1517
+ return scriptRegistry.get(id);
1518
+ },
1519
+ set(id, snapshot, languageId, _plugins = plugins) {
1520
+ if (!languageId) for (const plugin of plugins) {
1521
+ languageId = plugin.getLanguageId?.(id);
1522
+ if (languageId) break;
1523
+ }
1524
+ if (!languageId) {
1525
+ console.warn(`languageId not found for ${String(id)}`);
1526
+ return;
1527
+ }
1528
+ let associatedOnly = false;
1529
+ for (const plugin of plugins) if (plugin.isAssociatedFileOnly?.(id, languageId)) {
1530
+ associatedOnly = true;
1531
+ break;
1532
+ }
1533
+ if (scriptRegistry.has(id)) {
1534
+ const sourceScript = scriptRegistry.get(id);
1535
+ if (sourceScript.languageId !== languageId || sourceScript.associatedOnly !== associatedOnly) {
1536
+ this.delete(id);
1537
+ triggerTargetsDirty(sourceScript);
1538
+ return this.set(id, snapshot, languageId);
1539
+ } else if (associatedOnly) {
1540
+ if (sourceScript.snapshot !== snapshot) {
1541
+ sourceScript.snapshot = snapshot;
1542
+ triggerTargetsDirty(sourceScript);
1543
+ }
1544
+ } else if (sourceScript.isAssociationDirty || sourceScript.snapshot !== snapshot) {
1545
+ if (sourceScript.snapshot !== snapshot) {
1546
+ sourceScript.snapshot = snapshot;
1547
+ triggerTargetsDirty(sourceScript);
1548
+ }
1549
+ const codegenCtx = prepareCreateVirtualCode(sourceScript);
1550
+ if (sourceScript.generated) {
1551
+ const { updateVirtualCode, createVirtualCode } = sourceScript.generated.languagePlugin;
1552
+ const newVirtualCode = updateVirtualCode ? updateVirtualCode(id, sourceScript.generated.root, snapshot, codegenCtx) : createVirtualCode?.(id, languageId, snapshot, codegenCtx);
1553
+ if (newVirtualCode) {
1554
+ sourceScript.generated.root = newVirtualCode;
1555
+ sourceScript.generated.embeddedCodes.clear();
1556
+ for (const code of forEachEmbeddedCode(sourceScript.generated.root)) {
1557
+ virtualCodeToSourceScriptMap.set(code, sourceScript);
1558
+ sourceScript.generated.embeddedCodes.set(code.id, code);
1559
+ }
1560
+ return sourceScript;
1561
+ } else {
1562
+ this.delete(id);
1563
+ return;
1564
+ }
1565
+ }
1566
+ } else return sourceScript;
1567
+ } else {
1568
+ const sourceScript = {
1569
+ id,
1570
+ languageId,
1571
+ snapshot,
1572
+ associatedIds: /* @__PURE__ */ new Set(),
1573
+ targetIds: /* @__PURE__ */ new Set(),
1574
+ associatedOnly
1575
+ };
1576
+ scriptRegistry.set(id, sourceScript);
1577
+ if (associatedOnly) return sourceScript;
1578
+ for (const languagePlugin of _plugins) {
1579
+ const virtualCode = languagePlugin.createVirtualCode?.(id, languageId, snapshot, prepareCreateVirtualCode(sourceScript));
1580
+ if (virtualCode) {
1581
+ sourceScript.generated = {
1582
+ root: virtualCode,
1583
+ languagePlugin,
1584
+ embeddedCodes: /* @__PURE__ */ new Map()
1585
+ };
1586
+ for (const code of forEachEmbeddedCode(virtualCode)) {
1587
+ virtualCodeToSourceScriptMap.set(code, sourceScript);
1588
+ sourceScript.generated.embeddedCodes.set(code.id, code);
1589
+ }
1590
+ break;
1591
+ }
1592
+ }
1593
+ return sourceScript;
1594
+ }
1595
+ },
1596
+ delete(id) {
1597
+ const sourceScript = scriptRegistry.get(id);
1598
+ if (sourceScript) {
1599
+ sourceScript.generated?.languagePlugin.disposeVirtualCode?.(id, sourceScript.generated.root);
1600
+ scriptRegistry.delete(id);
1601
+ triggerTargetsDirty(sourceScript);
1602
+ }
1603
+ }
1604
+ },
1605
+ maps: {
1606
+ get(virtualCode, sourceScript) {
1607
+ let mapCache = virtualCodeToSourceMap.get(virtualCode.snapshot);
1608
+ if (!mapCache) virtualCodeToSourceMap.set(virtualCode.snapshot, mapCache = /* @__PURE__ */ new WeakMap());
1609
+ if (!mapCache.has(sourceScript.snapshot)) {
1610
+ const mappings = virtualCode.associatedScriptMappings?.get(sourceScript.id) ?? virtualCode.mappings;
1611
+ mapCache.set(sourceScript.snapshot, language.mapperFactory(mappings));
1612
+ }
1613
+ return mapCache.get(sourceScript.snapshot);
1614
+ },
1615
+ *forEach(virtualCode) {
1616
+ const sourceScript = virtualCodeToSourceScriptMap.get(virtualCode);
1617
+ yield [sourceScript, this.get(virtualCode, sourceScript)];
1618
+ if (virtualCode.associatedScriptMappings) for (const [relatedScriptId] of virtualCode.associatedScriptMappings) {
1619
+ const relatedSourceScript = scriptRegistry.get(relatedScriptId);
1620
+ if (relatedSourceScript) yield [relatedSourceScript, this.get(virtualCode, relatedSourceScript)];
1621
+ }
1622
+ }
1623
+ },
1624
+ linkedCodeMaps: { get(virtualCode) {
1625
+ const sourceScript = virtualCodeToSourceScriptMap.get(virtualCode);
1626
+ let mapCache = virtualCodeToLinkedCodeMap.get(virtualCode.snapshot);
1627
+ if (mapCache?.[0] !== sourceScript.snapshot) virtualCodeToLinkedCodeMap.set(virtualCode.snapshot, mapCache = [sourceScript.snapshot, virtualCode.linkedCodeMappings ? new linkedCodeMap_1.LinkedCodeMap(virtualCode.linkedCodeMappings) : void 0]);
1628
+ return mapCache[1];
1629
+ } }
1630
+ };
1631
+ return language;
1632
+ function triggerTargetsDirty(sourceScript) {
1633
+ sourceScript.targetIds.forEach((id) => {
1634
+ const sourceScript = scriptRegistry.get(id);
1635
+ if (sourceScript) {
1636
+ sourceScript.isAssociationDirty = true;
1637
+ onAssociationDirty?.(sourceScript.id);
1638
+ }
1639
+ });
1640
+ }
1641
+ function prepareCreateVirtualCode(sourceScript) {
1642
+ for (const id of sourceScript.associatedIds) scriptRegistry.get(id)?.targetIds.delete(sourceScript.id);
1643
+ sourceScript.associatedIds.clear();
1644
+ sourceScript.isAssociationDirty = false;
1645
+ return { getAssociatedScript(id) {
1646
+ sync(id, true, true);
1647
+ const relatedSourceScript = scriptRegistry.get(id);
1648
+ if (relatedSourceScript) {
1649
+ relatedSourceScript.targetIds.add(sourceScript.id);
1650
+ sourceScript.associatedIds.add(relatedSourceScript.id);
1651
+ }
1652
+ return relatedSourceScript;
1653
+ } };
1654
+ }
1655
+ }
1656
+ function* forEachEmbeddedCode(virtualCode) {
1657
+ yield virtualCode;
1658
+ if (virtualCode.embeddedCodes) for (const embeddedCode of virtualCode.embeddedCodes) yield* forEachEmbeddedCode(embeddedCode);
1659
+ }
1660
+ }));
1661
+
1662
+ //#endregion
1663
+ //#region ../typescript-plugin/src/transform.js
1664
+ var import_language_core = require_language_core();
1665
+ /** @import * as AST from 'estree'; */
1666
+ /** @import {CompileError, VolarMappingsResult, CodeMapping} from '@tsrx/core/types' */
1667
+ /**
1668
+ * The compiler contract every TSRX target exposes for editor tooling. Octane
1669
+ * and consumer-declared modules may spell the entry `compileToVolarMappings`;
1670
+ * see `normalize_tsrx_compiler_module` in `language.js`.
1671
+ * @typedef {{
1672
+ * compile?: (source: string, filename: string, options?: TsrxTransformOptions) => { code?: string, errors?: CompileError[] },
1673
+ * compile_to_volar_mappings(source: string, filename: string, options?: { loose?: boolean } & TsrxTransformOptions): VolarMappingsResult,
1674
+ * }} TSRXCompilerModule
1675
+ */
1676
+ /**
1677
+ * @typedef {object} TsrxTransformOptions
1678
+ * @property {'web' | 'ios' | 'android'} [platform] Platform selected for `import.meta.env.platform` flags.
1679
+ */
1680
+ /**
1681
+ * A `<style>` or `<script>` body inside a `.tsrx` file, located by source
1682
+ * offset. Both region kinds map 1:1 onto their source text.
1683
+ * @typedef {object} EmbeddedRegion
1684
+ * @property {string} id Stable id, e.g. `style_0` / `script_0`.
1685
+ * @property {number} start Source offset of the first character of the body.
1686
+ * @property {number} length Body length in UTF-16 code units.
1687
+ * @property {string} content The body text.
1688
+ */
1689
+ /**
1690
+ * The type-only transform of one `.tsrx` file, free of any Volar or
1691
+ * TypeScript-host types so that both the classic Volar language plugin and the
1692
+ * TypeScript 7 content mapper can consume it.
1693
+ *
1694
+ * `fatalError` is set when the compiler threw: `text` is then `''`,
1695
+ * `mappings` is empty and `sourceAst` is `null`. Otherwise `text` is the
1696
+ * generated TSX, `mappings` maps it back to the source, `errors` holds the
1697
+ * non-fatal (usage) diagnostics and the regions describe the embedded
1698
+ * `<style>` / `<script>` bodies.
1699
+ * @typedef {object} TsrxTransformResult
1700
+ * @property {string} text
1701
+ * @property {CodeMapping[]} mappings
1702
+ * @property {EmbeddedRegion[]} cssRegions
1703
+ * @property {EmbeddedRegion[]} scriptRegions
1704
+ * @property {CompileError[]} errors
1705
+ * @property {CompileError | null} fatalError
1706
+ * @property {AST.Program | null} sourceAst
1707
+ */
1708
+ /**
1709
+ * Run a TSRX compiler's type-only transform in loose mode.
1710
+ *
1711
+ * Pure with respect to its inputs: the compiler module is the only
1712
+ * collaborator, no caches are consulted and nothing is logged.
1713
+ * @param {TSRXCompilerModule} compiler
1714
+ * @param {string} file_name
1715
+ * @param {string} content
1716
+ * @param {TsrxTransformOptions} [options]
1717
+ * @returns {TsrxTransformResult}
1718
+ */
1719
+ function transform_tsrx(compiler, file_name, content, options = {}) {
1720
+ /** @type {VolarMappingsResult} */
1721
+ let transpiled;
1722
+ try {
1723
+ transpiled = compiler.compile_to_volar_mappings(content, file_name, {
1724
+ loose: true,
1725
+ platform: options.platform
1726
+ });
1727
+ } catch (e) {
1728
+ const error = e;
1729
+ error.type = "fatal";
1730
+ return {
1731
+ text: "",
1732
+ mappings: [],
1733
+ cssRegions: [],
1734
+ scriptRegions: [],
1735
+ errors: [],
1736
+ fatalError: error,
1737
+ sourceAst: null
1738
+ };
1739
+ }
1740
+ const scriptRegions = regions_from_mappings(transpiled.scriptMappings ?? []);
1741
+ const embedded = embed_script_bodies(blank_script_bodies(transpiled.code ?? "", scriptRegions), transpiled.mappings ?? [], scriptRegions);
1742
+ return {
1743
+ text: embedded.text,
1744
+ mappings: embedded.mappings,
1745
+ cssRegions: regions_from_mappings(transpiled.cssMappings ?? []),
1746
+ scriptRegions,
1747
+ errors: transpiled.errors ?? [],
1748
+ fatalError: null,
1749
+ sourceAst: transpiled.sourceAst ?? null
1750
+ };
1751
+ }
1752
+ /**
1753
+ * The mapping data of a `<script>` body embedded in the generated TSX: every
1754
+ * language feature except formatting, exactly like the compiler's own spans.
1755
+ */
1756
+ const SCRIPT_BODY_MAPPING_DATA = {
1757
+ verification: true,
1758
+ completion: true,
1759
+ semantic: true,
1760
+ navigation: true,
1761
+ structure: true,
1762
+ format: false,
1763
+ customData: {}
1764
+ };
1765
+ /**
1766
+ * `import` declarations at the top level of a `<script>` body, by offset. A
1767
+ * conservative statement scanner (a line starting with `import`, up to the
1768
+ * module specifier and optional attributes) rather than a parser: the body is
1769
+ * plain TypeScript and the transform has no TypeScript parser of its own.
1770
+ */
1771
+ const IMPORT_DECLARATION = /^[ \t]*import\s+(?:type\s+)?(?:(?:[\w$]+\s*,\s*)?(?:\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+)?(['"])[^'"\n]*\1(?:\s+with\s*\{[^}]*\})?[ \t]*;?/gm;
1772
+ /**
1773
+ * Whole export statements that carry no declaration: re-exports
1774
+ * (`export ... from '...'`), local export lists (`export { a as b };`),
1775
+ * `export type { T };` and `export = x;`. Module-level syntax with nothing to
1776
+ * export from an inline script, blanked entirely.
1777
+ */
1778
+ const EXPORT_STATEMENT = /^[ \t]*export\s+(?:type\s+)?(?:(?:\{[^}]*\}|\*(?:\s+as\s+[\w$]+)?)(?:\s+from\s+(['"])[^'"\n]*\1(?:\s+with\s*\{[^}]*\})?)?|=\s*[^;\n]*)[ \t]*;?/gm;
1779
+ /**
1780
+ * `export default` in front of a named function or class declaration: only the
1781
+ * keywords are blanked, so the declaration keeps its name in the block's scope.
1782
+ */
1783
+ const EXPORT_DEFAULT_NAMED = /^([ \t]*)(export[ \t]+default[ \t]+)(?=(?:async[ \t]+)?function[ \t]*\*?[ \t]*[A-Za-z_$]|(?:abstract[ \t]+)?class[ \t]+(?!(?:extends|implements)\b)[A-Za-z_$])/gm;
1784
+ /**
1785
+ * `export default` in front of an expression, an anonymous function or an
1786
+ * anonymous class: replaced by a same-length `const <name>=` so the rest stays
1787
+ * a valid, checked initializer (an anonymous `function () {}` or `class {}` is
1788
+ * only valid as an expression).
1789
+ */
1790
+ const EXPORT_DEFAULT = /^([ \t]*)(export[ \t]+default[ \t]+)(?=\S)/gm;
1791
+ /** The `export` keyword in front of a declaration. */
1792
+ const EXPORT_KEYWORD = /^([ \t]*)(export[ \t]+)(?=(?:async[ \t]+)?(?:const|let|var|function|class|type|interface|enum|abstract|declare|namespace|module)\b)/gm;
1793
+ /**
1794
+ * A `<script type="module">` body may `export`, but nothing can import an inline
1795
+ * script, so its exports are dead and a block cannot hold them: statements that
1796
+ * only export are blanked, `export default` becomes a same-length `const`
1797
+ * binding, and the keyword in front of a declaration is blanked, keeping every
1798
+ * length so the body's mapping stays one to one.
1799
+ * @param {string} body
1800
+ * @returns {string}
1801
+ */
1802
+ function blank_export_syntax(body) {
1803
+ return body.replace(EXPORT_STATEMENT, (statement) => statement.replace(/[^\r\n]/g, " ")).replace(EXPORT_DEFAULT_NAMED, (_match, indent, keywords) => indent + " ".repeat(keywords.length)).replace(EXPORT_DEFAULT, (_match, indent, keywords) => {
1804
+ return `${indent}const ${"_default".padEnd(keywords.length - 6 - 1, "_")}=`;
1805
+ }).replace(EXPORT_KEYWORD, (_match, indent, keyword) => indent + " ".repeat(keyword.length));
1806
+ }
1807
+ /**
1808
+ * @param {string} body
1809
+ * @returns {Array<{ start: number, end: number }>}
1810
+ */
1811
+ function find_import_declarations(body) {
1812
+ /** @type {Array<{ start: number, end: number }>} */
1813
+ const imports = [];
1814
+ for (const match of body.matchAll(IMPORT_DECLARATION)) {
1815
+ const start = match.index + match[0].length - match[0].trimStart().length;
1816
+ imports.push({
1817
+ start,
1818
+ end: match.index + match[0].length
1819
+ });
1820
+ }
1821
+ return imports;
1822
+ }
1823
+ /**
1824
+ * Append every `<script>` body to the generated TSX as a block statement, so
1825
+ * TypeScript checks it in the same file as the component, on every path that
1826
+ * consumes the transform (the language server, tsserver through the plugin, and
1827
+ * the content mapper), with ordinary mappings back to the source. A block keeps
1828
+ * one body's declarations from colliding with another's or with the
1829
+ * component's, and contributes nothing to declaration output.
1830
+ *
1831
+ * `import` declarations cannot live in a block, so each body's imports are
1832
+ * hoisted verbatim in front of its block, at module level, where TypeScript
1833
+ * resolves them like any other import (a browser-only URL in a
1834
+ * `<script type="module">` yields a mapped "cannot find module"); their place
1835
+ * in the block is blanked. `export` syntax is blanked in place
1836
+ * ({@link blank_export_syntax}). Top-level `await` is legal inside a block of a
1837
+ * module and stays as written. Each body maps in one multi-segment mapping.
1838
+ * @param {string} text
1839
+ * @param {CodeMapping[]} mappings
1840
+ * @param {EmbeddedRegion[]} script_regions
1841
+ * @returns {{ text: string, mappings: CodeMapping[] }}
1842
+ */
1843
+ function embed_script_bodies(text, mappings, script_regions) {
1844
+ const result_mappings = [...mappings];
1845
+ for (const region of script_regions) {
1846
+ if (region.length === 0 || region.content.length !== region.length) continue;
1847
+ const imports = find_import_declarations(region.content);
1848
+ /** @type {number[]} */
1849
+ const sourceOffsets = [];
1850
+ /** @type {number[]} */
1851
+ const generatedOffsets = [];
1852
+ /** @type {number[]} */
1853
+ const lengths = [];
1854
+ let hoisted = "";
1855
+ let body = blank_export_syntax(region.content);
1856
+ for (const { start, end } of imports) {
1857
+ sourceOffsets.push(region.start + start);
1858
+ generatedOffsets.push(text.length + 1 + hoisted.length);
1859
+ lengths.push(end - start);
1860
+ hoisted += region.content.slice(start, end) + "\n";
1861
+ body = body.slice(0, start) + " ".repeat(end - start) + body.slice(end);
1862
+ }
1863
+ const block_prefix = `\n${hoisted};{\n`;
1864
+ const body_offset = text.length + block_prefix.length;
1865
+ let cursor = 0;
1866
+ for (const { start, end } of [...imports, {
1867
+ start: region.length,
1868
+ end: region.length
1869
+ }]) {
1870
+ if (start > cursor) {
1871
+ sourceOffsets.push(region.start + cursor);
1872
+ generatedOffsets.push(body_offset + cursor);
1873
+ lengths.push(start - cursor);
1874
+ }
1875
+ cursor = end;
1876
+ }
1877
+ text += `${block_prefix}${body}\n}\n`;
1878
+ if (sourceOffsets.length > 0) result_mappings.push({
1879
+ sourceOffsets,
1880
+ generatedOffsets,
1881
+ lengths,
1882
+ generatedLengths: [...lengths],
1883
+ data: {
1884
+ ...SCRIPT_BODY_MAPPING_DATA,
1885
+ customData: { embeddedId: region.id }
1886
+ }
1887
+ });
1888
+ }
1889
+ return {
1890
+ text,
1891
+ mappings: result_mappings
1892
+ };
1893
+ }
1894
+ /**
1895
+ * Blank every `<script>` body in the generated TSX, keeping its length and
1896
+ * line breaks. The compilers copy the body verbatim into the JSX text of the
1897
+ * `<script>` element, where a `<` (as in `1 < 2`) parses as a tag and yields a
1898
+ * syntax error that only the Volar path used to hide (it drops diagnostics
1899
+ * with no source mapping; the content-mapper protocol reports them). The body
1900
+ * is type-checked as a block appended by {@link embed_script_bodies}, and no
1901
+ * mapping of the generated TSX points into the copy in the JSX text
1902
+ * (`regions_from_mappings`), so blanking it loses nothing. A body is located by its text followed by the closing tag; a body
1903
+ * that is not found unchanged in the output is left alone.
1904
+ * @param {string} text
1905
+ * @param {EmbeddedRegion[]} script_regions
1906
+ * @returns {string}
1907
+ */
1908
+ function blank_script_bodies(text, script_regions) {
1909
+ let cursor = 0;
1910
+ for (const region of script_regions) {
1911
+ if (region.length === 0) continue;
1912
+ const needle = `${region.content}<\/script>`;
1913
+ const index = text.indexOf(needle, cursor);
1914
+ if (index < 0) continue;
1915
+ const blank = region.content.replace(/[^\r\n]/g, " ");
1916
+ text = text.slice(0, index) + blank + text.slice(index + region.content.length);
1917
+ cursor = index + needle.length;
1918
+ }
1919
+ return text;
1920
+ }
1921
+ /**
1922
+ * @param {CodeMapping[]} mappings
1923
+ * @returns {EmbeddedRegion[]}
1924
+ */
1925
+ function regions_from_mappings(mappings) {
1926
+ return mappings.map((mapping) => ({
1927
+ id: String(mapping.data?.customData?.embeddedId ?? ""),
1928
+ start: mapping.sourceOffsets[0],
1929
+ length: mapping.lengths[0],
1930
+ content: String(mapping.data?.customData?.content ?? "")
1931
+ }));
1932
+ }
1933
+
1934
+ //#endregion
1935
+ //#region ../typescript-plugin/src/language.js
1936
+ /** @import * as AST from 'estree'; */
1937
+ /** @import {CompileError, CodeMapping} from '@tsrx/core/types' */
1938
+ /** @typedef {import('./transform.js').TSRXCompilerModule} TSRXCompilerModule */
1939
+ /** @typedef {import('./transform.js').TsrxTransformResult} TsrxTransformResult */
1940
+ /** @typedef {import('./transform.js').EmbeddedRegion} EmbeddedRegion */
1941
+ /** @typedef {Map<string, CodeMapping>} CachedMappings */
1942
+ /** @typedef {import('typescript').CompilerOptions} CompilerOptions */
1943
+ /** @typedef {import('@volar/language-core').IScriptSnapshot} IScriptSnapshot */
1944
+ /** @typedef {import('@volar/language-core').VirtualCode} VirtualCode */
1945
+ /** @typedef {string | { fsPath: string }} ScriptId */
1946
+ /** @typedef {typeof import('@volar/typescript')} _VolarTypeScriptAugmentation */
1947
+ /** @typedef {import('./consumer-compiler.js').CompilerResolutionOptions} CompilerResolutionOptions */
1948
+ /** @typedef {import('@volar/language-core').LanguagePlugin<ScriptId, VirtualCode>} TsrxLanguagePlugin */
1949
+ /** @typedef {InstanceType<typeof import('./language.js')["TSRXVirtualCode"]>} TSRXVirtualCodeInstance */
1950
+ const require$2 = createRequire$1(import.meta.url);
1951
+ const root_dirname = path$1.dirname(fileURLToPath$1(import.meta.url));
1952
+ const { log, logWarning, logError } = createLogging("[TSRX Language]");
1953
+ /** @type {Set<string>} */
1954
+ const loggedCompilationFailures = /* @__PURE__ */ new Set();
1955
+ /**
1956
+ * `[package name, package directory parts, supported extensions, package hints, entry candidates?]`.
1957
+ * Entry candidates are relative to the package directory and are probed in order,
1958
+ * so a package that ships both a build output and its sources lists the published
1959
+ * layout first.
1960
+ * @typedef {[string, string[], string[], string[], string[][]?]} CompilerCandidate
1961
+ */
1962
+ /** @type {CompilerCandidate[]} */
1963
+ const COMPILER_CANDIDATES = [
1964
+ [
1965
+ "@tsrx/ripple",
1966
+ [
1967
+ "node_modules",
1968
+ "@tsrx",
1969
+ "ripple"
1970
+ ],
1971
+ [".tsrx"],
1972
+ [
1973
+ "@tsrx/ripple",
1974
+ "ripple",
1975
+ "@ripple-ts/vite-plugin"
1976
+ ]
1977
+ ],
1978
+ [
1979
+ "@tsrx/react",
1980
+ [
1981
+ "node_modules",
1982
+ "@tsrx",
1983
+ "react"
1984
+ ],
1985
+ [".tsrx"],
1986
+ ["@tsrx/react", "@tsrx/vite-plugin-react"]
1987
+ ],
1988
+ [
1989
+ "@tsrx/solid",
1990
+ [
1991
+ "node_modules",
1992
+ "@tsrx",
1993
+ "solid"
1994
+ ],
1995
+ [".tsrx"],
1996
+ ["@tsrx/solid", "@tsrx/vite-plugin-solid"]
1997
+ ],
1998
+ [
1999
+ "@tsrx/preact",
2000
+ [
2001
+ "node_modules",
2002
+ "@tsrx",
2003
+ "preact"
2004
+ ],
2005
+ [".tsrx"],
2006
+ ["@tsrx/preact", "@tsrx/vite-plugin-preact"]
2007
+ ],
2008
+ [
2009
+ "@tsrx/vue",
2010
+ [
2011
+ "node_modules",
2012
+ "@tsrx",
2013
+ "vue"
2014
+ ],
2015
+ [".tsrx"],
2016
+ ["@tsrx/vue", "@tsrx/vite-plugin-vue"]
2017
+ ],
2018
+ [
2019
+ "@tsrx/hono",
2020
+ [
2021
+ "node_modules",
2022
+ "@tsrx",
2023
+ "hono"
2024
+ ],
2025
+ [".tsrx"],
2026
+ ["@tsrx/hono", "@tsrx/vite-plugin-hono"]
2027
+ ],
2028
+ [
2029
+ "octane",
2030
+ ["node_modules", "octane"],
2031
+ [".tsrx"],
2032
+ ["octane", "@octanejs/vite-plugin"],
2033
+ [[
2034
+ "dist",
2035
+ "compiler",
2036
+ "volar.js"
2037
+ ], [
2038
+ "src",
2039
+ "compiler",
2040
+ "volar.js"
2041
+ ]]
2042
+ ]
2043
+ ];
2044
+ /** @type {string[][]} */
2045
+ const DEFAULT_COMPILER_ENTRY_CANDIDATES = [["src", "index.js"]];
2046
+ /**
2047
+ * Tokenize enough of a source text to find member chains: comments and
2048
+ * string literals are skipped, template literals contribute only their
2049
+ * `${...}` expressions, and every identifier, `.` and `?.` is a token.
2050
+ * It tokenizes independently of any grammar, so partially authored TSRX and
2051
+ * template syntax (`@{`, `@if`) are fine.
2052
+ * @param {string} source
2053
+ * @returns {Array<{ kind: 'word' | 'dot' | 'question-dot' | 'other', text: string }>}
2054
+ */
2055
+ function tokenize_member_chains(source) {
2056
+ /** @type {Array<{ kind: 'word' | 'dot' | 'question-dot' | 'other', text: string }>} */
2057
+ const tokens = [];
2058
+ const length = source.length;
2059
+ let index = 0;
2060
+ /** Brace depth at which each open template substitution started, innermost last. */
2061
+ /** @type {number[]} */
2062
+ const template_braces = [];
2063
+ let brace_depth = 0;
2064
+ /** Skip template text from `index` to the closing backtick or the next substitution. */
2065
+ function skip_template_text() {
2066
+ while (index < length && source[index] !== "`") {
2067
+ if (source[index] === "\\") {
2068
+ index += 2;
2069
+ continue;
2070
+ }
2071
+ if (source[index] === "$" && source[index + 1] === "{") {
2072
+ template_braces.push(brace_depth);
2073
+ index += 2;
2074
+ return;
2075
+ }
2076
+ index += 1;
2077
+ }
2078
+ if (index < length) index += 1;
2079
+ }
2080
+ while (index < length) {
2081
+ const char = source[index];
2082
+ const next = source[index + 1];
2083
+ if (/\s/.test(char)) index += 1;
2084
+ else if (char === "/" && next === "/") while (index < length && source[index] !== "\n") index += 1;
2085
+ else if (char === "/" && next === "*") {
2086
+ const end = source.indexOf("*/", index + 2);
2087
+ index = end < 0 ? length : end + 2;
2088
+ } else if (char === "\"" || char === "'") {
2089
+ index += 1;
2090
+ while (index < length && source[index] !== char && source[index] !== "\n") {
2091
+ if (source[index] === "\\") index += 1;
2092
+ index += 1;
2093
+ }
2094
+ index += 1;
2095
+ } else if (char === "`") {
2096
+ index += 1;
2097
+ skip_template_text();
2098
+ } else if (char === "}" && template_braces.length > 0 && template_braces[template_braces.length - 1] === brace_depth) {
2099
+ template_braces.pop();
2100
+ index += 1;
2101
+ skip_template_text();
2102
+ } else if (/[A-Za-z_$]/.test(char)) {
2103
+ let end = index + 1;
2104
+ while (end < length && /[\w$]/.test(source[end])) end += 1;
2105
+ tokens.push({
2106
+ kind: "word",
2107
+ text: source.slice(index, end)
2108
+ });
2109
+ index = end;
2110
+ } else if (char === "?" && next === ".") {
2111
+ tokens.push({
2112
+ kind: "question-dot",
2113
+ text: "?."
2114
+ });
2115
+ index += 2;
2116
+ } else if (char === ".") {
2117
+ tokens.push({
2118
+ kind: "dot",
2119
+ text: "."
2120
+ });
2121
+ index += 1;
2122
+ } else {
2123
+ if (char === "{") brace_depth += 1;
2124
+ else if (char === "}") brace_depth -= 1;
2125
+ tokens.push({
2126
+ kind: "other",
2127
+ text: char
2128
+ });
2129
+ index += 1;
2130
+ }
2131
+ }
2132
+ return tokens;
2133
+ }
2134
+ /**
2135
+ * Detect exact platform property paths (`import.meta.env.platform.web` and
2136
+ * the `ios` and `android` twins) without matching comments or string
2137
+ * literals, and without TypeScript's scanner so the native path needs no
2138
+ * TypeScript.
2139
+ *
2140
+ * @param {string} source
2141
+ * @param {unknown} [_typescript] Accepted for older callers; unused.
2142
+ * @returns {boolean}
2143
+ */
2144
+ function source_uses_platform_flag(source, _typescript) {
2145
+ const tokens = tokenize_member_chains(source);
2146
+ const prefix = [
2147
+ "import",
2148
+ ".",
2149
+ "meta",
2150
+ ".",
2151
+ "env",
2152
+ ".",
2153
+ "platform",
2154
+ "."
2155
+ ];
2156
+ for (let index = 0; index + prefix.length < tokens.length; index += 1) {
2157
+ if (index > 0 && (tokens[index - 1].kind === "dot" || tokens[index - 1].kind === "question-dot")) continue;
2158
+ if (!prefix.every((text, offset) => tokens[index + offset].text === text)) continue;
2159
+ const name = tokens[index + prefix.length].text;
2160
+ if (name === "web" || name === "ios" || name === "android") return true;
2161
+ }
2162
+ return false;
2163
+ }
2164
+ /** @type {Map<string, string | null>} */
2165
+ const path2TsrxCompilerPathMap = /* @__PURE__ */ new Map();
2166
+ /** @type {Map<string, { name: string | null, dependencies: Set<string> } | null>} */
2167
+ const pathToPackageManifestCache = /* @__PURE__ */ new Map();
2168
+ /**
2169
+ * @param {string} start_dir
2170
+ * @param {(file_path: import('fs').PathLike) => boolean} [exists_sync]
2171
+ * @returns {{ name: string | null, dependencies: Set<string> } | null}
2172
+ */
2173
+ function get_nearest_package_manifest(start_dir, exists_sync = fs$1.existsSync) {
2174
+ let current_dir = start_dir;
2175
+ /** @type {string[]} */
2176
+ const visited_dirs = [];
2177
+ while (current_dir) {
2178
+ if (pathToPackageManifestCache.has(current_dir)) {
2179
+ const cached_manifest = pathToPackageManifestCache.get(current_dir) ?? null;
2180
+ for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, cached_manifest);
2181
+ return cached_manifest;
2182
+ }
2183
+ visited_dirs.push(current_dir);
2184
+ const package_json_path = path$1.join(current_dir, "package.json");
2185
+ if (exists_sync(package_json_path)) try {
2186
+ const package_json = JSON.parse(fs$1.readFileSync(package_json_path, "utf8"));
2187
+ const dependencies = /* @__PURE__ */ new Set([
2188
+ ...Object.keys(package_json.dependencies ?? {}),
2189
+ ...Object.keys(package_json.devDependencies ?? {}),
2190
+ ...Object.keys(package_json.peerDependencies ?? {}),
2191
+ ...Object.keys(package_json.optionalDependencies ?? {})
2192
+ ]);
2193
+ const package_manifest = {
2194
+ name: typeof package_json.name === "string" ? package_json.name : null,
2195
+ dependencies
2196
+ };
2197
+ for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, package_manifest);
2198
+ return package_manifest;
2199
+ } catch {
2200
+ for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, null);
2201
+ return null;
2202
+ }
2203
+ const parent_dir = path$1.dirname(current_dir);
2204
+ if (parent_dir === current_dir) break;
2205
+ current_dir = parent_dir;
2206
+ }
2207
+ for (const visited_dir of visited_dirs) pathToPackageManifestCache.set(visited_dir, null);
2208
+ return null;
2209
+ }
2210
+ /**
2211
+ * @param {{ name: string | null, dependencies: Set<string> } | null} package_manifest
2212
+ * @param {string} compiler_name
2213
+ * @param {string[]} package_hints
2214
+ * @returns {boolean}
2215
+ */
2216
+ function package_manifest_matches_compiler(package_manifest, compiler_name, package_hints) {
2217
+ if (!package_manifest) return false;
2218
+ if (package_manifest.name === compiler_name || package_hints.includes(package_manifest.name ?? "")) return true;
2219
+ if (package_manifest.dependencies.has(compiler_name)) return true;
2220
+ for (const package_hint of package_hints) if (package_manifest.dependencies.has(package_hint)) return true;
2221
+ return false;
2222
+ }
2223
+ /**
2224
+ * Load a resolved compiler entry and normalize its contract.
2225
+ * @param {string} compiler_path
2226
+ * @returns {TSRXCompilerModule}
2227
+ */
2228
+ function require_tsrx_compiler(compiler_path) {
2229
+ return normalize_tsrx_compiler_module(require$2(compiler_path));
2230
+ }
2231
+ /**
2232
+ * Normalize the compiler contract used by Octane and consumer-declared modules.
2233
+ * @param {TSRXCompilerModule & { compileToVolarMappings?: TSRXCompilerModule['compile_to_volar_mappings'] }} compiler_module
2234
+ * @returns {TSRXCompilerModule}
2235
+ */
2236
+ function normalize_tsrx_compiler_module(compiler_module) {
2237
+ if (typeof compiler_module?.compile_to_volar_mappings !== "function" && typeof compiler_module?.compileToVolarMappings === "function") return {
2238
+ ...compiler_module,
2239
+ compile_to_volar_mappings: compiler_module.compileToVolarMappings
2240
+ };
2241
+ return compiler_module;
2242
+ }
2243
+ /**
2244
+ * @param {string} normalized_file_name
2245
+ * @param {(file_path: import('fs').PathLike) => boolean} [exists_sync]
2246
+ * @param {Map<string, string | null>} [compiler_path_map]
2247
+ * @returns {string | undefined}
2248
+ */
2249
+ function find_workspace_compiler_entry_for_file(normalized_file_name, exists_sync = fs$1.existsSync, compiler_path_map = path2TsrxCompilerPathMap) {
2250
+ const parts = normalized_file_name.split("/");
2251
+ const ext = path$1.extname(normalized_file_name);
2252
+ for (let i = parts.length - 2; i >= 0; i--) {
2253
+ const dir = parts.slice(0, i + 1).join("/");
2254
+ const cache_key = dir + "\0" + ext;
2255
+ if (!compiler_path_map.has(cache_key)) {
2256
+ /** @type {Array<[string, string, string[]]>} */
2257
+ const available_candidates = [];
2258
+ for (const [compiler_name, compiler_dir_parts, supported_extensions, package_hints, entry_candidates = DEFAULT_COMPILER_ENTRY_CANDIDATES] of COMPILER_CANDIDATES) {
2259
+ if (!supported_extensions.includes(ext)) continue;
2260
+ for (const entry_parts of entry_candidates) {
2261
+ const full_path = [
2262
+ dir,
2263
+ ...compiler_dir_parts,
2264
+ ...entry_parts
2265
+ ].join("/");
2266
+ if (exists_sync(full_path)) {
2267
+ available_candidates.push([
2268
+ compiler_name,
2269
+ full_path,
2270
+ package_hints
2271
+ ]);
2272
+ break;
2273
+ }
2274
+ }
2275
+ }
2276
+ let found_path = null;
2277
+ if (available_candidates.length > 0) {
2278
+ const package_manifest = get_nearest_package_manifest(dir, exists_sync);
2279
+ found_path = available_candidates.find(([compiler_name, , package_hints]) => package_manifest_matches_compiler(package_manifest, compiler_name, package_hints))?.[1] ?? available_candidates[0][1];
2280
+ log("Found tsrx compiler at:", found_path, "for extension:", ext);
2281
+ }
2282
+ compiler_path_map.set(cache_key, found_path);
2283
+ }
2284
+ const compiler_path = compiler_path_map.get(cache_key);
2285
+ if (compiler_path) return compiler_path;
2286
+ }
2287
+ }
2288
+ /**
2289
+ * @param {string} normalized_file_name
2290
+ * @param {CompilerResolutionOptions} [options]
2291
+ * @returns {string | undefined}
2292
+ */
2293
+ function get_compiler_entry_for_file(normalized_file_name, options) {
2294
+ const ext = path$1.extname(normalized_file_name);
2295
+ const consumer_compiler_path = resolve_consumer_compiler_for_file(normalized_file_name, options);
2296
+ if (consumer_compiler_path !== void 0) return consumer_compiler_path ?? void 0;
2297
+ const package_manifest = get_nearest_package_manifest(path$1.dirname(normalized_file_name));
2298
+ const workspace_compiler_path = find_workspace_compiler_entry_for_file(normalized_file_name);
2299
+ if (workspace_compiler_path) return workspace_compiler_path;
2300
+ const warn_message = `No supported tsrx compiler found in workspace for ${normalized_file_name}.`;
2301
+ let current_dir = root_dirname;
2302
+ while (current_dir) {
2303
+ /** @type {Array<[string, string, string[]]>} */
2304
+ const available_candidates = [];
2305
+ for (const [compiler_name, compiler_dir_parts, supported_extensions, package_hints, entry_candidates = DEFAULT_COMPILER_ENTRY_CANDIDATES] of COMPILER_CANDIDATES) {
2306
+ if (!supported_extensions.includes(ext)) continue;
2307
+ const full_path = path$1.join(current_dir, ...compiler_dir_parts);
2308
+ for (const entry_parts of entry_candidates) {
2309
+ const entry_path = path$1.join(full_path, ...entry_parts);
2310
+ if (fs$1.existsSync(entry_path)) {
2311
+ available_candidates.push([
2312
+ compiler_name,
2313
+ entry_path,
2314
+ package_hints
2315
+ ]);
2316
+ break;
2317
+ }
2318
+ }
2319
+ }
2320
+ if (available_candidates.length > 0) {
2321
+ const entry_path = available_candidates.find(([compiler_name, , package_hints]) => package_manifest_matches_compiler(package_manifest, compiler_name, package_hints))?.[1] ?? available_candidates[0][1];
2322
+ logWarning(`${warn_message} Using packaged version at ${entry_path}`);
2323
+ return entry_path;
2324
+ }
2325
+ const parent_dir = path$1.dirname(current_dir);
2326
+ if (parent_dir === current_dir) break;
2327
+ current_dir = parent_dir;
2328
+ }
2329
+ }
2330
+ /**
2331
+ * Drop compiler-selection state. Loaded ESM compiler graphs cannot be evicted
2332
+ * safely in-process; language-server package watchers restart the process.
2333
+ */
2334
+ function invalidateCompilerResolutionCaches() {
2335
+ path2TsrxCompilerPathMap.clear();
2336
+ pathToPackageManifestCache.clear();
2337
+ reset_consumer_compiler_resolution_caches();
2338
+ loggedCompilationFailures.clear();
2339
+ }
2340
+
2341
+ //#endregion
2342
+ //#region ../tsrx/src/diagnostics.js
2343
+ /**
2344
+ * The source TSRX's errors are reported under, in capitals like TypeScript's
2345
+ * own `TS2322`: `@tsrx/content-mapper` declares it to TypeScript 7, which shows
2346
+ * its errors as `TSRX2002`, and the TSRX language server reports its compile
2347
+ * errors with it.
2348
+ */
2349
+ const DIAGNOSTIC_SOURCE = "TSRX";
2350
+ /** See {@link TYPESCRIPT_CODE_PREFIX}. */
2351
+ const MAPPER_CODE_PREFIX = "77";
2352
+ /** @param {number} number */
2353
+ /* @__NO_SIDE_EFFECTS__ */
2354
+ function mapper_code(number) {
2355
+ return Number(`${"77"}${number}`);
2356
+ }
2357
+ /** The errors `@tsrx/content-mapper` reports itself. */
2358
+ const MAPPER_CODES = {
2359
+ /** A file that doesn't compile, with an error that has no code. */
2360
+ COMPILE_ERROR: /* @__PURE__ */ mapper_code(1e3),
2361
+ /** An error without a TSRX or TypeScript code. */
2362
+ USAGE_ERROR: /* @__PURE__ */ mapper_code(1001),
2363
+ /** No TSRX compiler found for a file. */
2364
+ NO_COMPILER: /* @__PURE__ */ mapper_code(1002),
2365
+ /** The project's TSRX configuration is invalid. */
2366
+ INVALID_CONFIG: /* @__PURE__ */ mapper_code(1003)
2367
+ };
2368
+
2369
+ //#endregion
2370
+ //#region src/diagnostic-directives.js
2371
+ /** @import * as AST from 'estree' */
2372
+ /** @import {CodeMapping, CompileError} from '@tsrx/core/types' */
2373
+ /** @import {DiagnosticDirectives} from './protocol.js' */
2374
+ /**
2375
+ * The nodes whose generated code an error's directive covers: the innermost
2376
+ * statement, declaration, class or type member, or element that holds the
2377
+ * error.
2378
+ */
2379
+ const HOLDER_TYPE = /(?:Statement|Declaration|Definition|Signature)$|^(?:StaticBlock|AccessorProperty|JSXElement|JSXFragment|JSXStyleElement)$/;
2380
+ /** Keys of a tree node that hold no child nodes, or nodes that aren't its children. */
2381
+ const NOT_CHILDREN = /* @__PURE__ */ new Set([
2382
+ "metadata",
2383
+ "loc",
2384
+ "range",
2385
+ "parent",
2386
+ "comments",
2387
+ "leadingComments",
2388
+ "trailingComments"
2389
+ ]);
2390
+ /**
2391
+ * An `ignore` directive for each error the mapper reports, so that a mistake
2392
+ * shows once. TypeScript reports some mistakes itself from the generated code,
2393
+ * with a code of its own, and would show them next to the mapper's error. The
2394
+ * directive hides TypeScript's errors in the generated code of the statement,
2395
+ * class or type member, or element that holds the error, until the error is
2396
+ * fixed and the mapper stops sending it. The mapper's own errors are not
2397
+ * TypeScript's, so they stay.
2398
+ *
2399
+ * The ranges come from what every TSRX compiler returns, whatever its target:
2400
+ * the source tree (`sourceAst`) finds the node that holds an error, and the
2401
+ * mappings give that node's generated code. Without a source tree the error's
2402
+ * own span stands in. A node without mappings gets no directive.
2403
+ * @param {readonly CompileError[]} errors
2404
+ * @param {AST.Program | null} source_ast
2405
+ * @param {readonly CodeMapping[]} mappings
2406
+ * @param {number} original_length
2407
+ * @param {number} generated_length
2408
+ * @returns {DiagnosticDirectives | null}
2409
+ */
2410
+ function ignore_directives(errors, source_ast, mappings, original_length, generated_length) {
2411
+ /** @type {Array<[original_start: number, original_end: number, generated_start: number, generated_end: number]>} */
2412
+ const ranges = [];
2413
+ for (const error of errors) {
2414
+ if (typeof error.pos !== "number") continue;
2415
+ const holder = source_ast ? holder_at(source_ast, error.pos) : null;
2416
+ const start = holder ? holder.start : error.pos;
2417
+ const end = holder ? holder.end : typeof error.end === "number" && error.end > error.pos ? error.end : error.pos + 1;
2418
+ for (const generated of generated_ranges(mappings, start, end)) ranges.push([
2419
+ Math.min(start, original_length),
2420
+ Math.min(end, original_length),
2421
+ Math.min(generated[0], generated_length),
2422
+ Math.min(generated[1], generated_length)
2423
+ ]);
2424
+ }
2425
+ if (ranges.length === 0) return null;
2426
+ ranges.sort((a, b) => a[2] - b[2]);
2427
+ /** @type {typeof ranges} */
2428
+ const merged = [];
2429
+ for (const range of ranges) {
2430
+ const last = merged.at(-1);
2431
+ if (last && range[2] < last[3]) {
2432
+ last[0] = Math.min(last[0], range[0]);
2433
+ last[1] = Math.max(last[1], range[1]);
2434
+ last[3] = Math.max(last[3], range[3]);
2435
+ } else merged.push([...range]);
2436
+ }
2437
+ return {
2438
+ unusedExpectDirectiveDiagnostics: [],
2439
+ directives: merged.map(([original_start, original_end, generated_start, generated_end]) => [
2440
+ original_start,
2441
+ original_end - original_start,
2442
+ generated_start,
2443
+ generated_end,
2444
+ DiagnosticDirectivePolicy.Ignore
2445
+ ])
2446
+ };
2447
+ }
2448
+ /**
2449
+ * The innermost holder node (see {@link HOLDER_TYPE}) that contains `position`,
2450
+ * found by descending from the root through the child that contains it.
2451
+ * @param {AST.Node} root
2452
+ * @param {number} position
2453
+ * @returns {AST.Node | null}
2454
+ */
2455
+ function holder_at(root, position) {
2456
+ /** @type {AST.Node | null} */
2457
+ let holder = null;
2458
+ /** @type {AST.Node | null} */
2459
+ let node = root;
2460
+ while (node) {
2461
+ if (HOLDER_TYPE.test(node.type)) holder = node;
2462
+ node = child_at(node, position);
2463
+ }
2464
+ return holder;
2465
+ }
2466
+ /**
2467
+ * @param {AST.Node} node
2468
+ * @param {number} position
2469
+ * @returns {AST.Node | null}
2470
+ */
2471
+ function child_at(node, position) {
2472
+ for (const [key, value] of Object.entries(node)) {
2473
+ if (NOT_CHILDREN.has(key) || !value || typeof value !== "object") continue;
2474
+ for (const child of Array.isArray(value) ? value : [value]) if (child && typeof child.type === "string" && typeof child.start === "number" && typeof child.end === "number" && child.start <= position && position < child.end) return child;
2475
+ }
2476
+ return null;
2477
+ }
2478
+ /**
2479
+ * The generated ranges of the mapped code between `start` and `end` in the
2480
+ * original. A node's generated code need not be in one piece: a compiler can
2481
+ * hoist part of it (a static element above the component), and a `<script>`
2482
+ * body is checked as a block at the end of the file. So each range runs from
2483
+ * the first to the last generated offset of the node's segments until code
2484
+ * mapped from outside the node follows, and the next of its segments starts a
2485
+ * new range; a range never covers another component's code. A segment of the
2486
+ * same length on both sides that encloses the original range, as a verbatim
2487
+ * `<script>` body does, gives the matching part of its generated text.
2488
+ * @param {readonly CodeMapping[]} mappings
2489
+ * @param {number} start
2490
+ * @param {number} end
2491
+ * @returns {Array<[number, number]>}
2492
+ */
2493
+ function generated_ranges(mappings, start, end) {
2494
+ /** @type {Array<[generated_start: number, generated_end: number, inside: boolean]>} */
2495
+ const segments = [];
2496
+ for (const mapping of mappings) for (let i = 0; i < mapping.sourceOffsets.length; i++) {
2497
+ const source = mapping.sourceOffsets[i];
2498
+ const length = mapping.lengths[i];
2499
+ const generated = mapping.generatedOffsets[i];
2500
+ const generated_length = mapping.generatedLengths?.[i] ?? length;
2501
+ if (source >= start && source + length <= end) segments.push([
2502
+ generated,
2503
+ generated + generated_length,
2504
+ true
2505
+ ]);
2506
+ else if (source <= start && end <= source + length && generated_length === length) segments.push([
2507
+ generated + start - source,
2508
+ generated + end - source,
2509
+ true
2510
+ ]);
2511
+ else segments.push([
2512
+ generated,
2513
+ generated + generated_length,
2514
+ false
2515
+ ]);
2516
+ }
2517
+ segments.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
2518
+ /** @type {Array<[number, number]>} */
2519
+ const ranges = [];
2520
+ /** @type {[number, number] | null} */
2521
+ let range = null;
2522
+ for (const [segment_start, segment_end, inside] of segments) if (inside) {
2523
+ if (range) range[1] = Math.max(range[1], segment_end);
2524
+ else range = [segment_start, segment_end];
2525
+ } else if (range && segment_start >= range[1]) {
2526
+ if (range[1] > range[0]) ranges.push(range);
2527
+ range = null;
2528
+ }
2529
+ if (range && range[1] > range[0]) ranges.push(range);
2530
+ return ranges;
2531
+ }
2532
+
2533
+ //#endregion
2534
+ //#region src/export-stub.js
2535
+ /** @import * as AST from 'estree' */
2536
+ /**
2537
+ * Build a TypeScript stub that preserves a module's export surface while the
2538
+ * file cannot be compiled.
2539
+ *
2540
+ * Raw TSRX, or the last good TSX (which may carry type errors of its own),
2541
+ * would give the checker noise to report. Instead every
2542
+ * export from the last successful transform's source AST is re-declared as
2543
+ * `any` (both as a value and as a type, so `new X()`, `X.y` and `let v: X` all
2544
+ * keep resolving), re-exports from other modules are kept as written (including
2545
+ * their `type` modifiers, so `isolatedModules` and `verbatimModuleSyntax` do
2546
+ * not reject the stub), and the compile error is reported through the mapper's
2547
+ * own diagnostics. Importers keep resolving; the author sees one error at the
2548
+ * right place.
2549
+ * @param {AST.Program | null | undefined} program The last successfully parsed source AST, if any.
2550
+ * @returns {string}
2551
+ */
2552
+ function build_export_stub(program) {
2553
+ /** @type {string[]} */
2554
+ const lines = [];
2555
+ /** @type {Set<string>} */
2556
+ const names = /* @__PURE__ */ new Set();
2557
+ let has_default = false;
2558
+ for (const statement of program?.body ?? []) switch (statement.type) {
2559
+ case "ExportAllDeclaration": {
2560
+ const exported = statement.exported ? ` as ${print_name(statement.exported)}` : "";
2561
+ lines.push(`export ${type_modifier(statement)}*${exported} from ${JSON.stringify(String(statement.source.value))};`);
2562
+ break;
2563
+ }
2564
+ case "ExportDefaultDeclaration":
2565
+ has_default = true;
2566
+ break;
2567
+ case "ExportNamedDeclaration":
2568
+ if (statement.source) {
2569
+ const statement_is_type = type_modifier(statement) !== "";
2570
+ const specifiers = statement.specifiers.map((specifier) => {
2571
+ const local = print_name(specifier.local);
2572
+ const exported = print_name(specifier.exported);
2573
+ return `${statement_is_type ? "" : type_modifier(specifier)}${local === exported ? local : `${local} as ${exported}`}`;
2574
+ });
2575
+ lines.push(`export ${type_modifier(statement)}{ ${specifiers.join(", ")} } from ${JSON.stringify(String(statement.source.value))};`);
2576
+ break;
2577
+ }
2578
+ for (const specifier of statement.specifiers) {
2579
+ const exported = export_name(specifier.exported);
2580
+ if (exported === "default") has_default = true;
2581
+ else names.add(exported);
2582
+ }
2583
+ if (statement.declaration) for (const name of declaration_names(statement.declaration)) names.add(name);
2584
+ }
2585
+ let next_local = 0;
2586
+ for (const name of names) {
2587
+ if (identifier_pattern$1.test(name) && !UNDECLARABLE_NAMES.has(name)) {
2588
+ lines.push(`export declare const ${name}: any;`);
2589
+ lines.push(`export type ${name} = any;`);
2590
+ continue;
2591
+ }
2592
+ let local = `_$_export_${next_local++}`;
2593
+ while (names.has(local)) local = `_$_export_${next_local++}`;
2594
+ lines.push(`declare const ${local}: any;`);
2595
+ lines.push(`type ${local} = any;`);
2596
+ lines.push(`export { ${local} as ${module_export_name(name)} };`);
2597
+ }
2598
+ if (has_default) {
2599
+ lines.push("declare const _default: any;");
2600
+ lines.push("export default _default;");
2601
+ }
2602
+ if (lines.length === 0) lines.push("export {};");
2603
+ return lines.join("\n") + "\n";
2604
+ }
2605
+ /**
2606
+ * `type ` for a type-only export statement or specifier (the ESTree-TS
2607
+ * `exportKind` field), else the empty string.
2608
+ * @param {AST.Node} node
2609
+ * @returns {'type ' | ''}
2610
+ */
2611
+ function type_modifier(node) {
2612
+ return node.exportKind === "type" ? "type " : "";
2613
+ }
2614
+ const identifier_pattern$1 = /^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u;
2615
+ /**
2616
+ * Identifier names that `export declare const x: any; export type x = any;`
2617
+ * can't declare in a module: reserved words (TS1389), words reserved in strict
2618
+ * mode (TS1214), `await`, `let`, `arguments` and `eval`, the names of
2619
+ * TypeScript's own types (TS2457), and `as`, which `export type as` misreads.
2620
+ */
2621
+ const UNDECLARABLE_NAMES = /* @__PURE__ */ new Set([
2622
+ "break",
2623
+ "case",
2624
+ "catch",
2625
+ "class",
2626
+ "const",
2627
+ "continue",
2628
+ "debugger",
2629
+ "default",
2630
+ "delete",
2631
+ "do",
2632
+ "else",
2633
+ "enum",
2634
+ "export",
2635
+ "extends",
2636
+ "false",
2637
+ "finally",
2638
+ "for",
2639
+ "function",
2640
+ "if",
2641
+ "import",
2642
+ "in",
2643
+ "instanceof",
2644
+ "new",
2645
+ "null",
2646
+ "return",
2647
+ "super",
2648
+ "switch",
2649
+ "this",
2650
+ "throw",
2651
+ "true",
2652
+ "try",
2653
+ "typeof",
2654
+ "var",
2655
+ "void",
2656
+ "while",
2657
+ "with",
2658
+ "implements",
2659
+ "interface",
2660
+ "package",
2661
+ "private",
2662
+ "protected",
2663
+ "public",
2664
+ "static",
2665
+ "yield",
2666
+ "await",
2667
+ "let",
2668
+ "arguments",
2669
+ "eval",
2670
+ "any",
2671
+ "bigint",
2672
+ "boolean",
2673
+ "never",
2674
+ "number",
2675
+ "object",
2676
+ "string",
2677
+ "symbol",
2678
+ "undefined",
2679
+ "unknown",
2680
+ "as"
2681
+ ]);
2682
+ /**
2683
+ * The name an export binds, as a plain string: `a` for `export { a }` and
2684
+ * `foo-bar` for `export { "foo-bar" as a } from`.
2685
+ * @param {AST.Identifier | AST.Literal | AST.Expression} node
2686
+ * @returns {string}
2687
+ */
2688
+ function export_name(node) {
2689
+ if (node.type === "Identifier") return node.name;
2690
+ if (node.type === "Literal") return String(node.value);
2691
+ return "";
2692
+ }
2693
+ /**
2694
+ * The name as it must be written back in a re-export: an identifier as is, an
2695
+ * arbitrary module namespace name (`export { "foo-bar" as a } from`,
2696
+ * `export * as "ns-name" from`) quoted, so the stub stays valid TypeScript.
2697
+ * @param {AST.Identifier | AST.Literal | AST.Expression} node
2698
+ * @returns {string}
2699
+ */
2700
+ function print_name(node) {
2701
+ return module_export_name(export_name(node));
2702
+ }
2703
+ /**
2704
+ * A name as an export specifier takes it: any identifier name, reserved words
2705
+ * too, as is, and anything else quoted.
2706
+ * @param {string} name
2707
+ * @returns {string}
2708
+ */
2709
+ function module_export_name(name) {
2710
+ return identifier_pattern$1.test(name) ? name : JSON.stringify(name);
2711
+ }
2712
+ /**
2713
+ * @param {AST.Declaration | AST.Node} declaration
2714
+ * @returns {string[]}
2715
+ */
2716
+ function declaration_names(declaration) {
2717
+ switch (declaration.type) {
2718
+ case "VariableDeclaration": return declaration.declarations.flatMap((declarator) => pattern_names(declarator.id));
2719
+ case "FunctionDeclaration":
2720
+ case "ClassDeclaration": return declaration.id ? [declaration.id.name] : [];
2721
+ default: {
2722
+ const id = declaration.id;
2723
+ return id && id.type === "Identifier" ? [id.name] : [];
2724
+ }
2725
+ }
2726
+ }
2727
+ /**
2728
+ * @param {AST.Pattern} pattern
2729
+ * @returns {string[]}
2730
+ */
2731
+ function pattern_names(pattern) {
2732
+ switch (pattern.type) {
2733
+ case "Identifier": return [pattern.name];
2734
+ case "ObjectPattern": return pattern.properties.flatMap((property) => property.type === "RestElement" ? pattern_names(property.argument) : pattern_names(property.value));
2735
+ case "ArrayPattern": return pattern.elements.flatMap((element) => element ? pattern_names(element) : []);
2736
+ case "RestElement": return pattern_names(pattern.argument);
2737
+ case "AssignmentPattern": return pattern_names(pattern.left);
2738
+ default: return [];
2739
+ }
2740
+ }
2741
+
2742
+ //#endregion
2743
+ //#region src/span-mappings.js
2744
+ /** @import {CodeMapping} from '@tsrx/core/types' */
2745
+ /** @import {SpanMapping} from './protocol.js' */
2746
+ const semantic_features = SpanMapFeature.Hover | SpanMapFeature.SignatureHelp | SpanMapFeature.InlayHints | SpanMapFeature.SemanticTokens;
2747
+ const completion_features = SpanMapFeature.Completion | SpanMapFeature.AutoInsert;
2748
+ const navigation_features = SpanMapFeature.Definition | SpanMapFeature.TypeDefinition | SpanMapFeature.Implementation | SpanMapFeature.References | SpanMapFeature.DocumentHighlights | SpanMapFeature.Rename | SpanMapFeature.CallHierarchy | SpanMapFeature.CodeActions | SpanMapFeature.LinkedEditing;
2749
+ const structure_features = SpanMapFeature.FoldingRanges | SpanMapFeature.SelectionRanges | SpanMapFeature.DocumentSymbols | SpanMapFeature.CodeLens;
2750
+ const identifier_pattern = /^[\p{ID_Start}_$][\p{ID_Continue}$‌‍]*$/u;
2751
+ /**
2752
+ * @typedef {object} Candidate
2753
+ * @property {number} generatedStart
2754
+ * @property {number} generatedEnd
2755
+ * @property {number} originalStart
2756
+ * @property {number} originalEnd
2757
+ * @property {0 | 1 | 2} kind
2758
+ * @property {number} features
2759
+ */
2760
+ /**
2761
+ * Translate a Volar `CodeMapping['data']` into content-mapper feature bits.
2762
+ *
2763
+ * `verification` has no bit: diagnostics always apply. Spans that carry CSS
2764
+ * class hover/definition metadata (`customData.hover` / `customData.definition`)
2765
+ * leave Hover and Definition off so the TSRX language server owns those
2766
+ * features. `semantic.shouldHighlight()` returning `false` (string-literal
2767
+ * spans) drops SemanticTokens.
2768
+ * @param {CodeMapping['data'] | undefined} data
2769
+ * @returns {number}
2770
+ */
2771
+ function features_from_mapping_data(data) {
2772
+ if (!data || typeof data !== "object") return SpanMapFeature.None;
2773
+ let features = SpanMapFeature.None;
2774
+ if (data.semantic) {
2775
+ features |= semantic_features;
2776
+ if (typeof data.semantic === "object" && data.semantic.shouldHighlight?.() === false) features &= ~SpanMapFeature.SemanticTokens;
2777
+ }
2778
+ if (data.completion) features |= completion_features;
2779
+ if (data.navigation) {
2780
+ features |= navigation_features;
2781
+ if (typeof data.navigation === "object") {
2782
+ if (data.navigation.shouldHighlight?.() === false) features &= ~SpanMapFeature.DocumentHighlights;
2783
+ if (data.navigation.shouldRename?.() === false) features &= ~SpanMapFeature.Rename;
2784
+ }
2785
+ }
2786
+ if (data.structure) features |= structure_features;
2787
+ if (data.format) features |= SpanMapFeature.Formatting;
2788
+ const custom = data.customData;
2789
+ if (custom && (custom.hover !== void 0 || custom.definition !== void 0)) features &= ~(SpanMapFeature.Hover | SpanMapFeature.Definition);
2790
+ return features;
2791
+ }
2792
+ /**
2793
+ * Convert the type-only transform's Volar mappings into a content-mapper span
2794
+ * map: an ordered, disjoint (in generated space) list of
2795
+ * `[generatedStart, generatedLength, originalStart, originalLength, kind, features]`.
2796
+ *
2797
+ * - Equal length and identical text → `Verbatim` (the only edit-safe kind).
2798
+ * - An identifier whose generated spelling differs (obfuscated `_$_` names,
2799
+ * renamed or capitalized identifiers) → `Alias`, so diagnostics that cover
2800
+ * the span exactly show the authored name.
2801
+ * - Anything else → `Atom`.
2802
+ *
2803
+ * The transform emits container spans (statements, control-flow bodies) that
2804
+ * enclose token spans. TypeScript requires generated spans to be disjoint, so
2805
+ * candidates are ranked Verbatim first, then shorter before longer, and a
2806
+ * candidate that overlaps an already selected span in generated space is
2807
+ * dropped. Overlap in original space is allowed by the protocol (one source
2808
+ * range may be projected several times) and is kept.
2809
+ *
2810
+ * Neighbouring Verbatim spans with equal feature bits whose gap is the same
2811
+ * text in both files are then coalesced into one span (see
2812
+ * {@link coalesce_verbatim_spans}), so a statement such as
2813
+ * `import { a } from './x';` is one edit-safe span rather than four tokens
2814
+ * with unmapped punctuation between them. TypeScript only applies text edits
2815
+ * (auto-import, rename, code actions) that fit inside a single Verbatim span.
2816
+ * @param {readonly CodeMapping[]} mappings
2817
+ * @param {string} generated_text
2818
+ * @param {string} original_text
2819
+ * @param {{ languageFeatures?: boolean }} [options] `languageFeatures: false` clears every feature bit (CLI-only projects).
2820
+ * @returns {SpanMapping[]}
2821
+ */
2822
+ function to_span_mappings(mappings, generated_text, original_text, options = {}) {
2823
+ const language_features = options.languageFeatures !== false;
2824
+ /** @type {Candidate[]} */
2825
+ const candidates = [];
2826
+ for (const mapping of mappings) {
2827
+ const count = Math.min(mapping.sourceOffsets.length, mapping.generatedOffsets.length);
2828
+ for (let index = 0; index < count; index++) {
2829
+ const original_start = mapping.sourceOffsets[index];
2830
+ const generated_start = mapping.generatedOffsets[index];
2831
+ const original_length = mapping.lengths[index] ?? mapping.lengths[0];
2832
+ const generated_length = mapping.generatedLengths?.[index] ?? mapping.generatedLengths?.[0] ?? original_length;
2833
+ if (!Number.isInteger(original_start) || !Number.isInteger(generated_start) || !Number.isInteger(original_length) || !Number.isInteger(generated_length) || original_start < 0 || generated_start < 0 || original_length <= 0 || generated_length <= 0) continue;
2834
+ const generated_end = generated_start + generated_length;
2835
+ const original_end = original_start + original_length;
2836
+ if (generated_end > generated_text.length || original_end > original_text.length) continue;
2837
+ const generated_slice = generated_text.slice(generated_start, generated_end);
2838
+ const original_slice = original_text.slice(original_start, original_end);
2839
+ /** @type {0 | 1 | 2} */
2840
+ let kind;
2841
+ if (generated_length === original_length && generated_slice === original_slice) kind = SpanMapKind.Verbatim;
2842
+ else if (is_whole_identifier(generated_text, generated_start, generated_end) && is_whole_token(original_text, original_start, original_end)) kind = SpanMapKind.Alias;
2843
+ else if (is_partial_identifier(original_text, original_start, original_end)) continue;
2844
+ else kind = SpanMapKind.Atom;
2845
+ candidates.push({
2846
+ generatedStart: generated_start,
2847
+ generatedEnd: generated_end,
2848
+ originalStart: original_start,
2849
+ originalEnd: original_end,
2850
+ kind,
2851
+ features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None
2852
+ });
2853
+ }
2854
+ }
2855
+ candidates.sort((left, right) => Number(left.kind !== SpanMapKind.Verbatim) - Number(right.kind !== SpanMapKind.Verbatim) || left.generatedEnd - left.generatedStart - (right.generatedEnd - right.generatedStart) || left.generatedStart - right.generatedStart || left.originalStart - right.originalStart);
2856
+ /** @type {Candidate[]} */
2857
+ const selected = [];
2858
+ const occupied = new IntervalSet();
2859
+ for (const candidate of candidates) {
2860
+ if (!occupied.add(candidate.generatedStart, candidate.generatedEnd)) continue;
2861
+ selected.push(candidate);
2862
+ }
2863
+ selected.sort((left, right) => left.generatedStart - right.generatedStart);
2864
+ return extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text).map((candidate) => [
2865
+ candidate.generatedStart,
2866
+ candidate.generatedEnd - candidate.generatedStart,
2867
+ candidate.originalStart,
2868
+ candidate.originalEnd - candidate.originalStart,
2869
+ candidate.kind,
2870
+ candidate.features
2871
+ ]);
2872
+ }
2873
+ /**
2874
+ * Merge runs of Verbatim spans, sorted by generated start, when the two spans
2875
+ * carry the same feature bits and the text between them is identical (and of
2876
+ * equal length) in the generated and the original file. The merged span is
2877
+ * Verbatim by construction: every position inside it maps with the same
2878
+ * offset and the same text.
2879
+ * @param {Candidate[]} spans
2880
+ * @param {string} generated_text
2881
+ * @param {string} original_text
2882
+ * @returns {Candidate[]}
2883
+ */
2884
+ function coalesce_verbatim_spans(spans, generated_text, original_text) {
2885
+ /** @type {Candidate[]} */
2886
+ const merged = [];
2887
+ for (const span of spans) {
2888
+ const previous = merged[merged.length - 1];
2889
+ if (previous && previous.kind === SpanMapKind.Verbatim && span.kind === SpanMapKind.Verbatim && previous.features === span.features && span.originalStart >= previous.originalEnd && span.generatedStart - previous.generatedEnd === span.originalStart - previous.originalEnd && generated_text.slice(previous.generatedEnd, span.generatedStart) === original_text.slice(previous.originalEnd, span.originalStart)) {
2890
+ previous.generatedEnd = span.generatedEnd;
2891
+ previous.originalEnd = span.originalEnd;
2892
+ continue;
2893
+ }
2894
+ merged.push({ ...span });
2895
+ }
2896
+ return merged;
2897
+ }
2898
+ /**
2899
+ * Extend every Verbatim span forward over whitespace that is identical in the
2900
+ * generated and the original file, up to the next span in either file.
2901
+ *
2902
+ * TypeScript's edits routinely end at the start of the line after a statement
2903
+ * (an organize-imports edit for the import block ends after the last import's
2904
+ * newline), and TypeScript 7 discards a whole edit when any of its ranges does
2905
+ * not map. A span that stops at a statement's last character therefore made
2906
+ * "Organize Imports" a no-op on `.tsrx` files; covering the newline that follows
2907
+ * fixes that at no cost, since identical whitespace maps verbatim.
2908
+ * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
2909
+ * @param {string} generated_text
2910
+ * @param {string} original_text
2911
+ * @returns {Candidate[]}
2912
+ */
2913
+ function extend_verbatim_spans_over_whitespace(spans, generated_text, original_text) {
2914
+ for (let index = 0; index < spans.length; index++) {
2915
+ const span = spans[index];
2916
+ if (span.kind !== SpanMapKind.Verbatim) continue;
2917
+ const next = spans[index + 1];
2918
+ const generated_limit = next ? next.generatedStart : generated_text.length;
2919
+ const original_limit = next ? next.originalStart : original_text.length;
2920
+ while (span.generatedEnd < generated_limit && span.originalEnd < original_limit && generated_text[span.generatedEnd] === original_text[span.originalEnd] && /[ \t\r\n]/.test(generated_text[span.generatedEnd])) {
2921
+ span.generatedEnd++;
2922
+ span.originalEnd++;
2923
+ }
2924
+ }
2925
+ return spans;
2926
+ }
2927
+ const identifier_part = /[\p{ID_Continue}$\u200c\u200d]/u;
2928
+ const token_part = /[\p{ID_Continue}$#@\u200c\u200d]/u;
2929
+ /**
2930
+ * Whether `[start, end)` is a complete identifier in `text`: identifier
2931
+ * syntax inside and no identifier character touching either edge.
2932
+ * @param {string} text
2933
+ * @param {number} start
2934
+ * @param {number} end
2935
+ */
2936
+ function is_whole_identifier(text, start, end) {
2937
+ return identifier_pattern.test(text.slice(start, end)) && (start === 0 || !identifier_part.test(text[start - 1])) && (end === text.length || !identifier_part.test(text[end]));
2938
+ }
2939
+ /**
2940
+ * Whether `[start, end)` is a piece of a longer identifier in `text`:
2941
+ * identifier characters inside and an identifier character touching an edge.
2942
+ * @param {string} text
2943
+ * @param {number} start
2944
+ * @param {number} end
2945
+ */
2946
+ function is_partial_identifier(text, start, end) {
2947
+ const slice = text.slice(start, end);
2948
+ return slice.length > 0 && [...slice].every((character) => identifier_part.test(character)) && (start > 0 && identifier_part.test(text[start - 1]) || end < text.length && identifier_part.test(text[end]));
2949
+ }
2950
+ /**
2951
+ * Whether `[start, end)` is a complete authored token: no whitespace inside
2952
+ * and no token character (identifier characters plus the TSRX `#`/`@`
2953
+ * sigils) touching either edge.
2954
+ * @param {string} text
2955
+ * @param {number} start
2956
+ * @param {number} end
2957
+ */
2958
+ function is_whole_token(text, start, end) {
2959
+ const slice = text.slice(start, end);
2960
+ return slice.length > 0 && !/\s/.test(slice) && (start === 0 || !token_part.test(text[start - 1])) && (end === text.length || !token_part.test(text[end]));
2961
+ }
2962
+ /**
2963
+ * Sorted set of half-open intervals supporting an "add if disjoint" query.
2964
+ * Intervals are kept sorted by start in a plain array; a binary search finds
2965
+ * the neighbours to test, so adding is O(n) in the worst case, which is fine
2966
+ * for the few thousand spans a file produces.
2967
+ */
2968
+ var IntervalSet = class {
2969
+ /** @type {number[]} */
2970
+ #starts = [];
2971
+ /** @type {number[]} */
2972
+ #ends = [];
2973
+ /**
2974
+ * @param {number} start
2975
+ * @param {number} end
2976
+ * @returns {boolean} Whether the interval was added (it overlapped nothing).
2977
+ */
2978
+ add(start, end) {
2979
+ const starts = this.#starts;
2980
+ let low = 0;
2981
+ let high = starts.length;
2982
+ while (low < high) {
2983
+ const middle = low + high >>> 1;
2984
+ if (starts[middle] < start) low = middle + 1;
2985
+ else high = middle;
2986
+ }
2987
+ if (low < starts.length && starts[low] < end) return false;
2988
+ if (low > 0 && this.#ends[low - 1] > start) return false;
2989
+ starts.splice(low, 0, start);
2990
+ this.#ends.splice(low, 0, end);
2991
+ return true;
2992
+ }
2993
+ };
2994
+
2995
+ //#endregion
2996
+ //#region src/mapper.js
2997
+ /** @import * as AST from 'estree' */
2998
+ /** @import {CompileError} from '@tsrx/core/types' */
2999
+ /** @import {InitializeParams, InitializeResult, OpenProjectParams, OpenProjectResult, TransformParams, TransformResult, MapperDiagnostic} from './protocol.js' */
3000
+ const require$1 = createRequire(import.meta.url);
3001
+ const bare_package_specifier_pattern = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/;
3002
+ /**
3003
+ * The mapper entry's `options` object in tsconfig (`contentMappers[].options`)
3004
+ * or in an inferred-project contribution.
3005
+ * @typedef {object} MapperOptions
3006
+ * @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
3007
+ * @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
3008
+ * @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
3009
+ */
3010
+ /**
3011
+ * @typedef {object} ProjectState
3012
+ * @property {string | undefined} configFileName
3013
+ * @property {MapperOptions} options
3014
+ * @property {Set<string>} dependencies Files whose content affects transform output.
3015
+ * @property {Map<string, AST.Program>} lastGood Last successfully parsed source AST per file, for the compile-failure stub. Shared by every project state of a mapper (see {@link create_tsrx_content_mapper}).
3016
+ */
3017
+ /**
3018
+ * @typedef {object} ContentMapper
3019
+ * @property {(params: InitializeParams) => InitializeResult} initialize
3020
+ * @property {(params: OpenProjectParams) => OpenProjectResult} openProject
3021
+ * @property {(params: { projectHandle: string }) => void} closeProject
3022
+ * @property {(params: TransformParams) => TransformResult} transform
3023
+ */
3024
+ /**
3025
+ * Create the `.tsrx` content mapper. Each `projectHandle` owns its own state;
3026
+ * nothing is shared between projects except the process-wide compiler
3027
+ * resolution caches, which are keyed by directory and reset on every
3028
+ * `openProject`, and the last successfully parsed AST per file. The latter is
3029
+ * keyed by file name and independent of the project, and TypeScript reopens a
3030
+ * project (same or new handle) whenever its identity or a watched file
3031
+ * changes, so keeping it at the mapper level is what lets a file that still
3032
+ * fails to compile keep its export stub across a reopen.
3033
+ * The mapper needs no TypeScript of its own: tsconfig files are read and
3034
+ * compilers resolved through `@tsrx/typescript-plugin`'s own reader and
3035
+ * package walk, so the native compiler's `typescript` package (which has no
3036
+ * JavaScript API) can be the only TypeScript in a project.
3037
+ * @param {{ host?: import('@tsrx/typescript-plugin/src/config-host.js').ConfigHost }} [context]
3038
+ * @returns {ContentMapper}
3039
+ */
3040
+ function create_tsrx_content_mapper(context = {}) {
3041
+ const host = context.host ?? NODE_CONFIG_HOST;
3042
+ /** @type {Map<string, ProjectState>} */
3043
+ const projects = /* @__PURE__ */ new Map();
3044
+ /** @type {Map<string, AST.Program>} */
3045
+ const last_good = /* @__PURE__ */ new Map();
3046
+ /** Transforms that arrive without a project handle. */
3047
+ const standalone = create_project_state(void 0, {});
3048
+ /** @type {ContentMapper['initialize']} */
3049
+ function initialize(params) {
3050
+ if (!params.positionEncodings?.includes("utf-16")) throw new Error("@tsrx/content-mapper requires UTF-16 position encoding");
3051
+ return {
3052
+ positionEncoding: "utf-16",
3053
+ diagnosticSource: DIAGNOSTIC_SOURCE
3054
+ };
3055
+ }
3056
+ /** @type {ContentMapper['openProject']} */
3057
+ function openProject(params) {
3058
+ invalidateCompilerResolutionCaches();
3059
+ const { options, optionDiagnostics } = validate_options(params.options);
3060
+ const state = create_project_state(params.configFileName || void 0, options);
3061
+ projects.set(params.projectHandle, state);
3062
+ try {
3063
+ resolve_compiler(state, probe_file_name(state));
3064
+ } catch {}
3065
+ const watchedFiles = [...state.dependencies].sort();
3066
+ return {
3067
+ configIdentity: compute_identity(state, watchedFiles),
3068
+ watchedFiles,
3069
+ ...optionDiagnostics.length > 0 ? { optionDiagnostics } : null
3070
+ };
3071
+ }
3072
+ /** @type {ContentMapper['closeProject']} */
3073
+ function closeProject(params) {
3074
+ projects.delete(params.projectHandle);
3075
+ }
3076
+ /** @type {ContentMapper['transform']} */
3077
+ function transform(params) {
3078
+ const state = params.projectHandle ? projects.get(params.projectHandle) : standalone;
3079
+ if (!state) throw new Error(`Unknown @tsrx/content-mapper project handle: ${params.projectHandle}`);
3080
+ const file_name = params.fileName.replace(/\\/g, "/");
3081
+ const content = params.content;
3082
+ /** @type {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null} */
3083
+ let compiler;
3084
+ try {
3085
+ compiler = resolve_compiler(state, file_name);
3086
+ } catch (error) {
3087
+ return failure(state, file_name, content, {
3088
+ start: 0,
3089
+ length: 0,
3090
+ code: MAPPER_CODES.INVALID_CONFIG,
3091
+ messageText: error_message(error)
3092
+ });
3093
+ }
3094
+ if (!compiler) return failure(state, file_name, content, {
3095
+ start: 0,
3096
+ length: 0,
3097
+ code: MAPPER_CODES.NO_COMPILER,
3098
+ messageText: `No TSRX compiler found for ${file_name}. Install a target compiler (for example @tsrx/react) next to the project, or select one with "tsrx": { "compiler": "<package>" } in tsconfig.json or "options": { "compiler": "<package>" } on the content mapper entry.`
3099
+ });
3100
+ /** @type {'web' | 'ios' | 'android' | undefined} */
3101
+ let platform;
3102
+ try {
3103
+ platform = state.options.platform ?? resolve_consumer_platform_for_file(file_name, {
3104
+ configFileName: state.configFileName,
3105
+ configHost: host,
3106
+ dependencies: state.dependencies,
3107
+ requirePlatformResolution: source_uses_platform_flag(content)
3108
+ });
3109
+ } catch (error) {
3110
+ return failure(state, file_name, content, {
3111
+ start: 0,
3112
+ length: 0,
3113
+ code: MAPPER_CODES.INVALID_CONFIG,
3114
+ messageText: error_message(error)
3115
+ });
3116
+ }
3117
+ const result = transform_tsrx(compiler, file_name, content, { platform });
3118
+ if (result.fatalError) return failure(state, file_name, content, to_diagnostic(result.fatalError, content.length, MAPPER_CODES.COMPILE_ERROR));
3119
+ if (result.sourceAst) state.lastGood.set(file_name, result.sourceAst);
3120
+ const language_features = state.options.languageFeatures !== false;
3121
+ const mappings = to_span_mappings(result.mappings, result.text, content, { languageFeatures: language_features });
3122
+ const diagnostics = result.errors.map((error) => to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR));
3123
+ const diagnosticDirectives = ignore_directives(result.errors, result.sourceAst, result.mappings, content.length, result.text.length);
3124
+ return {
3125
+ text: result.text,
3126
+ extension: ".tsx",
3127
+ mappings,
3128
+ ...diagnostics.length > 0 ? { diagnostics } : null,
3129
+ ...diagnosticDirectives ? { diagnosticDirectives } : null
3130
+ };
3131
+ }
3132
+ /**
3133
+ * @param {string | undefined} config_file_name
3134
+ * @param {MapperOptions} options
3135
+ * @returns {ProjectState}
3136
+ */
3137
+ function create_project_state(config_file_name, options) {
3138
+ return {
3139
+ configFileName: config_file_name ? path.normalize(config_file_name) : void 0,
3140
+ options,
3141
+ dependencies: /* @__PURE__ */ new Set(),
3142
+ lastGood: last_good
3143
+ };
3144
+ }
3145
+ /**
3146
+ * A `.tsrx` path inside the project directory, used to drive compiler
3147
+ * resolution before any real file is transformed.
3148
+ * @param {ProjectState} state
3149
+ */
3150
+ function probe_file_name(state) {
3151
+ const dir = state.configFileName ? path.dirname(state.configFileName) : process.cwd();
3152
+ return path.join(dir, "__tsrx_content_mapper_probe__.tsrx").replace(/\\/g, "/");
3153
+ }
3154
+ /**
3155
+ * Precedence: the mapper entry's `options.compiler` wins over `tsrx.compiler`
3156
+ * in the tsconfig chain, which wins over auto-detection of an installed
3157
+ * target compiler. Whatever is found, its `package.json` joins the watched
3158
+ * files so a compiler upgrade invalidates the project.
3159
+ * @param {ProjectState} state
3160
+ * @param {string} file_name
3161
+ * @returns {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null}
3162
+ */
3163
+ function resolve_compiler(state, file_name) {
3164
+ /** @type {string | undefined} */
3165
+ let entry;
3166
+ if (state.options.compiler !== void 0) entry = resolve_declared_compiler(state, file_name, state.options.compiler);
3167
+ else entry = get_compiler_entry_for_file(file_name, {
3168
+ configFileName: state.configFileName,
3169
+ configHost: host,
3170
+ dependencies: state.dependencies
3171
+ });
3172
+ if (!entry) return null;
3173
+ const manifest = nearest_package_manifest(entry);
3174
+ if (manifest) state.dependencies.add(manifest);
3175
+ return require_tsrx_compiler(entry);
3176
+ }
3177
+ /**
3178
+ * @param {ProjectState} state
3179
+ * @param {string} file_name
3180
+ * @param {string} specifier
3181
+ * @returns {string}
3182
+ */
3183
+ function resolve_declared_compiler(state, file_name, specifier) {
3184
+ if (!bare_package_specifier_pattern.test(specifier)) throw new Error(`The content mapper option "compiler" must be a bare package specifier, got ${JSON.stringify(specifier)}.`);
3185
+ const anchor = state.configFileName ?? file_name;
3186
+ try {
3187
+ return createRequire(anchor).resolve(specifier);
3188
+ } catch {
3189
+ const resolved = resolve_package_entry(specifier, path.dirname(anchor), { host });
3190
+ if (!resolved) throw new Error(`Unable to resolve the TSRX compiler ${JSON.stringify(specifier)} declared in the content mapper options from ${anchor}.`);
3191
+ return resolved;
3192
+ }
3193
+ }
3194
+ /**
3195
+ * @param {ProjectState} state
3196
+ * @param {string[]} watched_files
3197
+ * @returns {string}
3198
+ */
3199
+ function compute_identity(state, watched_files) {
3200
+ const hash = createHash("sha256");
3201
+ hash.update(JSON.stringify(state.options));
3202
+ hash.update("\0");
3203
+ for (const file of watched_files) {
3204
+ hash.update(file);
3205
+ hash.update("\0");
3206
+ hash.update(host.readFile(file) ?? "");
3207
+ hash.update("\0");
3208
+ }
3209
+ return hash.digest("hex");
3210
+ }
3211
+ /**
3212
+ * @param {ProjectState} state
3213
+ * @param {string} file_name
3214
+ * @param {string} content
3215
+ * @param {MapperDiagnostic} diagnostic
3216
+ * @returns {TransformResult}
3217
+ */
3218
+ function failure(state, file_name, content, diagnostic) {
3219
+ return {
3220
+ text: build_export_stub(state.lastGood.get(file_name)),
3221
+ extension: ".ts",
3222
+ mappings: [],
3223
+ diagnostics: [clamp_diagnostic(diagnostic, content.length)]
3224
+ };
3225
+ }
3226
+ return {
3227
+ initialize,
3228
+ openProject,
3229
+ closeProject,
3230
+ transform
3231
+ };
3232
+ }
3233
+ /**
3234
+ * @param {unknown} raw
3235
+ * @returns {{ options: MapperOptions, optionDiagnostics: NonNullable<OpenProjectResult['optionDiagnostics']> }}
3236
+ */
3237
+ function validate_options(raw) {
3238
+ /** @type {MapperOptions} */
3239
+ const options = {};
3240
+ /** @type {NonNullable<OpenProjectResult['optionDiagnostics']>} */
3241
+ const optionDiagnostics = [];
3242
+ if (raw === void 0 || raw === null) return {
3243
+ options,
3244
+ optionDiagnostics
3245
+ };
3246
+ if (typeof raw !== "object" || Array.isArray(raw)) {
3247
+ optionDiagnostics.push({
3248
+ path: [],
3249
+ messageText: "Content mapper options must be an object.",
3250
+ code: MAPPER_CODES.INVALID_CONFIG
3251
+ });
3252
+ return {
3253
+ options,
3254
+ optionDiagnostics
3255
+ };
3256
+ }
3257
+ const record = raw;
3258
+ for (const key of Object.keys(record)) {
3259
+ const value = record[key];
3260
+ switch (key) {
3261
+ case "compiler":
3262
+ if (typeof value === "string" && bare_package_specifier_pattern.test(value.trim())) options.compiler = value.trim();
3263
+ else optionDiagnostics.push({
3264
+ path: [key],
3265
+ messageText: "\"compiler\" must be a bare package specifier such as \"@tsrx/react\".",
3266
+ code: MAPPER_CODES.INVALID_CONFIG
3267
+ });
3268
+ break;
3269
+ case "platform":
3270
+ if (value === "web" || value === "ios" || value === "android") options.platform = value;
3271
+ else optionDiagnostics.push({
3272
+ path: [key],
3273
+ messageText: "\"platform\" must be \"web\", \"ios\", or \"android\".",
3274
+ code: MAPPER_CODES.INVALID_CONFIG
3275
+ });
3276
+ break;
3277
+ case "languageFeatures":
3278
+ if (typeof value === "boolean") options.languageFeatures = value;
3279
+ else optionDiagnostics.push({
3280
+ path: [key],
3281
+ messageText: "\"languageFeatures\" must be a boolean.",
3282
+ code: MAPPER_CODES.INVALID_CONFIG
3283
+ });
3284
+ break;
3285
+ default: optionDiagnostics.push({
3286
+ path: [key],
3287
+ messageText: `Unknown content mapper option "${key}".`,
3288
+ code: MAPPER_CODES.INVALID_CONFIG
3289
+ });
3290
+ }
3291
+ }
3292
+ return {
3293
+ options,
3294
+ optionDiagnostics
3295
+ };
3296
+ }
3297
+ const TSRX_CODE = /^TSRX(\d+)$/;
3298
+ const TYPESCRIPT_CODE = /^TS(\d+)$/;
3299
+ /**
3300
+ * Translate a compiler `CompileError` into a mapper diagnostic in original
3301
+ * offsets. TypeScript shows the mapper's diagnostics as `TSRX<number>`, so a
3302
+ * TSRX code goes as its number (`TSRX2002` → `2002`) and a TypeScript code as
3303
+ * `TYPESCRIPT_CODE_PREFIX` then its number (`TS1005` → `111005`), which keeps
3304
+ * the code in the message too. An error without either uses `fallback_code`
3305
+ * and keeps any other code in the message.
3306
+ * @param {CompileError} error
3307
+ * @param {number} content_length
3308
+ * @param {number} fallback_code
3309
+ * @returns {MapperDiagnostic}
3310
+ */
3311
+ function to_diagnostic(error, content_length, fallback_code) {
3312
+ const start = typeof error.pos === "number" ? error.pos : 0;
3313
+ const end = typeof error.end === "number" && error.end > start ? error.end : start + 1;
3314
+ const code = typeof error.code === "string" ? error.code : "";
3315
+ const tsrx = TSRX_CODE.exec(code);
3316
+ const typescript = TYPESCRIPT_CODE.exec(code);
3317
+ const message = String(error.message ?? error);
3318
+ return clamp_diagnostic({
3319
+ start,
3320
+ length: end - start,
3321
+ code: tsrx ? Number(tsrx[1]) : typescript ? Number(`${"11"}${typescript[1]}`) : fallback_code,
3322
+ messageText: code && !tsrx ? `${message} [${code}]` : message
3323
+ }, content_length);
3324
+ }
3325
+ /**
3326
+ * @param {MapperDiagnostic} diagnostic
3327
+ * @param {number} content_length
3328
+ * @returns {MapperDiagnostic}
3329
+ */
3330
+ function clamp_diagnostic(diagnostic, content_length) {
3331
+ const start = Math.max(0, Math.min(diagnostic.start, content_length));
3332
+ const end = Math.max(start, Math.min(diagnostic.start + diagnostic.length, content_length));
3333
+ return {
3334
+ ...diagnostic,
3335
+ start,
3336
+ length: end - start
3337
+ };
3338
+ }
3339
+ /**
3340
+ * @param {unknown} error
3341
+ * @returns {string}
3342
+ */
3343
+ function error_message(error) {
3344
+ return error instanceof Error ? error.message : String(error);
3345
+ }
3346
+ /**
3347
+ * The `package.json` that owns a compiler entry file, stopping at a
3348
+ * `node_modules` boundary.
3349
+ * @param {string} entry
3350
+ * @returns {string | undefined}
3351
+ */
3352
+ function nearest_package_manifest(entry) {
3353
+ let dir = path.dirname(entry);
3354
+ while (dir) {
3355
+ const candidate = path.join(dir, "package.json");
3356
+ if (fs.existsSync(candidate)) return candidate;
3357
+ if (path.basename(dir) === "node_modules") return void 0;
3358
+ const parent = path.dirname(dir);
3359
+ if (parent === dir) return void 0;
3360
+ dir = parent;
3361
+ }
3362
+ }
3363
+
3364
+ //#endregion
3365
+ export { validate_options as i, require$1 as n, to_diagnostic as r, create_tsrx_content_mapper as t };
3366
+ //# sourceMappingURL=mapper-B4f--1ac.js.map