targeted-mutation 0.0.0-stage → 0.1.1
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 +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +149 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function shiftedReplacement(source, site, adjustment) {
|
|
2
|
+
const operand = source.subarray(...site.right).toString();
|
|
3
|
+
const literal = /^-?\s*\d+$/.test(operand) ? Number(operand.replace(/\s+/g, '')) : NaN;
|
|
4
|
+
return Number.isSafeInteger(literal) && Number.isSafeInteger(literal + adjustment)
|
|
5
|
+
? String(literal + adjustment)
|
|
6
|
+
: `((${operand}) ${adjustment < 0 ? '-' : '+'} ${Math.abs(adjustment)})`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function tighteningEdit(source, site) {
|
|
10
|
+
const adjustment = site.operator === '<' ? -1 : 1;
|
|
11
|
+
return { site, edit: site.right, replacement: shiftedReplacement(source, site, adjustment), rule: 'comparison-tighten/v1', adjustment };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function tightenComparison(source, site, observation, enabled) {
|
|
15
|
+
if (!enabled || !observation.complete || !observation.rows.length || !['<', '>'].includes(site.operator)) return null;
|
|
16
|
+
const trial = tighteningEdit(source, site);
|
|
17
|
+
if (observation.rows.some(({ operands }) => !Number.isSafeInteger(operands[1] + trial.adjustment))) return null;
|
|
18
|
+
return { ...trial, observation };
|
|
19
|
+
}
|
package/src/extract.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { isUtf8 } from 'node:buffer';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { types } from 'node:util';
|
|
5
|
+
import { isMainThread } from 'node:worker_threads';
|
|
6
|
+
import { binaryPath } from './runtime-binaries.mjs';
|
|
7
|
+
import { invalidEncoding, normalize, optionsFor } from './source-text.mjs';
|
|
8
|
+
|
|
9
|
+
export { byteOffsets, sourceDialect } from './source-text.mjs';
|
|
10
|
+
|
|
11
|
+
const load = createRequire(import.meta.url);
|
|
12
|
+
const nativePath = binaryPath('tmt.node');
|
|
13
|
+
let native = null;
|
|
14
|
+
let nativeLoadError = null;
|
|
15
|
+
if (nativePath) {
|
|
16
|
+
try {
|
|
17
|
+
native = load(nativePath);
|
|
18
|
+
} catch (error) {
|
|
19
|
+
nativeLoadError = error;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const operators = ['', '<', '<=', '>', '>='];
|
|
23
|
+
const reasons = ['', 'outside-l1', 'source-limit', 'depth-limit', 'candidate-limit', 'duplicate-lexical'];
|
|
24
|
+
export const rule = 'comparison-boundary/v1';
|
|
25
|
+
|
|
26
|
+
// Extracted operator starts are in byte order and lie on UTF-8 code-point boundaries.
|
|
27
|
+
export function byteLocations(source, offsets) {
|
|
28
|
+
if (!offsets.length) return [];
|
|
29
|
+
if (native?.locations && source.length < 0xffffffff) return native.locations(source, Uint32Array.from(offsets));
|
|
30
|
+
return offsets.flatMap(offset => {
|
|
31
|
+
const lines = source.toString('utf8', 0, offset).split(/\r\n|[\n\r\u2028\u2029]/);
|
|
32
|
+
return [lines.length, lines.at(-1).length + 1];
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function duplicateLexical(source, rows, file, metrics) {
|
|
37
|
+
const [, , , , first, firstEnd, start, end] = rows;
|
|
38
|
+
const name = source.toString('utf8', start, end);
|
|
39
|
+
return { path: 'diagnostic', reason: 'duplicate-lexical', metrics, candidates: [], diagnostics: [{
|
|
40
|
+
severity: 'error', message: `Identifier '${name}' has already been declared`, path: file ?? null, start, end,
|
|
41
|
+
labels: [
|
|
42
|
+
{ start: first, end: firstEnd, message: `'${name}' was first declared as a variable here` },
|
|
43
|
+
{ start, end, message: 'cannot be redeclared here' },
|
|
44
|
+
],
|
|
45
|
+
help: `Consider removing or renaming this declaration of '${name}'`,
|
|
46
|
+
}] };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function extractFallback(input, options = {}) {
|
|
50
|
+
const source = normalize(input);
|
|
51
|
+
if (source === null) return invalidEncoding();
|
|
52
|
+
const { dialect, mode } = optionsFor(options);
|
|
53
|
+
const parserOptions = { dialect, mode, logical: !!options.logical, file: options.file };
|
|
54
|
+
if (isMainThread) {
|
|
55
|
+
try {
|
|
56
|
+
const { extractTypeScript } = load('./typescript-extraction.mjs');
|
|
57
|
+
return extractTypeScript(source, parserOptions);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (!(error instanceof RangeError && error.message === 'Maximum call stack size exceeded')) throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Worker stacks can be smaller than the compiler's recursive parser requires.
|
|
64
|
+
const { spawnSync } = load('node:child_process');
|
|
65
|
+
const child = spawnSync(process.execPath, [
|
|
66
|
+
'--max-old-space-size=512', fileURLToPath(new URL('./fallback-process.mjs', import.meta.url)),
|
|
67
|
+
], {
|
|
68
|
+
input: JSON.stringify({ source, options: parserOptions }),
|
|
69
|
+
stdio: ['pipe', 'ignore', 'pipe', 'pipe'],
|
|
70
|
+
encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024, killSignal: 'SIGKILL',
|
|
71
|
+
});
|
|
72
|
+
if (child.error || child.status !== 0) {
|
|
73
|
+
const reason = child.error?.message ?? (child.signal ? `signal ${child.signal}` : `status ${child.status}`);
|
|
74
|
+
const stderr = child.stderr?.trim();
|
|
75
|
+
const cause = child.error ?? (stderr ? new Error(stderr.slice(0, 1024)) : undefined);
|
|
76
|
+
throw new Error(`The isolated parser failed with ${reason}`, { cause });
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
return JSON.parse(child.output[3]);
|
|
80
|
+
} catch (cause) {
|
|
81
|
+
throw new Error('The isolated parser returned an unreadable result', { cause });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function extract(input, options = {}) {
|
|
86
|
+
if (!native && options.requireNative) throw new Error(`The native extractor is not available for ${process.platform} ${process.arch}. ` +
|
|
87
|
+
(nativeLoadError ? `Loading ${nativePath} failed (${nativeLoadError.code ?? nativeLoadError.message}). ` : '') +
|
|
88
|
+
'Prebuilt binaries cover macOS and Linux (glibc) on arm64 and x64; check that optional dependencies were installed. ' +
|
|
89
|
+
'In a source checkout, run npm run build:native to build the extractor.');
|
|
90
|
+
const { dialect, mode } = optionsFor(options);
|
|
91
|
+
let reason = 'native-unavailable';
|
|
92
|
+
let metrics;
|
|
93
|
+
let fallbackInput = input;
|
|
94
|
+
if (native) {
|
|
95
|
+
const inputString = typeof input === 'string';
|
|
96
|
+
let source;
|
|
97
|
+
if (inputString) {
|
|
98
|
+
if (!input.isWellFormed()) return invalidEncoding();
|
|
99
|
+
source = Buffer.from(input);
|
|
100
|
+
} else {
|
|
101
|
+
try {
|
|
102
|
+
const view = ArrayBuffer.isView(input);
|
|
103
|
+
if (!view && !types.isAnyArrayBuffer(input)) return invalidEncoding();
|
|
104
|
+
const buffer = view ? input.buffer : input;
|
|
105
|
+
source = Buffer.from(buffer, view ? input.byteOffset : 0, input.byteLength);
|
|
106
|
+
if (types.isSharedArrayBuffer(buffer)) fallbackInput = source = Buffer.from(source);
|
|
107
|
+
if (!isUtf8(source)) return invalidEncoding();
|
|
108
|
+
} catch {
|
|
109
|
+
return invalidEncoding();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const rows = native.parse(source, dialect === 'tsx', mode === 'module');
|
|
113
|
+
if (!types.isUint32Array(rows)) throw new Error('Run npm run build:native to rebuild the extractor');
|
|
114
|
+
const status = rows[0];
|
|
115
|
+
metrics = { maxDepth: rows[1], astNodes: rows[2], candidateBytes: rows[3] };
|
|
116
|
+
if (status === 0) {
|
|
117
|
+
const candidates = [];
|
|
118
|
+
for (let i = 4; i < rows.length; i += 8) {
|
|
119
|
+
candidates.push({
|
|
120
|
+
rule, operator: operators[rows[i]], replacement: operators[rows[i + 1]],
|
|
121
|
+
edit: [rows[i + 2], rows[i + 3]], left: [rows[i + 4], rows[i + 5]], right: [rows[i + 6], rows[i + 7]],
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return { path: 'fast', metrics, candidates };
|
|
125
|
+
}
|
|
126
|
+
reason = reasons[status];
|
|
127
|
+
if (status === 5) return duplicateLexical(source, rows, options.file, metrics);
|
|
128
|
+
if (native.standalone) {
|
|
129
|
+
return { path: 'diagnostic', reason, metrics, candidates: [], diagnostics: [{
|
|
130
|
+
severity: 'error', message: 'Standalone Low* extraction declined the source', start: 0, end: 0,
|
|
131
|
+
}] };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { ...extractFallback(fallbackInput, options), reason, metrics };
|
|
135
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
3
|
+
import { extractTypeScript } from './typescript-extraction.mjs';
|
|
4
|
+
|
|
5
|
+
if (isMainThread) {
|
|
6
|
+
const input = JSON.parse(readFileSync(0, 'utf8'));
|
|
7
|
+
const parser = new Worker(new URL(import.meta.url), {
|
|
8
|
+
workerData: input, resourceLimits: { stackSizeMb: 16 },
|
|
9
|
+
});
|
|
10
|
+
parser.once('message', result => writeFileSync(3, JSON.stringify(result)));
|
|
11
|
+
} else {
|
|
12
|
+
const { source, options } = workerData;
|
|
13
|
+
parentPort.postMessage(extractTypeScript(source, options));
|
|
14
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Runs a task for each item with at most `limit` running at once and returns the results in the items' order.
|
|
2
|
+
// The first failure is rethrown after the tasks already started have settled, and no further task starts.
|
|
3
|
+
export async function inParallel(items, limit, task) {
|
|
4
|
+
const results = new Array(items.length);
|
|
5
|
+
let next = 0;
|
|
6
|
+
let failure;
|
|
7
|
+
const lanes = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
|
|
8
|
+
while (next < items.length && !failure) {
|
|
9
|
+
const index = next++;
|
|
10
|
+
try {
|
|
11
|
+
results[index] = await task(items[index], index);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
failure ??= { error };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
await Promise.all(lanes);
|
|
18
|
+
if (failure) throw failure.error;
|
|
19
|
+
return results;
|
|
20
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { binaryPath } from './runtime-binaries.mjs';
|
|
3
|
+
|
|
4
|
+
let executable;
|
|
5
|
+
const boundaryFlips = new Map([['<', '<='], ['<=', '<'], ['>', '>='], ['>=', '>']]);
|
|
6
|
+
|
|
7
|
+
export function runDecisionBatch(requests, args = []) {
|
|
8
|
+
if (!requests.length) return null;
|
|
9
|
+
executable ??= binaryPath('tmt-decide') ?? '';
|
|
10
|
+
if (!executable) return null;
|
|
11
|
+
const result = spawnSync(executable, args, {
|
|
12
|
+
encoding: 'utf8', input: JSON.stringify(requests), timeout: 15_000, maxBuffer: 4 * 1024 * 1024,
|
|
13
|
+
});
|
|
14
|
+
if (result.status !== 0) return null;
|
|
15
|
+
try {
|
|
16
|
+
const answers = JSON.parse(result.stdout);
|
|
17
|
+
return Array.isArray(answers) && answers.length === requests.length ? answers : null;
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function checkReplay(requests) {
|
|
24
|
+
return runDecisionBatch(requests.map(request => {
|
|
25
|
+
if (request != null && Object.hasOwn(request, 'boundarySummary')) return null;
|
|
26
|
+
if (!Array.isArray(request?.observations) || !boundaryFlips.has(request.original) ||
|
|
27
|
+
boundaryFlips.get(request.original) !== request.replacement) return request;
|
|
28
|
+
const { observations, ...header } = request;
|
|
29
|
+
let safeAndUnequal = true;
|
|
30
|
+
for (const pair of observations) {
|
|
31
|
+
if (!Array.isArray(pair) || pair.length !== 2 || !Number.isSafeInteger(pair[0]) ||
|
|
32
|
+
!Number.isSafeInteger(pair[1]) || pair[0] === pair[1]) {
|
|
33
|
+
safeAndUnequal = false;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return { ...header, boundarySummary: { count: observations.length, safeAndUnequal } };
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { analyze, baselineRunSymbol, completeAnalysis, prepareAnalysis } from './analysis.mjs';
|
|
2
|
+
import { analyzeConventional } from './conventional.mjs';
|
|
3
|
+
|
|
4
|
+
const order = (a, b) => a.location.file.localeCompare(b.location.file) || a.location.start - b.location.start ||
|
|
5
|
+
b.location.end - a.location.end;
|
|
6
|
+
|
|
7
|
+
function fromSession(mutant, profile) {
|
|
8
|
+
const { source: _source, operatorSwap: _swap, ...reported } = mutant;
|
|
9
|
+
if (profile === 'full') return reported;
|
|
10
|
+
// A targeted edit replaces a whole expression, so the report keeps the text it replaced.
|
|
11
|
+
return { site: reported.id, rule: reported.mutatorName, ...reported, id: undefined, mutatorName: undefined };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const definitive = new Set(['killed', 'survived', 'timeout', 'unreached']);
|
|
15
|
+
|
|
16
|
+
// How far a threshold or tightening trial moves the right side of its comparison, or nothing for other trials.
|
|
17
|
+
function shiftOf(trial) {
|
|
18
|
+
if (trial.source || trial.rule === trial.site.rule) return undefined;
|
|
19
|
+
const shift = trial.adjustment ?? (trial.rule === 'comparison-threshold/v1' ? Number(trial.replacement) - trial.threshold?.meta.threshold : undefined);
|
|
20
|
+
return Number.isSafeInteger(shift) && shift !== 0 ? shift : undefined;
|
|
21
|
+
}
|
|
22
|
+
const shiftKey = (trial, shift) => `${trial.site.location.file}:${(trial.site.operatorEdit ?? trial.site.edit)[0]}:${shift}`;
|
|
23
|
+
|
|
24
|
+
// The trials the session can run through a comparison's shift switch, without the ones a recorded run already decided.
|
|
25
|
+
export function shiftTrials(prepared) {
|
|
26
|
+
const listed = new Map();
|
|
27
|
+
for (const [index, trial] of (prepared.trials ?? []).entries()) {
|
|
28
|
+
const shift = shiftOf(trial);
|
|
29
|
+
if (shift === undefined || prepared.skips?.has(index)) continue;
|
|
30
|
+
listed.set(shiftKey(trial, shift), { file: trial.site.location.file, at: (trial.site.operatorEdit ?? trial.site.edit)[0], shift });
|
|
31
|
+
}
|
|
32
|
+
return [...listed.values()];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// A comparison boundary is the same edit in both parts, so the session's run of it answers the focused trial.
|
|
36
|
+
// A threshold or tightening trial is answered by the extra trial the session ran for the same comparison and shift.
|
|
37
|
+
function sessionVerdicts(session, extras = []) {
|
|
38
|
+
const shifted = new Map(extras.map((extra, index) => [`${extra.file}:${extra.at}:${extra.shift}`,
|
|
39
|
+
(session.extras ?? []).find(result => result.extra === index)]));
|
|
40
|
+
const swaps = new Map(session.mutants.filter(mutant => mutant.operatorSwap && definitive.has(mutant.status))
|
|
41
|
+
.map(mutant => [`${mutant.location.file}:${mutant.operatorSwap.join(':')}`, mutant]));
|
|
42
|
+
return trial => {
|
|
43
|
+
const shift = shiftOf(trial);
|
|
44
|
+
const mutant = shift !== undefined ? shifted.get(shiftKey(trial, shift))
|
|
45
|
+
: trial.rule !== trial.site.rule || trial.source ? undefined
|
|
46
|
+
: swaps.get(`${trial.site.location.file}:${trial.edit[0]}:${trial.replacement}`);
|
|
47
|
+
if (mutant && !definitive.has(mutant.status)) return undefined;
|
|
48
|
+
// The focused analysis decides between unreached and survived from its own recorded comparisons.
|
|
49
|
+
return mutant && { status: mutant.status === 'unreached' ? 'survived' : mutant.status, tests: mutant.tests };
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function carryBaseline(target, source) {
|
|
54
|
+
if (source?.[baselineRunSymbol]) {
|
|
55
|
+
Object.defineProperty(target, baselineRunSymbol, { value: source[baselineRunSymbol], enumerable: false });
|
|
56
|
+
}
|
|
57
|
+
return target;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Starts the session, prepares the focused analysis while it runs, and waits for both.
|
|
61
|
+
// `ended` holds the focused report when that analysis finished in its preparation.
|
|
62
|
+
async function besideSession(project, files, options, run, profile, stopsSession) {
|
|
63
|
+
const stop = new AbortController();
|
|
64
|
+
let listExtras;
|
|
65
|
+
const extras = new Promise(resolveList => { listExtras = resolveList; });
|
|
66
|
+
const started = run.analyzeConventional(project, files, {
|
|
67
|
+
mutators: profile, lines: options.lines, since: options.since, config: options.config, test: options.test,
|
|
68
|
+
'copy-exclude': options['copy-exclude'], dialect: options.dialect, 'isolated-trials': options['isolated-trials'],
|
|
69
|
+
concurrency: options.concurrency, 'verify-trials': options['verify-trials'], timeout: options.timeout, signal: stop.signal, extras,
|
|
70
|
+
}).then(report => ({ report }), error => ({ error }));
|
|
71
|
+
let prepared;
|
|
72
|
+
try {
|
|
73
|
+
prepared = run.prepareAnalysis(project, files, { ...options, mutators: undefined, traceIsBaseline: true });
|
|
74
|
+
} catch (error) {
|
|
75
|
+
listExtras([]);
|
|
76
|
+
stop.abort();
|
|
77
|
+
await started;
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
// Without planned trials the focused analysis ended in its preparation.
|
|
81
|
+
const ended = prepared.trials ? null : prepared.report;
|
|
82
|
+
const listed = shiftTrials(prepared);
|
|
83
|
+
listExtras(listed);
|
|
84
|
+
if (ended && stopsSession(ended)) {
|
|
85
|
+
stop.abort();
|
|
86
|
+
await started;
|
|
87
|
+
return { prepared, ended, stopped: true, extras: listed };
|
|
88
|
+
}
|
|
89
|
+
return { prepared, ended, extras: listed, ...await started };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Vitest (without --audit): built-in mutations run in one switched session with per-test coverage while
|
|
93
|
+
// comparison tracing prepares boundaries and thresholds, and the session's verdicts answer shared edits.
|
|
94
|
+
// Playwright, --audit, and Vitest setups the session cannot drive rewrite the source for each mutation instead.
|
|
95
|
+
export async function analyzeOperators(project, files, options, run = { analyze, prepareAnalysis, completeAnalysis, analyzeConventional }) {
|
|
96
|
+
const profile = options.mutators ?? 'targeted';
|
|
97
|
+
const rewriting = () => {
|
|
98
|
+
const out = run.analyze(project, files, { ...options, mutators: profile });
|
|
99
|
+
return carryBaseline({ ...out, mutators: profile, operatorExecution: 'source-rewrite' }, out);
|
|
100
|
+
};
|
|
101
|
+
if (options.runner === 'playwright' || options.audit) return rewriting();
|
|
102
|
+
const { prepared, ended, stopped, extras, report: session, error } = await besideSession(project, files, options, run, profile,
|
|
103
|
+
report => report.evaluation === 'baseline_error' || report.extraction.some(file => file.path === 'diagnostic'));
|
|
104
|
+
if (stopped) return carryBaseline({ ...ended, mutators: profile }, ended);
|
|
105
|
+
if (error) throw error;
|
|
106
|
+
if (session.evaluation === 'baseline_error') return rewriting();
|
|
107
|
+
const completed = ended ?? run.completeAnalysis(prepared, sessionVerdicts(session, extras));
|
|
108
|
+
const focused = carryBaseline({ ...completed, mutators: profile }, completed);
|
|
109
|
+
if (session.evaluation === 'no_sites') return carryBaseline({ ...focused, operatorExecution: 'session' }, focused);
|
|
110
|
+
// A comparison boundary appears in both parts. The focused result carries the missing input, so it is the one kept.
|
|
111
|
+
const boundaries = new Set(focused.mutants.map(mutant => `${mutant.location.file}:${mutant.edit[0]}:${mutant.replacement}`));
|
|
112
|
+
const added = session.mutants.filter(mutant => !(mutant.operatorSwap &&
|
|
113
|
+
boundaries.has(`${mutant.location.file}:${mutant.operatorSwap.join(':')}`)));
|
|
114
|
+
return carryBaseline({
|
|
115
|
+
...focused,
|
|
116
|
+
operatorExecution: 'session',
|
|
117
|
+
trials: session.trials,
|
|
118
|
+
baseline: focused.baseline ?? session.baseline,
|
|
119
|
+
evaluation: session.evaluation === 'incomplete' || focused.evaluation === 'incomplete' ? 'incomplete' : 'evaluated',
|
|
120
|
+
mutants: [...focused.mutants, ...added.map(mutant => fromSession(mutant, profile))].sort(order),
|
|
121
|
+
diagnostics: [...focused.diagnostics, ...(session.diagnostics ?? [])],
|
|
122
|
+
}, focused);
|
|
123
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, relative, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { inside, runnerPackage } from './vitest.mjs';
|
|
7
|
+
|
|
8
|
+
const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
|
|
9
|
+
const defaultConfigs = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs'].map(ext => 'playwright.config.' + ext);
|
|
10
|
+
|
|
11
|
+
function configuration(root, name) {
|
|
12
|
+
const selected = name ?? defaultConfigs.find(file => existsSync(resolve(root, file)));
|
|
13
|
+
if (!selected) throw new Error('Playwright runs require a project configuration file');
|
|
14
|
+
const original = inside(root, selected);
|
|
15
|
+
const wrapper = resolve(dirname(original), `.tmt-playwright-${randomUUID()}.config.mts`);
|
|
16
|
+
writeFileSync(wrapper, `import imported from ${JSON.stringify('./' + basename(original))};
|
|
17
|
+
import { realpathSync } from 'node:fs';
|
|
18
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
const config = imported.default ?? imported;
|
|
21
|
+
const root = process.env.TMT_WORKSPACE;
|
|
22
|
+
const configDirectory = dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
const own = directory => {
|
|
24
|
+
const resolved = realpathSync(resolve(configDirectory, directory ?? '.'));
|
|
25
|
+
const target = relative(root, resolved);
|
|
26
|
+
if (isAbsolute(target) || target === '..' || target.startsWith('..' + sep)) {
|
|
27
|
+
throw new Error('Managed webServer cwd escapes the trial workspace');
|
|
28
|
+
}
|
|
29
|
+
return resolved;
|
|
30
|
+
};
|
|
31
|
+
const settings = Array.isArray(config.webServer) ? config.webServer : config.webServer ? [config.webServer] : [];
|
|
32
|
+
if (!settings.length) throw new Error('Playwright analysis requires a managed webServer');
|
|
33
|
+
const loopback = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
34
|
+
const origins = new Set();
|
|
35
|
+
const servers = settings.map(server => {
|
|
36
|
+
const url = new URL(server.url ?? ('http://localhost:' + server.port));
|
|
37
|
+
if (!loopback.has(url.hostname) || !['http:', 'https:'].includes(url.protocol)) {
|
|
38
|
+
throw new Error('The managed webServer must listen on loopback');
|
|
39
|
+
}
|
|
40
|
+
if (typeof server.command !== 'string' ||
|
|
41
|
+
(process.env.TMT_ORIGINAL && server.command.includes(process.env.TMT_ORIGINAL))) {
|
|
42
|
+
throw new Error('The managed webServer command must run the trial workspace');
|
|
43
|
+
}
|
|
44
|
+
origins.add(url.origin);
|
|
45
|
+
return { ...server, cwd: own(server.cwd), reuseExistingServer: false };
|
|
46
|
+
});
|
|
47
|
+
for (const project of config.projects?.length ? config.projects : [config]) {
|
|
48
|
+
const target = project.use?.baseURL ?? config.use?.baseURL;
|
|
49
|
+
if (target && !origins.has(new URL(target).origin)) {
|
|
50
|
+
throw new Error('Playwright baseURL must target a managed webServer origin');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const browser = (project) => project.use?.browserName ?? project.use?.defaultBrowserType ?? config.use?.browserName ?? 'chromium';
|
|
54
|
+
const projects = config.projects?.map(project => ({ ...project,
|
|
55
|
+
metadata: { ...project.metadata, tmtBrowser: browser(project) },
|
|
56
|
+
}));
|
|
57
|
+
const webServer = Array.isArray(config.webServer) ? servers : servers[0];
|
|
58
|
+
export default { ...config, projects, webServer,
|
|
59
|
+
metadata: { ...config.metadata, tmtBrowser: browser(config) }
|
|
60
|
+
};
|
|
61
|
+
`, { flag: 'wx' });
|
|
62
|
+
return wrapper;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function classifyPlaywright(report, exitCode, workspace) {
|
|
66
|
+
const browsers = new Map(report.config.projects.map(project => [project.name, project.metadata?.tmtBrowser]));
|
|
67
|
+
const fallback = report.config.metadata?.tmtBrowser;
|
|
68
|
+
const tests = [];
|
|
69
|
+
let timeout = false;
|
|
70
|
+
let unstable = false;
|
|
71
|
+
let incomplete = false;
|
|
72
|
+
|
|
73
|
+
function walk(suite, parents = []) {
|
|
74
|
+
const headings = suite.title && !suite.file?.endsWith(suite.title) ? [...parents, suite.title] : parents;
|
|
75
|
+
for (const child of suite.suites ?? []) walk(child, headings);
|
|
76
|
+
for (const spec of suite.specs ?? []) {
|
|
77
|
+
const seen = new Map();
|
|
78
|
+
for (const test of spec.tests) {
|
|
79
|
+
const count = seen.get(test.projectName) ?? 0;
|
|
80
|
+
seen.set(test.projectName, count + 1);
|
|
81
|
+
const last = test.results.at(-1);
|
|
82
|
+
const status = test.status === 'flaky' ? 'unstable' : test.status === 'skipped' ? 'skipped'
|
|
83
|
+
: test.status === 'expected' ? 'passed' : 'failed';
|
|
84
|
+
if (test.results.some(attempt => attempt.status === 'timedOut')) timeout = true;
|
|
85
|
+
if (test.status === 'flaky' || test.results.some(attempt => attempt.status === 'interrupted')) unstable = true;
|
|
86
|
+
if (!last && status !== 'skipped') incomplete = true;
|
|
87
|
+
tests.push({
|
|
88
|
+
id: `${spec.id}:${count}`, file: workspace ? relative(workspace, resolve(report.config.rootDir, spec.file)) : spec.file, project: test.projectName, browser: browsers.get(test.projectName) ?? fallback,
|
|
89
|
+
name: [...headings, spec.title].join(' > '), status, worker: last?.workerIndex, parallelIndex: last?.parallelIndex,
|
|
90
|
+
retry: last?.retry, failures: (last?.errors ?? []).map(error => error.message),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
for (const root of report.suites) walk(root);
|
|
96
|
+
|
|
97
|
+
const failed = tests.some(test => test.status === 'failed');
|
|
98
|
+
const status = report.errors.length || incomplete || !tests.length ? 'error'
|
|
99
|
+
: timeout ? 'timeout' : unstable ? 'unstable'
|
|
100
|
+
: exitCode === 0 && !failed && tests.some(test => test.status === 'passed') ? 'passed'
|
|
101
|
+
: exitCode === 1 && failed ? 'failed' : 'error';
|
|
102
|
+
return { status, tests, errors: report.errors.map(error => error.message) };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Playwright takes test files as patterns, so a path is passed with its pattern characters escaped.
|
|
106
|
+
export const testFilters = (root, tests = []) => [...new Set(tests.map(file => relative(root, inside(root, file))))]
|
|
107
|
+
.map(file => file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
108
|
+
|
|
109
|
+
export function runPlaywright(root, temp, { config, projects = [], tests = [], timeout = 60_000, original } = {}) {
|
|
110
|
+
const bin = resolve(dirname(runnerPackage(root, 'playwright')), 'cli.js');
|
|
111
|
+
const wrapper = configuration(root, config);
|
|
112
|
+
const report = resolve(temp, 'playwright.json');
|
|
113
|
+
const pid = resolve(temp, 'playwright.pid');
|
|
114
|
+
const server = resolve(temp, 'server.pid');
|
|
115
|
+
const attempt = randomUUID();
|
|
116
|
+
const child = spawnSync(process.execPath, [supervisor, pid, String(timeout), bin,
|
|
117
|
+
'test', '--config', wrapper, '--workers=1', '--reporter=json', '--global-timeout', String(Math.max(100, timeout - 3000)),
|
|
118
|
+
'--output', resolve(temp, 'results'),
|
|
119
|
+
...projects.flatMap(project => ['--project', project]),
|
|
120
|
+
...testFilters(root, tests),
|
|
121
|
+
], {
|
|
122
|
+
cwd: root, encoding: 'utf8', timeout: timeout + 5000, maxBuffer: 4 * 1024 * 1024,
|
|
123
|
+
env: {
|
|
124
|
+
...process.env, CI: 'true', PLAYWRIGHT_JSON_OUTPUT_FILE: report, TMT_RUN_ID: attempt, TMT_SERVER_PID_FILE: server,
|
|
125
|
+
TMT_WORKSPACE: root, TMT_ORIGINAL: original ?? '',
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
const output = child.error?.message ?? child.stderr + child.stdout;
|
|
129
|
+
const runnerPid = existsSync(pid) ? Number(readFileSync(pid, 'utf8')) : undefined;
|
|
130
|
+
const serverPid = existsSync(server) ? Number(readFileSync(server, 'utf8')) : undefined;
|
|
131
|
+
const metadata = { output, attempt, runnerPid, serverPid };
|
|
132
|
+
if (child.status === 124 || child.error?.code === 'ETIMEDOUT') return { status: 'timeout', ...metadata };
|
|
133
|
+
if (child.error || !existsSync(report)) return { status: 'error', ...metadata };
|
|
134
|
+
try {
|
|
135
|
+
return { ...classifyPlaywright(JSON.parse(readFileSync(report, 'utf8')), child.status, root), ...metadata };
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return { status: 'error', ...metadata, output: output + '\n' + error.message };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { relative } from 'node:path';
|
|
3
|
+
import { getCurrentTest } from 'vitest/suite';
|
|
4
|
+
|
|
5
|
+
const trace = process.env.TMT_TRACE;
|
|
6
|
+
// Use the native module cache even when Vite evaluates or resets this module.
|
|
7
|
+
const writer = trace && createRequire(import.meta.url)('./trace-buffer.mjs').workerTraceWriter(
|
|
8
|
+
trace, (test, finish) => test.context.onTestFinished(finish), process.env.TMT_TRACE_SYNC === '1');
|
|
9
|
+
const active = process.env.TMT_ACTIVE_SITE;
|
|
10
|
+
const workspace = process.env.TMT_WORKSPACE;
|
|
11
|
+
const isSafeInteger = Number.isSafeInteger;
|
|
12
|
+
|
|
13
|
+
export function loaded(ids) {
|
|
14
|
+
if (writer) writer.write({ loaded: ids });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function testIdentity(test) {
|
|
18
|
+
return test ? {
|
|
19
|
+
id: test.id, project: test.file.projectName ?? '', file: relative(workspace, test.file.filepath),
|
|
20
|
+
} : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function hit(site) {
|
|
24
|
+
if (writer) {
|
|
25
|
+
const test = getCurrentTest();
|
|
26
|
+
writer.write({ hit: site, identity: testIdentity(test) }, test);
|
|
27
|
+
}
|
|
28
|
+
return site;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function compare(site, original, replacement, lhs, rhs) {
|
|
32
|
+
const test = getCurrentTest();
|
|
33
|
+
const identity = testIdentity(test);
|
|
34
|
+
const safe = isSafeInteger(lhs) && isSafeInteger(rhs);
|
|
35
|
+
const operator = site === active ? replacement : original;
|
|
36
|
+
let result;
|
|
37
|
+
try {
|
|
38
|
+
switch (operator) {
|
|
39
|
+
case '<': result = lhs < rhs; break;
|
|
40
|
+
case '<=': result = lhs <= rhs; break;
|
|
41
|
+
case '>': result = lhs > rhs; break;
|
|
42
|
+
case '>=': result = lhs >= rhs; break;
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
} finally {
|
|
46
|
+
if (writer) writer.write({
|
|
47
|
+
site, identity, operands: safe ? [lhs, rhs] : null, result: result ?? null, operator,
|
|
48
|
+
}, test);
|
|
49
|
+
}
|
|
50
|
+
}
|