@tsrx/content-mapper 0.1.1 → 0.1.3

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.
@@ -1,4 +1,4 @@
1
- import { DIAGNOSTIC_CODE_COMPILE_ERROR, DIAGNOSTIC_CODE_INVALID_CONFIG, DIAGNOSTIC_CODE_NO_COMPILER, DIAGNOSTIC_CODE_USAGE_ERROR, DIAGNOSTIC_SOURCE, SpanMapFeature, SpanMapKind } from "./protocol.js";
1
+ import { DiagnosticDirectivePolicy, SpanMapFeature, SpanMapKind } from "./protocol.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash } from "node:crypto";
4
4
  import fs from "node:fs";
@@ -2338,6 +2338,370 @@ function invalidateCompilerResolutionCaches() {
2338
2338
  loggedCompilationFailures.clear();
2339
2339
  }
2340
2340
 
2341
+ //#endregion
2342
+ //#region ../tsrx/src/diagnostics.js
2343
+ /**
2344
+ * TSRX's own error codes, one per mistake only TSRX reports. The TSRX
2345
+ * specification lists each with its message and an example (its appendix,
2346
+ * "Error codes"). A mistake TypeScript also reports has TypeScript's code
2347
+ * instead (`TS1005`), from {@link TS_ERRORS}.
2348
+ *
2349
+ * - `TSRX1xxx`: markup syntax only TSRX has
2350
+ * - `TSRX2xxx`: template rules
2351
+ * - `TSRX3xxx`: `<style>` and CSS
2352
+ * - `TSRX4xxx`: everything else
2353
+ */
2354
+ const DIAGNOSTIC_CODES = {
2355
+ /** An element has no closing tag before the end of its template. */
2356
+ UNCLOSED_TAG: "TSRX1001",
2357
+ /** A closing tag doesn't match the element it closes. */
2358
+ MISMATCHED_CLOSING_TAG: "TSRX1002",
2359
+ /** A closing tag with no element open. */
2360
+ UNEXPECTED_CLOSING_TAG: "TSRX1003",
2361
+ /** A `<\/script` in a `<script>` body that isn't its closing tag, where HTML would end the script. */
2362
+ SCRIPT_END_TAG_IN_BODY: "TSRX1004",
2363
+ /** A namespaced element name (`<foo:bar>`). */
2364
+ NAMESPACED_ELEMENT: "TSRX1005",
2365
+ /** A spread as an attribute's value (`a={...b}`). */
2366
+ ATTRIBUTE_VALUE_SPREAD: "TSRX1006",
2367
+ /** A `;` at the end of an expression container (`{a;}`). */
2368
+ TEMPLATE_EXPRESSION_TRAILING_SEMICOLON: "TSRX1007",
2369
+ /** A directive without its `{ … }` body. */
2370
+ DIRECTIVE_BODY_EXPECTED: "TSRX1008",
2371
+ /** A directive's next branch written without its `@` (`else`, `empty`, `pending`, `catch`). */
2372
+ DIRECTIVE_BRANCH_EXPECTED: "TSRX1009",
2373
+ /** An `@try` with neither `@catch` nor `@pending`. */
2374
+ TRY_HANDLER_MISSING: "TSRX1010",
2375
+ /** An `@for`'s `index` or `key` clause is incomplete or out of order. */
2376
+ FOR_CLAUSE: "TSRX1011",
2377
+ /** A `return` in a template. */
2378
+ TEMPLATE_RETURN_STATEMENT: "TSRX2001",
2379
+ /** A `return` in an `@if` body. */
2380
+ IF_RETURN_STATEMENT: "TSRX2002",
2381
+ /** A `break` in an `@if` body. */
2382
+ IF_BREAK_STATEMENT: "TSRX2003",
2383
+ /** A `continue` in an `@if` body. */
2384
+ IF_CONTINUE_STATEMENT: "TSRX2004",
2385
+ /** A `return` in an `@for` body. */
2386
+ FOR_RETURN_STATEMENT: "TSRX2005",
2387
+ /** A `break` in an `@for` body. */
2388
+ FOR_BREAK_STATEMENT: "TSRX2006",
2389
+ /** A `continue` in an `@for` body. */
2390
+ FOR_CONTINUE_STATEMENT: "TSRX2007",
2391
+ /** A `break` in an `@case` body. */
2392
+ SWITCH_CASE_BREAK_STATEMENT: "TSRX2008",
2393
+ /** A `return` in an `@case` body. */
2394
+ SWITCH_CASE_RETURN_STATEMENT: "TSRX2009",
2395
+ /** Template output nothing renders: not returned, assigned, or part of the output. */
2396
+ FORGOTTEN_STATEMENT_CONTAINER: "TSRX2010",
2397
+ /** A `@{ … }` body with more than one output node. */
2398
+ CODE_BLOCK_SINGLE_OUTPUT: "TSRX2011",
2399
+ /** A statement after a `@{ … }` body's output. */
2400
+ CODE_BLOCK_STATEMENT_AFTER_OUTPUT: "TSRX2012",
2401
+ /** A JSX spread child (`{...items}`), which parses but no target supports. */
2402
+ JSX_SPREAD_CHILD: "TSRX2013",
2403
+ /** A dynamic tag expression (`<{expr}>`) other than an identifier, a member access, or a string literal. */
2404
+ DYNAMIC_TAG_EXPRESSION: "TSRX2014",
2405
+ /** An `@for` over something other than `for…of`. */
2406
+ FOR_OF_ONLY: "TSRX2015",
2407
+ /** An element with more than one `ref` attribute. */
2408
+ MULTIPLE_REFS: "TSRX2016",
2409
+ /** An element nested where HTML doesn't allow it (`<p>` in `<p>`). */
2410
+ INVALID_HTML_NESTING: "TSRX2017",
2411
+ /** A JavaScript `try…finally` in a template. */
2412
+ TEMPLATE_TRY_FINALLY: "TSRX2018",
2413
+ /** A `try` in a template with neither a `pending` nor a `catch` block. */
2414
+ TEMPLATE_TRY_HANDLER: "TSRX2019",
2415
+ /** An `@pending` block on a target without it. */
2416
+ TARGET_PENDING_UNSUPPORTED: "TSRX2020",
2417
+ /** An `await` where the target can't await (in a callback, or in its components). */
2418
+ TARGET_AWAIT_UNSUPPORTED: "TSRX2021",
2419
+ /** A `yield` in a part of the template that runs in a callback. */
2420
+ TARGET_YIELD_UNSUPPORTED: "TSRX2022",
2421
+ /** A `super` in a part of the template that's lowered into a generator function. */
2422
+ TARGET_SUPER_UNSUPPORTED: "TSRX2023",
2423
+ /** A `for await…of` in a template on a target without it. */
2424
+ TARGET_FOR_AWAIT_UNSUPPORTED: "TSRX2024",
2425
+ /** A top-level `await` in a TSRX function without a module-level `"use server"`. */
2426
+ TOP_LEVEL_AWAIT_USE_SERVER: "TSRX2025",
2427
+ /** An `@catch` reset parameter on a target whose error boundary has none. */
2428
+ TARGET_CATCH_RESET_UNSUPPORTED: "TSRX2026",
2429
+ /** An `@for` head that assigns to existing variables, or declares its loop variable with `var` or `using`. */
2430
+ FOR_HEAD: "TSRX2027",
2431
+ /** A component read above its declaration on a target that compiles it to a constant, where moving the declaration up would change what it reads. */
2432
+ TARGET_COMPONENT_READ_BEFORE_DECLARATION: "TSRX2028",
2433
+ /** A destructured prop default the target's component compiler drops. */
2434
+ TARGET_PROP_DEFAULT_UNSUPPORTED: "TSRX2029",
2435
+ /** A `var` declared in a nested `@{ … }` block or an `@if`, `@for`, `@switch` or `@try` body, outside any function or class in it. */
2436
+ DIRECTIVE_BODY_VAR: "TSRX2030",
2437
+ /** A destructured prop key the target's component compiler reads as another prop, or leaves out. */
2438
+ TARGET_PROP_KEY_UNSUPPORTED: "TSRX2031",
2439
+ /** A binding of a name the target's toolchain finds by name: Vue's `defineVaporComponent`. */
2440
+ TARGET_RESERVED_NAME: "TSRX2032",
2441
+ /** Type arguments after a dynamic tag (`<{Tag}<T> />`). */
2442
+ DYNAMIC_TAG_TYPE_ARGUMENTS: "TSRX2033",
2443
+ /** A `yield` in a template value the target's JSX compiler moves into an effect, getter or callback. */
2444
+ TARGET_TEMPLATE_YIELD_UNSUPPORTED: "TSRX2034",
2445
+ /**
2446
+ * A warning: a `@{ … }` with no output whose only statement is an
2447
+ * expression there only for its value, such as `<p>@{user.name}</p>`, so
2448
+ * it renders nothing.
2449
+ */
2450
+ CODE_BLOCK_EXPRESSION_ONLY: "TSRX2035",
2451
+ /** `<style apply>` carries no expression value. */
2452
+ STYLE_APPLY_VALUE: "TSRX3001",
2453
+ /** An `apply` entry is not an identifier, member, or array of those, or does not resolve to a style block. */
2454
+ STYLE_APPLY_TARGET: "TSRX3002",
2455
+ /** An `apply` target is declared after the applying block in source order. */
2456
+ STYLE_APPLY_BEFORE_DECLARATION: "TSRX3003",
2457
+ /** Two `apply` attributes on one `<style>` block. */
2458
+ STYLE_APPLY_DUPLICATE: "TSRX3004",
2459
+ /** `apply` on a `<head>` style or a resource (`href`) style. */
2460
+ STYLE_APPLY_UNSUPPORTED_HOST: "TSRX3005",
2461
+ /** An assigned style block authors a `.$class` class selector. */
2462
+ STYLE_RESERVED_CLASS_KEY: "TSRX3006",
2463
+ /** A standalone `<style>` block at module scope. */
2464
+ STYLE_STANDALONE_AT_MODULE_SCOPE: "TSRX3007",
2465
+ /** A standalone `<style>` block with CSS text outside any `@{ … }` or control-flow body. */
2466
+ STYLE_STANDALONE_OUTSIDE_TEMPLATE: "TSRX3008",
2467
+ /** A standalone `<style>` block in a statement slot: the lone output of a `@{ … }` or control-flow body, or a statement. */
2468
+ STYLE_STANDALONE_NEEDS_FRAGMENT: "TSRX3009",
2469
+ /** A `<style>` attribute other than `ref` and `apply`. */
2470
+ STYLE_UNKNOWN_ATTRIBUTE: "TSRX3010",
2471
+ /** `:global` used where the scoping rules do not allow it. */
2472
+ CSS_GLOBAL_PLACEMENT: "TSRX3011",
2473
+ /** An `@import` rule in a `<style>` block, whose rules would not be scoped. */
2474
+ CSS_IMPORT: "TSRX3012",
2475
+ /** CSS in a `<style>` block that doesn't parse. */
2476
+ CSS_SYNTAX: "TSRX3013",
2477
+ /** A `<style>` block in a child expression container (`{<style>…</style>}`), which renders its class map. */
2478
+ STYLE_IN_EXPRESSION_CONTAINER: "TSRX3014",
2479
+ /** A recognized `import.meta.env.platform.*` flag is used without a selected platform. */
2480
+ PLATFORM_REQUIRED: "TSRX4001",
2481
+ /** A name that starts with the prefix the compiler reserves for its own identifiers. */
2482
+ RESERVED_IDENTIFIER_PREFIX: "TSRX4002",
2483
+ /** JavaScript syntax the parser rejects that TypeScript accepts (an escaped `import.meta`). */
2484
+ JAVASCRIPT_SYNTAX: "TSRX4003"
2485
+ };
2486
+ /**
2487
+ * The source TSRX's errors are reported under, in capitals like TypeScript's
2488
+ * own `TS2322`: `@tsrx/content-mapper` declares it to TypeScript 7, which shows
2489
+ * its errors as `TSRX2002`, and the TSRX language server reports its compile
2490
+ * errors with it.
2491
+ */
2492
+ const DIAGNOSTIC_SOURCE = "TSRX";
2493
+ /** See {@link TYPESCRIPT_CODE_PREFIX}. */
2494
+ const MAPPER_CODE_PREFIX = "77";
2495
+ /** @param {number} number */
2496
+ /* @__NO_SIDE_EFFECTS__ */
2497
+ function mapper_code(number) {
2498
+ return Number(`${"77"}${number}`);
2499
+ }
2500
+ /** The errors `@tsrx/content-mapper` reports itself. */
2501
+ const MAPPER_CODES = {
2502
+ /** A file that doesn't compile, with an error that has no code. */
2503
+ COMPILE_ERROR: /* @__PURE__ */ mapper_code(1e3),
2504
+ /** An error without a TSRX or TypeScript code. */
2505
+ USAGE_ERROR: /* @__PURE__ */ mapper_code(1001),
2506
+ /** No TSRX compiler found for a file. */
2507
+ NO_COMPILER: /* @__PURE__ */ mapper_code(1002),
2508
+ /** The project's TSRX configuration is invalid. */
2509
+ INVALID_CONFIG: /* @__PURE__ */ mapper_code(1003)
2510
+ };
2511
+
2512
+ //#endregion
2513
+ //#region src/diagnostic-directives.js
2514
+ /** @import * as AST from 'estree' */
2515
+ /** @import {CodeMapping, CompileError} from '@tsrx/core/types' */
2516
+ /** @import {DiagnosticDirectives} from './protocol.js' */
2517
+ /**
2518
+ * The nodes whose generated code an error's directive covers: the innermost
2519
+ * statement, declaration, class or type member, or element that holds the
2520
+ * error.
2521
+ */
2522
+ const HOLDER_TYPE = /(?:Statement|Declaration|Definition|Signature)$|^(?:StaticBlock|AccessorProperty|JSXElement|JSXFragment|JSXStyleElement)$/;
2523
+ /** Keys of a tree node that hold no child nodes, or nodes that aren't its children. */
2524
+ const NOT_CHILDREN = /* @__PURE__ */ new Set([
2525
+ "metadata",
2526
+ "loc",
2527
+ "range",
2528
+ "parent",
2529
+ "comments",
2530
+ "leadingComments",
2531
+ "trailingComments"
2532
+ ]);
2533
+ /**
2534
+ * An `ignore` directive for each error the mapper reports, so that a mistake
2535
+ * shows once. TypeScript reports some mistakes itself from the generated code,
2536
+ * with a code of its own, and would show them next to the mapper's error. The
2537
+ * directive hides TypeScript's errors in the generated code of the statement,
2538
+ * class or type member, or element that holds the error, until the error is
2539
+ * fixed and the mapper stops sending it. The mapper's own errors are not
2540
+ * TypeScript's, so they stay.
2541
+ *
2542
+ * The ranges come from what every TSRX compiler returns, whatever its target:
2543
+ * the source tree (`sourceAst`) finds the node that holds an error, and the
2544
+ * mappings give that node's generated code. Without a source tree the error's
2545
+ * own span stands in. A node without mappings gets no directive.
2546
+ * @param {readonly CompileError[]} errors
2547
+ * @param {AST.Program | null} source_ast
2548
+ * @param {readonly CodeMapping[]} mappings
2549
+ * @param {number} original_length
2550
+ * @param {number} generated_length
2551
+ * @returns {DiagnosticDirectives | null}
2552
+ */
2553
+ function ignore_directives(errors, source_ast, mappings, original_length, generated_length) {
2554
+ /** @type {Array<[original_start: number, original_end: number, generated_start: number, generated_end: number]>} */
2555
+ const ranges = [];
2556
+ for (const error of errors) {
2557
+ if (typeof error.pos !== "number") continue;
2558
+ const on_tag = reported_on_tag(error);
2559
+ const position = on_tag ? error.raisedAt - 1 : error.pos;
2560
+ const holder = source_ast ? holder_at(source_ast, position) : null;
2561
+ const start = holder ? holder.start : error.pos;
2562
+ const end = holder ? holder.end : typeof error.end === "number" && error.end > error.pos ? error.end : error.pos + 1;
2563
+ const own_code = on_tag && !holder;
2564
+ for (const generated of generated_ranges(mappings, start, end, own_code)) ranges.push([
2565
+ Math.min(start, original_length),
2566
+ Math.min(end, original_length),
2567
+ Math.min(generated[0], generated_length),
2568
+ Math.min(generated[1], generated_length)
2569
+ ]);
2570
+ }
2571
+ if (ranges.length === 0) return null;
2572
+ ranges.sort((a, b) => a[2] - b[2]);
2573
+ /** @type {typeof ranges} */
2574
+ const merged = [];
2575
+ for (const range of ranges) {
2576
+ const last = merged.at(-1);
2577
+ if (last && range[2] < last[3]) {
2578
+ last[0] = Math.min(last[0], range[0]);
2579
+ last[1] = Math.max(last[1], range[1]);
2580
+ last[3] = Math.max(last[3], range[3]);
2581
+ } else merged.push([...range]);
2582
+ }
2583
+ return {
2584
+ unusedExpectDirectiveDiagnostics: [],
2585
+ directives: merged.map(([original_start, original_end, generated_start, generated_end]) => [
2586
+ original_start,
2587
+ original_end - original_start,
2588
+ generated_start,
2589
+ generated_end,
2590
+ DiagnosticDirectivePolicy.Ignore
2591
+ ])
2592
+ };
2593
+ }
2594
+ /**
2595
+ * Whether `error` is an unclosed tag reported on the tag and found where the
2596
+ * parser stopped, one before `raisedAt`: the end of its template, or the start
2597
+ * of a `<style>` or `<script>` body. Its directive holds there, not at the error:
2598
+ * the closing tag that recovery adds has no mapping, so TypeScript's error on it
2599
+ * could only show at the top of the file, and the tag's own statement can end
2600
+ * before it. At the end of the file nothing holds that place, as the tag's
2601
+ * declaration has stretched around the code that follows, which the directive
2602
+ * must not hide. A compiler from before tags were reported on themselves has its
2603
+ * error where the parser stopped already, with `raisedAt` no further than `end`,
2604
+ * and the mapper runs whichever compiler the project has.
2605
+ * @param {CompileError} error
2606
+ * @returns {boolean}
2607
+ */
2608
+ function reported_on_tag({ code, end, raisedAt }) {
2609
+ return code === DIAGNOSTIC_CODES.UNCLOSED_TAG && typeof raisedAt === "number" && typeof end === "number" && raisedAt > end;
2610
+ }
2611
+ /**
2612
+ * The innermost holder node (see {@link HOLDER_TYPE}) that contains `position`,
2613
+ * found by descending from the root through the child that contains it.
2614
+ * @param {AST.Node} root
2615
+ * @param {number} position
2616
+ * @returns {AST.Node | null}
2617
+ */
2618
+ function holder_at(root, position) {
2619
+ /** @type {AST.Node | null} */
2620
+ let holder = null;
2621
+ /** @type {AST.Node | null} */
2622
+ let node = root;
2623
+ while (node) {
2624
+ if (HOLDER_TYPE.test(node.type)) holder = node;
2625
+ node = child_at(node, position);
2626
+ }
2627
+ return holder;
2628
+ }
2629
+ /**
2630
+ * @param {AST.Node} node
2631
+ * @param {number} position
2632
+ * @returns {AST.Node | null}
2633
+ */
2634
+ function child_at(node, position) {
2635
+ for (const [key, value] of Object.entries(node)) {
2636
+ if (NOT_CHILDREN.has(key) || !value || typeof value !== "object") continue;
2637
+ 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;
2638
+ }
2639
+ return null;
2640
+ }
2641
+ /**
2642
+ * The generated ranges of the mapped code between `start` and `end` in the
2643
+ * original. A node's generated code need not be in one piece: a compiler can
2644
+ * hoist part of it (a static element above the component), and a `<script>`
2645
+ * body is checked as a block at the end of the file. So each range runs from
2646
+ * the first to the last generated offset of the node's segments until code
2647
+ * mapped from outside the node follows, and the next of its segments starts a
2648
+ * new range; a range never covers another component's code. A segment of the
2649
+ * same length on both sides that encloses the original range, as a verbatim
2650
+ * `<script>` body does, gives the matching part of its generated text.
2651
+ * @param {readonly CodeMapping[]} mappings
2652
+ * @param {number} start
2653
+ * @param {number} end
2654
+ * @param {boolean} [own_code] Count only segments inside the range, and no
2655
+ * error's anchor. A segment that encloses the range doesn't count: a mapping of
2656
+ * the whole file can have the same length on both sides by chance. An anchor
2657
+ * still ends a range, as any code from outside the node does.
2658
+ * @returns {Array<[number, number]>}
2659
+ */
2660
+ function generated_ranges(mappings, start, end, own_code = false) {
2661
+ /** @type {Array<[generated_start: number, generated_end: number, inside: boolean]>} */
2662
+ const segments = [];
2663
+ for (const mapping of mappings) for (let i = 0; i < mapping.sourceOffsets.length; i++) {
2664
+ const source = mapping.sourceOffsets[i];
2665
+ const length = mapping.lengths[i];
2666
+ const generated = mapping.generatedOffsets[i];
2667
+ const generated_length = mapping.generatedLengths?.[i] ?? length;
2668
+ if (own_code && mapping.data?.customData?.diagnosticAnchor) segments.push([
2669
+ generated,
2670
+ generated + generated_length,
2671
+ false
2672
+ ]);
2673
+ else if (source >= start && source + length <= end) segments.push([
2674
+ generated,
2675
+ generated + generated_length,
2676
+ true
2677
+ ]);
2678
+ else if (!own_code && source <= start && end <= source + length && generated_length === length) segments.push([
2679
+ generated + start - source,
2680
+ generated + end - source,
2681
+ true
2682
+ ]);
2683
+ else segments.push([
2684
+ generated,
2685
+ generated + generated_length,
2686
+ false
2687
+ ]);
2688
+ }
2689
+ segments.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
2690
+ /** @type {Array<[number, number]>} */
2691
+ const ranges = [];
2692
+ /** @type {[number, number] | null} */
2693
+ let range = null;
2694
+ for (const [segment_start, segment_end, inside] of segments) if (inside) {
2695
+ if (range) range[1] = Math.max(range[1], segment_end);
2696
+ else range = [segment_start, segment_end];
2697
+ } else if (range && segment_start >= range[1]) {
2698
+ if (range[1] > range[0]) ranges.push(range);
2699
+ range = null;
2700
+ }
2701
+ if (range && range[1] > range[0]) ranges.push(range);
2702
+ return ranges;
2703
+ }
2704
+
2341
2705
  //#endregion
2342
2706
  //#region src/export-stub.js
2343
2707
  /** @import * as AST from 'estree' */
@@ -2345,9 +2709,8 @@ function invalidateCompilerResolutionCaches() {
2345
2709
  * Build a TypeScript stub that preserves a module's export surface while the
2346
2710
  * file cannot be compiled.
2347
2711
  *
2348
- * The native content-mapper protocol offers no way to suppress TypeScript's
2349
- * own diagnostics, so feeding raw TSRX (or the last good TSX, which may carry
2350
- * type errors of its own) to the checker would produce noise. Instead every
2712
+ * Raw TSRX, or the last good TSX (which may carry type errors of its own),
2713
+ * would give the checker noise to report. Instead every
2351
2714
  * export from the last successful transform's source AST is re-declared as
2352
2715
  * `any` (both as a value and as a type, so `new X()`, `X.y` and `let v: X` all
2353
2716
  * keep resolving), re-exports from other modules are kept as written (including
@@ -2391,10 +2754,18 @@ function build_export_stub(program) {
2391
2754
  }
2392
2755
  if (statement.declaration) for (const name of declaration_names(statement.declaration)) names.add(name);
2393
2756
  }
2757
+ let next_local = 0;
2394
2758
  for (const name of names) {
2395
- if (!identifier_pattern$1.test(name)) continue;
2396
- lines.push(`export declare const ${name}: any;`);
2397
- lines.push(`export type ${name} = any;`);
2759
+ if (identifier_pattern$1.test(name) && !UNDECLARABLE_NAMES.has(name)) {
2760
+ lines.push(`export declare const ${name}: any;`);
2761
+ lines.push(`export type ${name} = any;`);
2762
+ continue;
2763
+ }
2764
+ let local = `_$_export_${next_local++}`;
2765
+ while (names.has(local)) local = `_$_export_${next_local++}`;
2766
+ lines.push(`declare const ${local}: any;`);
2767
+ lines.push(`type ${local} = any;`);
2768
+ lines.push(`export { ${local} as ${module_export_name(name)} };`);
2398
2769
  }
2399
2770
  if (has_default) {
2400
2771
  lines.push("declare const _default: any;");
@@ -2414,6 +2785,73 @@ function type_modifier(node) {
2414
2785
  }
2415
2786
  const identifier_pattern$1 = /^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u;
2416
2787
  /**
2788
+ * Identifier names that `export declare const x: any; export type x = any;`
2789
+ * can't declare in a module: reserved words (TS1389), words reserved in strict
2790
+ * mode (TS1214), `await`, `let`, `arguments` and `eval`, the names of
2791
+ * TypeScript's own types (TS2457), and `as`, which `export type as` misreads.
2792
+ */
2793
+ const UNDECLARABLE_NAMES = /* @__PURE__ */ new Set([
2794
+ "break",
2795
+ "case",
2796
+ "catch",
2797
+ "class",
2798
+ "const",
2799
+ "continue",
2800
+ "debugger",
2801
+ "default",
2802
+ "delete",
2803
+ "do",
2804
+ "else",
2805
+ "enum",
2806
+ "export",
2807
+ "extends",
2808
+ "false",
2809
+ "finally",
2810
+ "for",
2811
+ "function",
2812
+ "if",
2813
+ "import",
2814
+ "in",
2815
+ "instanceof",
2816
+ "new",
2817
+ "null",
2818
+ "return",
2819
+ "super",
2820
+ "switch",
2821
+ "this",
2822
+ "throw",
2823
+ "true",
2824
+ "try",
2825
+ "typeof",
2826
+ "var",
2827
+ "void",
2828
+ "while",
2829
+ "with",
2830
+ "implements",
2831
+ "interface",
2832
+ "package",
2833
+ "private",
2834
+ "protected",
2835
+ "public",
2836
+ "static",
2837
+ "yield",
2838
+ "await",
2839
+ "let",
2840
+ "arguments",
2841
+ "eval",
2842
+ "any",
2843
+ "bigint",
2844
+ "boolean",
2845
+ "never",
2846
+ "number",
2847
+ "object",
2848
+ "string",
2849
+ "symbol",
2850
+ "undefined",
2851
+ "unknown",
2852
+ "as"
2853
+ ]);
2854
+ /**
2417
2855
  * The name an export binds, as a plain string: `a` for `export { a }` and
2418
2856
  * `foo-bar` for `export { "foo-bar" as a } from`.
2419
2857
  * @param {AST.Identifier | AST.Literal | AST.Expression} node
@@ -2432,7 +2870,15 @@ function export_name(node) {
2432
2870
  * @returns {string}
2433
2871
  */
2434
2872
  function print_name(node) {
2435
- const name = export_name(node);
2873
+ return module_export_name(export_name(node));
2874
+ }
2875
+ /**
2876
+ * A name as an export specifier takes it: any identifier name, reserved words
2877
+ * too, as is, and anything else quoted.
2878
+ * @param {string} name
2879
+ * @returns {string}
2880
+ */
2881
+ function module_export_name(name) {
2436
2882
  return identifier_pattern$1.test(name) ? name : JSON.stringify(name);
2437
2883
  }
2438
2884
  /**
@@ -2465,10 +2911,83 @@ function pattern_names(pattern) {
2465
2911
  }
2466
2912
  }
2467
2913
 
2914
+ //#endregion
2915
+ //#region src/platform-globals.js
2916
+ /** @import {CodeMapping} from '@tsrx/core/types' */
2917
+ /**
2918
+ * The editor-only `ImportMetaEnv` / `ImportMeta` globals that `withPlatformTypes`
2919
+ * in `@tsrx/core` appends to the generated TSX of a module that keeps a platform
2920
+ * flag, exactly as it prints them, with the three flag value types captured.
2921
+ */
2922
+ const PLATFORM_GLOBALS = /\ndeclare global \{\n\tinterface ImportMetaEnv \{\n\t\treadonly platform: string & \{\n\t\t\treadonly web: (true|false|boolean);\n\t\t\treadonly ios: (true|false|boolean);\n\t\t\treadonly android: (true|false|boolean);\n\t\t\};\n\t\}\n\tinterface ImportMeta \{\n\t\treadonly \[key: `env\$\{string\}`\]: ImportMetaEnv;\n\t\}\n\}\n/;
2923
+ /** The `platform-globals/` file that declares each set of flag value types. */
2924
+ const PLATFORM_FILES = /* @__PURE__ */ new Map([
2925
+ ["true,false,false", "web"],
2926
+ ["false,true,false", "ios"],
2927
+ ["false,false,true", "android"],
2928
+ ["boolean,boolean,boolean", "unconfigured"]
2929
+ ]);
2930
+ /** @type {Map<string, string | null>} */
2931
+ const files = /* @__PURE__ */ new Map();
2932
+ /**
2933
+ * Replace a module's copy of the platform globals in its generated TSX with a
2934
+ * reference to the shared file that declares the same globals. Native
2935
+ * TypeScript merges every module's copy into one `ImportMeta` and reports the
2936
+ * repeated index signature (TS2374), and declaration output keeps every
2937
+ * `declare global` block. The shared file is in the program once, and
2938
+ * declaration output drops a `/// <reference path>` directive.
2939
+ *
2940
+ * The copy is blanked in place, and the directive goes at the start of the
2941
+ * text, where TypeScript reads it, so every generated offset moves by its
2942
+ * length. A directive is not an import: organize imports and auto-import still
2943
+ * see only the module's own imports, and TypeScript 7 maps their edits only
2944
+ * when the last of them is the module's last import. Text without the exact
2945
+ * copy (another TSRX version, a third-party compiler), or that starts with a
2946
+ * hashbang, comes back unchanged.
2947
+ * @param {string} text
2948
+ * @param {readonly CodeMapping[]} mappings
2949
+ * @returns {{ text: string, mappings: readonly CodeMapping[] }}
2950
+ */
2951
+ function share_platform_globals(text, mappings) {
2952
+ const match = PLATFORM_GLOBALS.exec(text);
2953
+ const name = match && PLATFORM_FILES.get(match.slice(1).join(","));
2954
+ const file = name && !text.startsWith("#!") ? platform_globals_file(name) : null;
2955
+ if (!match || !file) return {
2956
+ text,
2957
+ mappings
2958
+ };
2959
+ const directive = `/// <reference path="${file}" />\n`;
2960
+ const end = match.index + match[0].length;
2961
+ return {
2962
+ text: `${directive}${text.slice(0, match.index)}${match[0].replace(/[^\n]/g, " ")}${text.slice(end)}`,
2963
+ mappings: mappings.map((mapping) => ({
2964
+ ...mapping,
2965
+ generatedOffsets: mapping.generatedOffsets.map((offset) => offset + directive.length)
2966
+ }))
2967
+ };
2968
+ }
2969
+ /**
2970
+ * The path of a `platform-globals/` file, with forward slashes. The directory
2971
+ * sits next to `src/` and `dist/`, so one relative URL serves both. A file
2972
+ * missing from the installed package, or a path a directive cannot quote,
2973
+ * leaves the copy in place.
2974
+ * @param {string} name
2975
+ * @returns {string | null}
2976
+ */
2977
+ function platform_globals_file(name) {
2978
+ let file = files.get(name);
2979
+ if (file === void 0) {
2980
+ const path = fileURLToPath(new URL(`../platform-globals/${name}.d.cts`, import.meta.url));
2981
+ file = fs.existsSync(path) && !/["\r\n]/.test(path) ? path.replace(/\\/g, "/") : null;
2982
+ files.set(name, file);
2983
+ }
2984
+ return file;
2985
+ }
2986
+
2468
2987
  //#endregion
2469
2988
  //#region src/span-mappings.js
2470
2989
  /** @import {CodeMapping} from '@tsrx/core/types' */
2471
- /** @import {SpanMapping} from './protocol.js' */
2990
+ /** @import {SpanMapping, VerificationMapping} from './protocol.js' */
2472
2991
  const semantic_features = SpanMapFeature.Hover | SpanMapFeature.SignatureHelp | SpanMapFeature.InlayHints | SpanMapFeature.SemanticTokens;
2473
2992
  const completion_features = SpanMapFeature.Completion | SpanMapFeature.AutoInsert;
2474
2993
  const navigation_features = SpanMapFeature.Definition | SpanMapFeature.TypeDefinition | SpanMapFeature.Implementation | SpanMapFeature.References | SpanMapFeature.DocumentHighlights | SpanMapFeature.Rename | SpanMapFeature.CallHierarchy | SpanMapFeature.CodeActions | SpanMapFeature.LinkedEditing;
@@ -2482,6 +3001,9 @@ const identifier_pattern = /^[\p{ID_Start}_$][\p{ID_Continue}$‌‍]*$/u;
2482
3001
  * @property {number} originalEnd
2483
3002
  * @property {0 | 1 | 2} kind
2484
3003
  * @property {number} features
3004
+ * @property {boolean} [positionOnly] From a mapping with no Volar feature, not even
3005
+ * `verification`: it only places diagnostics, so coalescing may join it to
3006
+ * its neighbours like an unmapped gap.
2485
3007
  */
2486
3008
  /**
2487
3009
  * Translate a Volar `CodeMapping['data']` into content-mapper feature bits.
@@ -2539,6 +3061,11 @@ function features_from_mapping_data(data) {
2539
3061
  * `import { a } from './x';` is one edit-safe span rather than four tokens
2540
3062
  * with unmapped punctuation between them. TypeScript only applies text edits
2541
3063
  * (auto-import, rename, code actions) that fit inside a single Verbatim span.
3064
+ * A dropped candidate then keeps its uncovered edges (see
3065
+ * {@link map_dropped_edges}), so a diagnostic over a whole container starts and
3066
+ * ends where the container does in the original. Last, identical text left
3067
+ * between spans with different feature bits maps without features (see
3068
+ * {@link map_identical_gaps}).
2542
3069
  * @param {readonly CodeMapping[]} mappings
2543
3070
  * @param {string} generated_text
2544
3071
  * @param {string} original_text
@@ -2574,20 +3101,21 @@ function to_span_mappings(mappings, generated_text, original_text, options = {})
2574
3101
  originalStart: original_start,
2575
3102
  originalEnd: original_end,
2576
3103
  kind,
2577
- features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None
3104
+ features: language_features ? features_from_mapping_data(mapping.data) : SpanMapFeature.None,
3105
+ positionOnly: is_position_only(mapping.data)
2578
3106
  });
2579
3107
  }
2580
3108
  }
2581
3109
  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);
2582
3110
  /** @type {Candidate[]} */
2583
3111
  const selected = [];
3112
+ /** @type {Candidate[]} */
3113
+ const dropped = [];
2584
3114
  const occupied = new IntervalSet();
2585
- for (const candidate of candidates) {
2586
- if (!occupied.add(candidate.generatedStart, candidate.generatedEnd)) continue;
2587
- selected.push(candidate);
2588
- }
3115
+ for (const candidate of candidates) if (occupied.add(candidate.generatedStart, candidate.generatedEnd)) selected.push(candidate);
3116
+ else dropped.push(candidate);
2589
3117
  selected.sort((left, right) => left.generatedStart - right.generatedStart);
2590
- return extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text).map((candidate) => [
3118
+ return map_identical_gaps(map_dropped_edges(extend_verbatim_spans_over_whitespace(coalesce_verbatim_spans(selected, generated_text, original_text), generated_text, original_text), dropped, generated_text, original_text), generated_text, original_text).map((candidate) => [
2591
3119
  candidate.generatedStart,
2592
3120
  candidate.generatedEnd - candidate.generatedStart,
2593
3121
  candidate.originalStart,
@@ -2597,11 +3125,54 @@ function to_span_mappings(mappings, generated_text, original_text, options = {})
2597
3125
  ]);
2598
3126
  }
2599
3127
  /**
3128
+ * Whether a mapping has no Volar feature at all, not even `verification`. The
3129
+ * transform emits such mappings only to give TypeScript 7 a place for
3130
+ * diagnostics (the brackets of a respaced literal); Volar ignores them.
3131
+ * @param {CodeMapping['data'] | undefined} data
3132
+ * @returns {boolean}
3133
+ */
3134
+ function is_position_only(data) {
3135
+ return !!data && typeof data === "object" && !data.verification && !data.completion && !data.semantic && !data.navigation && !data.structure && !data.format;
3136
+ }
3137
+ /**
3138
+ * The transform's own mappings for diagnostics, for command-line checkers (the
3139
+ * `verificationMappings` mapper option): every mapping whose `data.verification`
3140
+ * is set, in the transform's order, with its offsets and lengths as emitted.
3141
+ * This is what `tsrx-tsc` hands Volar, so Volar's `SourceMap#toSourceRange`
3142
+ * (with `fallbackToAnyMatch`) over it maps a diagnostic exactly as `tsrx-tsc`
3143
+ * does. The grouping matters: Volar maps a range through one mapping that holds
3144
+ * both of its ends, such as the start and end points of a literal, and tries
3145
+ * mappings in this order, narrower first. When any mapping's verification is a
3146
+ * `shouldReport` callback, the result is empty: the callback depends on the
3147
+ * diagnostic and doesn't serialize, and leaving out only that mapping could
3148
+ * let an overlapping one map a diagnostic somewhere else.
3149
+ * @param {readonly CodeMapping[]} mappings
3150
+ * @returns {VerificationMapping[]}
3151
+ */
3152
+ function to_verification_mappings(mappings) {
3153
+ /** @type {VerificationMapping[]} */
3154
+ const result = [];
3155
+ for (const mapping of mappings) {
3156
+ const verification = mapping.data?.verification;
3157
+ if (!verification) continue;
3158
+ if (typeof verification === "object" && typeof verification.shouldReport === "function") return [];
3159
+ result.push({
3160
+ sourceOffsets: [...mapping.sourceOffsets],
3161
+ generatedOffsets: [...mapping.generatedOffsets],
3162
+ lengths: [...mapping.lengths],
3163
+ generatedLengths: [...mapping.generatedLengths ?? mapping.lengths],
3164
+ data: { verification: true }
3165
+ });
3166
+ }
3167
+ return result;
3168
+ }
3169
+ /**
2600
3170
  * Merge runs of Verbatim spans, sorted by generated start, when the two spans
2601
3171
  * carry the same feature bits and the text between them is identical (and of
2602
3172
  * equal length) in the generated and the original file. The merged span is
2603
3173
  * Verbatim by construction: every position inside it maps with the same
2604
- * offset and the same text.
3174
+ * offset and the same text. A position-only span joins a neighbour whatever
3175
+ * its features, and takes them, as the unmapped text it covers would.
2605
3176
  * @param {Candidate[]} spans
2606
3177
  * @param {string} generated_text
2607
3178
  * @param {string} original_text
@@ -2612,9 +3183,13 @@ function coalesce_verbatim_spans(spans, generated_text, original_text) {
2612
3183
  const merged = [];
2613
3184
  for (const span of spans) {
2614
3185
  const previous = merged[merged.length - 1];
2615
- 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)) {
3186
+ if (previous && previous.kind === SpanMapKind.Verbatim && span.kind === SpanMapKind.Verbatim && (previous.features === span.features || previous.positionOnly || span.positionOnly) && 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)) {
2616
3187
  previous.generatedEnd = span.generatedEnd;
2617
3188
  previous.originalEnd = span.originalEnd;
3189
+ if (previous.positionOnly && !span.positionOnly) {
3190
+ previous.features = span.features;
3191
+ previous.positionOnly = false;
3192
+ }
2618
3193
  continue;
2619
3194
  }
2620
3195
  merged.push({ ...span });
@@ -2650,6 +3225,219 @@ function extend_verbatim_spans_over_whitespace(spans, generated_text, original_t
2650
3225
  }
2651
3226
  return spans;
2652
3227
  }
3228
+ /**
3229
+ * Map the uncovered edges of each candidate that lost to the spans it
3230
+ * overlaps: the part before its first span and the part after its last.
3231
+ *
3232
+ * A container (a whole import type, a statement) encloses the token spans that
3233
+ * beat it, and TypeScript reports some diagnostics over the whole container.
3234
+ * When the printed text differs from the source (`import( './x' )` printed
3235
+ * as `import('./x')`), the container's start lies in unmapped text, and
3236
+ * TypeScript would report the diagnostic at the nearest earlier mapped
3237
+ * position instead. An edge runs from the container's boundary to the
3238
+ * neighbouring span, in both files, so it maps only when that span's original
3239
+ * range starts (or ends) inside the container's. Each edge is split by
3240
+ * {@link split_edge} so that a node inside it without a span of its own keeps
3241
+ * its position. Edges carry no feature bits: they place diagnostics and change
3242
+ * no editor feature. Gaps between a container's spans get no edge;
3243
+ * {@link map_identical_gaps} maps the ones whose text is identical.
3244
+ * Candidates are visited shortest first, so a nested container's edge bounds
3245
+ * the edge of the one around it.
3246
+ * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
3247
+ * @param {readonly Candidate[]} dropped
3248
+ * @param {string} generated_text
3249
+ * @param {string} original_text
3250
+ * @returns {Candidate[]}
3251
+ */
3252
+ function map_dropped_edges(spans, dropped, generated_text, original_text) {
3253
+ const result = spans.slice();
3254
+ /**
3255
+ * @param {Candidate | null} edge
3256
+ * @param {boolean} trailing
3257
+ */
3258
+ const add = (edge, trailing) => {
3259
+ if (!edge) return;
3260
+ for (const span of split_edge(edge, generated_text, original_text, trailing)) {
3261
+ if (span.kind === SpanMapKind.Atom && is_partial_identifier(original_text, span.originalStart, span.originalEnd)) continue;
3262
+ result.splice(last_span_at_or_before(result, span.generatedStart) + 1, 0, span);
3263
+ }
3264
+ };
3265
+ for (const candidate of dropped) {
3266
+ add(leading_edge(result, candidate), false);
3267
+ add(trailing_edge(result, candidate), true);
3268
+ }
3269
+ return result;
3270
+ }
3271
+ /**
3272
+ * @param {readonly Candidate[]} spans
3273
+ * @param {Candidate} candidate
3274
+ * @returns {Candidate | null}
3275
+ */
3276
+ function leading_edge(spans, candidate) {
3277
+ const index = last_span_at_or_before(spans, candidate.generatedStart);
3278
+ if (index >= 0 && spans[index].generatedEnd > candidate.generatedStart) return null;
3279
+ const next = spans[index + 1];
3280
+ if (!next || next.generatedStart >= candidate.generatedEnd || next.originalStart <= candidate.originalStart || next.originalStart > candidate.originalEnd) return null;
3281
+ return edge(candidate.generatedStart, next.generatedStart, candidate.originalStart, next.originalStart, SpanMapKind.Atom);
3282
+ }
3283
+ /**
3284
+ * @param {readonly Candidate[]} spans
3285
+ * @param {Candidate} candidate
3286
+ * @returns {Candidate | null}
3287
+ */
3288
+ function trailing_edge(spans, candidate) {
3289
+ const previous = spans[last_span_at_or_before(spans, candidate.generatedEnd - 1)];
3290
+ if (!previous || previous.generatedEnd >= candidate.generatedEnd || previous.generatedEnd <= candidate.generatedStart || previous.originalEnd < candidate.originalStart || previous.originalEnd >= candidate.originalEnd) return null;
3291
+ return edge(previous.generatedEnd, candidate.generatedEnd, previous.originalEnd, candidate.originalEnd, SpanMapKind.Atom);
3292
+ }
3293
+ /**
3294
+ * Split an edge into `Verbatim` runs of the text it shares with the source,
3295
+ * matched from the container's boundary (the start of a leading edge, the end
3296
+ * of a trailing one) with whitespace that only one side has skipped, and one
3297
+ * `Atom` for whatever follows the first other difference. The printer mostly
3298
+ * changes spacing: in `Record< {}, 1 >`, printed `Record<{ }, 1>`, the `{` of
3299
+ * the `{}` that has no span of its own then maps to itself instead of to the
3300
+ * container's `<`. An edge whose boundary character differs stays one `Atom`,
3301
+ * and no run starts or ends inside an identifier.
3302
+ * @param {Candidate} whole
3303
+ * @param {string} generated_text
3304
+ * @param {string} original_text
3305
+ * @param {boolean} from_end
3306
+ * @returns {Candidate[]}
3307
+ */
3308
+ function split_edge(whole, generated_text, original_text, from_end) {
3309
+ const generated = generated_text.slice(whole.generatedStart, whole.generatedEnd);
3310
+ const original = original_text.slice(whole.originalStart, whole.originalEnd);
3311
+ /**
3312
+ * The character `index` steps from the boundary.
3313
+ * @param {string} text
3314
+ * @param {number} index
3315
+ */
3316
+ const at = (text, index) => text[from_end ? text.length - 1 - index : index];
3317
+ if (at(generated, 0) !== at(original, 0)) return [whole];
3318
+ /** Runs as `[generated step, original step, length]`, in steps from the boundary. */
3319
+ /** @type {Array<[number, number, number]>} */
3320
+ const runs = [];
3321
+ let i = 0;
3322
+ let j = 0;
3323
+ while (i < generated.length && j < original.length) {
3324
+ const g = at(generated, i);
3325
+ const o = at(original, j);
3326
+ if (g === o) {
3327
+ const run = runs.at(-1);
3328
+ if (run && run[0] + run[2] === i && run[1] + run[2] === j) run[2]++;
3329
+ else runs.push([
3330
+ i,
3331
+ j,
3332
+ 1
3333
+ ]);
3334
+ i++;
3335
+ j++;
3336
+ } else if (/\s/.test(g)) i++;
3337
+ else if (/\s/.test(o)) j++;
3338
+ else break;
3339
+ }
3340
+ /** @param {string} text @param {number} index */
3341
+ const splits = (text, index) => identifier_part.test(at(text, index - 1) ?? "") && identifier_part.test(at(text, index) ?? "");
3342
+ /** @type {Array<[number, number, number]>} */
3343
+ const kept = [];
3344
+ for (const [g, o, length] of runs) {
3345
+ if (splits(generated, g) || splits(original, o)) break;
3346
+ let end = length;
3347
+ while (end > 0 && (splits(generated, g + end) || splits(original, o + end))) end--;
3348
+ if (end > 0) kept.push([
3349
+ g,
3350
+ o,
3351
+ end
3352
+ ]);
3353
+ if (end < length) break;
3354
+ }
3355
+ const last = kept.at(-1);
3356
+ if (!last) return [whole];
3357
+ i = last[0] + last[2];
3358
+ j = last[1] + last[2];
3359
+ /** @type {Candidate[]} */
3360
+ const spans = kept.map(([g, o, length]) => from_end ? edge_span(whole.generatedEnd - g - length, whole.originalEnd - o - length, length) : edge_span(whole.generatedStart + g, whole.originalStart + o, length));
3361
+ if (i < generated.length && j < original.length) spans.push(from_end ? edge(whole.generatedStart, whole.generatedEnd - i, whole.originalStart, whole.originalEnd - j, SpanMapKind.Atom) : edge(whole.generatedStart + i, whole.generatedEnd, whole.originalStart + j, whole.originalEnd, SpanMapKind.Atom));
3362
+ return spans;
3363
+ }
3364
+ /**
3365
+ * @param {number} generated_start
3366
+ * @param {number} original_start
3367
+ * @param {number} length
3368
+ * @returns {Candidate}
3369
+ */
3370
+ function edge_span(generated_start, original_start, length) {
3371
+ return edge(generated_start, generated_start + length, original_start, original_start + length, SpanMapKind.Verbatim);
3372
+ }
3373
+ /**
3374
+ * @param {number} generated_start
3375
+ * @param {number} generated_end
3376
+ * @param {number} original_start
3377
+ * @param {number} original_end
3378
+ * @param {0 | 1 | 2} kind
3379
+ * @returns {Candidate}
3380
+ */
3381
+ function edge(generated_start, generated_end, original_start, original_end, kind) {
3382
+ return {
3383
+ generatedStart: generated_start,
3384
+ generatedEnd: generated_end,
3385
+ originalStart: original_start,
3386
+ originalEnd: original_end,
3387
+ kind,
3388
+ features: SpanMapFeature.None
3389
+ };
3390
+ }
3391
+ /**
3392
+ * The index of the last span that starts at or before `position`, or -1.
3393
+ * @param {readonly Candidate[]} spans Sorted by generated start.
3394
+ * @param {number} position
3395
+ */
3396
+ function last_span_at_or_before(spans, position) {
3397
+ let low = 0;
3398
+ let high = spans.length;
3399
+ while (low < high) {
3400
+ const middle = low + high >>> 1;
3401
+ if (spans[middle].generatedStart <= position) low = middle + 1;
3402
+ else high = middle;
3403
+ }
3404
+ return low - 1;
3405
+ }
3406
+ /**
3407
+ * Give the text that follows a Verbatim span, and is identical in the generated
3408
+ * and the original file up to the next span in either file, a Verbatim span of
3409
+ * its own with no feature bits. TypeScript 7 offers no auto-import completion at
3410
+ * the end of a span that unmapped text separates from the next span, such as at
3411
+ * `helperB` in `{helperB()}<Button />`: the `<` of a tag maps with other features
3412
+ * than `helperB`, so `()}` joins neither span (#1028). The text keeps no features
3413
+ * of its neighbours, as when it was unmapped.
3414
+ * @param {Candidate[]} spans Sorted by generated start, non-overlapping.
3415
+ * @param {string} generated_text
3416
+ * @param {string} original_text
3417
+ * @returns {Candidate[]}
3418
+ */
3419
+ function map_identical_gaps(spans, generated_text, original_text) {
3420
+ /** @type {Candidate[]} */
3421
+ const result = [];
3422
+ for (let index = 0; index < spans.length; index++) {
3423
+ const span = spans[index];
3424
+ result.push(span);
3425
+ const next = spans[index + 1];
3426
+ if (span.kind !== SpanMapKind.Verbatim || !next) continue;
3427
+ let length = 0;
3428
+ while (span.generatedEnd + length < next.generatedStart && span.originalEnd + length < next.originalStart && generated_text[span.generatedEnd + length] === original_text[span.originalEnd + length]) length++;
3429
+ if (length === 0) continue;
3430
+ result.push({
3431
+ generatedStart: span.generatedEnd,
3432
+ generatedEnd: span.generatedEnd + length,
3433
+ originalStart: span.originalEnd,
3434
+ originalEnd: span.originalEnd + length,
3435
+ kind: SpanMapKind.Verbatim,
3436
+ features: SpanMapFeature.None
3437
+ });
3438
+ }
3439
+ return result;
3440
+ }
2653
3441
  const identifier_part = /[\p{ID_Continue}$\u200c\u200d]/u;
2654
3442
  const token_part = /[\p{ID_Continue}$#@\u200c\u200d]/u;
2655
3443
  /**
@@ -2732,6 +3520,7 @@ const bare_package_specifier_pattern = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a
2732
3520
  * @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
2733
3521
  * @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
2734
3522
  * @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
3523
+ * @property {boolean} [verificationMappings] `true` adds `verificationMappings` to each transform result: the transform's own diagnostics mappings, in Volar's shape and order, for command-line checkers. Off by default; TypeScript ignores the field.
2735
3524
  */
2736
3525
  /**
2737
3526
  * @typedef {object} ProjectState
@@ -2813,14 +3602,14 @@ function create_tsrx_content_mapper(context = {}) {
2813
3602
  return failure(state, file_name, content, {
2814
3603
  start: 0,
2815
3604
  length: 0,
2816
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
3605
+ code: MAPPER_CODES.INVALID_CONFIG,
2817
3606
  messageText: error_message(error)
2818
3607
  });
2819
3608
  }
2820
3609
  if (!compiler) return failure(state, file_name, content, {
2821
3610
  start: 0,
2822
3611
  length: 0,
2823
- code: DIAGNOSTIC_CODE_NO_COMPILER,
3612
+ code: MAPPER_CODES.NO_COMPILER,
2824
3613
  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.`
2825
3614
  });
2826
3615
  /** @type {'web' | 'ios' | 'android' | undefined} */
@@ -2836,21 +3625,26 @@ function create_tsrx_content_mapper(context = {}) {
2836
3625
  return failure(state, file_name, content, {
2837
3626
  start: 0,
2838
3627
  length: 0,
2839
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
3628
+ code: MAPPER_CODES.INVALID_CONFIG,
2840
3629
  messageText: error_message(error)
2841
3630
  });
2842
3631
  }
2843
3632
  const result = transform_tsrx(compiler, file_name, content, { platform });
2844
- if (result.fatalError) return failure(state, file_name, content, to_diagnostic(result.fatalError, content.length, DIAGNOSTIC_CODE_COMPILE_ERROR));
3633
+ if (result.fatalError) return failure(state, file_name, content, to_diagnostic(result.fatalError, content.length, MAPPER_CODES.COMPILE_ERROR));
2845
3634
  if (result.sourceAst) state.lastGood.set(file_name, result.sourceAst);
3635
+ const generated = share_platform_globals(result.text, result.mappings);
2846
3636
  const language_features = state.options.languageFeatures !== false;
2847
- const mappings = to_span_mappings(result.mappings, result.text, content, { languageFeatures: language_features });
2848
- const diagnostics = result.errors.map((error) => to_diagnostic(error, content.length, DIAGNOSTIC_CODE_USAGE_ERROR));
3637
+ const mappings = to_span_mappings(generated.mappings, generated.text, content, { languageFeatures: language_features });
3638
+ const errors = result.errors.filter((error) => error.severity !== "warning");
3639
+ const diagnostics = errors.map((error) => to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR));
3640
+ const diagnosticDirectives = ignore_directives(errors, result.sourceAst, generated.mappings, content.length, generated.text.length);
2849
3641
  return {
2850
- text: result.text,
3642
+ text: generated.text,
2851
3643
  extension: ".tsx",
2852
3644
  mappings,
2853
- ...diagnostics.length > 0 ? { diagnostics } : null
3645
+ ...diagnostics.length > 0 ? { diagnostics } : null,
3646
+ ...diagnosticDirectives ? { diagnosticDirectives } : null,
3647
+ ...state.options.verificationMappings ? { verificationMappings: to_verification_mappings(generated.mappings) } : null
2854
3648
  };
2855
3649
  }
2856
3650
  /**
@@ -2944,7 +3738,8 @@ function create_tsrx_content_mapper(context = {}) {
2944
3738
  text: build_export_stub(state.lastGood.get(file_name)),
2945
3739
  extension: ".ts",
2946
3740
  mappings: [],
2947
- diagnostics: [clamp_diagnostic(diagnostic, content.length)]
3741
+ diagnostics: [clamp_diagnostic(diagnostic, content.length)],
3742
+ ...state.options.verificationMappings ? { verificationMappings: [] } : null
2948
3743
  };
2949
3744
  }
2950
3745
  return {
@@ -2971,7 +3766,7 @@ function validate_options(raw) {
2971
3766
  optionDiagnostics.push({
2972
3767
  path: [],
2973
3768
  messageText: "Content mapper options must be an object.",
2974
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3769
+ code: MAPPER_CODES.INVALID_CONFIG
2975
3770
  });
2976
3771
  return {
2977
3772
  options,
@@ -2987,7 +3782,7 @@ function validate_options(raw) {
2987
3782
  else optionDiagnostics.push({
2988
3783
  path: [key],
2989
3784
  messageText: "\"compiler\" must be a bare package specifier such as \"@tsrx/react\".",
2990
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3785
+ code: MAPPER_CODES.INVALID_CONFIG
2991
3786
  });
2992
3787
  break;
2993
3788
  case "platform":
@@ -2995,21 +3790,22 @@ function validate_options(raw) {
2995
3790
  else optionDiagnostics.push({
2996
3791
  path: [key],
2997
3792
  messageText: "\"platform\" must be \"web\", \"ios\", or \"android\".",
2998
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3793
+ code: MAPPER_CODES.INVALID_CONFIG
2999
3794
  });
3000
3795
  break;
3001
3796
  case "languageFeatures":
3002
- if (typeof value === "boolean") options.languageFeatures = value;
3797
+ case "verificationMappings":
3798
+ if (typeof value === "boolean") options[key] = value;
3003
3799
  else optionDiagnostics.push({
3004
3800
  path: [key],
3005
- messageText: "\"languageFeatures\" must be a boolean.",
3006
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3801
+ messageText: `"${key}" must be a boolean.`,
3802
+ code: MAPPER_CODES.INVALID_CONFIG
3007
3803
  });
3008
3804
  break;
3009
3805
  default: optionDiagnostics.push({
3010
3806
  path: [key],
3011
3807
  messageText: `Unknown content mapper option "${key}".`,
3012
- code: DIAGNOSTIC_CODE_INVALID_CONFIG
3808
+ code: MAPPER_CODES.INVALID_CONFIG
3013
3809
  });
3014
3810
  }
3015
3811
  }
@@ -3018,10 +3814,15 @@ function validate_options(raw) {
3018
3814
  optionDiagnostics
3019
3815
  };
3020
3816
  }
3817
+ const TSRX_CODE = /^TSRX(\d+)$/;
3818
+ const TYPESCRIPT_CODE = /^TS(\d+)$/;
3021
3819
  /**
3022
3820
  * Translate a compiler `CompileError` into a mapper diagnostic in original
3023
- * offsets. Coded errors keep their string code in the message and derive a
3024
- * stable numeric code from it; uncoded ones use `fallback_code`.
3821
+ * offsets. TypeScript shows the mapper's diagnostics as `TSRX<number>`, so a
3822
+ * TSRX code goes as its number (`TSRX2002` → `2002`) and a TypeScript code as
3823
+ * `TYPESCRIPT_CODE_PREFIX` then its number (`TS1005` → `111005`), which keeps
3824
+ * the code in the message too. An error without either uses `fallback_code`
3825
+ * and keeps any other code in the message.
3025
3826
  * @param {CompileError} error
3026
3827
  * @param {number} content_length
3027
3828
  * @param {number} fallback_code
@@ -3030,31 +3831,18 @@ function validate_options(raw) {
3030
3831
  function to_diagnostic(error, content_length, fallback_code) {
3031
3832
  const start = typeof error.pos === "number" ? error.pos : 0;
3032
3833
  const end = typeof error.end === "number" && error.end > start ? error.end : start + 1;
3033
- const code = typeof error.code === "string" && error.code ? numeric_code(error.code) : fallback_code;
3834
+ const code = typeof error.code === "string" ? error.code : "";
3835
+ const tsrx = TSRX_CODE.exec(code);
3836
+ const typescript = TYPESCRIPT_CODE.exec(code);
3034
3837
  const message = String(error.message ?? error);
3035
3838
  return clamp_diagnostic({
3036
3839
  start,
3037
3840
  length: end - start,
3038
- code,
3039
- messageText: typeof error.code === "string" && error.code ? `${message} [${error.code}]` : message
3841
+ code: tsrx ? Number(tsrx[1]) : typescript ? Number(`${"11"}${typescript[1]}`) : fallback_code,
3842
+ messageText: code && !tsrx ? `${message} [${code}]` : message
3040
3843
  }, content_length);
3041
3844
  }
3042
3845
  /**
3043
- * Stable numeric code for a TSRX string diagnostic code (FNV-1a 32-bit,
3044
- * folded into the 10000..99999 range so it never collides with the fixed
3045
- * codes below 10000).
3046
- * @param {string} code
3047
- * @returns {number}
3048
- */
3049
- function numeric_code(code) {
3050
- let hash = 2166136261;
3051
- for (let index = 0; index < code.length; index++) {
3052
- hash ^= code.charCodeAt(index);
3053
- hash = Math.imul(hash, 16777619);
3054
- }
3055
- return 1e4 + (hash >>> 0) % 9e4;
3056
- }
3057
- /**
3058
3846
  * @param {MapperDiagnostic} diagnostic
3059
3847
  * @param {number} content_length
3060
3848
  * @returns {MapperDiagnostic}
@@ -3094,5 +3882,5 @@ function nearest_package_manifest(entry) {
3094
3882
  }
3095
3883
 
3096
3884
  //#endregion
3097
- export { validate_options as a, to_diagnostic as i, numeric_code as n, require$1 as r, create_tsrx_content_mapper as t };
3098
- //# sourceMappingURL=mapper-DATqGboo.js.map
3885
+ export { validate_options as i, require$1 as n, to_diagnostic as r, create_tsrx_content_mapper as t };
3886
+ //# sourceMappingURL=mapper-Gc2yuGNf.js.map