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,110 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { verdict } from './analysis.mjs';
3
+ import { inParallel } from './in-parallel.mjs';
4
+
5
+ const isValue = value => value === null || ['string', 'boolean'].includes(typeof value) || (Number.isFinite(value) && !Object.is(value, -0));
6
+ const nonempty = value => typeof value === 'string' && value.trim().length > 0;
7
+
8
+ export function prepareContracts(specification, selection, snapshots, { discovered = false } = {}) {
9
+ if (specification === null || typeof specification !== 'object' || !Array.isArray(specification.witnessPlans)) {
10
+ throw new Error('Expected a specification with a witnessPlans array');
11
+ }
12
+ if (specification.witnessPlans.length > 32) throw new Error('At most 32 witness plans can be verified in one run');
13
+ const names = new Set();
14
+ return specification.witnessPlans.flatMap((plan, index) => {
15
+ if (!plan || ![plan.name, plan.requirement, plan.testFile, plan.seedTest, plan.observe].every(nonempty) ||
16
+ !isValue(plan.expected) || !isValue(plan.alternate) || Object.is(plan.expected, plan.alternate) ||
17
+ !Array.isArray(plan.edits) || ![1, 2].includes(plan.edits.length) || names.has(plan.name)) {
18
+ throw new Error(`Invalid witness plan ${index + 1}`);
19
+ }
20
+ names.add(plan.name);
21
+ for (const edit of plan.edits) {
22
+ if (!edit || !nonempty(edit.file) || !Number.isSafeInteger(edit.line) || edit.line < 1 ||
23
+ !nonempty(edit.original) || /[\r\n\u2028\u2029]/.test(edit.original) ||
24
+ typeof edit.replacement !== 'string' || edit.replacement === edit.original) {
25
+ throw new Error(`Invalid source edit in witness plan ${plan.name}`);
26
+ }
27
+ }
28
+ if (!plan.edits.every(edit => selection.get(edit.file)?.(edit.line))) return [];
29
+ const edits = plan.edits.map(edit => {
30
+ const file = snapshots.get(edit.file);
31
+ if (file === undefined) throw new Error(`Source unavailable for witness plan ${plan.name}: ${edit.file}`);
32
+ const lines = file.split(/(\r\n|[\r\n\u2028\u2029])/);
33
+ const line = lines[(edit.line - 1) * 2];
34
+ const lineStart = lines.slice(0, (edit.line - 1) * 2).join('').length;
35
+ const first = discovered ? edit.start - lineStart : line?.indexOf(edit.original) ?? -1;
36
+ if (first < 0 || (discovered ? !Number.isSafeInteger(first) || line?.slice(first, first + edit.original.length) !== edit.original
37
+ : first !== line.lastIndexOf(edit.original))) {
38
+ throw new Error(`Expected one exact source edit match in ${edit.file}:${edit.line}`);
39
+ }
40
+ const start = lineStart + first;
41
+ return { ...edit, start, end: start + edit.original.length };
42
+ });
43
+ if (edits.length === 2 && edits[0].file === edits[1].file &&
44
+ edits[0].start < edits[1].end && edits[1].start < edits[0].end) {
45
+ throw new Error(`Overlapping source edits in witness plan ${plan.name}`);
46
+ }
47
+ const id = createHash('sha256').update(JSON.stringify([plan.name, edits])).digest('hex');
48
+ return [{ ...plan, id, edits }];
49
+ });
50
+ }
51
+
52
+ export function confirmsContract(status, seedPassed, singletons, checked) {
53
+ return status === 'survived' && seedPassed && singletons.every(result => result.status === 'killed' && result.seedFailed) && checked;
54
+ }
55
+
56
+ export async function evaluateContracts(plans, attempt, baseline, snapshots, verifyAppend, report, concurrency = 1) {
57
+ const testFiles = new Set(baseline.tests.map(test => test.file));
58
+ const evaluated = await inParallel(plans, concurrency, async plan => {
59
+ const { id, edits, name, seedTest, testFile, expected, alternate, requirement, observe, expectation, borrowedFrom, observation, connection } = plan;
60
+ const rule = edits.length === 2 ? 'paired-source/v1' : 'contract-source/v1';
61
+ const scope = edits.map(edit => {
62
+ const source = snapshots.get(edit.file);
63
+ return { ...edit, start: Buffer.byteLength(source.slice(0, edit.start)), end: Buffer.byteLength(source.slice(0, edit.end)) };
64
+ });
65
+ const seeds = baseline.tests.filter(test => test.file === testFile && test.name === seedTest);
66
+ const seed = seeds.length === 1 && seeds[0].status === 'passed' && !seeds[0].retry && !seeds[0].repeats ? seeds[0] : null;
67
+ const result = { id, rule, name, edits: scope, location: { file: scope[0].file, line: scope[0].line,
68
+ start: scope[0].start, end: scope[0].end }, status: 'unevaluated' };
69
+ if (!seed || edits.some(edit => testFiles.has(edit.file)) || !snapshots.has(testFile)) {
70
+ result.statusReason = 'Expected one passing, unmodified seed test';
71
+ return { result };
72
+ }
73
+ const raw = await attempt(edits);
74
+ result.status = verdict(raw, baseline);
75
+ result.evidence = 'reexecuted';
76
+ if (result.status !== 'survived') return { result };
77
+ const singletons = edits.length === 2 ? await Promise.all(edits.map(async edit => {
78
+ const single = await attempt([edit]);
79
+ return { status: verdict(single, baseline), seedFailed: !!single.tests?.some(test => test.file === seed.file &&
80
+ test.project === seed.project && test.id === seed.id && test.name === seed.name && test.status === 'failed') };
81
+ })) : [];
82
+ if (edits.length === 2) result.singletons = singletons;
83
+ if (!confirmsContract(result.status, true, singletons, true)) return { result };
84
+
85
+ const suffix = randomUUID().replaceAll('-', '');
86
+ const marker = 'TMT witness ' + suffix;
87
+ const append = { file: testFile, source: `
88
+ import { expect as __tmtExpect_${suffix}, it as __tmtIt_${suffix} } from 'vitest';
89
+ __tmtIt_${suffix}(${JSON.stringify(marker)}, async () => {
90
+ const actual = await (${observe});
91
+ const isExpected = Object.is(actual, ${JSON.stringify(expected)});
92
+ if (!isExpected && !Object.is(actual, ${JSON.stringify(alternate)})) throw new Error('Unexpected witness result');
93
+ __tmtExpect_${suffix}(isExpected, ${JSON.stringify(marker)}).toBe(true);
94
+ });
95
+ ` };
96
+ if (!await verifyAppend(attempt, baseline, edits, append, marker, true, false)) return { result };
97
+ return { result, diagnostic: {
98
+ kind: edits.length === 2 ? 'PAIRED MUTATION GAP' : 'STATE ASSERTION GAP',
99
+ site: id, rule, location: result.location, requirement, seed: { file: testFile, test: seedTest },
100
+ borrowedFrom, observation, connection,
101
+ witness: { expression: observe, original: expected, mutant: alternate, expectation: expectation === 'original' ? 'original' : 'specification' },
102
+ suggestedTest: `expect(await (${observe})).toBe(${JSON.stringify(expected)})`,
103
+ verification: { status: 'confirmed', original: 'passed', rewrite: 'failed' },
104
+ } };
105
+ });
106
+ for (const { result, diagnostic } of evaluated) {
107
+ report.mutants.push(result);
108
+ if (diagnostic) report.diagnostics.push(diagnostic);
109
+ }
110
+ }
@@ -0,0 +1,239 @@
1
+ import { loadTypeScript } from './typescript-compiler.mjs';
2
+ import { bare, functionParts, integer } from './witness-rules.mjs';
3
+ import { importedBindings, importMatches, registeredTests } from './witness-fixtures.mjs';
4
+
5
+ const ts = loadTypeScript();
6
+
7
+ const named = (node, name) => !!node && ts.isIdentifier(node) && (name === undefined || node.text === name);
8
+ const property = node => !!node && ts.isPropertyAccessExpression(node) && !node.questionDotToken;
9
+ const invoked = node => !!node && ts.isCallExpression(node) && !node.questionDotToken;
10
+ const returned = statement => statement && ts.isReturnStatement(statement) ? bare(statement.expression) : null;
11
+ const expression = statement => statement && ts.isExpressionStatement(statement) ? bare(statement.expression) : null;
12
+ const modifiers = (node, kind) => node.modifiers?.some(modifier => modifier.kind === kind);
13
+
14
+ function constBinding(statement) {
15
+ if (!statement || !ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const) ||
16
+ statement.declarationList.declarations.length !== 1) return null;
17
+ const [declaration] = statement.declarationList.declarations;
18
+ return named(declaration.name) && declaration.initializer
19
+ ? { name: declaration.name.text, value: bare(declaration.initializer) } : null;
20
+ }
21
+
22
+ function construct(node, name, count) {
23
+ return !!node && ts.isNewExpression(node) && named(node.expression, name) && (node.arguments?.length ?? 0) === count;
24
+ }
25
+
26
+ function sourceEdit(tree, node, replacement, start = node.getStart(tree)) {
27
+ const original = tree.text.slice(start, node.getEnd());
28
+ if (/[\r\n\u2028\u2029]/.test(original)) return null;
29
+ const { line } = tree.getLineAndCharacterOfPosition(start);
30
+ return { file: tree.fileName, line: line + 1, start, original, replacement };
31
+ }
32
+
33
+ function endianEndpoint(tree, name, fn) {
34
+ if (!fn.body || !ts.isBlock(fn.body) || fn.parameters.length !== 1 ||
35
+ !named(fn.parameters[0].name) || fn.parameters[0].initializer || fn.parameters[0].dotDotDotToken ||
36
+ fn.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.AsyncKeyword) || fn.asteriskToken) return null;
37
+ const parameter = fn.parameters[0].name.text;
38
+ const body = fn.body.statements;
39
+ const allocation = body.length === 3 ? constBinding(body[0]) : null;
40
+ const producer = !!allocation;
41
+ const call = producer ? expression(body[1]) : body.length === 1 ? returned(body[0]) : null;
42
+ if (!invoked(call) || !property(call.expression)) return null;
43
+ const { expression: view, name: method } = call.expression;
44
+ const bits = new RegExp('^' + (producer ? 'set' : 'get') + 'Uint(16|32)$').exec(method.text)?.[1];
45
+ if (!bits || !construct(view, 'DataView', 1) || call.arguments.length !== (producer ? 3 : 2) || integer(call.arguments[0]) !== 0) return null;
46
+ const buffer = view.arguments[0];
47
+ if (!property(buffer) || buffer.name.text !== 'buffer' || !named(buffer.expression, producer ? allocation.name : parameter)) return null;
48
+ if (producer && (!construct(allocation.value, 'Uint8Array', 1) || integer(allocation.value.arguments[0]) !== Number(bits) / 8 ||
49
+ !named(returned(body[2]), allocation.name) || !named(call.arguments[1], parameter))) return null;
50
+ const flag = call.arguments.at(-1);
51
+ if (![ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword].includes(flag.kind)) return null;
52
+ const little = flag.kind === ts.SyntaxKind.TrueKeyword;
53
+ const start = method.getStart(tree);
54
+ const edit = sourceEdit(tree, call, tree.text.slice(start, flag.getStart(tree)) +
55
+ String(!little) + tree.text.slice(flag.getEnd(), call.getEnd()), start);
56
+ return edit && { name, kind: producer ? 'encoder' : 'decoder', bits: Number(bits), little, edit };
57
+ }
58
+
59
+ function methodName(node) {
60
+ return ts.isMethodDeclaration(node) && named(node.name) && !node.questionToken && node.body &&
61
+ !node.modifiers?.some(modifier => [ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.StaticKeyword,
62
+ ts.SyntaxKind.AsyncKeyword, ts.SyntaxKind.AbstractKeyword].includes(modifier.kind)) ? node.name.text : null;
63
+ }
64
+
65
+ function storeEndpoint(tree, node) {
66
+ if (!ts.isClassDeclaration(node) || !node.name || !modifiers(node, ts.SyntaxKind.ExportKeyword) ||
67
+ modifiers(node, ts.SyntaxKind.DefaultKeyword) || node.heritageClauses?.length ||
68
+ node.members.some(member => ts.isConstructorDeclaration(member))) return null;
69
+ const writes = new Map(), reads = new Set();
70
+ for (const method of node.members) {
71
+ const name = methodName(method);
72
+ if (!name || method.parameters.length !== 1 || !named(method.parameters[0].name)) continue;
73
+ const parameter = method.parameters[0].name.text;
74
+ const statements = method.body.statements;
75
+ const read = statements.length === 1 ? returned(statements[0]) : null;
76
+ if (invoked(read) && property(read.expression) && read.expression.name.text === 'get' &&
77
+ property(read.expression.expression) && read.expression.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
78
+ read.arguments.length === 1 && named(read.arguments[0], parameter)) reads.add(name);
79
+ const first = statements[0], next = statements[1];
80
+ if (!first || !ts.isIfStatement(first) || first.elseStatement || !next || !ts.isForOfStatement(next) ||
81
+ !named(next.expression, parameter) || returned(first.thenStatement)?.kind !== ts.SyntaxKind.FalseKeyword) continue;
82
+ const check = bare(first.expression);
83
+ if (!invoked(check) || !property(check.expression) || check.expression.name.text !== 'some' ||
84
+ !named(check.expression.expression, parameter) || check.arguments.length !== 1) continue;
85
+ const edit = sourceEdit(tree, first, '');
86
+ if (edit) writes.set(name, edit);
87
+ }
88
+ return writes.size && reads.size ? { file: tree.fileName, name: node.name.text, writes, reads } : null;
89
+ }
90
+
91
+ export function discoverySources(tree, selected) {
92
+ if (tree.parseDiagnostics.length) return { endpoints: [], stores: [] };
93
+ const endpoints = [], stores = [];
94
+ for (const statement of tree.statements) {
95
+ for (const [name, fn] of functionParts(statement)) {
96
+ const endpoint = endianEndpoint(tree, name.text, fn);
97
+ if (endpoint && selected(endpoint.edit.line)) endpoints.push(endpoint);
98
+ }
99
+ const store = storeEndpoint(tree, statement);
100
+ if (store) {
101
+ for (const [name, edit] of store.writes) if (!selected(edit.line)) store.writes.delete(name);
102
+ if (store.writes.size) stores.push(store);
103
+ }
104
+ }
105
+ return { endpoints, stores };
106
+ }
107
+
108
+ function scalar(node) {
109
+ return ts.isStringLiteral(node) ? node.text : integer(node);
110
+ }
111
+
112
+ function assertion(node, imports) {
113
+ if (!invoked(node) || !property(node.expression) || node.expression.name.text !== 'toBe' || node.arguments.length !== 1) return null;
114
+ const expect = node.expression.expression;
115
+ if (!invoked(expect) || !named(expect.expression) || expect.arguments.length !== 1) return null;
116
+ const binding = imports.get(expect.expression.text);
117
+ return binding?.name === 'expect' && binding.module === 'vitest'
118
+ ? { value: bare(expect.arguments[0]), expected: bare(node.arguments[0]) } : null;
119
+ }
120
+
121
+ function testCases(fixtures, baseline, project) {
122
+ const result = [];
123
+ const inventory = new Map();
124
+ for (const test of baseline.tests) {
125
+ const key = JSON.stringify([test.file, test.name]);
126
+ inventory.set(key, inventory.has(key) ? null : test);
127
+ }
128
+ for (const { file, tree } of fixtures) {
129
+ if (tree.parseDiagnostics.length) continue;
130
+ for (const { name, callback, imports } of registeredTests(tree.statements, importedBindings(tree))) {
131
+ if (callback.modifiers?.length) continue;
132
+ const known = inventory.get(JSON.stringify([file, name]));
133
+ if (known?.status !== 'passed' || known.retry || known.repeats || known.concurrent) continue;
134
+ const statements = ts.isBlock(callback.body) ? [...callback.body.statements] : null;
135
+ result.push({ file, title: name, imports, statements, concise: statements ? null : callback.body, project });
136
+ }
137
+ }
138
+ return result;
139
+ }
140
+
141
+ function matchesBinding(test, expression, candidates, file) {
142
+ if (!named(expression)) return null;
143
+ const binding = test.imports.get(expression.text);
144
+ if (!binding) return null;
145
+ const matches = candidates.filter(candidate => binding.name === candidate.name && importMatches(test.file, binding.module, file(candidate), test.project));
146
+ return matches.length === 1 ? matches[0] : null;
147
+ }
148
+
149
+ function pairPlan(test, sources) {
150
+ if (test.statements && (test.statements.length > 2 || !test.statements.length)) return null;
151
+ const observed = assertion(test.concise ?? expression(test.statements?.at(-1)), test.imports);
152
+ const outer = observed?.value;
153
+ if (!invoked(outer) || outer.arguments.length !== 1) return null;
154
+ const variable = test.statements?.length === 2 ? constBinding(test.statements[0]) : null;
155
+ if (test.statements?.length === 2 && (!variable || !named(outer.arguments[0], variable.name))) return null;
156
+ const inner = variable?.value ?? bare(outer.arguments[0]);
157
+ if (!invoked(inner) || inner.arguments.length !== 1) return null;
158
+ const file = endpoint => endpoint.edit.file;
159
+ const decoder = matchesBinding(test, outer.expression, sources.filter(item => item.kind === 'decoder'), file);
160
+ const encoder = matchesBinding(test, inner.expression, sources.filter(item => item.kind === 'encoder'), file);
161
+ const input = integer(inner.arguments[0]);
162
+ if (!encoder || !decoder || encoder.bits !== decoder.bits || encoder.little !== decoder.little ||
163
+ input === undefined || input < 0 || input >= 2 ** encoder.bits || input !== integer(observed.expected)) return null;
164
+ const bytes = new Uint8Array(encoder.bits / 8);
165
+ const data = new DataView(bytes.buffer);
166
+ (encoder.bits === 16 ? data.setUint16 : data.setUint32).call(data, 0, input, encoder.little);
167
+ const expected = bytes.join(',');
168
+ const alternate = [...bytes].reverse().join(',');
169
+ if (alternate === expected) return null;
170
+ return { name: `Automatic byte order through ${encoder.name} and ${decoder.name} in ${test.file} / ${test.title}`,
171
+ requirement: 'The observed round trip passes the producer output to the decoder. The wire assertion preserves the original representation.',
172
+ testFile: test.file, seedTest: test.title, edits: [encoder.edit, decoder.edit],
173
+ observe: `${inner.expression.text}(${inner.arguments[0].getText()}).join(',')`, expected, alternate,
174
+ expectation: 'original', connection: { producer: encoder.name, consumer: decoder.name } };
175
+ }
176
+
177
+ function storeTest(test, stores) {
178
+ const binding = constBinding(test.statements?.[0]);
179
+ if (!binding || !construct(binding.value, undefined, 0)) return null;
180
+ const store = matchesBinding(test, binding.value.expression, stores, candidate => candidate.file);
181
+ return store && { test, store, binding };
182
+ }
183
+
184
+ function instanceCall(node, receiver) {
185
+ return invoked(node) && property(node.expression) && named(node.expression.expression, receiver) ? node : null;
186
+ }
187
+
188
+ function* statePlans(tests, stores) {
189
+ const cases = tests.map(test => storeTest(test, stores)).filter(Boolean);
190
+ for (const { test, store, binding } of cases) {
191
+ if (test.statements.length !== 2) continue;
192
+ const observed = assertion(expression(test.statements[1]), test.imports);
193
+ const operation = instanceCall(observed?.value, binding.name);
194
+ if (!operation || observed.expected.kind !== ts.SyntaxKind.FalseKeyword || operation.arguments.length !== 1) continue;
195
+ const edit = store.writes.get(operation.expression.name.text);
196
+ const entries = operation.arguments[0];
197
+ if (!edit || !ts.isArrayLiteralExpression(entries) || !entries.elements.length || entries.elements.length > 8 ||
198
+ entries.elements.some(entry => !ts.isArrayLiteralExpression(entry) || entry.elements.length !== 2 ||
199
+ !ts.isStringLiteral(entry.elements[0]) || scalar(entry.elements[1]) === undefined)) continue;
200
+ for (const donor of cases) {
201
+ if (donor.store !== store || donor.test.file !== test.file || donor.test === test ||
202
+ !donor.test.statements.slice(1).every(statement => ts.isExpressionStatement(statement))) continue;
203
+ for (const statement of donor.test.statements.slice(1)) {
204
+ const verified = assertion(expression(statement), donor.test.imports);
205
+ const read = instanceCall(verified?.value, donor.binding.name);
206
+ if (!read || read.arguments.length !== 1 || !ts.isStringLiteral(read.arguments[0]) || !store.reads.has(read.expression.name.text)) continue;
207
+ const method = read.expression.name.text;
208
+ const constructor = binding.value.expression.text;
209
+ const instance = constructor === '__tmtInstance' ? '__tmtInstance_' : '__tmtInstance';
210
+ for (const entry of entries.elements) {
211
+ const [keyNode, valueNode] = entry.elements;
212
+ const key = keyNode.text;
213
+ const alternate = scalar(valueNode);
214
+ if (alternate === '' || Object.is(alternate, -0)) continue;
215
+ yield { name: `Automatic batch read ${method}(${JSON.stringify(key)}) in ${test.file} / ${test.title}`,
216
+ requirement: 'Read the key attempted by the rejected batch through a public reader used in a passing test.',
217
+ testFile: test.file, seedTest: test.title, edits: [edit], expected: null, alternate, expectation: 'original',
218
+ borrowedFrom: { file: donor.test.file, test: donor.test.title, method, argument: read.arguments[0].text },
219
+ observation: { method, argument: key },
220
+ observe: `(() => { const ${instance} = new ${constructor}(); ${instance}.${operation.expression.name.text}(${entries.getText()}); return ${instance}.${method}(${JSON.stringify(key)}) ?? null; })()` };
221
+ }
222
+ }
223
+ }
224
+ }
225
+ }
226
+
227
+ export function discoverContracts(fixtures, baseline, sources, { limit = 32, project } = {}) {
228
+ const tests = testCases(fixtures, baseline, project);
229
+ const endpoints = sources.flatMap(source => source.endpoints);
230
+ const stores = sources.flatMap(source => source.stores);
231
+ const plans = new Map();
232
+ for (const drafts of [tests.values().map(test => pairPlan(test, endpoints)), statePlans(tests, stores)]) {
233
+ for (const plan of drafts) {
234
+ if (plan && !plans.has(plan.name)) plans.set(plan.name, plan);
235
+ if (plans.size >= limit) return [...plans.values()];
236
+ }
237
+ }
238
+ return [...plans.values()];
239
+ }
@@ -0,0 +1,148 @@
1
+ import { realpathSync, statSync } from 'node:fs';
2
+ import { dirname, extname, resolve } from 'node:path';
3
+ import { loadTypeScript } from './typescript-compiler.mjs';
4
+ import { bare, integer } from './witness-rules.mjs';
5
+ import { orderProjection } from './witness-order.mjs';
6
+
7
+ const ts = loadTypeScript();
8
+
9
+ function literal(node, shape) {
10
+ node = bare(node);
11
+ if (shape === 'string') return ts.isStringLiteral(node) ? { node, value: node.text } : null;
12
+ if (shape === 'number') {
13
+ const value = integer(node);
14
+ return value === undefined ? null : { node, value };
15
+ }
16
+ if ((shape === 'array' || shape.items) && ts.isArrayLiteralExpression(node) && node.elements.length <= 256) {
17
+ const items = node.elements.map(item => literal(item, shape.items ?? 'number'));
18
+ return items.includes(null) ? null : { node, value: items.map(item => item.value), items };
19
+ }
20
+ if ((!Array.isArray(shape) && !shape.record) || !ts.isObjectLiteralExpression(node)) return null;
21
+ const fields = new Map();
22
+ for (const field of node.properties) {
23
+ if (!ts.isPropertyAssignment(field) || !ts.isIdentifier(field.name) || fields.has(field.name.text) ||
24
+ field.name.text === '__proto__') return null;
25
+ const type = shape.record ? Object.hasOwn(shape.record, field.name.text) && shape.record[field.name.text] : 'number';
26
+ if (!type) return null;
27
+ const datum = literal(field.initializer, type);
28
+ if (!datum) return null;
29
+ fields.set(field.name.text, datum);
30
+ }
31
+ if ((shape.record ? Object.keys(shape.record) : shape).some(field => !fields.has(field))) return null;
32
+ return { node, value: Object.fromEntries([...fields].map(([key, datum]) => [key, datum.value])), fields };
33
+ }
34
+
35
+ export function importedBindings(tree) {
36
+ if (!tree.locals) ts.bindSourceFile(tree, {});
37
+ const names = new Map();
38
+ for (const declaration of tree.statements) {
39
+ if (!ts.isImportDeclaration(declaration) || !ts.isStringLiteral(declaration.moduleSpecifier) ||
40
+ declaration.importClause?.isTypeOnly) continue;
41
+ const bindings = declaration.importClause?.namedBindings;
42
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
43
+ for (const item of bindings.elements) {
44
+ if (item.isTypeOnly) continue;
45
+ names.set(item.name.text, { name: (item.propertyName ?? item.name).text, module: declaration.moduleSpecifier.text });
46
+ }
47
+ }
48
+ return names;
49
+ }
50
+
51
+ const moduleExtensions = ['.mjs', '.js', '.cjs', '.mts', '.ts', '.cts', '.jsx', '.tsx', '.json'];
52
+
53
+ export function importMatches(file, specifier, subject, project) {
54
+ if (!specifier.startsWith('.')) return false;
55
+ const root = project ?? '.';
56
+ const path = resolve(root, dirname(file), specifier);
57
+ const source = resolve(root, subject);
58
+ if (project && statSync(path, { throwIfNoEntry: false })?.isFile()) return realpathSync(path) === source;
59
+ const extension = extname(path);
60
+ const substitutes = { '.js': ['.ts', '.tsx'], '.jsx': ['.tsx'], '.mjs': ['.mts'], '.cjs': ['.cts'] };
61
+ const candidates = Object.hasOwn(substitutes, extension)
62
+ ? substitutes[extension].map(ext => path.slice(0, -extension.length) + ext)
63
+ : moduleExtensions.includes(extension) ? []
64
+ : [...moduleExtensions.map(ext => path + ext), ...moduleExtensions.map(ext => resolve(path, 'index' + ext))];
65
+ if (!project) return source === path || candidates.includes(source);
66
+ const existing = new Set(candidates.filter(candidate => statSync(candidate, { throwIfNoEntry: false })?.isFile())
67
+ .map(candidate => realpathSync(candidate)));
68
+ return existing.size === 1 && existing.has(source);
69
+ }
70
+
71
+ function callbackImports(callback, imports) {
72
+ return new Map([...imports].filter(([name]) => {
73
+ const local = callback.locals?.get(ts.escapeLeadingUnderscores(name));
74
+ return name !== callback.name?.text && !(local?.flags & ts.SymbolFlags.Value);
75
+ }));
76
+ }
77
+
78
+ export function* registeredTests(statements, imports, parents = []) {
79
+ for (const statement of statements) {
80
+ if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression) || statement.expression.questionDotToken) continue;
81
+ const { expression, arguments: args } = statement.expression;
82
+ const registration = ts.isIdentifier(expression) && imports.get(expression.text);
83
+ if (registration?.module !== 'vitest' || args.length !== 2) continue;
84
+ const [title, callback] = args;
85
+ if (!ts.isStringLiteralLike(title) || !(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) ||
86
+ callback.parameters.length || callback.asteriskToken) continue;
87
+ const path = [...parents, title.text];
88
+ if (registration.name === 'it' || registration.name === 'test') {
89
+ yield { name: path.join(' > '), callback, imports: callbackImports(callback, imports) };
90
+ } else if ((registration.name === 'describe' || registration.name === 'suite') && ts.isBlock(callback.body)) {
91
+ yield* registeredTests(callback.body.statements, callbackImports(callback, imports), path);
92
+ }
93
+ }
94
+ }
95
+
96
+ export function fixtureCalls(tree, file, candidate, subject, project) {
97
+ if (tree.parseDiagnostics.length) return [];
98
+ const results = [];
99
+ for (const { name, callback: { body }, imports } of registeredTests(tree.statements, importedBindings(tree))) {
100
+ const assertion = ts.isBlock(body) ? body.statements.length === 1 && ts.isExpressionStatement(body.statements[0])
101
+ ? body.statements[0].expression : null : body;
102
+ if (!assertion || !ts.isCallExpression(assertion) || assertion.arguments.length !== 1 ||
103
+ !ts.isPropertyAccessExpression(assertion.expression) || assertion.expression.name.text !== 'toBe') continue;
104
+ const expect = assertion.expression.expression;
105
+ if (!ts.isCallExpression(expect) || !ts.isIdentifier(expect.expression) || expect.arguments.length !== 1) continue;
106
+ const match = imports.get(expect.expression.text);
107
+ if (match?.module !== 'vitest' || match.name !== 'expect') continue;
108
+ const root = bare(expect.arguments[0]);
109
+ const projection = candidate.order ? orderProjection(root) : null;
110
+ if (candidate.order && !projection) continue;
111
+ const call = projection?.call ?? root;
112
+ if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression) || call.arguments.length !== candidate.parameters.length) continue;
113
+ const binding = imports.get(call.expression.text);
114
+ if (binding?.name !== candidate.name || !importMatches(file, binding.module, subject, project)) continue;
115
+ const arguments_ = call.arguments.map((arg, index) => literal(arg, candidate.parameters[index].shape));
116
+ if (arguments_.includes(null)) continue;
117
+ const expected = bare(assertion.arguments[0]);
118
+ const value = expected.kind === ts.SyntaxKind.TrueKeyword ? true
119
+ : expected.kind === ts.SyntaxKind.FalseKeyword ? false : ts.isStringLiteral(expected) ? expected.text : integer(expected);
120
+ if (value === undefined) continue;
121
+ results.push({ file, name, module: binding.module, bindingName: call.expression.text,
122
+ expectEnd: expect.arguments[0].getEnd(), args: arguments_, expected: value, projection,
123
+ suffix: projection ? `.map(row => row.${projection.field}).join(${JSON.stringify(projection.separator)})` : '' });
124
+ }
125
+ return results;
126
+ }
127
+
128
+ export function witnessProposals(candidate, fixtures) {
129
+ return fixtures.flatMap(fixture => {
130
+ const args = fixture.args.map(datum => datum.value);
131
+ return candidate.propose(args, fixture).flatMap(proposal => {
132
+ if (!proposal.append && !Object.is(proposal.original, fixture.expected)) return [];
133
+ const datum = fixture.args[proposal.path[0]];
134
+ const previous = proposal.path.slice(1).reduce((current, item) => current?.items?.[item] ?? current?.fields?.get(item), datum);
135
+ const arguments_ = structuredClone(args);
136
+ const parent = proposal.path.slice(0, -1).reduce((value, index) => value[index], arguments_);
137
+ parent[proposal.path.at(-1)] = proposal.next;
138
+ const node = previous?.node;
139
+ const pos = datum.node.getEnd() - 1;
140
+ const rewrite = proposal.append ? null
141
+ : node ? { start: node.getStart(), end: node.getEnd(), original: node.getText(), replacement: JSON.stringify(proposal.next) }
142
+ : proposal.insert && datum.items.length && !datum.node.elements.hasTrailingComma
143
+ ? { start: pos, end: pos, original: '', replacement: ', ' + proposal.next } : null;
144
+ const distance = previous && typeof proposal.next === 'number' ? Math.abs(previous.value - proposal.next) : previous ? 1 : Infinity;
145
+ return [{ ...proposal, fixture, arguments: arguments_, rewrite, distance }];
146
+ });
147
+ }).sort((a, b) => !!b.rewrite - !!a.rewrite || a.distance - b.distance);
148
+ }
@@ -0,0 +1,83 @@
1
+ import { loadTypeScript } from './typescript-compiler.mjs';
2
+
3
+ const ts = loadTypeScript();
4
+
5
+ export function parseSortConstraints(specification) {
6
+ const entries = specification?.sortConstraints ?? [];
7
+ if (!Array.isArray(entries) || entries.some(entry => !entry ||
8
+ ![entry.file, entry.function, entry.before, entry.after].every(value => typeof value === 'string' && value.length) ||
9
+ entry.before === entry.after)) throw new Error('Invalid sortConstraints entry');
10
+ return entries;
11
+ }
12
+
13
+ function member(node, receiver) {
14
+ return ts.isPropertyAccessExpression(node) && !node.questionDotToken && ts.isIdentifier(node.expression) &&
15
+ node.expression.text === receiver ? node.name.text : null;
16
+ }
17
+
18
+ export function orderRules(parameters, expression, constraints) {
19
+ if (!ts.isCallExpression(expression) || expression.questionDotToken || expression.arguments.length !== 1) return [];
20
+ const method = expression.expression;
21
+ if (!ts.isPropertyAccessExpression(method) || method.questionDotToken) return [];
22
+ let array = method.expression;
23
+ if (method.name.text === 'sort' && ts.isArrayLiteralExpression(array) && array.elements.length === 1 &&
24
+ ts.isSpreadElement(array.elements[0])) array = array.elements[0].expression;
25
+ else if (method.name.text !== 'toSorted') return [];
26
+ if (!ts.isIdentifier(array)) return [];
27
+ const index = parameters.findIndex(parameter => parameter.name === array.text && parameter.shape.items?.record);
28
+ if (index < 0) return [];
29
+ const fields = parameters[index].shape.items.record;
30
+ if (constraints.some(({ before, after }) => fields[before] !== 'number' || fields[after] !== 'number')) {
31
+ throw new Error('Sort constraints must name numeric fields of the sorted records');
32
+ }
33
+ const comparator = expression.arguments[0];
34
+ if (!ts.isArrowFunction(comparator) || comparator.modifiers?.length || comparator.parameters.length !== 2 ||
35
+ comparator.parameters.some(param => !ts.isIdentifier(param.name) || param.initializer || param.dotDotDotToken)) return [];
36
+ const [left, right] = comparator.parameters.map(param => param.name.text);
37
+ const body = comparator.body;
38
+ if (!ts.isBinaryExpression(body) || body.operatorToken.kind !== ts.SyntaxKind.MinusToken) return [];
39
+ const originalKey = member(body.left, left);
40
+ if (originalKey === null || fields[originalKey] !== 'number' || member(body.right, right) !== originalKey) return [];
41
+ return Object.keys(fields).filter(field => fields[field] === 'number' && field !== originalKey).map(alternate => ({
42
+ rule: 'substitute-sort-key/v1', node: body, replacement: `${left}.${alternate} - ${right}.${alternate}`,
43
+ order: true, constraints,
44
+ propose(args, fixture) {
45
+ const rows = args[index];
46
+ const { field, separator } = fixture.projection ?? {};
47
+ if (!Object.hasOwn(fields, field) || field === originalKey || field === alternate || rows.length < 2 || rows.length > 16 ||
48
+ new Set(rows.map(row => String(row[field]))).size !== rows.length ||
49
+ rows.some(row => constraints.some(({ before, after }) => row[before] > row[after]))) return [];
50
+ const output = (key, records) => records.toSorted((a, b) => a[key] - b[key]).map(row => row[field]).join(separator);
51
+ const seed = output(originalKey, rows);
52
+ const proposals = [];
53
+ for (const [at, row] of rows.entries()) {
54
+ for (const other of rows) {
55
+ if (other === row || other[originalKey] === row[originalKey]) continue;
56
+ const next = other[alternate] + Math.sign(other[originalKey] - row[originalKey]);
57
+ if (!Number.isSafeInteger(next) || next === row[alternate]) continue;
58
+ const modified = { ...row, [alternate]: next };
59
+ if (constraints.some(({ before, after }) => modified[before] > modified[after])) continue;
60
+ const changed = rows.with(at, modified);
61
+ const mutant = output(alternate, changed);
62
+ if (mutant !== seed) proposals.push({ path: [index, at, alternate], next, original: seed, mutant });
63
+ }
64
+ }
65
+ return proposals;
66
+ },
67
+ }));
68
+ }
69
+
70
+ export function orderProjection(node) {
71
+ if (!ts.isCallExpression(node) || node.questionDotToken || node.arguments.length !== 1 || !ts.isStringLiteral(node.arguments[0])) return null;
72
+ const join = node.expression;
73
+ if (!ts.isPropertyAccessExpression(join) || join.questionDotToken || join.name.text !== 'join' || !ts.isCallExpression(join.expression)) return null;
74
+ const map = join.expression;
75
+ if (map.questionDotToken || !ts.isPropertyAccessExpression(map.expression) || map.expression.questionDotToken ||
76
+ map.expression.name.text !== 'map' || map.arguments.length !== 1) return null;
77
+ const callback = map.arguments[0];
78
+ if (!ts.isArrowFunction(callback) || callback.modifiers?.length || callback.parameters.length !== 1 ||
79
+ !ts.isIdentifier(callback.parameters[0].name) || callback.parameters[0].initializer || callback.parameters[0].dotDotDotToken) return null;
80
+ const field = member(callback.body, callback.parameters[0].name.text);
81
+ if (!field) return null;
82
+ return { call: map.expression.expression, field, separator: node.arguments[0].text };
83
+ }