targeted-mutation 0.2.3 → 0.4.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/README.md +22 -3
- package/bin/tmt.mjs +122 -10
- package/docs/analysis.md +2 -2
- package/docs/how-it-works.svg +99 -180
- package/docs/why-targeted.svg +117 -0
- package/package.json +5 -5
- package/src/analysis.mjs +45 -19
- package/src/builtin-mutations.mjs +29 -7
- package/src/builtin-switches.mjs +3 -1
- package/src/checkpoint.mjs +5 -0
- package/src/cli-output.mjs +101 -18
- package/src/conventional.mjs +43 -3
- package/src/operator-analysis.mjs +7 -0
- package/src/project-config.mjs +9 -1
- package/src/shard.mjs +8 -0
- package/src/standard-session.mjs +33 -13
- package/src/targeted-gaps.mjs +9 -2
- package/src/type-equivalence.mjs +411 -0
- package/src/vitest-related-worker.mjs +47 -0
- package/src/vitest.mjs +221 -8
package/src/standard-session.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { inside } from './vitest.mjs';
|
|
|
9
9
|
// Vitest and Vite are loaded on every run. Node keeps their compiled code between runs when it can.
|
|
10
10
|
try { enableCompileCache?.(); } catch { /* The cache is an optimisation only. */ }
|
|
11
11
|
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
12
|
-
const { workspace, config, files, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
|
|
12
|
+
const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000, baselineTimeout = runTimeout, baselineWorkers } = input;
|
|
13
13
|
const destination = resolve(temporary, 'coverage.jsonl');
|
|
14
14
|
const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
|
|
15
15
|
const lanes = [];
|
|
@@ -52,11 +52,17 @@ function follow(path) {
|
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
function filterSelectedSpecs(allSpecs) {
|
|
56
|
+
if (!selectedSpecs?.length) return allSpecs;
|
|
57
|
+
const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
|
|
58
|
+
return allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
|
|
59
|
+
}
|
|
60
|
+
|
|
55
61
|
// A lane is one Vitest instance with its own worker. The first lane also runs the baseline and the isolated trials.
|
|
56
|
-
async function openLane(index, serial = false) {
|
|
57
|
-
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial };
|
|
62
|
+
async function openLane(index, serial = false, workerOverride = undefined) {
|
|
63
|
+
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial, workerOverride };
|
|
58
64
|
lane.context = await createContext(lane);
|
|
59
|
-
lane.specs = await lane.context.globTestSpecifications(files);
|
|
65
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
60
66
|
return lane;
|
|
61
67
|
}
|
|
62
68
|
|
|
@@ -109,21 +115,21 @@ async function runInThread(lane, plans, limit, deadline) {
|
|
|
109
115
|
.filter(([, list]) => list.length));
|
|
110
116
|
await Promise.race([lane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
111
117
|
lane.context = await createContext(lane);
|
|
112
|
-
lane.specs = await lane.context.globTestSpecifications(files);
|
|
118
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
113
119
|
}
|
|
114
120
|
return events;
|
|
115
121
|
}
|
|
116
122
|
|
|
117
|
-
async function run(specs, state, lane = lanes[0]) {
|
|
123
|
+
async function run(specs, state, lane = lanes[0], timeoutMs = runTimeout) {
|
|
118
124
|
lane.snapshot = null;
|
|
119
125
|
rmSync(destination, { force: true });
|
|
120
126
|
lane.context.provide('tmtSession', { ...state, destination });
|
|
121
127
|
const timeout = setTimeout(() => {
|
|
122
128
|
record(state.id === undefined
|
|
123
|
-
? { baseline: { status: 'timeout' } }
|
|
129
|
+
? { baseline: { status: 'timeout', timeoutSeconds: Math.round(timeoutMs / 1000) } }
|
|
124
130
|
: { id: state.id, status: 'timeout', statusReason: 'Vitest did not finish before its deadline' });
|
|
125
131
|
process.exit(124);
|
|
126
|
-
},
|
|
132
|
+
}, timeoutMs);
|
|
127
133
|
try {
|
|
128
134
|
await lane.context.runTestSpecifications(specs);
|
|
129
135
|
if (!lane.snapshot) throw new Error('Vitest did not report a completed run');
|
|
@@ -166,8 +172,14 @@ try {
|
|
|
166
172
|
// its mutations are kept per file.
|
|
167
173
|
const oneByOne = { maxWorkers: 1, fileParallelism: false };
|
|
168
174
|
const beside = concurrency === 1 || isolatedTrials ? oneByOne : { maxWorkers: concurrency };
|
|
175
|
+
const resolveWorkers = lane => {
|
|
176
|
+
if (lane.workerOverride !== undefined) {
|
|
177
|
+
return lane.workerOverride === 1 ? oneByOne : { maxWorkers: lane.workerOverride };
|
|
178
|
+
}
|
|
179
|
+
return lane.serial ? oneByOne : beside;
|
|
180
|
+
};
|
|
169
181
|
createContext = async lane => {
|
|
170
|
-
const workers = lane
|
|
182
|
+
const workers = resolveWorkers(lane);
|
|
171
183
|
const created = await createVitest('test', {
|
|
172
184
|
root: workspace, config, watch: false, api: false, ui: false, cache: false,
|
|
173
185
|
pool: 'threads', isolate: true, maxConcurrency: 1, ...workers,
|
|
@@ -188,17 +200,25 @@ try {
|
|
|
188
200
|
}
|
|
189
201
|
return created;
|
|
190
202
|
};
|
|
191
|
-
|
|
192
|
-
const
|
|
203
|
+
const trialWorkers = concurrency === 1 || isolatedTrials ? 1 : concurrency;
|
|
204
|
+
const distinctBaselineLane = baselineWorkers !== undefined && baselineWorkers !== trialWorkers;
|
|
205
|
+
const baselineLane = await openLane('baseline', false, distinctBaselineLane ? baselineWorkers : undefined);
|
|
206
|
+
lanes.push(baselineLane);
|
|
207
|
+
const { specs } = baselineLane;
|
|
193
208
|
const discovered = new Set(specs.map(spec => inside(workspace, spec.moduleId)));
|
|
194
209
|
if (files.length && (files.some(file => !discovered.has(file)) || discovered.size !== files.length)) {
|
|
195
210
|
throw new Error('Vitest test selection mismatch');
|
|
196
211
|
}
|
|
197
212
|
const baselineState = { phase: 'baseline' };
|
|
198
213
|
const baselineStarted = Date.now();
|
|
199
|
-
const baseline = await run(specs, baselineState);
|
|
200
|
-
const baselineTiming =
|
|
214
|
+
const baseline = await run(specs, baselineState, baselineLane, baselineTimeout);
|
|
215
|
+
const baselineTiming = baselineLane.timing;
|
|
201
216
|
const baselineTime = Date.now() - baselineStarted;
|
|
217
|
+
if (distinctBaselineLane) {
|
|
218
|
+
await Promise.race([baselineLane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
219
|
+
lanes.length = 0;
|
|
220
|
+
lanes.push(await openLane(0));
|
|
221
|
+
}
|
|
202
222
|
const passed = baseline.snapshot.tests.filter(test => test.status === 'passed');
|
|
203
223
|
const tests = new Map(passed.map(test => [test.id, test]));
|
|
204
224
|
const coveredModules = new Set(baseline.records.flatMap(record => record.modules.map(([project, file]) =>
|
package/src/targeted-gaps.mjs
CHANGED
|
@@ -25,7 +25,7 @@ const roundingDiffers = { 'floor trunc': 'negative and not a whole number (-0.5)
|
|
|
25
25
|
'floor round': 'a number that rounds up (1.5, -1.5)', 'ceil round': 'a number that rounds down (1.4, -1.6)',
|
|
26
26
|
'round trunc': 'a number that rounds away from zero (1.5, -1.6)', 'ceil floor': 'not a whole number (0.5)' };
|
|
27
27
|
|
|
28
|
-
function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, key, boundKind, pruned, argName }, expression, rule, replacement) {
|
|
28
|
+
function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, rightFalsy, key, boundKind, pruned, argName }, expression, rule, replacement) {
|
|
29
29
|
const side = '`' + clip(left) + '`';
|
|
30
30
|
if (rule === rules.spreadDrop) return `a test in which \`${clip(left)}.${key}\` is missing or differs from its updated value`;
|
|
31
31
|
if (rule === rules.prefixSubstring) {
|
|
@@ -48,7 +48,14 @@ function missingInput({ operator, form, boolean, left, right: rightExpr, differs
|
|
|
48
48
|
}
|
|
49
49
|
if (form === 'true' || form === 'false') return `a test in which \`${clip(expression)}\` is ${form === 'true' ? 'false' : 'true'}`;
|
|
50
50
|
if (form === 'loose' || form === 'strict' || form === 'other') return `a test in which \`${clip(subject)}\` is ${differsFor}`;
|
|
51
|
-
if (form === 'or' || form === 'nullish')
|
|
51
|
+
if (form === 'or' || form === 'nullish') {
|
|
52
|
+
if (rightFalsy) {
|
|
53
|
+
const values = ['0', '0n', "''", 'false', 'NaN'].filter(value => value !== rightFalsy);
|
|
54
|
+
const list = `${values.slice(0, -1).join(', ')} or ${values.at(-1)}`;
|
|
55
|
+
return `a test in which ${side} is ${list}`;
|
|
56
|
+
}
|
|
57
|
+
return `a test in which ${side} is 0, 0n, '', false or NaN${pureRight ? ' and not the right side\'s value' : ''}`;
|
|
58
|
+
}
|
|
52
59
|
const takesRight = { '&&': 'truthy', '||': 'falsy', '??': 'null or undefined' }[operator];
|
|
53
60
|
if (form === 'left') return `a test in which ${side} is ${{ '&&': 'falsy', '||': 'truthy', '??': 'neither null nor undefined' }[operator]}`;
|
|
54
61
|
const kept = { '&&': 'true', '||': 'false', '??': 'undefined' }[operator];
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
4
|
+
|
|
5
|
+
const PRIMITIVE_PROTOTYPE_KEYS = new Set([
|
|
6
|
+
'__proto__',
|
|
7
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
8
|
+
...Object.getOwnPropertyNames(String.prototype),
|
|
9
|
+
...Object.getOwnPropertyNames(Number.prototype),
|
|
10
|
+
...Object.getOwnPropertyNames(Boolean.prototype),
|
|
11
|
+
...Object.getOwnPropertyNames(BigInt.prototype),
|
|
12
|
+
...Object.getOwnPropertyNames(Symbol.prototype),
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
function isGuaranteedNonPrimitiveObject(ts, checker, type) {
|
|
16
|
+
if (checker.isArrayType(type) || checker.isTupleType(type)) return true;
|
|
17
|
+
if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return true;
|
|
18
|
+
// Require at least one non-optional property that does not exist on built-in primitive prototypes;
|
|
19
|
+
// `{}` and `{ toString(): string }` accept primitives like `0`, `""`, and `false` in TypeScript.
|
|
20
|
+
for (const prop of type.getProperties()) {
|
|
21
|
+
if (prop.flags & ts.SymbolFlags.Optional) continue;
|
|
22
|
+
if (!PRIMITIVE_PROTOTYPE_KEYS.has(prop.name)) return true;
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function canContainNullish(ts, checker, type, kind, seen = new Set()) {
|
|
28
|
+
if (!type || seen.has(type)) return true;
|
|
29
|
+
seen.add(type);
|
|
30
|
+
const flags = type.flags;
|
|
31
|
+
// `void` can hold arbitrary return values at runtime (e.g. `const f: () => void = () => false`).
|
|
32
|
+
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Void)) return true;
|
|
33
|
+
if (flags & ts.TypeFlags.Never) return false;
|
|
34
|
+
if (kind === 'null' && (flags & ts.TypeFlags.Null)) return true;
|
|
35
|
+
if (kind === 'undefined' && (flags & ts.TypeFlags.Undefined)) return true;
|
|
36
|
+
if (type.isUnion()) return type.types.some(member => canContainNullish(ts, checker, member, kind, new Set(seen)));
|
|
37
|
+
if (type.isIntersection()) return type.types.every(member => canContainNullish(ts, checker, member, kind, new Set(seen)));
|
|
38
|
+
if (flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess | ts.TypeFlags.Conditional | ts.TypeFlags.Substitution | ts.TypeFlags.TemplateLiteral)) {
|
|
39
|
+
const constraint = checker.getBaseConstraintOfType(type);
|
|
40
|
+
return constraint ? canContainNullish(ts, checker, constraint, kind, seen) : true;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new Set()) {
|
|
46
|
+
if (!type || seen.has(type)) return 'any';
|
|
47
|
+
seen.add(type);
|
|
48
|
+
const flags = type.flags;
|
|
49
|
+
// `void` can hold arbitrary return values at runtime (e.g. `() => void` returning `false` or `0`).
|
|
50
|
+
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Void)) return 'any';
|
|
51
|
+
if (flags & (ts.TypeFlags.Never | ts.TypeFlags.Null | ts.TypeFlags.Undefined)) return out;
|
|
52
|
+
if (type.isUnion()) {
|
|
53
|
+
for (const member of type.types) {
|
|
54
|
+
if (collectNonNullishFalsy(ts, checker, member, out, new Set(seen)) === 'any') return 'any';
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
if (type.isIntersection()) {
|
|
59
|
+
if (type.types.some(member => member.flags & ts.TypeFlags.Never)) return out;
|
|
60
|
+
// Branded primitives (e.g. `string & { __brand: 'id' }`) still carry the primitive's runtime values,
|
|
61
|
+
// so over-approximating by collecting from all constituents is sound.
|
|
62
|
+
for (const member of type.types) {
|
|
63
|
+
if (collectNonNullishFalsy(ts, checker, member, out, new Set(seen)) === 'any') return 'any';
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
if (flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess | ts.TypeFlags.Conditional | ts.TypeFlags.Substitution)) {
|
|
68
|
+
const constraint = checker.getBaseConstraintOfType(type);
|
|
69
|
+
return constraint ? collectNonNullishFalsy(ts, checker, constraint, out, seen) : 'any';
|
|
70
|
+
}
|
|
71
|
+
if (flags & (ts.TypeFlags.String | ts.TypeFlags.TemplateLiteral | ts.TypeFlags.StringMapping)) {
|
|
72
|
+
out.add('string');
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
if (flags & ts.TypeFlags.StringLiteral) {
|
|
76
|
+
if (type.value === '') out.add('string');
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
if (flags & ts.TypeFlags.Boolean) {
|
|
80
|
+
out.add('boolean');
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
if (flags & ts.TypeFlags.BooleanLiteral) {
|
|
84
|
+
if (checker.typeToString(type) === 'false') out.add('boolean');
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
if (flags & ts.TypeFlags.BigInt) {
|
|
88
|
+
out.add('bigint');
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
if (flags & ts.TypeFlags.BigIntLiteral) {
|
|
92
|
+
if (type.value?.base10Value === '0') out.add('bigint');
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
if (flags & ts.TypeFlags.Number) {
|
|
96
|
+
out.add('number_zero');
|
|
97
|
+
out.add('number_nan');
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
if (flags & ts.TypeFlags.NumberLiteral) {
|
|
101
|
+
// Numeric enum types accept arbitrary numbers (including 0 and NaN) without a TypeScript error.
|
|
102
|
+
if ((flags & (ts.TypeFlags.Enum | ts.TypeFlags.EnumLiteral)) || type.value === 0 || Object.is(type.value, -0) || Number.isNaN(type.value)) {
|
|
103
|
+
out.add('number_zero');
|
|
104
|
+
out.add('number_nan');
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
if (flags & (ts.TypeFlags.ESSymbol | ts.TypeFlags.UniqueESSymbol | ts.TypeFlags.NonPrimitive)) {
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
if (flags & ts.TypeFlags.Object) {
|
|
112
|
+
return isGuaranteedNonPrimitiveObject(ts, checker, type) ? out : 'any';
|
|
113
|
+
}
|
|
114
|
+
return 'any';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function hasLocalUndefinedBinding(ts, checker, node) {
|
|
118
|
+
if (typeof checker.resolveName === 'function') {
|
|
119
|
+
const sym = checker.resolveName('undefined', node, ts.SymbolFlags.Value, false);
|
|
120
|
+
if (sym?.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) return true;
|
|
121
|
+
}
|
|
122
|
+
if (typeof checker.getSymbolsInScope === 'function') {
|
|
123
|
+
const inScope = checker.getSymbolsInScope(node, ts.SymbolFlags.Value);
|
|
124
|
+
for (const sym of inScope) {
|
|
125
|
+
if (sym.name === 'undefined' && sym.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) {
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function isUncheckedIndexedRead(ts, checker, node) {
|
|
134
|
+
while (node && ts.isParenthesizedExpression(node)) node = node.expression;
|
|
135
|
+
if (!node) return false;
|
|
136
|
+
if (ts.isElementAccessExpression(node)) return true;
|
|
137
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
138
|
+
const recvType = checker.getTypeAtLocation(node.expression);
|
|
139
|
+
if (recvType && checker.getIndexTypeOfType(recvType, ts.IndexKind.String) && !recvType.getProperty(node.name.text)) {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (ts.isIdentifier(node)) {
|
|
144
|
+
const sym = checker.getSymbolAtLocation(node);
|
|
145
|
+
const decl = sym?.valueDeclaration;
|
|
146
|
+
if (decl && ts.isVariableDeclaration(decl) && decl.initializer && isUncheckedIndexedRead(ts, checker, decl.initializer)) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function indexExpressions(ts, sourceFile) {
|
|
154
|
+
const nodes = new Map();
|
|
155
|
+
(function walk(node) {
|
|
156
|
+
if (!ts.isParenthesizedExpression(node)) {
|
|
157
|
+
const start = node.getStart(sourceFile);
|
|
158
|
+
const key = `${start}:${node.end}`;
|
|
159
|
+
if (!nodes.has(key)) nodes.set(key, node);
|
|
160
|
+
}
|
|
161
|
+
ts.forEachChild(node, walk);
|
|
162
|
+
})(sourceFile);
|
|
163
|
+
return nodes;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isWithinRoot(realRoot, candidate) {
|
|
167
|
+
const rel = relative(realRoot, candidate);
|
|
168
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function normalizePath(filePath) {
|
|
172
|
+
return existsSync(filePath) ? realpathSync(filePath) : resolve(filePath);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function readParsedConfig(ts, configPath, cache) {
|
|
176
|
+
const key = normalizePath(configPath);
|
|
177
|
+
if (cache.has(key)) return cache.get(key);
|
|
178
|
+
if (!existsSync(key)) {
|
|
179
|
+
const missing = { configPath: key, missing: true, strictNullChecks: false };
|
|
180
|
+
cache.set(key, missing);
|
|
181
|
+
return missing;
|
|
182
|
+
}
|
|
183
|
+
const read = ts.readConfigFile(key, ts.sys.readFile);
|
|
184
|
+
if (read.error || !read.config) {
|
|
185
|
+
const failed = { configPath: key, error: true, strictNullChecks: false };
|
|
186
|
+
cache.set(key, failed);
|
|
187
|
+
return failed;
|
|
188
|
+
}
|
|
189
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(key));
|
|
190
|
+
const compilerOptions = parsed.options ?? {};
|
|
191
|
+
const strictNullChecks = compilerOptions.strictNullChecks === true ||
|
|
192
|
+
(compilerOptions.strict === true && compilerOptions.strictNullChecks !== false);
|
|
193
|
+
const fileNames = new Set((parsed.fileNames ?? []).map(normalizePath));
|
|
194
|
+
const info = {
|
|
195
|
+
configPath: key,
|
|
196
|
+
parsed,
|
|
197
|
+
compilerOptions,
|
|
198
|
+
strictNullChecks,
|
|
199
|
+
noUncheckedIndexedAccess: compilerOptions.noUncheckedIndexedAccess === true,
|
|
200
|
+
projectReferences: parsed.projectReferences ?? [],
|
|
201
|
+
fileNames,
|
|
202
|
+
};
|
|
203
|
+
cache.set(key, info);
|
|
204
|
+
return info;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function resolveReferenceConfigPath(refPath) {
|
|
208
|
+
const resolved = resolve(refPath);
|
|
209
|
+
const st = statSync(resolved, { throwIfNoEntry: false });
|
|
210
|
+
if (st?.isDirectory()) return resolve(resolved, 'tsconfig.json');
|
|
211
|
+
return resolved;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function findConfigViaReferences(ts, configPath, absFile, cache, visited = new Set()) {
|
|
215
|
+
const key = normalizePath(configPath);
|
|
216
|
+
if (visited.has(key)) return null;
|
|
217
|
+
visited.add(key);
|
|
218
|
+
const info = readParsedConfig(ts, key, cache);
|
|
219
|
+
if (info.missing || info.error) return null;
|
|
220
|
+
for (const ref of info.projectReferences) {
|
|
221
|
+
const refConfigPath = resolveReferenceConfigPath(ref.path);
|
|
222
|
+
if (!existsSync(refConfigPath)) continue;
|
|
223
|
+
const refInfo = readParsedConfig(ts, refConfigPath, cache);
|
|
224
|
+
if (refInfo.missing || refInfo.error) continue;
|
|
225
|
+
if (refInfo.fileNames.has(absFile)) return refInfo.configPath;
|
|
226
|
+
if (refInfo.projectReferences.length) {
|
|
227
|
+
const nested = findConfigViaReferences(ts, refInfo.configPath, absFile, cache, visited);
|
|
228
|
+
if (nested) return nested;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function collectAncestorConfigsInRoot(ts, realRoot, startDir) {
|
|
235
|
+
const configs = [];
|
|
236
|
+
let dir = startDir;
|
|
237
|
+
while (isWithinRoot(realRoot, dir)) {
|
|
238
|
+
const candidate = resolve(dir, 'tsconfig.json');
|
|
239
|
+
if (ts.sys.fileExists(candidate)) configs.push(normalizePath(candidate));
|
|
240
|
+
const parent = dirname(dir);
|
|
241
|
+
if (parent === dir) break;
|
|
242
|
+
dir = parent;
|
|
243
|
+
}
|
|
244
|
+
return configs;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, cache) {
|
|
248
|
+
if (explicitConfigPath) return explicitConfigPath;
|
|
249
|
+
const ancestors = collectAncestorConfigsInRoot(ts, realRoot, dirname(absFile));
|
|
250
|
+
if (!ancestors.length) {
|
|
251
|
+
const fallback = ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
252
|
+
if (fallback) ancestors.push(normalizePath(fallback));
|
|
253
|
+
}
|
|
254
|
+
if (!ancestors.length) return null;
|
|
255
|
+
|
|
256
|
+
// Walk from nearest ancestor upward: if a config has projectReferences, prefer an owning
|
|
257
|
+
// referenced config before falling back to an ancestor config that merely includes absFile.
|
|
258
|
+
for (const configPath of ancestors) {
|
|
259
|
+
const info = readParsedConfig(ts, configPath, cache);
|
|
260
|
+
if (info.missing || info.error) continue;
|
|
261
|
+
if (info.projectReferences.length) {
|
|
262
|
+
const fromRef = findConfigViaReferences(ts, configPath, absFile, cache);
|
|
263
|
+
if (fromRef) return fromRef;
|
|
264
|
+
}
|
|
265
|
+
if (info.fileNames.has(absFile)) {
|
|
266
|
+
return configPath;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Fallback to the nearest ancestor tsconfig so warnings report the actual config checked.
|
|
271
|
+
return ancestors[0];
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function buildGroupContext(ts, info, absTargets) {
|
|
275
|
+
const { compilerOptions, noUncheckedIndexedAccess, parsed } = info;
|
|
276
|
+
const ambientDts = (parsed.fileNames ?? []).filter(file => file.endsWith('.d.ts'));
|
|
277
|
+
const rootNames = [...new Set([...absTargets, ...ambientDts])];
|
|
278
|
+
if (!rootNames.length) return () => null;
|
|
279
|
+
const program = ts.createProgram(rootNames, { ...compilerOptions, noEmit: true });
|
|
280
|
+
const checker = program.getTypeChecker();
|
|
281
|
+
const fileCache = new Map();
|
|
282
|
+
|
|
283
|
+
return (absFile, resolved) => {
|
|
284
|
+
if (fileCache.has(absFile)) return fileCache.get(absFile);
|
|
285
|
+
const sourceFile = program.getSourceFile(absFile) ?? program.getSourceFile(resolved);
|
|
286
|
+
if (!sourceFile) {
|
|
287
|
+
fileCache.set(absFile, null);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
const nodes = indexExpressions(ts, sourceFile);
|
|
291
|
+
const helper = {
|
|
292
|
+
isNullishEqualityEquivalent(subjectStart, subjectEnd, differsFor) {
|
|
293
|
+
if (differsFor !== 'null' && differsFor !== 'undefined') return false;
|
|
294
|
+
const node = nodes.get(`${subjectStart}:${subjectEnd}`);
|
|
295
|
+
if (!node) return false;
|
|
296
|
+
// Without `noUncheckedIndexedAccess`, indexed reads (`xs[i]`, `rec.missing`, or variables initialized from them) can evaluate to `undefined` at runtime.
|
|
297
|
+
if (!noUncheckedIndexedAccess && differsFor === 'undefined' && isUncheckedIndexedRead(ts, checker, node)) return false;
|
|
298
|
+
// If `undefined` is locally shadowed in scope, `x === undefined` / `=== undefined` does not compare against the built-in value.
|
|
299
|
+
if (hasLocalUndefinedBinding(ts, checker, node)) return false;
|
|
300
|
+
const type = checker.getTypeAtLocation(node);
|
|
301
|
+
if (!type) return false;
|
|
302
|
+
return !canContainNullish(ts, checker, type, differsFor);
|
|
303
|
+
},
|
|
304
|
+
isNullishFallbackEquivalent(leftStart, leftEnd, rightFalsy) {
|
|
305
|
+
const node = nodes.get(`${leftStart}:${leftEnd}`);
|
|
306
|
+
if (!node) return false;
|
|
307
|
+
const type = checker.getTypeAtLocation(node);
|
|
308
|
+
if (!type) return false;
|
|
309
|
+
const falsy = collectNonNullishFalsy(ts, checker, type);
|
|
310
|
+
if (falsy === 'any') return false;
|
|
311
|
+
if (falsy.size === 0) return true;
|
|
312
|
+
if (falsy.size === 1) {
|
|
313
|
+
if (falsy.has('string') && rightFalsy === "''") return true;
|
|
314
|
+
if (falsy.has('boolean') && rightFalsy === 'false') return true;
|
|
315
|
+
if (falsy.has('bigint') && rightFalsy === '0n') return true;
|
|
316
|
+
}
|
|
317
|
+
return false;
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
fileCache.set(absFile, helper);
|
|
321
|
+
return helper;
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function createTypeContext(root, targetFiles = [], { tsconfig, onWarning, ts = loadTypeScript() } = {}) {
|
|
326
|
+
const realRoot = existsSync(root) ? realpathSync(root) : resolve(root);
|
|
327
|
+
const configCache = new Map();
|
|
328
|
+
const warnings = [];
|
|
329
|
+
const seenWarnings = new Set();
|
|
330
|
+
const warn = message => {
|
|
331
|
+
if (seenWarnings.has(message)) return;
|
|
332
|
+
seenWarnings.add(message);
|
|
333
|
+
warnings.push(message);
|
|
334
|
+
onWarning?.(message);
|
|
335
|
+
};
|
|
336
|
+
const labelConfig = configPath => {
|
|
337
|
+
const rel = relative(realRoot, configPath);
|
|
338
|
+
return rel && !isAbsolute(rel) && !rel.startsWith('..' + sep) ? rel : configPath;
|
|
339
|
+
};
|
|
340
|
+
const explicitConfigPath = tsconfig ? resolve(realRoot, tsconfig) : null;
|
|
341
|
+
|
|
342
|
+
if (!targetFiles.length) {
|
|
343
|
+
const configPath = explicitConfigPath ?? ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
344
|
+
if (!configPath || !existsSync(configPath)) {
|
|
345
|
+
warn(explicitConfigPath
|
|
346
|
+
? `--type-check: tsconfig file not found (${tsconfig}); skipping type-based suppression.`
|
|
347
|
+
: '--type-check: no tsconfig.json found; skipping type-based suppression.');
|
|
348
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
349
|
+
}
|
|
350
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
351
|
+
if (info.error) {
|
|
352
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
353
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
354
|
+
}
|
|
355
|
+
if (!info.strictNullChecks) {
|
|
356
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
357
|
+
}
|
|
358
|
+
return { strictNullChecks: info.strictNullChecks, warnings, forFile: () => null };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const grouped = new Map();
|
|
362
|
+
const fileToConfig = new Map();
|
|
363
|
+
for (const file of targetFiles) {
|
|
364
|
+
const resolved = resolve(realRoot, file);
|
|
365
|
+
const absFile = normalizePath(resolved);
|
|
366
|
+
const configPath = resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, configCache);
|
|
367
|
+
if (!configPath) {
|
|
368
|
+
warn(`--type-check: no tsconfig.json found for ${file}; skipping type-based suppression.`);
|
|
369
|
+
fileToConfig.set(absFile, null);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
const key = normalizePath(configPath);
|
|
373
|
+
fileToConfig.set(absFile, key);
|
|
374
|
+
if (!grouped.has(key)) grouped.set(key, []);
|
|
375
|
+
grouped.get(key).push(absFile);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const groupLookups = new Map();
|
|
379
|
+
let anyStrictNullChecks = false;
|
|
380
|
+
for (const [configPath, absTargets] of grouped) {
|
|
381
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
382
|
+
if (info.missing) {
|
|
383
|
+
warn(`--type-check: tsconfig file not found (${tsconfig ?? labelConfig(configPath)}); skipping type-based suppression.`);
|
|
384
|
+
groupLookups.set(configPath, () => null);
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (info.error) {
|
|
388
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
389
|
+
groupLookups.set(configPath, () => null);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (!info.strictNullChecks) {
|
|
393
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
394
|
+
groupLookups.set(configPath, () => null);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
anyStrictNullChecks = true;
|
|
398
|
+
groupLookups.set(configPath, buildGroupContext(ts, info, absTargets));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function forFile(file) {
|
|
402
|
+
const resolved = resolve(realRoot, file);
|
|
403
|
+
const absFile = normalizePath(resolved);
|
|
404
|
+
const configKey = fileToConfig.get(absFile);
|
|
405
|
+
if (!configKey) return null;
|
|
406
|
+
const lookup = groupLookups.get(configKey);
|
|
407
|
+
return lookup ? lookup(absFile, resolved) : null;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return { strictNullChecks: anyStrictNullChecks, warnings, forFile };
|
|
411
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { relative } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { inside, runnerPackage } from './vitest.mjs';
|
|
6
|
+
|
|
7
|
+
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
8
|
+
const { workspace, config, targets, output } = input;
|
|
9
|
+
|
|
10
|
+
const manifest = runnerPackage(workspace, 'vitest');
|
|
11
|
+
const vitestNode = createRequire(manifest).resolve('vitest/node');
|
|
12
|
+
const { createVitest } = await import(pathToFileURL(vitestNode).href);
|
|
13
|
+
|
|
14
|
+
const vitest = await createVitest('test', {
|
|
15
|
+
root: workspace,
|
|
16
|
+
...(config === undefined ? {} : { config: inside(workspace, config) }),
|
|
17
|
+
watch: false,
|
|
18
|
+
api: false,
|
|
19
|
+
ui: false,
|
|
20
|
+
cache: false,
|
|
21
|
+
related: targets.map(file => inside(workspace, file)),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
let specs;
|
|
25
|
+
try {
|
|
26
|
+
if (typeof vitest.getRelevantTestSpecifications !== 'function') {
|
|
27
|
+
throw new Error('Installed Vitest version does not support programmatic related test resolution; specify test files with --test <FILE>');
|
|
28
|
+
}
|
|
29
|
+
specs = await vitest.getRelevantTestSpecifications();
|
|
30
|
+
} finally {
|
|
31
|
+
await vitest.close();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const resolved = [];
|
|
35
|
+
const seen = new Set();
|
|
36
|
+
for (const spec of specs ?? []) {
|
|
37
|
+
if (!spec?.moduleId) continue;
|
|
38
|
+
const project = spec.project?.name ?? '';
|
|
39
|
+
const file = relative(workspace, inside(workspace, spec.moduleId));
|
|
40
|
+
const key = JSON.stringify([project, file]);
|
|
41
|
+
if (!seen.has(key)) {
|
|
42
|
+
seen.add(key);
|
|
43
|
+
resolved.push({ project, file });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
resolved.sort((a, b) => a.file.localeCompare(b.file) || a.project.localeCompare(b.project));
|
|
47
|
+
writeFileSync(output, JSON.stringify({ specs: resolved }), 'utf8');
|