@tsrx/content-mapper 0.1.0
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/LICENSE +21 -0
- package/README.md +287 -0
- package/dist/server.js +3328 -0
- package/dist/server.js.map +1 -0
- package/package.json +65 -0
- package/src/export-stub.js +150 -0
- package/src/mapper.js +473 -0
- package/src/protocol.js +122 -0
- package/src/rpc.js +126 -0
- package/src/server.js +11 -0
- package/src/span-mappings.js +370 -0
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tsrx/content-mapper",
|
|
3
|
+
"description": "TypeScript 7 content mapper for .tsrx files",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Dominic Gannaway",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"homepage": "https://tsrx.dev/",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/tsrx-org/tsrx.git",
|
|
12
|
+
"directory": "packages/content-mapper"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/tsrx-org/tsrx/issues"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
"./package.json": "./package.json",
|
|
23
|
+
"./mapper": "./src/mapper.js",
|
|
24
|
+
"./rpc": "./src/rpc.js",
|
|
25
|
+
"./protocol": "./src/protocol.js"
|
|
26
|
+
},
|
|
27
|
+
"typescript": {
|
|
28
|
+
"contentMapper": {
|
|
29
|
+
"exec": [
|
|
30
|
+
"node",
|
|
31
|
+
"dist/server.js"
|
|
32
|
+
],
|
|
33
|
+
"dynamicConfig": true
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"jsonc-parser": "^3.3.1"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@solidjs/web": "2.0.0-rc.3",
|
|
41
|
+
"@tsrx/ripple": "^0.2.0",
|
|
42
|
+
"@types/estree": "^1.0.8",
|
|
43
|
+
"@types/node": "^24.3.0",
|
|
44
|
+
"@types/react": "^19.2.2",
|
|
45
|
+
"preact": "^10.27.0",
|
|
46
|
+
"react": "^19.2.0",
|
|
47
|
+
"ripple": "^0.4.0",
|
|
48
|
+
"solid-js": "2.0.0-rc.3",
|
|
49
|
+
"tsdown": "^0.23.0",
|
|
50
|
+
"typescript": "^5.9.3",
|
|
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"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsdown"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/** @import * as AST from 'estree' */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Build a TypeScript stub that preserves a module's export surface while the
|
|
5
|
+
* file cannot be compiled.
|
|
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
|
|
10
|
+
* export from the last successful transform's source AST is re-declared as
|
|
11
|
+
* `any` (both as a value and as a type, so `new X()`, `X.y` and `let v: X` all
|
|
12
|
+
* keep resolving), re-exports from other modules are kept as written (including
|
|
13
|
+
* their `type` modifiers, so `isolatedModules` and `verbatimModuleSyntax` do
|
|
14
|
+
* not reject the stub), and the compile error is reported through the mapper's
|
|
15
|
+
* own diagnostics. Importers keep resolving; the author sees one error at the
|
|
16
|
+
* right place.
|
|
17
|
+
* @param {AST.Program | null | undefined} program The last successfully parsed source AST, if any.
|
|
18
|
+
* @returns {string}
|
|
19
|
+
*/
|
|
20
|
+
export function build_export_stub(program) {
|
|
21
|
+
/** @type {string[]} */
|
|
22
|
+
const lines = [];
|
|
23
|
+
/** @type {Set<string>} */
|
|
24
|
+
const names = new Set();
|
|
25
|
+
let has_default = false;
|
|
26
|
+
|
|
27
|
+
for (const statement of program?.body ?? []) {
|
|
28
|
+
switch (statement.type) {
|
|
29
|
+
case 'ExportAllDeclaration': {
|
|
30
|
+
const exported = statement.exported ? ` as ${export_name(statement.exported)}` : '';
|
|
31
|
+
lines.push(
|
|
32
|
+
`export ${type_modifier(statement)}*${exported} from ${JSON.stringify(String(statement.source.value))};`,
|
|
33
|
+
);
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
case 'ExportDefaultDeclaration':
|
|
37
|
+
has_default = true;
|
|
38
|
+
break;
|
|
39
|
+
case 'ExportNamedDeclaration': {
|
|
40
|
+
if (statement.source) {
|
|
41
|
+
const statement_is_type = type_modifier(statement) !== '';
|
|
42
|
+
const specifiers = statement.specifiers.map((specifier) => {
|
|
43
|
+
const local = export_name(specifier.local);
|
|
44
|
+
const exported = export_name(specifier.exported);
|
|
45
|
+
// `export type { A }` marks the statement; `export { type A }`
|
|
46
|
+
// marks the specifier. Never write both.
|
|
47
|
+
const modifier = statement_is_type ? '' : type_modifier(specifier);
|
|
48
|
+
return `${modifier}${local === exported ? local : `${local} as ${exported}`}`;
|
|
49
|
+
});
|
|
50
|
+
lines.push(
|
|
51
|
+
`export ${type_modifier(statement)}{ ${specifiers.join(', ')} } from ${JSON.stringify(String(statement.source.value))};`,
|
|
52
|
+
);
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
for (const specifier of statement.specifiers) {
|
|
56
|
+
const exported = export_name(specifier.exported);
|
|
57
|
+
if (exported === 'default') has_default = true;
|
|
58
|
+
else names.add(exported);
|
|
59
|
+
}
|
|
60
|
+
if (statement.declaration) {
|
|
61
|
+
for (const name of declaration_names(statement.declaration)) {
|
|
62
|
+
names.add(name);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
default:
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
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
|
+
}
|
|
77
|
+
if (has_default) {
|
|
78
|
+
lines.push('declare const _default: any;');
|
|
79
|
+
lines.push('export default _default;');
|
|
80
|
+
}
|
|
81
|
+
if (lines.length === 0) {
|
|
82
|
+
lines.push('export {};');
|
|
83
|
+
}
|
|
84
|
+
return lines.join('\n') + '\n';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* `type ` for a type-only export statement or specifier (the ESTree-TS
|
|
89
|
+
* `exportKind` field), else the empty string.
|
|
90
|
+
* @param {AST.Node} node
|
|
91
|
+
* @returns {'type ' | ''}
|
|
92
|
+
*/
|
|
93
|
+
function type_modifier(node) {
|
|
94
|
+
return /** @type {{ exportKind?: string }} */ (node).exportKind === 'type' ? 'type ' : '';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @param {AST.Identifier | AST.Literal | AST.Expression} node
|
|
99
|
+
* @returns {string}
|
|
100
|
+
*/
|
|
101
|
+
function export_name(node) {
|
|
102
|
+
if (node.type === 'Identifier') return node.name;
|
|
103
|
+
if (node.type === 'Literal') return String(node.value);
|
|
104
|
+
return '';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {AST.Declaration | AST.Node} declaration
|
|
109
|
+
* @returns {string[]}
|
|
110
|
+
*/
|
|
111
|
+
function declaration_names(declaration) {
|
|
112
|
+
switch (declaration.type) {
|
|
113
|
+
case 'VariableDeclaration':
|
|
114
|
+
return declaration.declarations.flatMap((declarator) => pattern_names(declarator.id));
|
|
115
|
+
case 'FunctionDeclaration':
|
|
116
|
+
case 'ClassDeclaration':
|
|
117
|
+
return declaration.id ? [declaration.id.name] : [];
|
|
118
|
+
default: {
|
|
119
|
+
// TypeScript declarations (interface, type alias, enum, module) all
|
|
120
|
+
// carry an `id` identifier in the ESTree-TS shape.
|
|
121
|
+
const id = /** @type {{ id?: AST.Node }} */ (declaration).id;
|
|
122
|
+
return id && id.type === 'Identifier' ? [/** @type {AST.Identifier} */ (id).name] : [];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* @param {AST.Pattern} pattern
|
|
129
|
+
* @returns {string[]}
|
|
130
|
+
*/
|
|
131
|
+
function pattern_names(pattern) {
|
|
132
|
+
switch (pattern.type) {
|
|
133
|
+
case 'Identifier':
|
|
134
|
+
return [pattern.name];
|
|
135
|
+
case 'ObjectPattern':
|
|
136
|
+
return pattern.properties.flatMap((property) =>
|
|
137
|
+
property.type === 'RestElement'
|
|
138
|
+
? pattern_names(property.argument)
|
|
139
|
+
: pattern_names(property.value),
|
|
140
|
+
);
|
|
141
|
+
case 'ArrayPattern':
|
|
142
|
+
return pattern.elements.flatMap((element) => (element ? pattern_names(element) : []));
|
|
143
|
+
case 'RestElement':
|
|
144
|
+
return pattern_names(pattern.argument);
|
|
145
|
+
case 'AssignmentPattern':
|
|
146
|
+
return pattern_names(pattern.left);
|
|
147
|
+
default:
|
|
148
|
+
return [];
|
|
149
|
+
}
|
|
150
|
+
}
|
package/src/mapper.js
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
/** @import * as AST from 'estree' */
|
|
2
|
+
/** @import {CompileError} from '@tsrx/core/types' */
|
|
3
|
+
/** @import {InitializeParams, InitializeResult, OpenProjectParams, OpenProjectResult, TransformParams, TransformResult, MapperDiagnostic} from './protocol.js' */
|
|
4
|
+
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { NODE_CONFIG_HOST } from '@tsrx/typescript-plugin/src/config-host.js';
|
|
10
|
+
import { resolve_consumer_platform_for_file } from '@tsrx/typescript-plugin/src/consumer-compiler.js';
|
|
11
|
+
import { resolve_package_entry } from '@tsrx/typescript-plugin/src/package-resolution.js';
|
|
12
|
+
import {
|
|
13
|
+
get_compiler_entry_for_file,
|
|
14
|
+
invalidateCompilerResolutionCaches,
|
|
15
|
+
require_tsrx_compiler,
|
|
16
|
+
source_uses_platform_flag,
|
|
17
|
+
} from '@tsrx/typescript-plugin/src/language.js';
|
|
18
|
+
import { transform_tsrx } from '@tsrx/typescript-plugin/src/transform.js';
|
|
19
|
+
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
|
+
import { to_span_mappings } from './span-mappings.js';
|
|
28
|
+
|
|
29
|
+
const require = createRequire(import.meta.url);
|
|
30
|
+
const bare_package_specifier_pattern =
|
|
31
|
+
/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:\/[A-Za-z0-9][A-Za-z0-9._~-]*)*$/;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The mapper entry's `options` object in tsconfig (`contentMappers[].options`)
|
|
35
|
+
* or in an inferred-project contribution.
|
|
36
|
+
* @typedef {object} MapperOptions
|
|
37
|
+
* @property {string} [compiler] Bare package specifier of the TSRX compiler. Takes precedence over `tsrx.compiler` in the tsconfig chain.
|
|
38
|
+
* @property {'web' | 'ios' | 'android'} [platform] Platform for `import.meta.env.platform` flags. Takes precedence over `tsrx.platform`.
|
|
39
|
+
* @property {boolean} [languageFeatures] `false` clears every editor feature bit while keeping spans for diagnostics (CLI-only projects).
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @typedef {object} ProjectState
|
|
44
|
+
* @property {string | undefined} configFileName
|
|
45
|
+
* @property {MapperOptions} options
|
|
46
|
+
* @property {Set<string>} dependencies Files whose content affects transform output.
|
|
47
|
+
* @property {Map<string, AST.Program>} lastGood Last successfully parsed source AST per file, for the compile-failure stub. Shared by every project state of a mapper (see {@link create_tsrx_content_mapper}).
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} ContentMapper
|
|
52
|
+
* @property {(params: InitializeParams) => InitializeResult} initialize
|
|
53
|
+
* @property {(params: OpenProjectParams) => OpenProjectResult} openProject
|
|
54
|
+
* @property {(params: { projectHandle: string }) => void} closeProject
|
|
55
|
+
* @property {(params: TransformParams) => TransformResult} transform
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Create the `.tsrx` content mapper. Each `projectHandle` owns its own state;
|
|
60
|
+
* nothing is shared between projects except the process-wide compiler
|
|
61
|
+
* resolution caches, which are keyed by directory and reset on every
|
|
62
|
+
* `openProject`, and the last successfully parsed AST per file. The latter is
|
|
63
|
+
* keyed by file name and independent of the project, and TypeScript reopens a
|
|
64
|
+
* project (same or new handle) whenever its identity or a watched file
|
|
65
|
+
* changes, so keeping it at the mapper level is what lets a file that still
|
|
66
|
+
* fails to compile keep its export stub across a reopen.
|
|
67
|
+
* The mapper needs no TypeScript of its own: tsconfig files are read and
|
|
68
|
+
* compilers resolved through `@tsrx/typescript-plugin`'s own reader and
|
|
69
|
+
* package walk, so the native compiler's `typescript` package (which has no
|
|
70
|
+
* JavaScript API) can be the only TypeScript in a project.
|
|
71
|
+
* @param {{ host?: import('@tsrx/typescript-plugin/src/config-host.js').ConfigHost }} [context]
|
|
72
|
+
* @returns {ContentMapper}
|
|
73
|
+
*/
|
|
74
|
+
export function create_tsrx_content_mapper(context = {}) {
|
|
75
|
+
const host = context.host ?? NODE_CONFIG_HOST;
|
|
76
|
+
/** @type {Map<string, ProjectState>} */
|
|
77
|
+
const projects = new Map();
|
|
78
|
+
/** @type {Map<string, AST.Program>} */
|
|
79
|
+
const last_good = new Map();
|
|
80
|
+
/** Transforms that arrive without a project handle. */
|
|
81
|
+
const standalone = create_project_state(undefined, {});
|
|
82
|
+
|
|
83
|
+
/** @type {ContentMapper['initialize']} */
|
|
84
|
+
function initialize(params) {
|
|
85
|
+
if (!params.positionEncodings?.includes('utf-16')) {
|
|
86
|
+
throw new Error('@tsrx/content-mapper requires UTF-16 position encoding');
|
|
87
|
+
}
|
|
88
|
+
return { positionEncoding: 'utf-16', diagnosticSource: DIAGNOSTIC_SOURCE };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @type {ContentMapper['openProject']} */
|
|
92
|
+
function openProject(params) {
|
|
93
|
+
// TypeScript reopens a project when its identity or a watched file
|
|
94
|
+
// changes, which is exactly when directory-keyed discovery caches
|
|
95
|
+
// (installed compilers, package manifests) may be stale.
|
|
96
|
+
invalidateCompilerResolutionCaches();
|
|
97
|
+
const { options, optionDiagnostics } = validate_options(params.options);
|
|
98
|
+
const state = create_project_state(params.configFileName || undefined, options);
|
|
99
|
+
projects.set(params.projectHandle, state);
|
|
100
|
+
|
|
101
|
+
// Resolve the compiler once up front so the tsconfig chain and the
|
|
102
|
+
// compiler manifest are known and can be watched.
|
|
103
|
+
try {
|
|
104
|
+
resolve_compiler(state, probe_file_name(state));
|
|
105
|
+
} catch {
|
|
106
|
+
// Reported per file at transform time.
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const watchedFiles = [...state.dependencies].sort();
|
|
110
|
+
return {
|
|
111
|
+
configIdentity: compute_identity(state, watchedFiles),
|
|
112
|
+
watchedFiles,
|
|
113
|
+
...(optionDiagnostics.length > 0 ? { optionDiagnostics } : null),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** @type {ContentMapper['closeProject']} */
|
|
118
|
+
function closeProject(params) {
|
|
119
|
+
projects.delete(params.projectHandle);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** @type {ContentMapper['transform']} */
|
|
123
|
+
function transform(params) {
|
|
124
|
+
const state = params.projectHandle ? projects.get(params.projectHandle) : standalone;
|
|
125
|
+
if (!state) {
|
|
126
|
+
throw new Error(`Unknown @tsrx/content-mapper project handle: ${params.projectHandle}`);
|
|
127
|
+
}
|
|
128
|
+
const file_name = params.fileName.replace(/\\/g, '/');
|
|
129
|
+
const content = params.content;
|
|
130
|
+
|
|
131
|
+
/** @type {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null} */
|
|
132
|
+
let compiler;
|
|
133
|
+
try {
|
|
134
|
+
compiler = resolve_compiler(state, file_name);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return failure(state, file_name, content, {
|
|
137
|
+
start: 0,
|
|
138
|
+
length: 0,
|
|
139
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
140
|
+
messageText: error_message(error),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (!compiler) {
|
|
144
|
+
return failure(state, file_name, content, {
|
|
145
|
+
start: 0,
|
|
146
|
+
length: 0,
|
|
147
|
+
code: DIAGNOSTIC_CODE_NO_COMPILER,
|
|
148
|
+
messageText:
|
|
149
|
+
`No TSRX compiler found for ${file_name}. Install a target compiler ` +
|
|
150
|
+
'(for example @tsrx/react) next to the project, or select one with ' +
|
|
151
|
+
'"tsrx": { "compiler": "<package>" } in tsconfig.json or ' +
|
|
152
|
+
'"options": { "compiler": "<package>" } on the content mapper entry.',
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** @type {'web' | 'ios' | 'android' | undefined} */
|
|
157
|
+
let platform;
|
|
158
|
+
try {
|
|
159
|
+
platform =
|
|
160
|
+
state.options.platform ??
|
|
161
|
+
resolve_consumer_platform_for_file(file_name, {
|
|
162
|
+
configFileName: state.configFileName,
|
|
163
|
+
configHost: host,
|
|
164
|
+
dependencies: state.dependencies,
|
|
165
|
+
requirePlatformResolution: source_uses_platform_flag(content),
|
|
166
|
+
});
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return failure(state, file_name, content, {
|
|
169
|
+
start: 0,
|
|
170
|
+
length: 0,
|
|
171
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
172
|
+
messageText: error_message(error),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const result = transform_tsrx(compiler, file_name, content, { platform });
|
|
177
|
+
if (result.fatalError) {
|
|
178
|
+
return failure(
|
|
179
|
+
state,
|
|
180
|
+
file_name,
|
|
181
|
+
content,
|
|
182
|
+
to_diagnostic(result.fatalError, content.length, DIAGNOSTIC_CODE_COMPILE_ERROR),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
if (result.sourceAst) {
|
|
186
|
+
state.lastGood.set(file_name, result.sourceAst);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const language_features = state.options.languageFeatures !== false;
|
|
190
|
+
const mappings = to_span_mappings(result.mappings, result.text, content, {
|
|
191
|
+
languageFeatures: language_features,
|
|
192
|
+
});
|
|
193
|
+
const diagnostics = result.errors.map((error) =>
|
|
194
|
+
to_diagnostic(error, content.length, DIAGNOSTIC_CODE_USAGE_ERROR),
|
|
195
|
+
);
|
|
196
|
+
return {
|
|
197
|
+
text: result.text,
|
|
198
|
+
extension: '.tsx',
|
|
199
|
+
mappings,
|
|
200
|
+
...(diagnostics.length > 0 ? { diagnostics } : null),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* @param {string | undefined} config_file_name
|
|
206
|
+
* @param {MapperOptions} options
|
|
207
|
+
* @returns {ProjectState}
|
|
208
|
+
*/
|
|
209
|
+
function create_project_state(config_file_name, options) {
|
|
210
|
+
return {
|
|
211
|
+
configFileName: config_file_name ? path.normalize(config_file_name) : undefined,
|
|
212
|
+
options,
|
|
213
|
+
dependencies: new Set(),
|
|
214
|
+
lastGood: last_good,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A `.tsrx` path inside the project directory, used to drive compiler
|
|
220
|
+
* resolution before any real file is transformed.
|
|
221
|
+
* @param {ProjectState} state
|
|
222
|
+
*/
|
|
223
|
+
function probe_file_name(state) {
|
|
224
|
+
const dir = state.configFileName ? path.dirname(state.configFileName) : process.cwd();
|
|
225
|
+
return path.join(dir, '__tsrx_content_mapper_probe__.tsrx').replace(/\\/g, '/');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Precedence: the mapper entry's `options.compiler` wins over `tsrx.compiler`
|
|
230
|
+
* in the tsconfig chain, which wins over auto-detection of an installed
|
|
231
|
+
* target compiler. Whatever is found, its `package.json` joins the watched
|
|
232
|
+
* files so a compiler upgrade invalidates the project.
|
|
233
|
+
* @param {ProjectState} state
|
|
234
|
+
* @param {string} file_name
|
|
235
|
+
* @returns {import('@tsrx/typescript-plugin/src/transform.js').TSRXCompilerModule | null}
|
|
236
|
+
*/
|
|
237
|
+
function resolve_compiler(state, file_name) {
|
|
238
|
+
/** @type {string | undefined} */
|
|
239
|
+
let entry;
|
|
240
|
+
if (state.options.compiler !== undefined) {
|
|
241
|
+
entry = resolve_declared_compiler(state, file_name, state.options.compiler);
|
|
242
|
+
} else {
|
|
243
|
+
entry = get_compiler_entry_for_file(file_name, {
|
|
244
|
+
configFileName: state.configFileName,
|
|
245
|
+
configHost: host,
|
|
246
|
+
dependencies: state.dependencies,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
if (!entry) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
const manifest = nearest_package_manifest(entry);
|
|
253
|
+
if (manifest) {
|
|
254
|
+
state.dependencies.add(manifest);
|
|
255
|
+
}
|
|
256
|
+
return require_tsrx_compiler(entry);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* @param {ProjectState} state
|
|
261
|
+
* @param {string} file_name
|
|
262
|
+
* @param {string} specifier
|
|
263
|
+
* @returns {string}
|
|
264
|
+
*/
|
|
265
|
+
function resolve_declared_compiler(state, file_name, specifier) {
|
|
266
|
+
if (!bare_package_specifier_pattern.test(specifier)) {
|
|
267
|
+
throw new Error(
|
|
268
|
+
`The content mapper option "compiler" must be a bare package specifier, got ${JSON.stringify(specifier)}.`,
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
const anchor = state.configFileName ?? file_name;
|
|
272
|
+
try {
|
|
273
|
+
return createRequire(anchor).resolve(specifier);
|
|
274
|
+
} catch {
|
|
275
|
+
// Node keeps a negative lookup after a package is installed; the
|
|
276
|
+
// package walk reads manifests fresh.
|
|
277
|
+
const resolved = resolve_package_entry(specifier, path.dirname(anchor), { host });
|
|
278
|
+
if (!resolved) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`Unable to resolve the TSRX compiler ${JSON.stringify(specifier)} declared in the content mapper options from ${anchor}.`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
return resolved;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* @param {ProjectState} state
|
|
289
|
+
* @param {string[]} watched_files
|
|
290
|
+
* @returns {string}
|
|
291
|
+
*/
|
|
292
|
+
function compute_identity(state, watched_files) {
|
|
293
|
+
const hash = createHash('sha256');
|
|
294
|
+
hash.update(JSON.stringify(state.options));
|
|
295
|
+
hash.update('\0');
|
|
296
|
+
for (const file of watched_files) {
|
|
297
|
+
hash.update(file);
|
|
298
|
+
hash.update('\0');
|
|
299
|
+
hash.update(host.readFile(file) ?? '');
|
|
300
|
+
hash.update('\0');
|
|
301
|
+
}
|
|
302
|
+
return hash.digest('hex');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* @param {ProjectState} state
|
|
307
|
+
* @param {string} file_name
|
|
308
|
+
* @param {string} content
|
|
309
|
+
* @param {MapperDiagnostic} diagnostic
|
|
310
|
+
* @returns {TransformResult}
|
|
311
|
+
*/
|
|
312
|
+
function failure(state, file_name, content, diagnostic) {
|
|
313
|
+
return {
|
|
314
|
+
text: build_export_stub(state.lastGood.get(file_name)),
|
|
315
|
+
extension: '.ts',
|
|
316
|
+
mappings: [],
|
|
317
|
+
diagnostics: [clamp_diagnostic(diagnostic, content.length)],
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return { initialize, openProject, closeProject, transform };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* @param {unknown} raw
|
|
326
|
+
* @returns {{ options: MapperOptions, optionDiagnostics: NonNullable<OpenProjectResult['optionDiagnostics']> }}
|
|
327
|
+
*/
|
|
328
|
+
export function validate_options(raw) {
|
|
329
|
+
/** @type {MapperOptions} */
|
|
330
|
+
const options = {};
|
|
331
|
+
/** @type {NonNullable<OpenProjectResult['optionDiagnostics']>} */
|
|
332
|
+
const optionDiagnostics = [];
|
|
333
|
+
if (raw === undefined || raw === null) {
|
|
334
|
+
return { options, optionDiagnostics };
|
|
335
|
+
}
|
|
336
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
337
|
+
optionDiagnostics.push({
|
|
338
|
+
path: [],
|
|
339
|
+
messageText: 'Content mapper options must be an object.',
|
|
340
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
341
|
+
});
|
|
342
|
+
return { options, optionDiagnostics };
|
|
343
|
+
}
|
|
344
|
+
const record = /** @type {Record<string, unknown>} */ (raw);
|
|
345
|
+
for (const key of Object.keys(record)) {
|
|
346
|
+
const value = record[key];
|
|
347
|
+
switch (key) {
|
|
348
|
+
case 'compiler':
|
|
349
|
+
if (typeof value === 'string' && bare_package_specifier_pattern.test(value.trim())) {
|
|
350
|
+
options.compiler = value.trim();
|
|
351
|
+
} else {
|
|
352
|
+
optionDiagnostics.push({
|
|
353
|
+
path: [key],
|
|
354
|
+
messageText: '"compiler" must be a bare package specifier such as "@tsrx/react".',
|
|
355
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
break;
|
|
359
|
+
case 'platform':
|
|
360
|
+
if (value === 'web' || value === 'ios' || value === 'android') {
|
|
361
|
+
options.platform = value;
|
|
362
|
+
} else {
|
|
363
|
+
optionDiagnostics.push({
|
|
364
|
+
path: [key],
|
|
365
|
+
messageText: '"platform" must be "web", "ios", or "android".',
|
|
366
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
break;
|
|
370
|
+
case 'languageFeatures':
|
|
371
|
+
if (typeof value === 'boolean') {
|
|
372
|
+
options.languageFeatures = value;
|
|
373
|
+
} else {
|
|
374
|
+
optionDiagnostics.push({
|
|
375
|
+
path: [key],
|
|
376
|
+
messageText: '"languageFeatures" must be a boolean.',
|
|
377
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
break;
|
|
381
|
+
default:
|
|
382
|
+
optionDiagnostics.push({
|
|
383
|
+
path: [key],
|
|
384
|
+
messageText: `Unknown content mapper option "${key}".`,
|
|
385
|
+
code: DIAGNOSTIC_CODE_INVALID_CONFIG,
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return { options, optionDiagnostics };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* 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`.
|
|
396
|
+
* @param {CompileError} error
|
|
397
|
+
* @param {number} content_length
|
|
398
|
+
* @param {number} fallback_code
|
|
399
|
+
* @returns {MapperDiagnostic}
|
|
400
|
+
*/
|
|
401
|
+
export function to_diagnostic(error, content_length, fallback_code) {
|
|
402
|
+
const start = typeof error.pos === 'number' ? error.pos : 0;
|
|
403
|
+
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;
|
|
406
|
+
const message = String(error.message ?? error);
|
|
407
|
+
return clamp_diagnostic(
|
|
408
|
+
{
|
|
409
|
+
start,
|
|
410
|
+
length: end - start,
|
|
411
|
+
code,
|
|
412
|
+
messageText:
|
|
413
|
+
typeof error.code === 'string' && error.code ? `${message} [${error.code}]` : message,
|
|
414
|
+
},
|
|
415
|
+
content_length,
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
|
|
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
|
+
/**
|
|
436
|
+
* @param {MapperDiagnostic} diagnostic
|
|
437
|
+
* @param {number} content_length
|
|
438
|
+
* @returns {MapperDiagnostic}
|
|
439
|
+
*/
|
|
440
|
+
function clamp_diagnostic(diagnostic, content_length) {
|
|
441
|
+
const start = Math.max(0, Math.min(diagnostic.start, content_length));
|
|
442
|
+
const end = Math.max(start, Math.min(diagnostic.start + diagnostic.length, content_length));
|
|
443
|
+
return { ...diagnostic, start, length: end - start };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* @param {unknown} error
|
|
448
|
+
* @returns {string}
|
|
449
|
+
*/
|
|
450
|
+
function error_message(error) {
|
|
451
|
+
return error instanceof Error ? error.message : String(error);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The `package.json` that owns a compiler entry file, stopping at a
|
|
456
|
+
* `node_modules` boundary.
|
|
457
|
+
* @param {string} entry
|
|
458
|
+
* @returns {string | undefined}
|
|
459
|
+
*/
|
|
460
|
+
function nearest_package_manifest(entry) {
|
|
461
|
+
let dir = path.dirname(entry);
|
|
462
|
+
while (dir) {
|
|
463
|
+
const candidate = path.join(dir, 'package.json');
|
|
464
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
465
|
+
if (path.basename(dir) === 'node_modules') return undefined;
|
|
466
|
+
const parent = path.dirname(dir);
|
|
467
|
+
if (parent === dir) return undefined;
|
|
468
|
+
dir = parent;
|
|
469
|
+
}
|
|
470
|
+
return undefined;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export { require };
|