targeted-mutation 0.0.0-stage → 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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +148 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,185 @@
1
+ import { runDecisionBatch } from './lean-replay.mjs';
2
+
3
+ function evaluate(operator, lhs, rhs) {
4
+ switch (operator) {
5
+ case '<': return lhs < rhs;
6
+ case '<=': return lhs <= rhs;
7
+ case '>': return lhs > rhs;
8
+ case '>=': return lhs >= rhs;
9
+ }
10
+ }
11
+
12
+ const upperInclusive = operator => operator === '>' || operator === '<=';
13
+
14
+ export function thresholdGap(threshold, observations, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER, operator = '>=') {
15
+ if (!['<', '<=', '>', '>='].includes(operator) ||
16
+ ![threshold, min, max].every(Number.isSafeInteger) || threshold < min || threshold > max || !observations.length) {
17
+ return null;
18
+ }
19
+ const upper = upperInclusive(operator);
20
+ let lowerBound = min;
21
+ let upperBound = max;
22
+ for (const input of observations) {
23
+ if (!Number.isSafeInteger(input) || input < min || input > max) return null;
24
+ if (upper) {
25
+ if (input <= threshold) lowerBound = Math.max(lowerBound, input);
26
+ else upperBound = Math.min(upperBound, input - 1);
27
+ } else {
28
+ if (input < threshold) lowerBound = Math.max(lowerBound, input + 1);
29
+ else upperBound = Math.min(upperBound, input);
30
+ }
31
+ }
32
+
33
+ let alternate = null;
34
+ let witness = null;
35
+ if (upper) {
36
+ if (threshold < upperBound) {
37
+ alternate = threshold + 1;
38
+ witness = threshold + 1;
39
+ } else if (lowerBound < threshold) {
40
+ alternate = threshold - 1;
41
+ witness = threshold;
42
+ }
43
+ } else {
44
+ if (lowerBound < threshold) {
45
+ alternate = threshold - 1;
46
+ witness = threshold - 1;
47
+ } else if (threshold < upperBound) {
48
+ alternate = threshold + 1;
49
+ witness = threshold;
50
+ }
51
+ }
52
+ if (alternate === null) return null;
53
+ return {
54
+ interval: [lowerBound, upperBound],
55
+ alternate,
56
+ witness,
57
+ expected: evaluate(operator, witness, threshold),
58
+ mutant: evaluate(operator, witness, alternate),
59
+ };
60
+ }
61
+
62
+ function extremalObservations(threshold, observations, min, max, operator = '>=') {
63
+ if (!Array.isArray(observations)) return observations;
64
+ const upper = upperInclusive(operator);
65
+ let below;
66
+ let above;
67
+ for (const value of observations) {
68
+ if (!Number.isSafeInteger(value) || value < min || value > max) return [];
69
+ if (upper ? value <= threshold : value < threshold) below = Math.max(below ?? value, value);
70
+ else above = Math.min(above ?? value, value);
71
+ }
72
+ const evidence = [];
73
+ if (below !== undefined) evidence.push(below);
74
+ if (above !== undefined) evidence.push(above);
75
+ return evidence;
76
+ }
77
+
78
+ export function checkedThresholdGaps(requests) {
79
+ const batch = requests.map(({ threshold, observations, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER, operator = '>=' }) =>
80
+ ({ threshold, observations: extremalObservations(threshold, observations, min, max, operator), min, max, ...(operator === '>=' ? {} : { operator }) }));
81
+ const answers = runDecisionBatch(batch, ['thresholds']);
82
+ return answers?.every(gap => gap === null || Array.isArray(gap?.interval)) ? answers : null;
83
+ }
84
+
85
+ export function thresholdGaps(requests) {
86
+ return checkedThresholdGaps(requests) ?? requests.map(({ threshold, observations, min, max, operator = '>=' }) =>
87
+ thresholdGap(threshold, observations, min, max, operator));
88
+ }
89
+
90
+ export function marginGap(pairs, operator = '>=', min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
91
+ if (!['<', '<=', '>', '>='].includes(operator) ||
92
+ ![min, max].every(Number.isSafeInteger) || min > 0 || max < 0 || !Array.isArray(pairs) || !pairs.length) {
93
+ return null;
94
+ }
95
+ const diffs = [];
96
+ let safeLo = min;
97
+ let safeHi = max;
98
+ for (const pair of pairs) {
99
+ if (!Array.isArray(pair) || pair.length !== 2) return null;
100
+ const [lhs, rhs] = pair;
101
+ if (!Number.isSafeInteger(lhs) || !Number.isSafeInteger(rhs)) return null;
102
+ const diff = lhs - rhs;
103
+ if (!Number.isSafeInteger(diff) || diff < min || diff > max) return null;
104
+ diffs.push(diff);
105
+ // Restrict shift domain to shifts where `rhs + shift` remains a safe integer for every observed rhs.
106
+ const loForRhs = rhs < 0 ? Number.MIN_SAFE_INTEGER - rhs : Number.MIN_SAFE_INTEGER;
107
+ const hiForRhs = rhs > 0 ? Number.MAX_SAFE_INTEGER - rhs : Number.MAX_SAFE_INTEGER;
108
+ safeLo = Math.max(safeLo, loForRhs);
109
+ safeHi = Math.min(safeHi, hiForRhs);
110
+ }
111
+ // Compute bounds over full integer diffs, then intersect with [safeLo, safeHi] before choosing the nearest safe shift.
112
+ const upper = upperInclusive(operator);
113
+ let lowerBound = safeLo;
114
+ let upperBound = safeHi;
115
+ for (const d of diffs) {
116
+ if (upper) {
117
+ if (d <= 0) lowerBound = Math.max(lowerBound, d);
118
+ else upperBound = Math.min(upperBound, d - 1);
119
+ } else {
120
+ if (d < 0) lowerBound = Math.max(lowerBound, d + 1);
121
+ else upperBound = Math.min(upperBound, d);
122
+ }
123
+ }
124
+ let alternate = null;
125
+ let witness = null;
126
+ if (upper) {
127
+ if (0 < upperBound) (alternate = 1, witness = 1);
128
+ else if (lowerBound < 0) (alternate = -1, witness = 0);
129
+ } else {
130
+ if (lowerBound < 0) (alternate = -1, witness = -1);
131
+ else if (0 < upperBound) (alternate = 1, witness = 0);
132
+ }
133
+ if (alternate === null) return null;
134
+ if (pairs.some(([, rhs]) => !Number.isSafeInteger(rhs + alternate))) return null;
135
+ return {
136
+ interval: [lowerBound, upperBound],
137
+ alternate,
138
+ witness,
139
+ expected: evaluate(operator, witness, 0),
140
+ mutant: evaluate(operator, witness, alternate),
141
+ };
142
+ }
143
+
144
+ function extremalMarginPairs(pairs, min, max, operator = '>=') {
145
+ if (!Array.isArray(pairs) || !pairs.length) return [];
146
+ const upper = upperInclusive(operator);
147
+ let below;
148
+ let above;
149
+ let minRhs;
150
+ let maxRhs;
151
+ for (const pair of pairs) {
152
+ if (!Array.isArray(pair) || pair.length !== 2) return [];
153
+ const [lhs, rhs] = pair;
154
+ if (!Number.isSafeInteger(lhs) || !Number.isSafeInteger(rhs)) return [];
155
+ const diff = lhs - rhs;
156
+ if (!Number.isSafeInteger(diff) || diff < min || diff > max) return [];
157
+ if (upper ? diff <= 0 : diff < 0) {
158
+ if (!below || diff > below[0] - below[1]) below = pair;
159
+ } else if (!above || diff < above[0] - above[1]) {
160
+ above = pair;
161
+ }
162
+ if (!minRhs || rhs < minRhs[1]) minRhs = pair;
163
+ if (!maxRhs || rhs > maxRhs[1]) maxRhs = pair;
164
+ }
165
+ const seen = new Set();
166
+ const evidence = [];
167
+ for (const pair of [below, above, minRhs, maxRhs]) {
168
+ if (!pair) continue;
169
+ const key = `${pair[0]}:${pair[1]}`;
170
+ if (!seen.has(key)) (seen.add(key), evidence.push(pair));
171
+ }
172
+ return evidence;
173
+ }
174
+
175
+ export function checkedMarginGaps(requests) {
176
+ const batch = requests.map(({ pairs, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER, operator = '>=' }) =>
177
+ ({ pairs: extremalMarginPairs(pairs, min, max, operator), min, max, ...(operator === '>=' ? {} : { operator }) }));
178
+ const answers = runDecisionBatch(batch, ['margins']);
179
+ return answers?.every(gap => gap === null || Array.isArray(gap?.interval)) ? answers : null;
180
+ }
181
+
182
+ export function marginGaps(requests) {
183
+ return checkedMarginGaps(requests) ?? requests.map(({ pairs, operator = '>=', min, max }) =>
184
+ marginGap(pairs, operator, min, max));
185
+ }
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { appendFileSync, mkdtempSync, readdirSync, readFileSync, rmdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ const chunkSize = 64 * 1024;
6
+ const workerWriters = new Map();
7
+
8
+ export function pendingTraceDirectory(trace) {
9
+ return trace + '.pending';
10
+ }
11
+
12
+ export function createTraceWriter(trace, onFinished, { producer, immediate } = {}) {
13
+ const tasks = new WeakMap();
14
+ const pending = pendingTraceDirectory(trace);
15
+ const writerHeader = producer ? JSON.stringify({ traceWriter: producer }) + '\n' : '';
16
+ let active;
17
+ let lines = [];
18
+ let bytes = 0;
19
+
20
+ function publish(data) {
21
+ appendFileSync(trace, writerHeader + data);
22
+ }
23
+
24
+ function flush() {
25
+ if (!lines.length) return;
26
+ publish(lines.join('') + (producer ? '{"traceBuffer":"closed"}\n' : ''));
27
+ lines = [];
28
+ bytes = 0;
29
+ }
30
+
31
+ function begin(task, state) {
32
+ try {
33
+ onFinished(task, () => {
34
+ flush();
35
+ if (state.marker) rmdirSync(state.marker);
36
+ state.closed = true;
37
+ });
38
+ } catch {
39
+ state.closed = true;
40
+ }
41
+ if (!state.closed) state.marker = mkdtempSync(join(pending, 'task-'));
42
+ }
43
+
44
+ return { write(row, task) {
45
+ const line = JSON.stringify(row) + '\n';
46
+ if (immediate) {
47
+ publish(line);
48
+ return;
49
+ }
50
+ if (task !== active || !task) flush();
51
+ active = task;
52
+ if (!task) {
53
+ publish(line);
54
+ return;
55
+ }
56
+ const state = tasks.get(task);
57
+ if (!state) {
58
+ // Most tests see very few comparisons. Write the first event without registering a hook.
59
+ tasks.set(task, { marker: undefined, closed: false });
60
+ publish(line);
61
+ return;
62
+ }
63
+ if (!state.closed && !state.marker) begin(task, state);
64
+ if (state.closed) {
65
+ publish(line);
66
+ return;
67
+ }
68
+ if (producer && !lines.length) publish('{"traceBuffer":"open"}\n');
69
+ lines.push(line);
70
+ bytes += Buffer.byteLength(line);
71
+ if (bytes >= chunkSize) flush();
72
+ } };
73
+ }
74
+
75
+ export function workerTraceWriter(trace, onFinished, immediate) {
76
+ let writer = workerWriters.get(trace);
77
+ if (!writer) {
78
+ writer = createTraceWriter(trace, onFinished, { producer: randomUUID(), immediate });
79
+ workerWriters.set(trace, writer);
80
+ }
81
+ return writer;
82
+ }
83
+
84
+ export function inspectTrace(trace) {
85
+ try {
86
+ if (readdirSync(pendingTraceDirectory(trace)).length) return { rows: null, overlap: false };
87
+ const outstanding = new Set();
88
+ const rows = [];
89
+ let writer;
90
+ let overlap = false;
91
+ for (const line of readFileSync(trace, 'utf8').trim().split('\n').filter(Boolean)) {
92
+ const row = JSON.parse(line);
93
+ if (row?.traceWriter) {
94
+ writer = row.traceWriter;
95
+ // A foreign append during an open chunk may have passed an earlier observation.
96
+ overlap ||= outstanding.size > 0 && !outstanding.has(writer);
97
+ } else if (row?.traceBuffer === 'open') {
98
+ outstanding.add(writer);
99
+ } else if (row?.traceBuffer === 'closed') {
100
+ outstanding.delete(writer);
101
+ } else {
102
+ rows.push(row);
103
+ }
104
+ }
105
+ return { rows: overlap || outstanding.size ? null : rows, overlap };
106
+ } catch {
107
+ return { rows: null, overlap: false };
108
+ }
109
+ }
110
+
111
+ export function readCompletedTrace(trace) {
112
+ return inspectTrace(trace).rows;
113
+ }
114
+
115
+ export function sameObservations(reference, replay) {
116
+ if (!reference || !replay) return reference === replay;
117
+ let index = 0;
118
+ for (const row of reference) {
119
+ if (row?.hit !== undefined) continue;
120
+ while (index < replay.length && replay[index]?.hit !== undefined) index++;
121
+ if (index === replay.length || JSON.stringify(row) !== JSON.stringify(replay[index])) return false;
122
+ index++;
123
+ }
124
+ while (index < replay.length && replay[index]?.hit !== undefined) index++;
125
+ return index === replay.length;
126
+ }
@@ -0,0 +1,243 @@
1
+ const conflicts = {
2
+ Lexical: ['Lexical', 'Var', 'Function', 'Class', 'Enum', 'ConstEnum', 'Namespace', 'AmbientClass'],
3
+ Var: ['Lexical', 'Function', 'Class', 'Enum', 'ConstEnum', 'Namespace', 'AmbientClass'],
4
+ Function: ['Lexical', 'Var', 'Class', 'Enum', 'ConstEnum'],
5
+ Class: ['Lexical', 'Var', 'Function', 'Class', 'Type', 'Enum', 'ConstEnum', 'AmbientClass'],
6
+ Type: ['Class', 'Type', 'Interface', 'Enum', 'ConstEnum', 'AmbientClass'],
7
+ Interface: ['Type', 'Enum', 'ConstEnum'],
8
+ Enum: ['Lexical', 'Var', 'Function', 'Class', 'Type', 'Interface', 'ConstEnum', 'AmbientClass'],
9
+ ConstEnum: ['Lexical', 'Var', 'Function', 'Class', 'Type', 'Interface', 'Enum', 'Namespace', 'AmbientClass'],
10
+ Namespace: ['Lexical', 'Var', 'ConstEnum'],
11
+ Import: ['Import'],
12
+ AmbientClass: ['Lexical', 'Var', 'Class', 'Type', 'Enum', 'ConstEnum', 'AmbientClass'],
13
+ };
14
+
15
+ export function createTypeScriptBindings(ts) {
16
+ const {
17
+ ModifierFlags, NodeFlags, SyntaxKind, forEachChild, getCombinedModifierFlags, isArrayBindingPattern,
18
+ isBindingElement, isCaseBlock, isCaseOrDefaultClause, isCatchClause, isClassDeclaration, isClassLike,
19
+ isEmptyStatement, isEnumDeclaration, isExportAssignment, isExportDeclaration, isFunctionDeclaration,
20
+ isFunctionLike, isIdentifier, isImportDeclaration, isImportEqualsDeclaration, isInterfaceDeclaration,
21
+ isModuleBlock, isModuleDeclaration, isNamedExports, isNamedImports, isNamespaceExport, isNamespaceImport,
22
+ isObjectBindingPattern, isStatement, isTypeAliasDeclaration, isVariableDeclarationList, isVariableStatement,
23
+ } = ts;
24
+ const hasModifier = (node, flags) => (getCombinedModifierFlags(node) & flags) !== 0;
25
+
26
+ function namesIn(pattern) {
27
+ const pending = [pattern];
28
+ const names = [];
29
+ while (pending.length) {
30
+ const node = pending.pop();
31
+ if (isIdentifier(node)) {
32
+ names.push(node);
33
+ } else if (isObjectBindingPattern(node) || isArrayBindingPattern(node)) {
34
+ for (let index = node.elements.length - 1; index >= 0; index--) {
35
+ const element = node.elements[index];
36
+ if (isBindingElement(element)) pending.push(element.name);
37
+ }
38
+ }
39
+ }
40
+ return names;
41
+ }
42
+
43
+ function hasRuntimeMembers(namespace) {
44
+ const pending = [namespace];
45
+ while (pending.length) {
46
+ const node = pending.pop();
47
+ if (isModuleDeclaration(node)) {
48
+ if (node.body) pending.push(node.body);
49
+ } else if (isModuleBlock(node)) {
50
+ for (const statement of node.statements) pending.push(statement);
51
+ } else if (!isTypeAliasDeclaration(node) && !isInterfaceDeclaration(node) && !isEmptyStatement(node)) {
52
+ return true;
53
+ }
54
+ }
55
+ return false;
56
+ }
57
+
58
+ function declaration(statement, ambient = false) {
59
+ if (isVariableStatement(statement)) {
60
+ const { declarationList } = statement;
61
+ const kind = (declarationList.flags & NodeFlags.BlockScoped) === 0 ? 'Var' : 'Lexical';
62
+ return { kind, names: declarationList.declarations.flatMap(node => namesIn(node.name)) };
63
+ }
64
+ if (isFunctionDeclaration(statement)) return { kind: 'Function', names: statement.name ? [statement.name] : [] };
65
+ if (isClassDeclaration(statement)) {
66
+ const kind = ambient || hasModifier(statement, ModifierFlags.Ambient) ? 'AmbientClass' : 'Class';
67
+ return { kind, names: statement.name ? [statement.name] : [] };
68
+ }
69
+ if (isTypeAliasDeclaration(statement)) return { kind: 'Type', names: [statement.name] };
70
+ if (isInterfaceDeclaration(statement)) return { kind: 'Interface', names: [statement.name] };
71
+ if (isEnumDeclaration(statement)) {
72
+ const kind = hasModifier(statement, ModifierFlags.Const) ? 'ConstEnum' : 'Enum';
73
+ return { kind, names: [statement.name] };
74
+ }
75
+ if (isModuleDeclaration(statement) && isIdentifier(statement.name) &&
76
+ (statement.flags & NodeFlags.GlobalAugmentation) === 0 && hasRuntimeMembers(statement)) {
77
+ return { kind: 'Namespace', names: [statement.name] };
78
+ }
79
+ if (isImportDeclaration(statement) && statement.importClause) {
80
+ const { name, namedBindings } = statement.importClause;
81
+ const names = name ? [name] : [];
82
+ if (namedBindings && isNamespaceImport(namedBindings)) names.push(namedBindings.name);
83
+ if (namedBindings && isNamedImports(namedBindings)) {
84
+ for (const element of namedBindings.elements) names.push(element.name);
85
+ }
86
+ return { kind: 'Import', names };
87
+ }
88
+ if (isImportEqualsDeclaration(statement)) return { kind: 'Import', names: [statement.name] };
89
+ }
90
+
91
+ function duplicate(name, previous, report) {
92
+ report(name, `Identifier '${name.text}' has already been declared`, previous);
93
+ }
94
+
95
+ function nestedVarsIn(statement) {
96
+ const pending = [statement];
97
+ const names = [];
98
+ while (pending.length) {
99
+ const node = pending.pop();
100
+ if (isFunctionLike(node) || isClassLike(node) || isModuleDeclaration(node)) continue;
101
+ if (isVariableDeclarationList(node)) {
102
+ if ((node.flags & NodeFlags.BlockScoped) === 0) {
103
+ for (const declaration of node.declarations) names.push(...namesIn(declaration.name));
104
+ }
105
+ continue;
106
+ }
107
+ forEachChild(node, child => {
108
+ if (isStatement(child) || isVariableDeclarationList(child) ||
109
+ isCaseBlock(child) || isCaseOrDefaultClause(child) || isCatchClause(child)) {
110
+ pending.push(child);
111
+ }
112
+ });
113
+ }
114
+ return names;
115
+ }
116
+
117
+ function checkScope(statements, report, { parameters = [], catchPattern = false, nestedVars = [], ambient = false } = {}) {
118
+ const seen = new Map();
119
+ for (const name of parameters) {
120
+ const previous = seen.get(name.text);
121
+ if (previous) duplicate(name, previous.values().next().value, report);
122
+ seen.set(name.text, new Map([[catchPattern ? 'PatternParameter' : 'Parameter', name]]));
123
+ }
124
+ const entries = statements.map(statement => declaration(statement, ambient));
125
+ if (nestedVars.length) entries.push({ kind: 'Var', names: nestedVars });
126
+ for (const entry of entries) {
127
+ if (!entry) continue;
128
+ for (const name of entry.names) {
129
+ const already = seen.get(name.text) ?? new Map();
130
+ const collision = conflicts[entry.kind].find(kind => already.has(kind));
131
+ const hasValue = entry.kind !== 'Type' && entry.kind !== 'Interface';
132
+ const parameter = hasValue && (already.get('PatternParameter') ||
133
+ (entry.kind === 'Var' ? undefined : already.get('Parameter')));
134
+ const earlier = already.get(collision) ?? parameter;
135
+ if (earlier) duplicate(name, earlier, report);
136
+ if (!already.has(entry.kind)) already.set(entry.kind, name);
137
+ seen.set(name.text, already);
138
+ }
139
+ }
140
+ }
141
+
142
+ function checkExports(file, report, nestedVars) {
143
+ const locals = new Set(nestedVars.map(name => name.text));
144
+ for (const statement of file.statements) {
145
+ for (const name of declaration(statement)?.names ?? []) locals.add(name.text);
146
+ if (isModuleDeclaration(statement) && isIdentifier(statement.name)) locals.add(statement.name.text);
147
+ }
148
+
149
+ const exported = new Map();
150
+ let implicitDefault;
151
+ function record(name, node) {
152
+ if (exported.has(name)) report(node, `Duplicate export of '${name}'`, exported.get(name));
153
+ else exported.set(name, node);
154
+ }
155
+ for (const statement of file.statements) {
156
+ if (isExportDeclaration(statement)) {
157
+ const clause = statement.exportClause;
158
+ if (!clause) continue;
159
+ if (isNamespaceExport(clause)) {
160
+ record(clause.name.text, clause.name);
161
+ } else if (isNamedExports(clause)) {
162
+ for (const element of clause.elements) {
163
+ const local = element.propertyName ?? element.name;
164
+ if (!statement.moduleSpecifier && !statement.isTypeOnly && !element.isTypeOnly && !locals.has(local.text)) {
165
+ report(local, `Export '${local.text}' is not defined`);
166
+ }
167
+ record(element.name.text, element.name);
168
+ }
169
+ }
170
+ continue;
171
+ }
172
+ if (isExportAssignment(statement)) {
173
+ if (!statement.isExportEquals) {
174
+ if (implicitDefault) report(statement, "Duplicate export of 'default'", implicitDefault);
175
+ record('default', statement);
176
+ }
177
+ continue;
178
+ }
179
+ if (!hasModifier(statement, ModifierFlags.Export)) continue;
180
+ const defaultToken = statement.modifiers?.find(modifier => modifier.kind === SyntaxKind.DefaultKeyword);
181
+ if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement) ||
182
+ (isFunctionDeclaration(statement) && !statement.body)) {
183
+ implicitDefault ??= defaultToken;
184
+ continue;
185
+ }
186
+ if (defaultToken) {
187
+ record('default', defaultToken);
188
+ continue;
189
+ }
190
+ if (isVariableStatement(statement) || isClassDeclaration(statement) ||
191
+ isFunctionDeclaration(statement) || isImportEqualsDeclaration(statement)) {
192
+ for (const name of declaration(statement)?.names ?? []) record(name.text, name);
193
+ }
194
+ }
195
+ }
196
+
197
+ function checkNamespaceExports(file, report) {
198
+ const pending = [{ statements: file.statements, namespaces: new Map(), ambient: false, shared: false }];
199
+ while (pending.length) {
200
+ const { statements, namespaces, ambient, shared } = pending.pop();
201
+ for (const statement of statements) {
202
+ if (!isModuleDeclaration(statement)) continue;
203
+ const ambientNamespace = ambient || hasModifier(statement, ModifierFlags.Ambient);
204
+ const joinsNamespace = !shared || ambient || hasModifier(statement, ModifierFlags.Export);
205
+ let scope = namespaces;
206
+ let part = statement;
207
+ while (part && isModuleDeclaration(part) && part.body) {
208
+ const key = JSON.stringify([part.name.kind, part.name.text]);
209
+ const previous = joinsNamespace ? scope.get(key) : undefined;
210
+ const joined = previous ?? { namespaces: new Map(), exports: new Map() };
211
+ if (joinsNamespace && !previous) scope.set(key, joined);
212
+ if (isModuleBlock(part.body)) {
213
+ const children = part.body.statements;
214
+ const current = new Map();
215
+ for (const child of children) {
216
+ if (!ambientNamespace && !hasModifier(child, ModifierFlags.Export)) continue;
217
+ const entry = declaration(child, ambientNamespace);
218
+ if (!entry) continue;
219
+ for (const name of entry.names) {
220
+ const already = joined.exports.get(name.text);
221
+ const collision = already && conflicts[entry.kind].find(kind => already.has(kind));
222
+ if (collision) duplicate(name, already.get(collision), report);
223
+ const kinds = current.get(name.text) ?? new Map();
224
+ if (!kinds.has(entry.kind)) kinds.set(entry.kind, name);
225
+ current.set(name.text, kinds);
226
+ }
227
+ }
228
+ for (const [name, kinds] of current) {
229
+ const merged = joined.exports.get(name) ?? new Map();
230
+ for (const [kind, token] of kinds) if (!merged.has(kind)) merged.set(kind, token);
231
+ joined.exports.set(name, merged);
232
+ }
233
+ pending.push({ statements: children, namespaces: joined.namespaces, ambient: ambientNamespace, shared: true });
234
+ }
235
+ scope = joined.namespaces;
236
+ part = part.body;
237
+ }
238
+ }
239
+ }
240
+ }
241
+
242
+ return { namesIn, nestedVarsIn, checkScope, checkExports, checkNamespaceExports };
243
+ }
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { createRequire, enableCompileCache, getCompileCacheDir } from 'node:module';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const cacheRoot = new URL('../build/typescript-cache/', import.meta.url);
7
+ const bytecode = fileURLToPath(new URL('bytecode/', cacheRoot));
8
+ const syntaxPath = fileURLToPath(new URL('../build/typescript-syntax/typescript-syntax.cjs', import.meta.url));
9
+ const [major, minor] = process.versions.node.split('.', 2).map(Number);
10
+ export const supportsPortableCompileCache = major >= 25 || (major === 24 && minor >= 12);
11
+ const preload = /^(?:-r.*|--(?:require|import|loader|experimental-loader|experimental-config-file|experimental-default-config-file)(?:=.*)?)$/;
12
+ let prepareOnLoad = false;
13
+ let compilerPath;
14
+ let projected;
15
+
16
+ export function enablePreparedTypeScript() {
17
+ const environment = (process.env.NODE_OPTIONS ?? '').split(/\s+/).map(flag => flag.replace(/^["']|["']$/g, ''));
18
+ prepareOnLoad = supportsPortableCompileCache && !Object.hasOwn(process.env, 'NODE_DISABLE_COMPILE_CACHE') &&
19
+ !process.env.NODE_V8_COVERAGE && !process.permission && !getCompileCacheDir() &&
20
+ ![...process.execArgv, ...environment].some(flag => preload.test(flag.replaceAll('_', '-')));
21
+ }
22
+
23
+ function activateCompileCache() {
24
+ if (!existsSync(bytecode) || getCompileCacheDir() || require.cache[require.resolve('typescript')]) return;
25
+ let metadata;
26
+ try {
27
+ metadata = JSON.parse(readFileSync(new URL('engine.json', cacheRoot), 'utf8'));
28
+ } catch {
29
+ return;
30
+ }
31
+ if (metadata?.node !== process.version) return;
32
+ enableCompileCache({ directory: bytecode, portable: true });
33
+ }
34
+
35
+ export function loadTypeScript() {
36
+ if (prepareOnLoad) {
37
+ prepareOnLoad = false;
38
+ activateCompileCache();
39
+ }
40
+ return require('typescript');
41
+ }
42
+
43
+ export function withTypeScriptSyntax(read) {
44
+ compilerPath ??= require.resolve('typescript');
45
+ if (!require.cache[compilerPath]) {
46
+ try {
47
+ if (projected === undefined) {
48
+ const parser = existsSync(syntaxPath) ? require(syntaxPath) : null;
49
+ projected = parser?.version === require('typescript/package.json').version ? parser : null;
50
+ }
51
+ if (projected) return read(projected);
52
+ } catch (error) {
53
+ if (error instanceof RangeError && error.message === 'Maximum call stack size exceeded') throw error;
54
+ // The full compiler owns error recovery when the optional parser cannot complete.
55
+ projected = null;
56
+ }
57
+ }
58
+ return read(loadTypeScript());
59
+ }