@tsrx/content-mapper 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mapper.js CHANGED
@@ -1,3 +1,3 @@
1
- import { i as validate_options, n as require, r as to_diagnostic, t as create_tsrx_content_mapper } from "./mapper-B4f--1ac.js";
1
+ import { i as validate_options, n as require, r as to_diagnostic, t as create_tsrx_content_mapper } from "./mapper-SyX-87Od.js";
2
2
 
3
3
  export { create_tsrx_content_mapper, require, to_diagnostic, validate_options };
package/dist/protocol.js CHANGED
@@ -57,6 +57,22 @@ const DiagnosticDirectivePolicy = {
57
57
  * ]} SpanMapping
58
58
  */
59
59
  /**
60
+ * Not part of the TypeScript 7 protocol: what the `verificationMappings` mapper
61
+ * option adds to a transform result for command-line checkers. Every compiler
62
+ * mapping marked for diagnostics, in Volar's `CodeMapping` shape and in the
63
+ * transform's order, so `new SourceMap(verificationMappings).toSourceRange(start,
64
+ * end, true)` from `@volar/source-map` maps a diagnostic as `tsrx-tsc` does.
65
+ * Points (offsets with zero length) belong to the mapping they are listed in.
66
+ * Empty when the transform has a mapping whose verification is a `shouldReport`
67
+ * callback, which can't be serialized.
68
+ * @typedef {object} VerificationMapping
69
+ * @property {number[]} sourceOffsets
70
+ * @property {number[]} generatedOffsets
71
+ * @property {number[]} lengths
72
+ * @property {number[]} generatedLengths
73
+ * @property {{ verification: true }} data
74
+ */
75
+ /**
60
76
  * @typedef {object} MapperDiagnostic
61
77
  * @property {number} start Offset into the original text (UTF-16 code units).
62
78
  * @property {number} length
@@ -89,6 +105,7 @@ const DiagnosticDirectivePolicy = {
89
105
  * diagnostics?: MapperDiagnostic[],
90
106
  * diagnosticDirectives?: DiagnosticDirectives,
91
107
  * supplemental?: MappedOutput[],
108
+ * verificationMappings?: VerificationMapping[],
92
109
  * }} TransformResult
93
110
  */
94
111
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","names":[],"sources":["../src/protocol.js"],"sourcesContent":["/**\n * Constants of the TypeScript 7 content-mapper protocol, kept in sync with\n * `tsc/internal/contentmapper` and `tsc/internal/spanmap` in microsoft/TypeScript.\n */\n\n/** Span kinds. */\nexport const SpanMapKind = /** @type {const} */ ({\n\t/** Same length and identical text; the only kind that supports text edits. */\n\tVerbatim: 0,\n\t/** Same entity, different text or length. */\n\tAtom: 1,\n\t/** Different text; diagnostics covering the whole span exactly show the original text. */\n\tAlias: 2,\n});\n\n/** Feature bits a span opts into. Diagnostics ignore them. */\nexport const SpanMapFeature = /** @type {const} */ ({\n\tHover: 1 << 0,\n\tSignatureHelp: 1 << 1,\n\tCompletion: 1 << 2,\n\tDefinition: 1 << 3,\n\tTypeDefinition: 1 << 4,\n\tImplementation: 1 << 5,\n\tReferences: 1 << 6,\n\tDocumentHighlights: 1 << 7,\n\tRename: 1 << 8,\n\tCallHierarchy: 1 << 9,\n\tCodeActions: 1 << 10,\n\tFormatting: 1 << 11,\n\tInlayHints: 1 << 12,\n\tSemanticTokens: 1 << 13,\n\tFoldingRanges: 1 << 14,\n\tSelectionRanges: 1 << 15,\n\tLinkedEditing: 1 << 16,\n\tAutoInsert: 1 << 17,\n\tDocumentSymbols: 1 << 18,\n\tCodeLens: 1 << 19,\n\tNone: 0,\n\tAll: (1 << 20) - 1,\n});\n\n/**\n * Diagnostic-directive policies: `Ignore` hides TypeScript's errors in a\n * generated range; `Expect` also reports a diagnostic of the mapper's when\n * there are none there.\n */\nexport const DiagnosticDirectivePolicy = /** @type {const} */ ({ Ignore: 0, Expect: 1 });\n\n/**\n * @typedef {[\n * \tgeneratedStart: number,\n * \tgeneratedLength: number,\n * \toriginalStart: number,\n * \toriginalLength: number,\n * \tkind: 0 | 1 | 2,\n * \tfeatures: number,\n * ]} SpanMapping\n */\n\n/**\n * @typedef {object} MapperDiagnostic\n * @property {number} start Offset into the original text (UTF-16 code units).\n * @property {number} length\n * @property {number} code\n * @property {string} messageText\n */\n\n/**\n * @typedef {object} MappedOutput\n * @property {string} text\n * @property {'.js' | '.jsx' | '.mjs' | '.cjs' | '.ts' | '.tsx' | '.mts' | '.cts' | '.json'} extension\n * @property {SpanMapping[]} mappings\n */\n\n/**\n * @typedef {[\n * \toriginalStart: number,\n * \toriginalLength: number,\n * \tgeneratedStart: number,\n * \tgeneratedEnd: number,\n * \tpolicy: 0 | 1,\n * \tunusedExpectDirectiveIndex?: number,\n * ]} DiagnosticDirective\n */\n\n/**\n * @typedef {object} DiagnosticDirectives\n * @property {Array<{ code: number, messageText: string }>} unusedExpectDirectiveDiagnostics What an `Expect` directive reports when TypeScript has no error in its range.\n * @property {DiagnosticDirective[]} directives\n */\n\n/**\n * @typedef {MappedOutput & {\n * \tdiagnostics?: MapperDiagnostic[],\n * \tdiagnosticDirectives?: DiagnosticDirectives,\n * \tsupplemental?: MappedOutput[],\n * }} TransformResult\n */\n\n/**\n * @typedef {object} InitializeParams\n * @property {string} [locale]\n * @property {Array<'utf-8' | 'utf-16'>} positionEncodings\n */\n\n/**\n * @typedef {object} InitializeResult\n * @property {'utf-8' | 'utf-16'} positionEncoding\n * @property {string} diagnosticSource\n */\n\n/**\n * @typedef {object} OpenProjectParams\n * @property {string} configFileName Empty for inferred projects.\n * @property {string} projectHandle\n * @property {Record<string, unknown>} [options] The mapper entry's `options` object.\n * @property {Record<string, unknown>} compilerOptions Effective compiler options (wire format).\n */\n\n/**\n * @typedef {object} OpenProjectResult\n * @property {string} configIdentity\n * @property {string[]} [watchedFiles]\n * @property {Array<{ path: Array<string | number>, messageText: string, code: number }>} [optionDiagnostics]\n */\n\n/**\n * @typedef {object} TransformParams\n * @property {string} fileName\n * @property {string} content\n * @property {string} [projectHandle]\n */\n"],"mappings":";;;;;;AAMA,MAAa,cAAoC;;CAEhD,UAAU;;CAEV,MAAM;;CAEN,OAAO;AACR;;AAGA,MAAa,iBAAuC;CACnD,OAAO;CACP,eAAe;CACf,YAAY;CACZ,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,YAAY;CACZ,oBAAoB;CACpB,QAAQ;CACR,eAAe;CACf,aAAa;CACb,YAAY;CACZ,YAAY;CACZ,gBAAgB;CAChB,eAAe;CACf,iBAAiB;CACjB,eAAe;CACf,YAAY,KAAK;CACjB,iBAAiB,KAAK;CACtB,UAAU,KAAK;CACf,MAAM;CACN,MAAM,KAAK,MAAM;AAClB;;;;;;AAOA,MAAa,4BAAkD;CAAE,QAAQ;CAAG,QAAQ;AAAE"}
1
+ {"version":3,"file":"protocol.js","names":[],"sources":["../src/protocol.js"],"sourcesContent":["/**\n * Constants of the TypeScript 7 content-mapper protocol, kept in sync with\n * `tsc/internal/contentmapper` and `tsc/internal/spanmap` in microsoft/TypeScript.\n */\n\n/** Span kinds. */\nexport const SpanMapKind = /** @type {const} */ ({\n\t/** Same length and identical text; the only kind that supports text edits. */\n\tVerbatim: 0,\n\t/** Same entity, different text or length. */\n\tAtom: 1,\n\t/** Different text; diagnostics covering the whole span exactly show the original text. */\n\tAlias: 2,\n});\n\n/** Feature bits a span opts into. Diagnostics ignore them. */\nexport const SpanMapFeature = /** @type {const} */ ({\n\tHover: 1 << 0,\n\tSignatureHelp: 1 << 1,\n\tCompletion: 1 << 2,\n\tDefinition: 1 << 3,\n\tTypeDefinition: 1 << 4,\n\tImplementation: 1 << 5,\n\tReferences: 1 << 6,\n\tDocumentHighlights: 1 << 7,\n\tRename: 1 << 8,\n\tCallHierarchy: 1 << 9,\n\tCodeActions: 1 << 10,\n\tFormatting: 1 << 11,\n\tInlayHints: 1 << 12,\n\tSemanticTokens: 1 << 13,\n\tFoldingRanges: 1 << 14,\n\tSelectionRanges: 1 << 15,\n\tLinkedEditing: 1 << 16,\n\tAutoInsert: 1 << 17,\n\tDocumentSymbols: 1 << 18,\n\tCodeLens: 1 << 19,\n\tNone: 0,\n\tAll: (1 << 20) - 1,\n});\n\n/**\n * Diagnostic-directive policies: `Ignore` hides TypeScript's errors in a\n * generated range; `Expect` also reports a diagnostic of the mapper's when\n * there are none there.\n */\nexport const DiagnosticDirectivePolicy = /** @type {const} */ ({ Ignore: 0, Expect: 1 });\n\n/**\n * @typedef {[\n * \tgeneratedStart: number,\n * \tgeneratedLength: number,\n * \toriginalStart: number,\n * \toriginalLength: number,\n * \tkind: 0 | 1 | 2,\n * \tfeatures: number,\n * ]} SpanMapping\n */\n\n/**\n * Not part of the TypeScript 7 protocol: what the `verificationMappings` mapper\n * option adds to a transform result for command-line checkers. Every compiler\n * mapping marked for diagnostics, in Volar's `CodeMapping` shape and in the\n * transform's order, so `new SourceMap(verificationMappings).toSourceRange(start,\n * end, true)` from `@volar/source-map` maps a diagnostic as `tsrx-tsc` does.\n * Points (offsets with zero length) belong to the mapping they are listed in.\n * Empty when the transform has a mapping whose verification is a `shouldReport`\n * callback, which can't be serialized.\n * @typedef {object} VerificationMapping\n * @property {number[]} sourceOffsets\n * @property {number[]} generatedOffsets\n * @property {number[]} lengths\n * @property {number[]} generatedLengths\n * @property {{ verification: true }} data\n */\n\n/**\n * @typedef {object} MapperDiagnostic\n * @property {number} start Offset into the original text (UTF-16 code units).\n * @property {number} length\n * @property {number} code\n * @property {string} messageText\n */\n\n/**\n * @typedef {object} MappedOutput\n * @property {string} text\n * @property {'.js' | '.jsx' | '.mjs' | '.cjs' | '.ts' | '.tsx' | '.mts' | '.cts' | '.json'} extension\n * @property {SpanMapping[]} mappings\n */\n\n/**\n * @typedef {[\n * \toriginalStart: number,\n * \toriginalLength: number,\n * \tgeneratedStart: number,\n * \tgeneratedEnd: number,\n * \tpolicy: 0 | 1,\n * \tunusedExpectDirectiveIndex?: number,\n * ]} DiagnosticDirective\n */\n\n/**\n * @typedef {object} DiagnosticDirectives\n * @property {Array<{ code: number, messageText: string }>} unusedExpectDirectiveDiagnostics What an `Expect` directive reports when TypeScript has no error in its range.\n * @property {DiagnosticDirective[]} directives\n */\n\n/**\n * @typedef {MappedOutput & {\n * \tdiagnostics?: MapperDiagnostic[],\n * \tdiagnosticDirectives?: DiagnosticDirectives,\n * \tsupplemental?: MappedOutput[],\n * \tverificationMappings?: VerificationMapping[],\n * }} TransformResult\n */\n\n/**\n * @typedef {object} InitializeParams\n * @property {string} [locale]\n * @property {Array<'utf-8' | 'utf-16'>} positionEncodings\n */\n\n/**\n * @typedef {object} InitializeResult\n * @property {'utf-8' | 'utf-16'} positionEncoding\n * @property {string} diagnosticSource\n */\n\n/**\n * @typedef {object} OpenProjectParams\n * @property {string} configFileName Empty for inferred projects.\n * @property {string} projectHandle\n * @property {Record<string, unknown>} [options] The mapper entry's `options` object.\n * @property {Record<string, unknown>} compilerOptions Effective compiler options (wire format).\n */\n\n/**\n * @typedef {object} OpenProjectResult\n * @property {string} configIdentity\n * @property {string[]} [watchedFiles]\n * @property {Array<{ path: Array<string | number>, messageText: string, code: number }>} [optionDiagnostics]\n */\n\n/**\n * @typedef {object} TransformParams\n * @property {string} fileName\n * @property {string} content\n * @property {string} [projectHandle]\n */\n"],"mappings":";;;;;;AAMA,MAAa,cAAoC;;CAEhD,UAAU;;CAEV,MAAM;;CAEN,OAAO;AACR;;AAGA,MAAa,iBAAuC;CACnD,OAAO;CACP,eAAe;CACf,YAAY;CACZ,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,YAAY;CACZ,oBAAoB;CACpB,QAAQ;CACR,eAAe;CACf,aAAa;CACb,YAAY;CACZ,YAAY;CACZ,gBAAgB;CAChB,eAAe;CACf,iBAAiB;CACjB,eAAe;CACf,YAAY,KAAK;CACjB,iBAAiB,KAAK;CACtB,UAAU,KAAK;CACf,MAAM;CACN,MAAM,KAAK,MAAM;AAClB;;;;;;AAOA,MAAa,4BAAkD;CAAE,QAAQ;CAAG,QAAQ;AAAE"}
package/dist/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as create_tsrx_content_mapper } from "./mapper-B4f--1ac.js";
2
+ import { t as create_tsrx_content_mapper } from "./mapper-SyX-87Od.js";
3
3
  import { redirect_console_to_stderr, run_mapper_server } from "./rpc.js";
4
4
 
5
5
  //#region src/server.js
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tsrx/content-mapper",
3
3
  "description": "TypeScript 7 content mapper for .tsrx files",
4
- "version": "0.1.2",
4
+ "version": "0.1.4",
5
5
  "license": "MIT",
6
6
  "author": "Dominic Gannaway",
7
7
  "type": "module",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "files": [
18
18
  "dist",
19
+ "platform-globals",
19
20
  "src"
20
21
  ],
21
22
  "exports": {
@@ -44,17 +45,17 @@
44
45
  "@types/react": "^19.2.2",
45
46
  "preact": "^10.27.0",
46
47
  "react": "^19.2.0",
47
- "ripple": "^0.4.0",
48
+ "ripple": "^0.6.1",
48
49
  "solid-js": "2.0.0-rc.3",
49
50
  "tsdown": "^0.23.0",
50
51
  "typescript": "^5.9.3",
51
- "vue": "3.6.0-beta.12",
52
- "@tsrx/core": "0.5.3",
53
- "@tsrx/preact": "0.3.3",
54
- "@tsrx/react": "0.4.3",
55
- "@tsrx/typescript-plugin": "0.6.0",
56
- "@tsrx/solid": "0.3.3",
57
- "@tsrx/vue": "0.3.3"
52
+ "vue": "3.6.0-rc.14",
53
+ "@tsrx/core": "0.6.1",
54
+ "@tsrx/preact": "0.4.1",
55
+ "@tsrx/react": "0.5.1",
56
+ "@tsrx/solid": "0.4.1",
57
+ "@tsrx/typescript-plugin": "0.7.1",
58
+ "@tsrx/vue": "0.4.1"
58
59
  },
59
60
  "publishConfig": {
60
61
  "access": "public"
@@ -0,0 +1,17 @@
1
+ // Editor-only `import.meta.env.platform` types for the `android` platform.
2
+ // The content mapper references this file in place of the copy that
3
+ // `withPlatformTypes` in `@tsrx/core` appends to each module that keeps a
4
+ // flag (see `src/platform-globals.js`).
5
+ export {};
6
+ declare global {
7
+ interface ImportMetaEnv {
8
+ readonly platform: string & {
9
+ readonly web: false;
10
+ readonly ios: false;
11
+ readonly android: true;
12
+ };
13
+ }
14
+ interface ImportMeta {
15
+ readonly [key: `env${string}`]: ImportMetaEnv;
16
+ }
17
+ }
@@ -0,0 +1,17 @@
1
+ // Editor-only `import.meta.env.platform` types for the `ios` platform.
2
+ // The content mapper references this file in place of the copy that
3
+ // `withPlatformTypes` in `@tsrx/core` appends to each module that keeps a
4
+ // flag (see `src/platform-globals.js`).
5
+ export {};
6
+ declare global {
7
+ interface ImportMetaEnv {
8
+ readonly platform: string & {
9
+ readonly web: false;
10
+ readonly ios: true;
11
+ readonly android: false;
12
+ };
13
+ }
14
+ interface ImportMeta {
15
+ readonly [key: `env${string}`]: ImportMetaEnv;
16
+ }
17
+ }
@@ -0,0 +1,17 @@
1
+ // Editor-only `import.meta.env.platform` types for a project without a platform.
2
+ // The content mapper references this file in place of the copy that
3
+ // `withPlatformTypes` in `@tsrx/core` appends to each module that keeps a
4
+ // flag (see `src/platform-globals.js`).
5
+ export {};
6
+ declare global {
7
+ interface ImportMetaEnv {
8
+ readonly platform: string & {
9
+ readonly web: boolean;
10
+ readonly ios: boolean;
11
+ readonly android: boolean;
12
+ };
13
+ }
14
+ interface ImportMeta {
15
+ readonly [key: `env${string}`]: ImportMetaEnv;
16
+ }
17
+ }
@@ -0,0 +1,17 @@
1
+ // Editor-only `import.meta.env.platform` types for the `web` platform.
2
+ // The content mapper references this file in place of the copy that
3
+ // `withPlatformTypes` in `@tsrx/core` appends to each module that keeps a
4
+ // flag (see `src/platform-globals.js`).
5
+ export {};
6
+ declare global {
7
+ interface ImportMetaEnv {
8
+ readonly platform: string & {
9
+ readonly web: true;
10
+ readonly ios: false;
11
+ readonly android: false;
12
+ };
13
+ }
14
+ interface ImportMeta {
15
+ readonly [key: `env${string}`]: ImportMetaEnv;
16
+ }
17
+ }
@@ -2,6 +2,7 @@
2
2
  /** @import {CodeMapping, CompileError} from '@tsrx/core/types' */
3
3
  /** @import {DiagnosticDirectives} from './protocol.js' */
4
4
 
5
+ import { DIAGNOSTIC_CODES } from '@tsrx/core/diagnostics';
5
6
  import { DiagnosticDirectivePolicy } from './protocol.js';
6
7
 
7
8
  /**
@@ -40,24 +41,53 @@ const NOT_CHILDREN = new Set([
40
41
  * @param {AST.Program | null} source_ast
41
42
  * @param {readonly CodeMapping[]} mappings
42
43
  * @param {number} original_length
43
- * @param {number} generated_length
44
+ * @param {string} generated_text
44
45
  * @returns {DiagnosticDirectives | null}
45
46
  */
46
- export function ignore_directives(errors, source_ast, mappings, original_length, generated_length) {
47
+ export function ignore_directives(errors, source_ast, mappings, original_length, generated_text) {
48
+ const generated_length = generated_text.length;
47
49
  /** @type {Array<[original_start: number, original_end: number, generated_start: number, generated_end: number]>} */
48
50
  const ranges = [];
51
+ // The closing tags recovery adds, for every unclosed element, wherever the
52
+ // compiler reported its error: a compiler from before tags were reported on
53
+ // themselves reports them all where the parser stopped.
54
+ if (
55
+ source_ast &&
56
+ errors.some(
57
+ (error) => error.code === DIAGNOSTIC_CODES.UNCLOSED_TAG && typeof error.pos === 'number',
58
+ )
59
+ ) {
60
+ /** @type {Set<number>} */
61
+ const claimed = new Set();
62
+ for (const opening of unclosed_openings(source_ast)) {
63
+ const closing_tag = recovered_closing_tag(opening, mappings, generated_text, claimed);
64
+ if (closing_tag) {
65
+ ranges.push([
66
+ Math.min(opening.start, original_length),
67
+ Math.min(opening.end, original_length),
68
+ closing_tag[0],
69
+ closing_tag[1],
70
+ ]);
71
+ }
72
+ }
73
+ }
49
74
  for (const error of errors) {
50
75
  if (typeof error.pos !== 'number') {
51
76
  continue;
52
77
  }
53
- const holder = source_ast ? holder_at(source_ast, error.pos) : null;
78
+ const on_tag = reported_on_tag(error);
79
+ const position = on_tag ? /** @type {number} */ (error.raisedAt) - 1 : error.pos;
80
+ const holder = source_ast ? holder_at(source_ast, position) : null;
54
81
  const start = holder ? /** @type {number} */ (holder.start) : error.pos;
55
82
  const end = holder
56
83
  ? /** @type {number} */ (holder.end)
57
84
  : typeof error.end === 'number' && error.end > error.pos
58
85
  ? error.end
59
86
  : error.pos + 1;
60
- for (const generated of generated_ranges(mappings, start, end)) {
87
+ // With nothing holding an unclosed tag, only its own code is covered. Its
88
+ // anchor isn't that: it sits on whatever else is on its generated line.
89
+ const own_code = on_tag && !holder;
90
+ for (const generated of generated_ranges(mappings, start, end, own_code)) {
61
91
  ranges.push([
62
92
  Math.min(start, original_length),
63
93
  Math.min(end, original_length),
@@ -96,6 +126,152 @@ export function ignore_directives(errors, source_ast, mappings, original_length,
96
126
  };
97
127
  }
98
128
 
129
+ /**
130
+ * The generated range of the closing tag that recovery adds to an unclosed
131
+ * element, or `null`. The React, Preact, Vue and Hono targets give it no
132
+ * mapping, so TypeScript's error on it, such as TS2304 for a name that isn't a
133
+ * value, has no place in the file and shows at its top as TS18080. An ignore
134
+ * directive over just that tag holds no authored code, so it can't hide errors
135
+ * in the code that follows. The tag is the first `</name>` from the opening
136
+ * tag on that no other element has claimed and that no mapping ties to
137
+ * authored code: the only mapping it may have is its name's to the opening
138
+ * tag, as the Solid target maps it.
139
+ * @param {{ start: number, end: number, name: unknown }} opening
140
+ * @param {readonly CodeMapping[]} mappings
141
+ * @param {string} generated_text
142
+ * @param {Set<number>} claimed
143
+ * @returns {[number, number] | null}
144
+ */
145
+ function recovered_closing_tag(opening, mappings, generated_text, claimed) {
146
+ const name = jsx_name(opening.name);
147
+ if (!name) return null;
148
+ /** @type {number | undefined} */
149
+ let from;
150
+ for (const mapping of mappings) {
151
+ for (let i = 0; i < mapping.sourceOffsets.length; i++) {
152
+ const source = mapping.sourceOffsets[i];
153
+ if (source >= opening.start && source < opening.end) {
154
+ from = Math.min(from ?? Infinity, mapping.generatedOffsets[i]);
155
+ }
156
+ }
157
+ }
158
+ if (from === undefined) return null;
159
+ const text = `</${name}>`;
160
+ for (
161
+ let at = generated_text.indexOf(text, from);
162
+ at !== -1;
163
+ at = generated_text.indexOf(text, at + 1)
164
+ ) {
165
+ const name_start = at + '</'.length;
166
+ if (
167
+ claimed.has(at) ||
168
+ maps_authored_code(mappings, at, at + text.length, opening, name_start, name.length)
169
+ ) {
170
+ continue;
171
+ }
172
+ claimed.add(at);
173
+ return [at, at + text.length];
174
+ }
175
+ return null;
176
+ }
177
+
178
+ /**
179
+ * The opening tags of the elements the parser found unclosed, outermost first.
180
+ * @param {AST.Node} node
181
+ * @returns {Array<{ start: number, end: number, name: unknown }>}
182
+ */
183
+ function unclosed_openings(node) {
184
+ /** @type {Array<{ start: number, end: number, name: unknown }>} */
185
+ const openings = [];
186
+ /** @param {AST.Node} current */
187
+ const visit = (current) => {
188
+ const element = /** @type {any} */ (current);
189
+ if (
190
+ element.type === 'JSXElement' &&
191
+ element.unclosed &&
192
+ typeof element.openingElement?.start === 'number' &&
193
+ typeof element.openingElement?.end === 'number'
194
+ ) {
195
+ openings.push(element.openingElement);
196
+ }
197
+ for (const [key, value] of Object.entries(current)) {
198
+ if (NOT_CHILDREN.has(key) || !value || typeof value !== 'object') continue;
199
+ for (const child of Array.isArray(value) ? value : [value]) {
200
+ if (child && typeof child.type === 'string') visit(child);
201
+ }
202
+ }
203
+ };
204
+ visit(node);
205
+ return openings;
206
+ }
207
+
208
+ /**
209
+ * The text of a JSX tag name, as the recovered closing tag prints it.
210
+ * @param {any} name
211
+ * @returns {string | null}
212
+ */
213
+ function jsx_name(name) {
214
+ if (!name) return null;
215
+ if (name.type === 'JSXIdentifier' || name.type === 'Identifier') return name.name;
216
+ if (name.type === 'JSXMemberExpression') {
217
+ const object = jsx_name(name.object);
218
+ return object ? `${object}.${name.property.name}` : null;
219
+ }
220
+ if (name.type === 'JSXNamespacedName') return `${name.namespace.name}:${name.name.name}`;
221
+ return null;
222
+ }
223
+
224
+ /**
225
+ * Whether a mapping ties generated code in `[start, end)` to authored code:
226
+ * any mapping there but one of just the name, at `name_start`, to the opening
227
+ * tag, as the Solid target maps a recovered closing tag's name.
228
+ * @param {readonly CodeMapping[]} mappings
229
+ * @param {number} start
230
+ * @param {number} end
231
+ * @param {{ start: number, end: number }} opening
232
+ * @param {number} name_start
233
+ * @param {number} name_length
234
+ * @returns {boolean}
235
+ */
236
+ function maps_authored_code(mappings, start, end, opening, name_start, name_length) {
237
+ return mappings.some((mapping) =>
238
+ mapping.generatedOffsets.some((offset, i) => {
239
+ const length = mapping.generatedLengths?.[i] ?? mapping.lengths[i];
240
+ if (offset >= end || start >= offset + length) return false;
241
+ const source = mapping.sourceOffsets[i];
242
+ return !(
243
+ offset >= name_start &&
244
+ offset + length <= name_start + name_length &&
245
+ source >= opening.start &&
246
+ source + mapping.lengths[i] <= opening.end
247
+ );
248
+ }),
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Whether `error` is an unclosed tag reported on the tag and found where the
254
+ * parser stopped, one before `raisedAt`: the end of its template, or the start
255
+ * of a `<style>` or `<script>` body. Its directive holds there, not at the error:
256
+ * the closing tag that recovery adds has no mapping, so TypeScript's error on it
257
+ * could only show at the top of the file, and the tag's own statement can end
258
+ * before it. At the end of the file nothing holds that place, as the tag's
259
+ * declaration has stretched around the code that follows, which the directive
260
+ * must not hide. A compiler from before tags were reported on themselves has its
261
+ * error where the parser stopped already, with `raisedAt` no further than `end`,
262
+ * and the mapper runs whichever compiler the project has.
263
+ * @param {CompileError} error
264
+ * @returns {boolean}
265
+ */
266
+ function reported_on_tag({ code, end, raisedAt }) {
267
+ return (
268
+ code === DIAGNOSTIC_CODES.UNCLOSED_TAG &&
269
+ typeof raisedAt === 'number' &&
270
+ typeof end === 'number' &&
271
+ raisedAt > end
272
+ );
273
+ }
274
+
99
275
  /**
100
276
  * The innermost holder node (see {@link HOLDER_TYPE}) that contains `position`,
101
277
  * found by descending from the root through the child that contains it.
@@ -156,9 +332,13 @@ function child_at(node, position) {
156
332
  * @param {readonly CodeMapping[]} mappings
157
333
  * @param {number} start
158
334
  * @param {number} end
335
+ * @param {boolean} [own_code] Count only segments inside the range, and no
336
+ * error's anchor. A segment that encloses the range doesn't count: a mapping of
337
+ * the whole file can have the same length on both sides by chance. An anchor
338
+ * still ends a range, as any code from outside the node does.
159
339
  * @returns {Array<[number, number]>}
160
340
  */
161
- function generated_ranges(mappings, start, end) {
341
+ function generated_ranges(mappings, start, end, own_code = false) {
162
342
  /** @type {Array<[generated_start: number, generated_end: number, inside: boolean]>} */
163
343
  const segments = [];
164
344
  for (const mapping of mappings) {
@@ -167,9 +347,16 @@ function generated_ranges(mappings, start, end) {
167
347
  const length = mapping.lengths[i];
168
348
  const generated = mapping.generatedOffsets[i];
169
349
  const generated_length = mapping.generatedLengths?.[i] ?? length;
170
- if (source >= start && source + length <= end) {
350
+ if (own_code && mapping.data?.customData?.diagnosticAnchor) {
351
+ segments.push([generated, generated + generated_length, false]);
352
+ } else if (source >= start && source + length <= end) {
171
353
  segments.push([generated, generated + generated_length, true]);
172
- } else if (source <= start && end <= source + length && generated_length === length) {
354
+ } else if (
355
+ !own_code &&
356
+ source <= start &&
357
+ end <= source + length &&
358
+ generated_length === length
359
+ ) {
173
360
  segments.push([generated + start - source, generated + end - source, true]);
174
361
  } else {
175
362
  segments.push([generated, generated + generated_length, false]);
package/src/mapper.js CHANGED
@@ -19,7 +19,8 @@ import { transform_tsrx } from '@tsrx/typescript-plugin/src/transform.js';
19
19
  import { DIAGNOSTIC_SOURCE, MAPPER_CODES, TYPESCRIPT_CODE_PREFIX } from '@tsrx/core/diagnostics';
20
20
  import { ignore_directives } from './diagnostic-directives.js';
21
21
  import { build_export_stub } from './export-stub.js';
22
- import { to_span_mappings } from './span-mappings.js';
22
+ import { share_platform_globals } from './platform-globals.js';
23
+ import { to_span_mappings, to_verification_mappings } from './span-mappings.js';
23
24
 
24
25
  const require = createRequire(import.meta.url);
25
26
  const bare_package_specifier_pattern =
@@ -32,6 +33,7 @@ const bare_package_specifier_pattern =
32
33
  * @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
33
34
  * @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
34
35
  * @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
36
+ * @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.
35
37
  */
36
38
 
37
39
  /**
@@ -183,30 +185,42 @@ export function create_tsrx_content_mapper(context = {}) {
183
185
  state.lastGood.set(file_name, result.sourceAst);
184
186
  }
185
187
 
188
+ // The one generated output every consumer below reads, so that a rewrite of
189
+ // the text and its mappings reaches the spans, the directives and the
190
+ // verification mappings alike.
191
+ const generated = share_platform_globals(result.text, result.mappings);
186
192
  const language_features = state.options.languageFeatures !== false;
187
- const mappings = to_span_mappings(result.mappings, result.text, content, {
193
+ const mappings = to_span_mappings(generated.mappings, generated.text, content, {
188
194
  languageFeatures: language_features,
189
195
  });
190
196
  // Every error goes to TypeScript, even one with a TypeScript code: the
191
197
  // generated code can lose the mistake (a repeated modifier, a rest
192
198
  // parameter's `?`), and then TypeScript never reports it. Where TypeScript
193
199
  // does, the directives hide its copy until the mapper's error is fixed.
194
- const diagnostics = result.errors.map((error) =>
200
+ // A warning doesn't go: TypeScript shows each of the mapper's diagnostics
201
+ // as an error, as the protocol has no severity, so `tsc` would fail on
202
+ // code that compiles, and its directive would hide TypeScript's own
203
+ // errors in the statement that holds it.
204
+ const errors = result.errors.filter((error) => error.severity !== 'warning');
205
+ const diagnostics = errors.map((error) =>
195
206
  to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR),
196
207
  );
197
208
  const diagnosticDirectives = ignore_directives(
198
- result.errors,
209
+ errors,
199
210
  result.sourceAst,
200
- result.mappings,
211
+ generated.mappings,
201
212
  content.length,
202
- result.text.length,
213
+ generated.text,
203
214
  );
204
215
  return {
205
- text: result.text,
216
+ text: generated.text,
206
217
  extension: '.tsx',
207
218
  mappings,
208
219
  ...(diagnostics.length > 0 ? { diagnostics } : null),
209
220
  ...(diagnosticDirectives ? { diagnosticDirectives } : null),
221
+ ...(state.options.verificationMappings
222
+ ? { verificationMappings: to_verification_mappings(generated.mappings) }
223
+ : null),
210
224
  };
211
225
  }
212
226
 
@@ -324,6 +338,7 @@ export function create_tsrx_content_mapper(context = {}) {
324
338
  extension: '.ts',
325
339
  mappings: [],
326
340
  diagnostics: [clamp_diagnostic(diagnostic, content.length)],
341
+ ...(state.options.verificationMappings ? { verificationMappings: [] } : null),
327
342
  };
328
343
  }
329
344
 
@@ -377,12 +392,13 @@ export function validate_options(raw) {
377
392
  }
378
393
  break;
379
394
  case 'languageFeatures':
395
+ case 'verificationMappings':
380
396
  if (typeof value === 'boolean') {
381
- options.languageFeatures = value;
397
+ options[key] = value;
382
398
  } else {
383
399
  optionDiagnostics.push({
384
400
  path: [key],
385
- messageText: '"languageFeatures" must be a boolean.',
401
+ messageText: `"${key}" must be a boolean.`,
386
402
  code: MAPPER_CODES.INVALID_CONFIG,
387
403
  });
388
404
  }
@@ -0,0 +1,76 @@
1
+ /** @import {CodeMapping} from '@tsrx/core/types' */
2
+
3
+ import fs from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ /**
7
+ * The editor-only `ImportMetaEnv` / `ImportMeta` globals that `withPlatformTypes`
8
+ * in `@tsrx/core` appends to the generated TSX of a module that keeps a platform
9
+ * flag, exactly as it prints them, with the three flag value types captured.
10
+ */
11
+ const PLATFORM_GLOBALS =
12
+ /\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/;
13
+
14
+ /** The `platform-globals/` file that declares each set of flag value types. */
15
+ const PLATFORM_FILES = new Map([
16
+ ['true,false,false', 'web'],
17
+ ['false,true,false', 'ios'],
18
+ ['false,false,true', 'android'],
19
+ ['boolean,boolean,boolean', 'unconfigured'],
20
+ ]);
21
+
22
+ /** @type {Map<string, string | null>} */
23
+ const files = new Map();
24
+
25
+ /**
26
+ * Replace a module's copy of the platform globals in its generated TSX with a
27
+ * reference to the shared file that declares the same globals. Native
28
+ * TypeScript merges every module's copy into one `ImportMeta` and reports the
29
+ * repeated index signature (TS2374), and declaration output keeps every
30
+ * `declare global` block. The shared file is in the program once, and
31
+ * declaration output drops a `/// <reference path>` directive.
32
+ *
33
+ * The copy is blanked in place, and the directive goes at the start of the
34
+ * text, where TypeScript reads it, so every generated offset moves by its
35
+ * length. A directive is not an import: organize imports and auto-import still
36
+ * see only the module's own imports, and TypeScript 7 maps their edits only
37
+ * when the last of them is the module's last import. Text without the exact
38
+ * copy (another TSRX version, a third-party compiler), or that starts with a
39
+ * hashbang, comes back unchanged.
40
+ * @param {string} text
41
+ * @param {readonly CodeMapping[]} mappings
42
+ * @returns {{ text: string, mappings: readonly CodeMapping[] }}
43
+ */
44
+ export function share_platform_globals(text, mappings) {
45
+ const match = PLATFORM_GLOBALS.exec(text);
46
+ const name = match && PLATFORM_FILES.get(match.slice(1).join(','));
47
+ const file = name && !text.startsWith('#!') ? platform_globals_file(name) : null;
48
+ if (!match || !file) return { text, mappings };
49
+ const directive = `/// <reference path="${file}" />\n`;
50
+ const end = match.index + match[0].length;
51
+ return {
52
+ text: `${directive}${text.slice(0, match.index)}${match[0].replace(/[^\n]/g, ' ')}${text.slice(end)}`,
53
+ mappings: mappings.map((mapping) => ({
54
+ ...mapping,
55
+ generatedOffsets: mapping.generatedOffsets.map((offset) => offset + directive.length),
56
+ })),
57
+ };
58
+ }
59
+
60
+ /**
61
+ * The path of a `platform-globals/` file, with forward slashes. The directory
62
+ * sits next to `src/` and `dist/`, so one relative URL serves both. A file
63
+ * missing from the installed package, or a path a directive cannot quote,
64
+ * leaves the copy in place.
65
+ * @param {string} name
66
+ * @returns {string | null}
67
+ */
68
+ function platform_globals_file(name) {
69
+ let file = files.get(name);
70
+ if (file === undefined) {
71
+ const path = fileURLToPath(new URL(`../platform-globals/${name}.d.cts`, import.meta.url));
72
+ file = fs.existsSync(path) && !/["\r\n]/.test(path) ? path.replace(/\\/g, '/') : null;
73
+ files.set(name, file);
74
+ }
75
+ return file;
76
+ }
package/src/protocol.js CHANGED
@@ -57,6 +57,23 @@ export const DiagnosticDirectivePolicy = /** @type {const} */ ({ Ignore: 0, Expe
57
57
  * ]} SpanMapping
58
58
  */
59
59
 
60
+ /**
61
+ * Not part of the TypeScript 7 protocol: what the `verificationMappings` mapper
62
+ * option adds to a transform result for command-line checkers. Every compiler
63
+ * mapping marked for diagnostics, in Volar's `CodeMapping` shape and in the
64
+ * transform's order, so `new SourceMap(verificationMappings).toSourceRange(start,
65
+ * end, true)` from `@volar/source-map` maps a diagnostic as `tsrx-tsc` does.
66
+ * Points (offsets with zero length) belong to the mapping they are listed in.
67
+ * Empty when the transform has a mapping whose verification is a `shouldReport`
68
+ * callback, which can't be serialized.
69
+ * @typedef {object} VerificationMapping
70
+ * @property {number[]} sourceOffsets
71
+ * @property {number[]} generatedOffsets
72
+ * @property {number[]} lengths
73
+ * @property {number[]} generatedLengths
74
+ * @property {{ verification: true }} data
75
+ */
76
+
60
77
  /**
61
78
  * @typedef {object} MapperDiagnostic
62
79
  * @property {number} start Offset into the original text (UTF-16 code units).
@@ -94,6 +111,7 @@ export const DiagnosticDirectivePolicy = /** @type {const} */ ({ Ignore: 0, Expe
94
111
  * diagnostics?: MapperDiagnostic[],
95
112
  * diagnosticDirectives?: DiagnosticDirectives,
96
113
  * supplemental?: MappedOutput[],
114
+ * verificationMappings?: VerificationMapping[],
97
115
  * }} TransformResult
98
116
  */
99
117