@tsrx/content-mapper 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.0",
4
+ "version": "0.1.2",
5
5
  "license": "MIT",
6
6
  "author": "Dominic Gannaway",
7
7
  "type": "module",
@@ -20,9 +20,9 @@
20
20
  ],
21
21
  "exports": {
22
22
  "./package.json": "./package.json",
23
- "./mapper": "./src/mapper.js",
24
- "./rpc": "./src/rpc.js",
25
- "./protocol": "./src/protocol.js"
23
+ "./mapper": "./dist/mapper.js",
24
+ "./rpc": "./dist/rpc.js",
25
+ "./protocol": "./dist/protocol.js"
26
26
  },
27
27
  "typescript": {
28
28
  "contentMapper": {
@@ -49,12 +49,12 @@
49
49
  "tsdown": "^0.23.0",
50
50
  "typescript": "^5.9.3",
51
51
  "vue": "3.6.0-beta.12",
52
- "@tsrx/core": "0.2.4",
53
- "@tsrx/solid": "0.2.4",
54
- "@tsrx/preact": "0.2.4",
55
- "@tsrx/typescript-plugin": "0.4.6",
56
- "@tsrx/vue": "0.2.4",
57
- "@tsrx/react": "0.3.4"
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"
58
58
  },
59
59
  "publishConfig": {
60
60
  "access": "public"
@@ -0,0 +1,199 @@
1
+ /** @import * as AST from 'estree' */
2
+ /** @import {CodeMapping, CompileError} from '@tsrx/core/types' */
3
+ /** @import {DiagnosticDirectives} from './protocol.js' */
4
+
5
+ import { DiagnosticDirectivePolicy } from './protocol.js';
6
+
7
+ /**
8
+ * The nodes whose generated code an error's directive covers: the innermost
9
+ * statement, declaration, class or type member, or element that holds the
10
+ * error.
11
+ */
12
+ const HOLDER_TYPE =
13
+ /(?:Statement|Declaration|Definition|Signature)$|^(?:StaticBlock|AccessorProperty|JSXElement|JSXFragment|JSXStyleElement)$/;
14
+
15
+ /** Keys of a tree node that hold no child nodes, or nodes that aren't its children. */
16
+ const NOT_CHILDREN = new Set([
17
+ 'metadata',
18
+ 'loc',
19
+ 'range',
20
+ 'parent',
21
+ 'comments',
22
+ 'leadingComments',
23
+ 'trailingComments',
24
+ ]);
25
+
26
+ /**
27
+ * An `ignore` directive for each error the mapper reports, so that a mistake
28
+ * shows once. TypeScript reports some mistakes itself from the generated code,
29
+ * with a code of its own, and would show them next to the mapper's error. The
30
+ * directive hides TypeScript's errors in the generated code of the statement,
31
+ * class or type member, or element that holds the error, until the error is
32
+ * fixed and the mapper stops sending it. The mapper's own errors are not
33
+ * TypeScript's, so they stay.
34
+ *
35
+ * The ranges come from what every TSRX compiler returns, whatever its target:
36
+ * the source tree (`sourceAst`) finds the node that holds an error, and the
37
+ * mappings give that node's generated code. Without a source tree the error's
38
+ * own span stands in. A node without mappings gets no directive.
39
+ * @param {readonly CompileError[]} errors
40
+ * @param {AST.Program | null} source_ast
41
+ * @param {readonly CodeMapping[]} mappings
42
+ * @param {number} original_length
43
+ * @param {number} generated_length
44
+ * @returns {DiagnosticDirectives | null}
45
+ */
46
+ export function ignore_directives(errors, source_ast, mappings, original_length, generated_length) {
47
+ /** @type {Array<[original_start: number, original_end: number, generated_start: number, generated_end: number]>} */
48
+ const ranges = [];
49
+ for (const error of errors) {
50
+ if (typeof error.pos !== 'number') {
51
+ continue;
52
+ }
53
+ const holder = source_ast ? holder_at(source_ast, error.pos) : null;
54
+ const start = holder ? /** @type {number} */ (holder.start) : error.pos;
55
+ const end = holder
56
+ ? /** @type {number} */ (holder.end)
57
+ : typeof error.end === 'number' && error.end > error.pos
58
+ ? error.end
59
+ : error.pos + 1;
60
+ for (const generated of generated_ranges(mappings, start, end)) {
61
+ ranges.push([
62
+ Math.min(start, original_length),
63
+ Math.min(end, original_length),
64
+ Math.min(generated[0], generated_length),
65
+ Math.min(generated[1], generated_length),
66
+ ]);
67
+ }
68
+ }
69
+ if (ranges.length === 0) {
70
+ return null;
71
+ }
72
+
73
+ // TypeScript rejects directives whose generated ranges overlap.
74
+ ranges.sort((a, b) => a[2] - b[2]);
75
+ /** @type {typeof ranges} */
76
+ const merged = [];
77
+ for (const range of ranges) {
78
+ const last = merged.at(-1);
79
+ if (last && range[2] < last[3]) {
80
+ last[0] = Math.min(last[0], range[0]);
81
+ last[1] = Math.max(last[1], range[1]);
82
+ last[3] = Math.max(last[3], range[3]);
83
+ } else {
84
+ merged.push([...range]);
85
+ }
86
+ }
87
+ return {
88
+ unusedExpectDirectiveDiagnostics: [],
89
+ directives: merged.map(([original_start, original_end, generated_start, generated_end]) => [
90
+ original_start,
91
+ original_end - original_start,
92
+ generated_start,
93
+ generated_end,
94
+ DiagnosticDirectivePolicy.Ignore,
95
+ ]),
96
+ };
97
+ }
98
+
99
+ /**
100
+ * The innermost holder node (see {@link HOLDER_TYPE}) that contains `position`,
101
+ * found by descending from the root through the child that contains it.
102
+ * @param {AST.Node} root
103
+ * @param {number} position
104
+ * @returns {AST.Node | null}
105
+ */
106
+ function holder_at(root, position) {
107
+ /** @type {AST.Node | null} */
108
+ let holder = null;
109
+ /** @type {AST.Node | null} */
110
+ let node = root;
111
+ while (node) {
112
+ if (HOLDER_TYPE.test(node.type)) {
113
+ holder = node;
114
+ }
115
+ node = child_at(node, position);
116
+ }
117
+ return holder;
118
+ }
119
+
120
+ /**
121
+ * @param {AST.Node} node
122
+ * @param {number} position
123
+ * @returns {AST.Node | null}
124
+ */
125
+ function child_at(node, position) {
126
+ for (const [key, value] of Object.entries(node)) {
127
+ if (NOT_CHILDREN.has(key) || !value || typeof value !== 'object') {
128
+ continue;
129
+ }
130
+ for (const child of Array.isArray(value) ? value : [value]) {
131
+ if (
132
+ child &&
133
+ typeof child.type === 'string' &&
134
+ typeof child.start === 'number' &&
135
+ typeof child.end === 'number' &&
136
+ child.start <= position &&
137
+ position < child.end
138
+ ) {
139
+ return child;
140
+ }
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+
146
+ /**
147
+ * The generated ranges of the mapped code between `start` and `end` in the
148
+ * original. A node's generated code need not be in one piece: a compiler can
149
+ * hoist part of it (a static element above the component), and a `<script>`
150
+ * body is checked as a block at the end of the file. So each range runs from
151
+ * the first to the last generated offset of the node's segments until code
152
+ * mapped from outside the node follows, and the next of its segments starts a
153
+ * new range; a range never covers another component's code. A segment of the
154
+ * same length on both sides that encloses the original range, as a verbatim
155
+ * `<script>` body does, gives the matching part of its generated text.
156
+ * @param {readonly CodeMapping[]} mappings
157
+ * @param {number} start
158
+ * @param {number} end
159
+ * @returns {Array<[number, number]>}
160
+ */
161
+ function generated_ranges(mappings, start, end) {
162
+ /** @type {Array<[generated_start: number, generated_end: number, inside: boolean]>} */
163
+ const segments = [];
164
+ for (const mapping of mappings) {
165
+ for (let i = 0; i < mapping.sourceOffsets.length; i++) {
166
+ const source = mapping.sourceOffsets[i];
167
+ const length = mapping.lengths[i];
168
+ const generated = mapping.generatedOffsets[i];
169
+ const generated_length = mapping.generatedLengths?.[i] ?? length;
170
+ if (source >= start && source + length <= end) {
171
+ segments.push([generated, generated + generated_length, true]);
172
+ } else if (source <= start && end <= source + length && generated_length === length) {
173
+ segments.push([generated + start - source, generated + end - source, true]);
174
+ } else {
175
+ segments.push([generated, generated + generated_length, false]);
176
+ }
177
+ }
178
+ }
179
+ segments.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
180
+ /** @type {Array<[number, number]>} */
181
+ const ranges = [];
182
+ /** @type {[number, number] | null} */
183
+ let range = null;
184
+ for (const [segment_start, segment_end, inside] of segments) {
185
+ if (inside) {
186
+ if (range) {
187
+ range[1] = Math.max(range[1], segment_end);
188
+ } else {
189
+ range = [segment_start, segment_end];
190
+ }
191
+ } else if (range && segment_start >= range[1]) {
192
+ // Code from elsewhere follows: the node's next segment starts a new range.
193
+ if (range[1] > range[0]) ranges.push(range);
194
+ range = null;
195
+ }
196
+ }
197
+ if (range && range[1] > range[0]) ranges.push(range);
198
+ return ranges;
199
+ }
@@ -4,9 +4,8 @@
4
4
  * Build a TypeScript stub that preserves a module's export surface while the
5
5
  * file cannot be compiled.
6
6
  *
7
- * The native content-mapper protocol offers no way to suppress TypeScript's
8
- * own diagnostics, so feeding raw TSRX (or the last good TSX, which may carry
9
- * type errors of its own) to the checker would produce noise. Instead every
7
+ * Raw TSRX, or the last good TSX (which may carry type errors of its own),
8
+ * would give the checker noise to report. Instead every
10
9
  * export from the last successful transform's source AST is re-declared as
11
10
  * `any` (both as a value and as a type, so `new X()`, `X.y` and `let v: X` all
12
11
  * keep resolving), re-exports from other modules are kept as written (including
@@ -27,7 +26,7 @@ export function build_export_stub(program) {
27
26
  for (const statement of program?.body ?? []) {
28
27
  switch (statement.type) {
29
28
  case 'ExportAllDeclaration': {
30
- const exported = statement.exported ? ` as ${export_name(statement.exported)}` : '';
29
+ const exported = statement.exported ? ` as ${print_name(statement.exported)}` : '';
31
30
  lines.push(
32
31
  `export ${type_modifier(statement)}*${exported} from ${JSON.stringify(String(statement.source.value))};`,
33
32
  );
@@ -40,8 +39,8 @@ export function build_export_stub(program) {
40
39
  if (statement.source) {
41
40
  const statement_is_type = type_modifier(statement) !== '';
42
41
  const specifiers = statement.specifiers.map((specifier) => {
43
- const local = export_name(specifier.local);
44
- const exported = export_name(specifier.exported);
42
+ const local = print_name(specifier.local);
43
+ const exported = print_name(specifier.exported);
45
44
  // `export type { A }` marks the statement; `export { type A }`
46
45
  // marks the specifier. Never write both.
47
46
  const modifier = statement_is_type ? '' : type_modifier(specifier);
@@ -69,10 +68,21 @@ export function build_export_stub(program) {
69
68
  }
70
69
  }
71
70
 
71
+ // A name no declaration can have (`null`, `if`, `string` for a type, an
72
+ // arbitrary module namespace name such as `"foo-bar"`) is exported from a
73
+ // local binding of another name.
74
+ let next_local = 0;
72
75
  for (const name of names) {
73
- if (!/^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u.test(name)) continue;
74
- lines.push(`export declare const ${name}: any;`);
75
- lines.push(`export type ${name} = any;`);
76
+ if (identifier_pattern.test(name) && !UNDECLARABLE_NAMES.has(name)) {
77
+ lines.push(`export declare const ${name}: any;`);
78
+ lines.push(`export type ${name} = any;`);
79
+ continue;
80
+ }
81
+ let local = `_$_export_${next_local++}`;
82
+ while (names.has(local)) local = `_$_export_${next_local++}`;
83
+ lines.push(`declare const ${local}: any;`);
84
+ lines.push(`type ${local} = any;`);
85
+ lines.push(`export { ${local} as ${module_export_name(name)} };`);
76
86
  }
77
87
  if (has_default) {
78
88
  lines.push('declare const _default: any;');
@@ -94,7 +104,79 @@ function type_modifier(node) {
94
104
  return /** @type {{ exportKind?: string }} */ (node).exportKind === 'type' ? 'type ' : '';
95
105
  }
96
106
 
107
+ const identifier_pattern = /^[\p{ID_Start}_$][\p{ID_Continue}$]*$/u;
108
+
109
+ /**
110
+ * Identifier names that `export declare const x: any; export type x = any;`
111
+ * can't declare in a module: reserved words (TS1389), words reserved in strict
112
+ * mode (TS1214), `await`, `let`, `arguments` and `eval`, the names of
113
+ * TypeScript's own types (TS2457), and `as`, which `export type as` misreads.
114
+ */
115
+ const UNDECLARABLE_NAMES = new Set([
116
+ 'break',
117
+ 'case',
118
+ 'catch',
119
+ 'class',
120
+ 'const',
121
+ 'continue',
122
+ 'debugger',
123
+ 'default',
124
+ 'delete',
125
+ 'do',
126
+ 'else',
127
+ 'enum',
128
+ 'export',
129
+ 'extends',
130
+ 'false',
131
+ 'finally',
132
+ 'for',
133
+ 'function',
134
+ 'if',
135
+ 'import',
136
+ 'in',
137
+ 'instanceof',
138
+ 'new',
139
+ 'null',
140
+ 'return',
141
+ 'super',
142
+ 'switch',
143
+ 'this',
144
+ 'throw',
145
+ 'true',
146
+ 'try',
147
+ 'typeof',
148
+ 'var',
149
+ 'void',
150
+ 'while',
151
+ 'with',
152
+ 'implements',
153
+ 'interface',
154
+ 'package',
155
+ 'private',
156
+ 'protected',
157
+ 'public',
158
+ 'static',
159
+ 'yield',
160
+ 'await',
161
+ 'let',
162
+ 'arguments',
163
+ 'eval',
164
+ 'any',
165
+ 'bigint',
166
+ 'boolean',
167
+ 'never',
168
+ 'number',
169
+ 'object',
170
+ 'string',
171
+ 'symbol',
172
+ 'undefined',
173
+ 'unknown',
174
+ 'as',
175
+ ]);
176
+
97
177
  /**
178
+ * The name an export binds, as a plain string: `a` for `export { a }` and
179
+ * `foo-bar` for `export { "foo-bar" as a } from`.
98
180
  * @param {AST.Identifier | AST.Literal | AST.Expression} node
99
181
  * @returns {string}
100
182
  */
@@ -104,6 +186,27 @@ function export_name(node) {
104
186
  return '';
105
187
  }
106
188
 
189
+ /**
190
+ * The name as it must be written back in a re-export: an identifier as is, an
191
+ * arbitrary module namespace name (`export { "foo-bar" as a } from`,
192
+ * `export * as "ns-name" from`) quoted, so the stub stays valid TypeScript.
193
+ * @param {AST.Identifier | AST.Literal | AST.Expression} node
194
+ * @returns {string}
195
+ */
196
+ function print_name(node) {
197
+ return module_export_name(export_name(node));
198
+ }
199
+
200
+ /**
201
+ * A name as an export specifier takes it: any identifier name, reserved words
202
+ * too, as is, and anything else quoted.
203
+ * @param {string} name
204
+ * @returns {string}
205
+ */
206
+ function module_export_name(name) {
207
+ return identifier_pattern.test(name) ? name : JSON.stringify(name);
208
+ }
209
+
107
210
  /**
108
211
  * @param {AST.Declaration | AST.Node} declaration
109
212
  * @returns {string[]}
package/src/mapper.js CHANGED
@@ -16,14 +16,9 @@ import {
16
16
  source_uses_platform_flag,
17
17
  } from '@tsrx/typescript-plugin/src/language.js';
18
18
  import { transform_tsrx } from '@tsrx/typescript-plugin/src/transform.js';
19
+ import { DIAGNOSTIC_SOURCE, MAPPER_CODES, TYPESCRIPT_CODE_PREFIX } from '@tsrx/core/diagnostics';
20
+ import { ignore_directives } from './diagnostic-directives.js';
19
21
  import { build_export_stub } from './export-stub.js';
20
- import {
21
- DIAGNOSTIC_CODE_COMPILE_ERROR,
22
- DIAGNOSTIC_CODE_INVALID_CONFIG,
23
- DIAGNOSTIC_CODE_NO_COMPILER,
24
- DIAGNOSTIC_CODE_USAGE_ERROR,
25
- DIAGNOSTIC_SOURCE,
26
- } from './protocol.js';
27
22
  import { to_span_mappings } from './span-mappings.js';
28
23
 
29
24
  const require = createRequire(import.meta.url);
@@ -136,7 +131,7 @@ export function create_tsrx_content_mapper(context = {}) {
136
131
  return failure(state, file_name, content, {
137
132
  start: 0,
138
133
  length: 0,
139
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
134
+ code: MAPPER_CODES.INVALID_CONFIG,
140
135
  messageText: error_message(error),
141
136
  });
142
137
  }
@@ -144,7 +139,7 @@ export function create_tsrx_content_mapper(context = {}) {
144
139
  return failure(state, file_name, content, {
145
140
  start: 0,
146
141
  length: 0,
147
- code: DIAGNOSTIC_CODE_NO_COMPILER,
142
+ code: MAPPER_CODES.NO_COMPILER,
148
143
  messageText:
149
144
  `No TSRX compiler found for ${file_name}. Install a target compiler ` +
150
145
  '(for example @tsrx/react) next to the project, or select one with ' +
@@ -168,18 +163,20 @@ export function create_tsrx_content_mapper(context = {}) {
168
163
  return failure(state, file_name, content, {
169
164
  start: 0,
170
165
  length: 0,
171
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
166
+ code: MAPPER_CODES.INVALID_CONFIG,
172
167
  messageText: error_message(error),
173
168
  });
174
169
  }
175
170
 
176
171
  const result = transform_tsrx(compiler, file_name, content, { platform });
177
172
  if (result.fatalError) {
173
+ // The file has no generated code for TypeScript to check, so the error
174
+ // goes to TypeScript whatever its code.
178
175
  return failure(
179
176
  state,
180
177
  file_name,
181
178
  content,
182
- to_diagnostic(result.fatalError, content.length, DIAGNOSTIC_CODE_COMPILE_ERROR),
179
+ to_diagnostic(result.fatalError, content.length, MAPPER_CODES.COMPILE_ERROR),
183
180
  );
184
181
  }
185
182
  if (result.sourceAst) {
@@ -190,14 +187,26 @@ export function create_tsrx_content_mapper(context = {}) {
190
187
  const mappings = to_span_mappings(result.mappings, result.text, content, {
191
188
  languageFeatures: language_features,
192
189
  });
190
+ // Every error goes to TypeScript, even one with a TypeScript code: the
191
+ // generated code can lose the mistake (a repeated modifier, a rest
192
+ // parameter's `?`), and then TypeScript never reports it. Where TypeScript
193
+ // does, the directives hide its copy until the mapper's error is fixed.
193
194
  const diagnostics = result.errors.map((error) =>
194
- to_diagnostic(error, content.length, DIAGNOSTIC_CODE_USAGE_ERROR),
195
+ to_diagnostic(error, content.length, MAPPER_CODES.USAGE_ERROR),
196
+ );
197
+ const diagnosticDirectives = ignore_directives(
198
+ result.errors,
199
+ result.sourceAst,
200
+ result.mappings,
201
+ content.length,
202
+ result.text.length,
195
203
  );
196
204
  return {
197
205
  text: result.text,
198
206
  extension: '.tsx',
199
207
  mappings,
200
208
  ...(diagnostics.length > 0 ? { diagnostics } : null),
209
+ ...(diagnosticDirectives ? { diagnosticDirectives } : null),
201
210
  };
202
211
  }
203
212
 
@@ -337,7 +346,7 @@ export function validate_options(raw) {
337
346
  optionDiagnostics.push({
338
347
  path: [],
339
348
  messageText: 'Content mapper options must be an object.',
340
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
349
+ code: MAPPER_CODES.INVALID_CONFIG,
341
350
  });
342
351
  return { options, optionDiagnostics };
343
352
  }
@@ -352,7 +361,7 @@ export function validate_options(raw) {
352
361
  optionDiagnostics.push({
353
362
  path: [key],
354
363
  messageText: '"compiler" must be a bare package specifier such as "@tsrx/react".',
355
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
364
+ code: MAPPER_CODES.INVALID_CONFIG,
356
365
  });
357
366
  }
358
367
  break;
@@ -363,7 +372,7 @@ export function validate_options(raw) {
363
372
  optionDiagnostics.push({
364
373
  path: [key],
365
374
  messageText: '"platform" must be "web", "ios", or "android".',
366
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
375
+ code: MAPPER_CODES.INVALID_CONFIG,
367
376
  });
368
377
  }
369
378
  break;
@@ -374,7 +383,7 @@ export function validate_options(raw) {
374
383
  optionDiagnostics.push({
375
384
  path: [key],
376
385
  messageText: '"languageFeatures" must be a boolean.',
377
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
386
+ code: MAPPER_CODES.INVALID_CONFIG,
378
387
  });
379
388
  }
380
389
  break;
@@ -382,17 +391,23 @@ export function validate_options(raw) {
382
391
  optionDiagnostics.push({
383
392
  path: [key],
384
393
  messageText: `Unknown content mapper option "${key}".`,
385
- code: DIAGNOSTIC_CODE_INVALID_CONFIG,
394
+ code: MAPPER_CODES.INVALID_CONFIG,
386
395
  });
387
396
  }
388
397
  }
389
398
  return { options, optionDiagnostics };
390
399
  }
391
400
 
401
+ const TSRX_CODE = /^TSRX(\d+)$/;
402
+ const TYPESCRIPT_CODE = /^TS(\d+)$/;
403
+
392
404
  /**
393
405
  * Translate a compiler `CompileError` into a mapper diagnostic in original
394
- * offsets. Coded errors keep their string code in the message and derive a
395
- * stable numeric code from it; uncoded ones use `fallback_code`.
406
+ * offsets. TypeScript shows the mapper's diagnostics as `TSRX<number>`, so a
407
+ * TSRX code goes as its number (`TSRX2002` → `2002`) and a TypeScript code as
408
+ * `TYPESCRIPT_CODE_PREFIX` then its number (`TS1005` → `111005`), which keeps
409
+ * the code in the message too. An error without either uses `fallback_code`
410
+ * and keeps any other code in the message.
396
411
  * @param {CompileError} error
397
412
  * @param {number} content_length
398
413
  * @param {number} fallback_code
@@ -401,37 +416,25 @@ export function validate_options(raw) {
401
416
  export function to_diagnostic(error, content_length, fallback_code) {
402
417
  const start = typeof error.pos === 'number' ? error.pos : 0;
403
418
  const end = typeof error.end === 'number' && error.end > start ? error.end : start + 1;
404
- const code =
405
- typeof error.code === 'string' && error.code ? numeric_code(error.code) : fallback_code;
419
+ const code = typeof error.code === 'string' ? error.code : '';
420
+ const tsrx = TSRX_CODE.exec(code);
421
+ const typescript = TYPESCRIPT_CODE.exec(code);
406
422
  const message = String(error.message ?? error);
407
423
  return clamp_diagnostic(
408
424
  {
409
425
  start,
410
426
  length: end - start,
411
- code,
412
- messageText:
413
- typeof error.code === 'string' && error.code ? `${message} [${error.code}]` : message,
427
+ code: tsrx
428
+ ? Number(tsrx[1])
429
+ : typescript
430
+ ? Number(`${TYPESCRIPT_CODE_PREFIX}${typescript[1]}`)
431
+ : fallback_code,
432
+ messageText: code && !tsrx ? `${message} [${code}]` : message,
414
433
  },
415
434
  content_length,
416
435
  );
417
436
  }
418
437
 
419
- /**
420
- * Stable numeric code for a TSRX string diagnostic code (FNV-1a 32-bit,
421
- * folded into the 10000..99999 range so it never collides with the fixed
422
- * codes below 10000).
423
- * @param {string} code
424
- * @returns {number}
425
- */
426
- export function numeric_code(code) {
427
- let hash = 0x811c9dc5;
428
- for (let index = 0; index < code.length; index++) {
429
- hash ^= code.charCodeAt(index);
430
- hash = Math.imul(hash, 0x01000193);
431
- }
432
- return 10000 + ((hash >>> 0) % 90000);
433
- }
434
-
435
438
  /**
436
439
  * @param {MapperDiagnostic} diagnostic
437
440
  * @param {number} content_length
package/src/protocol.js CHANGED
@@ -39,21 +39,13 @@ export const SpanMapFeature = /** @type {const} */ ({
39
39
  All: (1 << 20) - 1,
40
40
  });
41
41
 
42
- /** Diagnostic-directive policies (unused by TSRX today; kept for completeness). */
42
+ /**
43
+ * Diagnostic-directive policies: `Ignore` hides TypeScript's errors in a
44
+ * generated range; `Expect` also reports a diagnostic of the mapper's when
45
+ * there are none there.
46
+ */
43
47
  export const DiagnosticDirectivePolicy = /** @type {const} */ ({ Ignore: 0, Expect: 1 });
44
48
 
45
- /** Prefix for mapper-authored diagnostics: `error tsrx(1000): ...`. */
46
- export const DIAGNOSTIC_SOURCE = 'tsrx';
47
-
48
- /** Numeric code for a fatal compile error (the file could not be transformed). */
49
- export const DIAGNOSTIC_CODE_COMPILE_ERROR = 1000;
50
- /** Numeric code for a usage error that carries no string code. */
51
- export const DIAGNOSTIC_CODE_USAGE_ERROR = 1001;
52
- /** Numeric code when no TSRX compiler can be resolved for a file. */
53
- export const DIAGNOSTIC_CODE_NO_COMPILER = 1002;
54
- /** Numeric code when the project's TSRX configuration is invalid. */
55
- export const DIAGNOSTIC_CODE_INVALID_CONFIG = 1003;
56
-
57
49
  /**
58
50
  * @typedef {[
59
51
  * generatedStart: number,
@@ -80,9 +72,27 @@ export const DIAGNOSTIC_CODE_INVALID_CONFIG = 1003;
80
72
  * @property {SpanMapping[]} mappings
81
73
  */
82
74
 
75
+ /**
76
+ * @typedef {[
77
+ * originalStart: number,
78
+ * originalLength: number,
79
+ * generatedStart: number,
80
+ * generatedEnd: number,
81
+ * policy: 0 | 1,
82
+ * unusedExpectDirectiveIndex?: number,
83
+ * ]} DiagnosticDirective
84
+ */
85
+
86
+ /**
87
+ * @typedef {object} DiagnosticDirectives
88
+ * @property {Array<{ code: number, messageText: string }>} unusedExpectDirectiveDiagnostics What an `Expect` directive reports when TypeScript has no error in its range.
89
+ * @property {DiagnosticDirective[]} directives
90
+ */
91
+
83
92
  /**
84
93
  * @typedef {MappedOutput & {
85
94
  * diagnostics?: MapperDiagnostic[],
95
+ * diagnosticDirectives?: DiagnosticDirectives,
86
96
  * supplemental?: MappedOutput[],
87
97
  * }} TransformResult
88
98
  */
package/src/rpc.js CHANGED
@@ -9,6 +9,8 @@
9
9
  * it from their own entry file.
10
10
  */
11
11
 
12
+ import { Console } from 'node:console';
13
+
12
14
  /**
13
15
  * @typedef {{ jsonrpc: '2.0', id?: number | string | null, method: string, params?: unknown }} RequestMessage
14
16
  */
@@ -119,8 +121,15 @@ export function run_mapper_server(mapper, streams = {}) {
119
121
 
120
122
  /**
121
123
  * Route every console method to stderr so stray logging (from a target
122
- * compiler, for example) can never corrupt the protocol stream on stdout.
124
+ * compiler, for example) can never corrupt the protocol stream on stdout: not
125
+ * only `log` but `dir`, `table`, `trace`, `group` and the rest write there, so
126
+ * each takes the method of a console whose stdout is stderr.
123
127
  */
124
128
  export function redirect_console_to_stderr() {
125
- console.log = console.info = console.warn = console.debug = (...args) => console.error(...args);
129
+ const to_stderr = new Console({ stdout: process.stderr, stderr: process.stderr });
130
+ for (const [name, method] of Object.entries(to_stderr)) {
131
+ if (typeof method === 'function') {
132
+ /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (console))[name] = method;
133
+ }
134
+ }
126
135
  }