@hughescr/stryker-bun-runner 1.5.2 → 1.6.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/README.md +491 -24
- package/dist/index.d.ts +486 -32
- package/dist/index.js +3490 -334
- package/dist/templates/coverage-preload.js +1128 -0
- package/dist/templates/import-scan.js +902 -0
- package/package.json +5 -2
- package/dist/coverage/preload-logic.js +0 -255
- package/dist/templates/coverage-preload.ts +0 -440
|
@@ -0,0 +1,1128 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/templates/coverage-preload.ts
|
|
3
|
+
import { beforeEach, afterEach, afterAll, describe as describe2, test, it } from "bun:test";
|
|
4
|
+
|
|
5
|
+
// src/coverage/preload-logic.ts
|
|
6
|
+
import { appendFileSync, closeSync, constants, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync } from "fs";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
|
|
9
|
+
// src/coverage/load-sensors.ts
|
|
10
|
+
var HEADER_FUNCTION = "stryNS_9fa48";
|
|
11
|
+
var NAMESPACE_KEY = "__stryker__";
|
|
12
|
+
var HEADER_STACK_FRAMES = 8;
|
|
13
|
+
function describe(error) {
|
|
14
|
+
try {
|
|
15
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
16
|
+
} catch {
|
|
17
|
+
return "an error that cannot be described";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function headerFileFromStack(stack) {
|
|
21
|
+
for (const raw of stack.split(`
|
|
22
|
+
`)) {
|
|
23
|
+
const line = raw.trim();
|
|
24
|
+
if (!line.startsWith(`at ${HEADER_FUNCTION} `)) {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const rest = line.slice(HEADER_FUNCTION.length + 4);
|
|
28
|
+
const location = rest.startsWith("(") && rest.endsWith(")") ? rest.slice(1, -1) : rest;
|
|
29
|
+
const position = /:\d+(?::\d+)?$/.exec(location);
|
|
30
|
+
if (position === null || position.index === 0) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return location.slice(0, position.index);
|
|
34
|
+
}
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
function captureStack(errorConstructor) {
|
|
38
|
+
const ctor = errorConstructor;
|
|
39
|
+
const limit = ctor.stackTraceLimit;
|
|
40
|
+
const prepare = ctor.prepareStackTrace;
|
|
41
|
+
ctor.stackTraceLimit = HEADER_STACK_FRAMES;
|
|
42
|
+
ctor.prepareStackTrace = undefined;
|
|
43
|
+
try {
|
|
44
|
+
const { stack } = new ctor("stryker-bun-runner load sensor");
|
|
45
|
+
return typeof stack === "string" ? stack : undefined;
|
|
46
|
+
} finally {
|
|
47
|
+
ctor.stackTraceLimit = limit;
|
|
48
|
+
ctor.prepareStackTrace = prepare;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
class CandidateIndex {
|
|
53
|
+
files;
|
|
54
|
+
byKey = new Map;
|
|
55
|
+
reals;
|
|
56
|
+
groups;
|
|
57
|
+
seen;
|
|
58
|
+
observed = [];
|
|
59
|
+
unseen;
|
|
60
|
+
constructor(files, realpath) {
|
|
61
|
+
this.files = files;
|
|
62
|
+
this.seen = files.map(() => false);
|
|
63
|
+
this.unseen = files.length;
|
|
64
|
+
this.reals = files.map((file) => {
|
|
65
|
+
try {
|
|
66
|
+
const real = realpath(file);
|
|
67
|
+
return real === file ? undefined : real;
|
|
68
|
+
} catch {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
const byIdentity = new Map;
|
|
73
|
+
for (const [index, file] of files.entries()) {
|
|
74
|
+
const identity = this.reals[index] ?? file;
|
|
75
|
+
const group = byIdentity.get(identity);
|
|
76
|
+
if (group === undefined) {
|
|
77
|
+
byIdentity.set(identity, [index]);
|
|
78
|
+
} else {
|
|
79
|
+
group.push(index);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
this.groups = files.map((file, index) => byIdentity.get(this.reals[index] ?? file));
|
|
83
|
+
for (const [index, file] of files.entries()) {
|
|
84
|
+
this.add(file, this.groups[index]);
|
|
85
|
+
const real = this.reals[index];
|
|
86
|
+
if (real !== undefined) {
|
|
87
|
+
this.add(real, this.groups[index]);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
add(key, group) {
|
|
92
|
+
const known = this.byKey.get(key);
|
|
93
|
+
if (known === undefined) {
|
|
94
|
+
this.byKey.set(key, group);
|
|
95
|
+
} else if (known !== group) {
|
|
96
|
+
this.byKey.set(key, [...new Set([...known, ...group])]);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
lookup(key) {
|
|
100
|
+
return this.byKey.get(key);
|
|
101
|
+
}
|
|
102
|
+
observe(indices, time, sensor, testKey) {
|
|
103
|
+
for (const index of indices) {
|
|
104
|
+
if (!this.seen[index]) {
|
|
105
|
+
this.seen[index] = true;
|
|
106
|
+
this.unseen--;
|
|
107
|
+
this.observed.push({ file: this.files[index], time, sensor, testKey });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
cached(cache) {
|
|
112
|
+
const found = [];
|
|
113
|
+
const swept = new Set;
|
|
114
|
+
for (const [index, file] of this.files.entries()) {
|
|
115
|
+
const group = this.groups[index];
|
|
116
|
+
const real = this.reals[index];
|
|
117
|
+
if (!this.seen[index] && !swept.has(group) && ((file in cache) || real !== undefined && (real in cache))) {
|
|
118
|
+
swept.add(group);
|
|
119
|
+
found.push(...group);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return found;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function candidatesOf(index, file, deps) {
|
|
126
|
+
const exact = index.lookup(file);
|
|
127
|
+
if (exact !== undefined) {
|
|
128
|
+
return exact;
|
|
129
|
+
}
|
|
130
|
+
let plain;
|
|
131
|
+
if (file.startsWith("file:")) {
|
|
132
|
+
try {
|
|
133
|
+
plain = deps.fileURLToPath(file);
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
} else {
|
|
138
|
+
const lastSlash = file.lastIndexOf("/");
|
|
139
|
+
const query = file.indexOf("?", lastSlash + 1);
|
|
140
|
+
plain = query === -1 ? file : file.slice(0, query);
|
|
141
|
+
}
|
|
142
|
+
const spelled = index.lookup(plain);
|
|
143
|
+
if (spelled !== undefined) {
|
|
144
|
+
return spelled;
|
|
145
|
+
}
|
|
146
|
+
let real;
|
|
147
|
+
try {
|
|
148
|
+
real = deps.realpath(plain);
|
|
149
|
+
} catch {
|
|
150
|
+
return [];
|
|
151
|
+
}
|
|
152
|
+
return index.lookup(real) ?? [];
|
|
153
|
+
}
|
|
154
|
+
function installLoadSensors(deps) {
|
|
155
|
+
const problems = new Map;
|
|
156
|
+
const problem = (kind, text) => {
|
|
157
|
+
if (!problems.has(kind)) {
|
|
158
|
+
problems.set(kind, text);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
let sensorMs = 0;
|
|
162
|
+
let time = "by-eager-end";
|
|
163
|
+
let finished = false;
|
|
164
|
+
let busy = false;
|
|
165
|
+
let index;
|
|
166
|
+
let installed;
|
|
167
|
+
const addElapsed = (started) => {
|
|
168
|
+
try {
|
|
169
|
+
if (started !== undefined) {
|
|
170
|
+
sensorMs += deps.now() - started;
|
|
171
|
+
}
|
|
172
|
+
} catch (error) {
|
|
173
|
+
problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
const measured = (work) => {
|
|
177
|
+
let started;
|
|
178
|
+
try {
|
|
179
|
+
started = deps.now();
|
|
180
|
+
work();
|
|
181
|
+
} catch (error) {
|
|
182
|
+
problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
|
|
183
|
+
} finally {
|
|
184
|
+
addElapsed(started);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const lookUpCache = (testKey) => {
|
|
188
|
+
if (index !== undefined && index.unseen > 0) {
|
|
189
|
+
index.observe(index.cached(deps.cache), time, "cache", testKey);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
try {
|
|
193
|
+
const candidates = new CandidateIndex(deps.candidates, deps.realpath);
|
|
194
|
+
index = candidates;
|
|
195
|
+
let current = deps.namespace;
|
|
196
|
+
const record = (stack) => {
|
|
197
|
+
const file = stack === undefined ? null : headerFileFromStack(stack);
|
|
198
|
+
if (file === undefined) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const found = file === null ? null : candidatesOf(candidates, file, deps);
|
|
202
|
+
if (found === null) {
|
|
203
|
+
const frame = stack?.split(`
|
|
204
|
+
`).find((line) => line.includes(HEADER_FUNCTION))?.trim() ?? "no stack";
|
|
205
|
+
problem("unreadable", `an instrumented file was evaluated but its path could not be read from the stack (${frame})`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (found.length > 0) {
|
|
209
|
+
candidates.observe(found, time, "header", time === "later" ? deps.currentTest() : null);
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
const getter = function strykerNamespaceSensor() {
|
|
213
|
+
if (!finished && !busy && candidates.unseen > 0) {
|
|
214
|
+
busy = true;
|
|
215
|
+
let started;
|
|
216
|
+
try {
|
|
217
|
+
started = deps.now();
|
|
218
|
+
record(deps.readStack());
|
|
219
|
+
} catch (error) {
|
|
220
|
+
problem("bookkeeping", `the load sensors failed: ${describe(error)}`);
|
|
221
|
+
} finally {
|
|
222
|
+
busy = false;
|
|
223
|
+
addElapsed(started);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return current;
|
|
227
|
+
};
|
|
228
|
+
Object.defineProperty(deps.global, NAMESPACE_KEY, {
|
|
229
|
+
configurable: true,
|
|
230
|
+
enumerable: true,
|
|
231
|
+
get: getter,
|
|
232
|
+
set(value) {
|
|
233
|
+
current = value;
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
installed = getter;
|
|
237
|
+
measured(() => {
|
|
238
|
+
lookUpCache(null);
|
|
239
|
+
});
|
|
240
|
+
} catch (error) {
|
|
241
|
+
problem("install", `the load sensors could not be installed: ${describe(error)}`);
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
markEagerEnd() {
|
|
245
|
+
measured(() => {
|
|
246
|
+
lookUpCache(null);
|
|
247
|
+
});
|
|
248
|
+
time = "later";
|
|
249
|
+
},
|
|
250
|
+
finish() {
|
|
251
|
+
measured(() => {
|
|
252
|
+
lookUpCache(null);
|
|
253
|
+
});
|
|
254
|
+
finished = true;
|
|
255
|
+
try {
|
|
256
|
+
if (installed !== undefined && Object.getOwnPropertyDescriptor(deps.global, NAMESPACE_KEY)?.get !== installed) {
|
|
257
|
+
problem("replaced", "globalThis.__stryker__ was redefined during the run");
|
|
258
|
+
}
|
|
259
|
+
} catch (error) {
|
|
260
|
+
problem("replaced", `globalThis.__stryker__ could not be checked at the end of the run: ${describe(error)}`);
|
|
261
|
+
}
|
|
262
|
+
return { observed: index?.observed ?? [], problems: [...problems.values()], sensorMs };
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/coverage/preload-logic.ts
|
|
268
|
+
var PreloadError = Error;
|
|
269
|
+
var preloadFs = { appendFileSync, closeSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync };
|
|
270
|
+
var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
|
|
271
|
+
var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
|
|
272
|
+
function getPreloadConfig() {
|
|
273
|
+
return {
|
|
274
|
+
syncPort: process.env.__STRYKER_SYNC_PORT__,
|
|
275
|
+
syncToken: process.env[SYNC_TOKEN_ENV],
|
|
276
|
+
coverageFile: process.env.__STRYKER_COVERAGE_FILE__,
|
|
277
|
+
activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__,
|
|
278
|
+
hitLimit: parseHitLimit(process.env.__STRYKER_HIT_LIMIT__),
|
|
279
|
+
hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV]
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function parseHitLimit(raw) {
|
|
283
|
+
const limit = Number(raw);
|
|
284
|
+
return Number.isInteger(limit) && limit > 0 ? limit : undefined;
|
|
285
|
+
}
|
|
286
|
+
function shouldCollectCoverage(config) {
|
|
287
|
+
return !config.activeMutant && !!config.coverageFile;
|
|
288
|
+
}
|
|
289
|
+
function waitForSyncReady(socket) {
|
|
290
|
+
return new Promise((resolve) => {
|
|
291
|
+
socket.addEventListener("message", (event) => {
|
|
292
|
+
if (event.data === "ready") {
|
|
293
|
+
resolve({ ready: true });
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
socket.addEventListener("error", () => {
|
|
297
|
+
resolve({ ready: false, problem: "failed with a connection error" });
|
|
298
|
+
});
|
|
299
|
+
socket.addEventListener("close", (event) => {
|
|
300
|
+
const reason = event.reason ? `, reason "${event.reason}"` : "";
|
|
301
|
+
resolve({ ready: false, problem: `closed (code ${event.code ?? "unknown"}${reason})` });
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function syncAddress(syncPort) {
|
|
306
|
+
return `ws://127.0.0.1:${syncPort}/sync`;
|
|
307
|
+
}
|
|
308
|
+
async function awaitRunnerReady(deps) {
|
|
309
|
+
const openSocket = deps.openSocket ?? ((url) => new WebSocket(url));
|
|
310
|
+
const fail = deps.fail ?? ((message) => {
|
|
311
|
+
console.error(message);
|
|
312
|
+
process.exit(1);
|
|
313
|
+
});
|
|
314
|
+
let socket;
|
|
315
|
+
let outcome;
|
|
316
|
+
try {
|
|
317
|
+
socket = openSocket(`${syncAddress(deps.syncPort)}/${deps.syncToken}`);
|
|
318
|
+
outcome = await waitForSyncReady(socket);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
const reason = redactToken(error instanceof Error ? error.message : String(error), deps.syncToken);
|
|
321
|
+
return fail(formatSyncNotReadyMessage(deps.syncPort, `could not be opened (${reason})`));
|
|
322
|
+
}
|
|
323
|
+
if (!outcome.ready) {
|
|
324
|
+
return fail(formatSyncNotReadyMessage(deps.syncPort, outcome.problem));
|
|
325
|
+
}
|
|
326
|
+
if (deps.keepOpen) {
|
|
327
|
+
return socket;
|
|
328
|
+
}
|
|
329
|
+
socket.close();
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
function redactToken(text, token) {
|
|
333
|
+
return token === "" ? text : text.replaceAll(token, "[redacted]");
|
|
334
|
+
}
|
|
335
|
+
function formatSyncNotReadyMessage(syncPort, problem) {
|
|
336
|
+
return [
|
|
337
|
+
`[Stryker] stryker-bun-runner: the dry run's sync connection to the runner (${syncAddress(syncPort)}) ${problem}`,
|
|
338
|
+
"before the runner signalled that it is ready to observe the tests. Exiting without running any test: tests run now",
|
|
339
|
+
"would not be seen by the runner's inspector, so their results and per-test coverage would be lost."
|
|
340
|
+
].join(" ");
|
|
341
|
+
}
|
|
342
|
+
var PRELOAD_TIMINGS_ENV = "__STRYKER_PRELOAD_TIMINGS__";
|
|
343
|
+
function preloadEpochNow() {
|
|
344
|
+
return performance.timeOrigin + performance.now();
|
|
345
|
+
}
|
|
346
|
+
var PRELOAD_TIMINGS_PREFIX = "[Stryker Timings] ";
|
|
347
|
+
function formatPreloadTimings(timings) {
|
|
348
|
+
return `
|
|
349
|
+
${PRELOAD_TIMINGS_PREFIX}${JSON.stringify(timings)}
|
|
350
|
+
`;
|
|
351
|
+
}
|
|
352
|
+
function initializeStrykerNamespace(globalObj) {
|
|
353
|
+
const g = globalObj;
|
|
354
|
+
g.__stryker__ ??= { mutantCoverage: { static: {}, perTest: {} } };
|
|
355
|
+
const strykerGlobal = g.__stryker__;
|
|
356
|
+
strykerGlobal.mutantCoverage ??= { static: {}, perTest: {} };
|
|
357
|
+
g.__mutantCoverage__ = strykerGlobal.mutantCoverage;
|
|
358
|
+
return strykerGlobal;
|
|
359
|
+
}
|
|
360
|
+
function setActiveMutant(strykerNamespace, activeMutant) {
|
|
361
|
+
strykerNamespace.activeMutant = activeMutant;
|
|
362
|
+
}
|
|
363
|
+
var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
|
|
364
|
+
function formatHitLimitSentinel(token, hitCount) {
|
|
365
|
+
return `
|
|
366
|
+
${HIT_LIMIT_SENTINEL} ${token} ${hitCount}
|
|
367
|
+
`;
|
|
368
|
+
}
|
|
369
|
+
function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
|
|
370
|
+
preloadFs.writeSync(2, line);
|
|
371
|
+
}, onFirstHit) {
|
|
372
|
+
let hitCount = 0;
|
|
373
|
+
let reported = false;
|
|
374
|
+
let firstHitSeen = onFirstHit === undefined;
|
|
375
|
+
strykerNamespace.hitLimit = hitLimit;
|
|
376
|
+
Object.defineProperty(strykerNamespace, "hitCount", {
|
|
377
|
+
configurable: true,
|
|
378
|
+
enumerable: true,
|
|
379
|
+
get: () => hitCount,
|
|
380
|
+
set: (value) => {
|
|
381
|
+
hitCount = value;
|
|
382
|
+
if (!firstHitSeen) {
|
|
383
|
+
firstHitSeen = true;
|
|
384
|
+
try {
|
|
385
|
+
onFirstHit?.();
|
|
386
|
+
} catch {}
|
|
387
|
+
}
|
|
388
|
+
if (!reported && hitCount > hitLimit) {
|
|
389
|
+
reported = true;
|
|
390
|
+
report(formatHitLimitSentinel(token, hitCount));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
class StaticGapTracker {
|
|
397
|
+
coverage;
|
|
398
|
+
held;
|
|
399
|
+
constructor(coverage) {
|
|
400
|
+
this.coverage = coverage;
|
|
401
|
+
}
|
|
402
|
+
open() {
|
|
403
|
+
this.close();
|
|
404
|
+
this.held = this.coverage.static;
|
|
405
|
+
this.coverage.static = {};
|
|
406
|
+
}
|
|
407
|
+
close() {
|
|
408
|
+
const held = this.held;
|
|
409
|
+
if (held === undefined) {
|
|
410
|
+
return [];
|
|
411
|
+
}
|
|
412
|
+
const gap = this.coverage.static;
|
|
413
|
+
this.coverage.static = held;
|
|
414
|
+
this.held = undefined;
|
|
415
|
+
const ids = Object.keys(gap);
|
|
416
|
+
for (const id of ids) {
|
|
417
|
+
held[id] = (held[id] ?? 0) + gap[id];
|
|
418
|
+
}
|
|
419
|
+
return ids;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
function serializeCoverageData(mutantCoverage, lateHits = [], gapTracker) {
|
|
423
|
+
gapTracker?.close();
|
|
424
|
+
const data = {
|
|
425
|
+
perTest: mutantCoverage?.perTest ?? {},
|
|
426
|
+
static: mutantCoverage?.static ?? {},
|
|
427
|
+
...lateHits.length > 0 ? { lateHits } : {}
|
|
428
|
+
};
|
|
429
|
+
return JSON.stringify(data);
|
|
430
|
+
}
|
|
431
|
+
var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
|
|
432
|
+
function writeCoverageToFile(coverageFile, data) {
|
|
433
|
+
const line = typeof data === "string" ? data : JSON.stringify(data);
|
|
434
|
+
const fd = preloadFs.openSync(coverageFile, COVERAGE_APPEND_FLAGS, 384);
|
|
435
|
+
try {
|
|
436
|
+
preloadFs.appendFileSync(fd, `${line}
|
|
437
|
+
`, "utf8");
|
|
438
|
+
} finally {
|
|
439
|
+
preloadFs.closeSync(fd);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
var DRY_RUN_PLAN_ENV = "__STRYKER_DRY_RUN_PLAN__";
|
|
443
|
+
var PLAN_FIELDS = new Set(["mode", "eager", "candidates", "recordFile", "nonce"]);
|
|
444
|
+
function isPathList(value) {
|
|
445
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry !== "");
|
|
446
|
+
}
|
|
447
|
+
function isNullOrText(value) {
|
|
448
|
+
return value === null || typeof value === "string" && value !== "";
|
|
449
|
+
}
|
|
450
|
+
function planFieldProblem(plan) {
|
|
451
|
+
const unexpected = Object.keys(plan).find((key) => !PLAN_FIELDS.has(key));
|
|
452
|
+
if (unexpected !== undefined) {
|
|
453
|
+
return `unexpected field ${JSON.stringify(unexpected)}`;
|
|
454
|
+
}
|
|
455
|
+
if (plan.mode !== "publish" && plan.mode !== "discover") {
|
|
456
|
+
return 'mode is neither "publish" nor "discover"';
|
|
457
|
+
}
|
|
458
|
+
if (!isPathList(plan.eager)) {
|
|
459
|
+
return "eager is not an array of paths";
|
|
460
|
+
}
|
|
461
|
+
if (plan.candidates !== null && !isPathList(plan.candidates)) {
|
|
462
|
+
return "candidates is neither null nor an array of paths";
|
|
463
|
+
}
|
|
464
|
+
if (!isNullOrText(plan.recordFile)) {
|
|
465
|
+
return "recordFile is neither null nor a path";
|
|
466
|
+
}
|
|
467
|
+
if (!isNullOrText(plan.nonce)) {
|
|
468
|
+
return "nonce is neither null nor a non-empty string";
|
|
469
|
+
}
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
function planCombinationProblem(plan) {
|
|
473
|
+
if (plan.mode === "discover") {
|
|
474
|
+
if (plan.eager.length > 0) {
|
|
475
|
+
return "a discover plan imports nothing first, but eager is not empty";
|
|
476
|
+
}
|
|
477
|
+
if (plan.candidates === null || plan.recordFile === null || plan.nonce === null) {
|
|
478
|
+
return "a discover plan needs candidates, a recordFile and a nonce";
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
if (plan.recordFile === null !== (plan.nonce === null)) {
|
|
482
|
+
return "a plan carries a nonce exactly when it has a recordFile";
|
|
483
|
+
}
|
|
484
|
+
if (plan.candidates !== null && plan.recordFile === null) {
|
|
485
|
+
return "candidates are watched, but there is no recordFile to report on";
|
|
486
|
+
}
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
function planProblem(value) {
|
|
490
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
491
|
+
return "not a JSON object";
|
|
492
|
+
}
|
|
493
|
+
return planFieldProblem(value) ?? planCombinationProblem(value);
|
|
494
|
+
}
|
|
495
|
+
function readDryRunPlan(file, read = (planFile) => preloadFs.readFileSync(planFile, "utf8")) {
|
|
496
|
+
let text;
|
|
497
|
+
try {
|
|
498
|
+
text = read(file);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw new Error(describeError(error), { cause: error });
|
|
501
|
+
}
|
|
502
|
+
let value;
|
|
503
|
+
try {
|
|
504
|
+
value = JSON.parse(text);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
throw new Error("not valid JSON", { cause: error });
|
|
507
|
+
}
|
|
508
|
+
const problem = planProblem(value);
|
|
509
|
+
if (problem !== undefined) {
|
|
510
|
+
throw new Error(problem);
|
|
511
|
+
}
|
|
512
|
+
return value;
|
|
513
|
+
}
|
|
514
|
+
function formatDryRunPlanMessage(file, problem) {
|
|
515
|
+
return `[Stryker] Cannot read the dry-run plan ${file} (${problem}); stopping instead of running the tests with nothing imported first.`;
|
|
516
|
+
}
|
|
517
|
+
function moduleCache() {
|
|
518
|
+
return createRequire(import.meta.url).cache;
|
|
519
|
+
}
|
|
520
|
+
function startLoadSensors(candidates, namespace, currentTest) {
|
|
521
|
+
const bun = globalThis.Bun;
|
|
522
|
+
return installLoadSensors({
|
|
523
|
+
global: globalThis,
|
|
524
|
+
namespace,
|
|
525
|
+
candidates,
|
|
526
|
+
cache: moduleCache(),
|
|
527
|
+
realpath: (file) => preloadFs.realpathSync(file),
|
|
528
|
+
fileURLToPath: (url) => bun.fileURLToPath(url),
|
|
529
|
+
readStack: () => captureStack(PreloadError),
|
|
530
|
+
now: () => performance.now(),
|
|
531
|
+
currentTest
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
function describeImportError(error) {
|
|
535
|
+
try {
|
|
536
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
537
|
+
} catch {
|
|
538
|
+
return "an error that cannot be described";
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function reachedMutantIds(mutantCoverage) {
|
|
542
|
+
const reached = new Set;
|
|
543
|
+
for (const counts of [mutantCoverage?.static ?? {}, ...Object.values(mutantCoverage?.perTest ?? {})]) {
|
|
544
|
+
for (const [id, count] of Object.entries(counts)) {
|
|
545
|
+
if (count > 0) {
|
|
546
|
+
reached.add(id);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return [...reached];
|
|
551
|
+
}
|
|
552
|
+
function buildDryRunRecord(plan, parts) {
|
|
553
|
+
const observation = {
|
|
554
|
+
nonce: plan.nonce ?? "",
|
|
555
|
+
complete: true,
|
|
556
|
+
observed: parts.sensors?.observed ?? [],
|
|
557
|
+
problems: parts.sensors?.problems ?? [],
|
|
558
|
+
eagerFailures: [...parts.eagerFailures],
|
|
559
|
+
sensorMs: parts.sensors?.sensorMs ?? 0
|
|
560
|
+
};
|
|
561
|
+
if (plan.mode === "publish") {
|
|
562
|
+
return observation;
|
|
563
|
+
}
|
|
564
|
+
return { ...observation, startedTests: parts.startedTests, reached: reachedMutantIds(parts.coverage) };
|
|
565
|
+
}
|
|
566
|
+
function distinctBy(entries, key) {
|
|
567
|
+
const seen = new Set;
|
|
568
|
+
return entries.filter((entry) => {
|
|
569
|
+
const k = key(entry);
|
|
570
|
+
if (seen.has(k)) {
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
seen.add(k);
|
|
574
|
+
return true;
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
function latestSightings(observations) {
|
|
578
|
+
const kept = new Map;
|
|
579
|
+
for (const sighting of observations) {
|
|
580
|
+
const known = kept.get(sighting.file);
|
|
581
|
+
if (known === undefined || known.time === "by-eager-end" && sighting.time === "later") {
|
|
582
|
+
kept.set(sighting.file, sighting);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return observations.filter((sighting) => kept.get(sighting.file) === sighting);
|
|
586
|
+
}
|
|
587
|
+
var hasOwnField = Object.hasOwn;
|
|
588
|
+
var ownField = (value, field) => hasOwnField(value, field) ? value[field] : undefined;
|
|
589
|
+
var isProblem = (value) => hasOwnField(value, "problem");
|
|
590
|
+
var isDiscoveryRecord = (record) => hasOwnField(record, "startedTests");
|
|
591
|
+
var isEntryObject = (entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry);
|
|
592
|
+
var isStringEntry = (entry) => typeof entry === "string";
|
|
593
|
+
var isListOf = (value, isEntry) => Array.isArray(value) && value.every((entry) => isEntry(entry));
|
|
594
|
+
var EARLIER_RECORD_PROBLEM = "an earlier record of this launch could not be read";
|
|
595
|
+
function mergeDryRunRecords(previous, next) {
|
|
596
|
+
if (previous === undefined) {
|
|
597
|
+
return next;
|
|
598
|
+
}
|
|
599
|
+
const earlier = isProblem(previous) ? previous : earlierRecordOf(previous.value, next.nonce, isDiscoveryRecord(next));
|
|
600
|
+
if (isProblem(earlier)) {
|
|
601
|
+
return { ...next, problems: [...next.problems, `${EARLIER_RECORD_PROBLEM}: ${earlier.problem}`] };
|
|
602
|
+
}
|
|
603
|
+
const merged = {
|
|
604
|
+
nonce: next.nonce,
|
|
605
|
+
complete: true,
|
|
606
|
+
observed: latestSightings([...earlier.observed, ...next.observed]),
|
|
607
|
+
problems: [...new Set([...earlier.problems, ...next.problems])],
|
|
608
|
+
eagerFailures: distinctBy([...earlier.eagerFailures, ...next.eagerFailures], (failure) => `${failure.file}\x00${failure.error}`),
|
|
609
|
+
sensorMs: earlier.sensorMs + next.sensorMs
|
|
610
|
+
};
|
|
611
|
+
if (!isDiscoveryRecord(next)) {
|
|
612
|
+
return merged;
|
|
613
|
+
}
|
|
614
|
+
return { ...merged, startedTests: earlier.startedTests + next.startedTests, reached: [...new Set([...earlier.reached, ...next.reached])] };
|
|
615
|
+
}
|
|
616
|
+
function earlierRecordOf(previous, nonce, discovery) {
|
|
617
|
+
if (!isEntryObject(previous)) {
|
|
618
|
+
return { problem: "it is not a JSON object" };
|
|
619
|
+
}
|
|
620
|
+
const field = (name) => ownField(previous, name);
|
|
621
|
+
if (field("nonce") !== nonce) {
|
|
622
|
+
return { problem: "it carries another launch's nonce" };
|
|
623
|
+
}
|
|
624
|
+
if (field("complete") !== true) {
|
|
625
|
+
return { problem: "it is not marked complete" };
|
|
626
|
+
}
|
|
627
|
+
const malformed = malformedEarlierField(field, discovery);
|
|
628
|
+
if (malformed !== undefined) {
|
|
629
|
+
return { problem: `its ${malformed} field is malformed` };
|
|
630
|
+
}
|
|
631
|
+
return {
|
|
632
|
+
observed: field("observed"),
|
|
633
|
+
problems: field("problems"),
|
|
634
|
+
eagerFailures: field("eagerFailures"),
|
|
635
|
+
sensorMs: field("sensorMs"),
|
|
636
|
+
startedTests: discovery ? field("startedTests") : 0,
|
|
637
|
+
reached: discovery ? field("reached") : []
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function isSighting(entry) {
|
|
641
|
+
if (!isEntryObject(entry)) {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
const time = ownField(entry, "time");
|
|
645
|
+
const sensor = ownField(entry, "sensor");
|
|
646
|
+
const testKey = ownField(entry, "testKey");
|
|
647
|
+
return typeof ownField(entry, "file") === "string" && (time === "by-eager-end" || time === "later") && (sensor === "header" || sensor === "cache") && (testKey === null || typeof testKey === "string");
|
|
648
|
+
}
|
|
649
|
+
function isImportFailure(entry) {
|
|
650
|
+
return isEntryObject(entry) && typeof ownField(entry, "file") === "string" && typeof ownField(entry, "error") === "string";
|
|
651
|
+
}
|
|
652
|
+
function isDuration(value) {
|
|
653
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
654
|
+
}
|
|
655
|
+
function isCount(value) {
|
|
656
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
657
|
+
}
|
|
658
|
+
function malformedEarlierField(field, discovery) {
|
|
659
|
+
if (!isListOf(field("observed"), isSighting)) {
|
|
660
|
+
return "observed";
|
|
661
|
+
}
|
|
662
|
+
if (!isListOf(field("problems"), isStringEntry)) {
|
|
663
|
+
return "problems";
|
|
664
|
+
}
|
|
665
|
+
if (!isListOf(field("eagerFailures"), isImportFailure)) {
|
|
666
|
+
return "eagerFailures";
|
|
667
|
+
}
|
|
668
|
+
if (!isDuration(field("sensorMs"))) {
|
|
669
|
+
return "sensorMs";
|
|
670
|
+
}
|
|
671
|
+
if (discovery && !isCount(field("startedTests"))) {
|
|
672
|
+
return "startedTests";
|
|
673
|
+
}
|
|
674
|
+
if (discovery && !isListOf(field("reached"), isStringEntry)) {
|
|
675
|
+
return "reached";
|
|
676
|
+
}
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
function readEarlierRecord(file) {
|
|
680
|
+
let text;
|
|
681
|
+
try {
|
|
682
|
+
text = preloadFs.readFileSync(file, "utf8");
|
|
683
|
+
} catch (error) {
|
|
684
|
+
return error?.code === "ENOENT" ? undefined : { problem: describeImportError(error) };
|
|
685
|
+
}
|
|
686
|
+
try {
|
|
687
|
+
return { value: JSON.parse(text) };
|
|
688
|
+
} catch (error) {
|
|
689
|
+
return { problem: `it is not JSON (${describeImportError(error)})` };
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
var PRIVATE_CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
|
|
693
|
+
function writePrivateFileAtomically(file, data) {
|
|
694
|
+
const temporary = `${file}.tmp`;
|
|
695
|
+
try {
|
|
696
|
+
preloadFs.unlinkSync(temporary);
|
|
697
|
+
} catch {}
|
|
698
|
+
const fd = preloadFs.openSync(temporary, PRIVATE_CREATE_FLAGS, 384);
|
|
699
|
+
try {
|
|
700
|
+
try {
|
|
701
|
+
preloadFs.appendFileSync(fd, data, "utf8");
|
|
702
|
+
} finally {
|
|
703
|
+
preloadFs.closeSync(fd);
|
|
704
|
+
}
|
|
705
|
+
preloadFs.renameSync(temporary, file);
|
|
706
|
+
} catch (error) {
|
|
707
|
+
try {
|
|
708
|
+
preloadFs.unlinkSync(temporary);
|
|
709
|
+
} catch {}
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
var WATCH_LIST_ENV = "__STRYKER_WATCH_LIST__";
|
|
714
|
+
var WITNESS_SENTINEL = "__STRYKER_UNIMPORTED_LOADED__";
|
|
715
|
+
var WATCH_LIST_PROBLEM_SENTINEL = "__STRYKER_WATCH_LIST_UNREADABLE__";
|
|
716
|
+
function formatWitnessLine(token, loaded) {
|
|
717
|
+
return `
|
|
718
|
+
${WITNESS_SENTINEL} ${token} ${JSON.stringify(loaded)}
|
|
719
|
+
`;
|
|
720
|
+
}
|
|
721
|
+
function formatWatchListProblem(token, problem) {
|
|
722
|
+
return `
|
|
723
|
+
${WATCH_LIST_PROBLEM_SENTINEL} ${token} ${JSON.stringify(problem)}
|
|
724
|
+
`;
|
|
725
|
+
}
|
|
726
|
+
function isWatchedFile(value) {
|
|
727
|
+
if (typeof value !== "object" || value === null) {
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
const { file, realpath } = value;
|
|
731
|
+
return typeof file === "string" && file !== "" && typeof realpath === "string" && realpath !== "" && Object.keys(value).length === 2;
|
|
732
|
+
}
|
|
733
|
+
function readWatchList(file, read = (listFile) => preloadFs.readFileSync(listFile, "utf8")) {
|
|
734
|
+
let text;
|
|
735
|
+
try {
|
|
736
|
+
text = read(file);
|
|
737
|
+
} catch (error) {
|
|
738
|
+
throw new Error(describeError(error), { cause: error });
|
|
739
|
+
}
|
|
740
|
+
let value;
|
|
741
|
+
try {
|
|
742
|
+
value = JSON.parse(text);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
throw new Error("not valid JSON", { cause: error });
|
|
745
|
+
}
|
|
746
|
+
if (!Array.isArray(value) || !value.every((entry) => isWatchedFile(entry))) {
|
|
747
|
+
throw new Error("not a JSON array of { file, realpath } entries");
|
|
748
|
+
}
|
|
749
|
+
return value;
|
|
750
|
+
}
|
|
751
|
+
function instrumentedCodeHasRun(strykerNamespace) {
|
|
752
|
+
if (strykerNamespace.activeMutant !== undefined || typeof strykerNamespace.hitCount === "number" && strykerNamespace.hitCount > 0) {
|
|
753
|
+
return true;
|
|
754
|
+
}
|
|
755
|
+
const coverage = strykerNamespace.mutantCoverage;
|
|
756
|
+
return Object.keys(coverage?.static ?? {}).length > 0 || Object.keys(coverage?.perTest ?? {}).length > 0;
|
|
757
|
+
}
|
|
758
|
+
function setUpWitness(deps) {
|
|
759
|
+
const write = deps.write ?? ((line) => {
|
|
760
|
+
preloadFs.writeSync(2, line);
|
|
761
|
+
});
|
|
762
|
+
if (deps.disarmed) {
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
let watched;
|
|
766
|
+
try {
|
|
767
|
+
watched = readWatchList(deps.file, deps.read);
|
|
768
|
+
} catch (error) {
|
|
769
|
+
try {
|
|
770
|
+
write(formatWatchListProblem(deps.token, `${deps.file}: ${error.message}`));
|
|
771
|
+
} catch {}
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
if (watched.length === 0) {
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
const { cache, token } = deps;
|
|
778
|
+
return () => {
|
|
779
|
+
const loaded = [];
|
|
780
|
+
for (const { file, realpath } of watched) {
|
|
781
|
+
if (file in cache || realpath !== file && realpath in cache) {
|
|
782
|
+
loaded.push(file);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (loaded.length > 0) {
|
|
786
|
+
try {
|
|
787
|
+
write(formatWitnessLine(token, loaded));
|
|
788
|
+
} catch {}
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
|
|
793
|
+
function describeError(error) {
|
|
794
|
+
const { code, message } = error;
|
|
795
|
+
return String(code ?? message);
|
|
796
|
+
}
|
|
797
|
+
function parseLifelineFd(value) {
|
|
798
|
+
if (value === undefined || !/^\d+$/.test(value)) {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
const fd = Number(value);
|
|
802
|
+
return Number.isSafeInteger(fd) && fd > 2 ? fd : undefined;
|
|
803
|
+
}
|
|
804
|
+
function openLifelineReader(fd, file) {
|
|
805
|
+
const openFile = file ?? ((lifelineFd) => globalThis.Bun.file(lifelineFd));
|
|
806
|
+
const reader = openFile(fd).stream().getReader();
|
|
807
|
+
let onEnd;
|
|
808
|
+
let onError;
|
|
809
|
+
const drain = async () => {
|
|
810
|
+
for (;; ) {
|
|
811
|
+
const { done } = await reader.read();
|
|
812
|
+
if (done) {
|
|
813
|
+
onEnd?.();
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
return {
|
|
819
|
+
once(_event, listener) {
|
|
820
|
+
onEnd = listener;
|
|
821
|
+
},
|
|
822
|
+
on(_event, listener) {
|
|
823
|
+
onError = listener;
|
|
824
|
+
},
|
|
825
|
+
resume() {
|
|
826
|
+
drain().catch((error) => {
|
|
827
|
+
onError?.(error);
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
function watchParentLifeline(deps) {
|
|
833
|
+
let settled = false;
|
|
834
|
+
const unavailable = (reason) => {
|
|
835
|
+
if (!settled) {
|
|
836
|
+
settled = true;
|
|
837
|
+
deps.onUnavailable(reason);
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
const fd = parseLifelineFd(deps.fdValue);
|
|
841
|
+
if (fd === undefined) {
|
|
842
|
+
unavailable(`${LIFELINE_FD_ENV}=${deps.fdValue ?? "(unset)"} names no lifeline descriptor`);
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
const open = deps.open ?? ((lifelineFd) => openLifelineReader(lifelineFd));
|
|
846
|
+
let lifeline;
|
|
847
|
+
try {
|
|
848
|
+
lifeline = open(fd);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
unavailable(`opening fd ${fd} failed: ${describeError(error)}`);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
lifeline.once("end", () => {
|
|
854
|
+
settled = true;
|
|
855
|
+
deps.onOrphaned();
|
|
856
|
+
});
|
|
857
|
+
lifeline.on("error", (error) => {
|
|
858
|
+
unavailable(`reading fd ${fd} failed: ${describeError(error)}`);
|
|
859
|
+
});
|
|
860
|
+
lifeline.resume();
|
|
861
|
+
}
|
|
862
|
+
function startOrphanWatchdog(deps) {
|
|
863
|
+
const originalPpid = deps.originalPpid ?? deps.getPpid();
|
|
864
|
+
let fired = false;
|
|
865
|
+
const intervalId = setInterval(() => {
|
|
866
|
+
if (fired || deps.getPpid() === originalPpid) {
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
fired = true;
|
|
870
|
+
deps.onOrphaned();
|
|
871
|
+
}, deps.intervalMs ?? 1000);
|
|
872
|
+
intervalId.unref();
|
|
873
|
+
return () => {
|
|
874
|
+
clearInterval(intervalId);
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
function guardAgainstOrphaning(deps) {
|
|
878
|
+
const originalPpid = deps.getPpid();
|
|
879
|
+
watchParentLifeline({
|
|
880
|
+
fdValue: deps.fdValue,
|
|
881
|
+
onOrphaned: deps.onOrphaned,
|
|
882
|
+
open: deps.open,
|
|
883
|
+
onUnavailable: (reason) => {
|
|
884
|
+
deps.log?.(`[Stryker] parent lifeline unavailable (${reason}); polling the parent PID on a timer instead`);
|
|
885
|
+
startOrphanWatchdog({ getPpid: deps.getPpid, onOrphaned: deps.onOrphaned, intervalMs: deps.intervalMs, originalPpid });
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
var ORPHAN_DEBUG_ENV = "STRYKER_BUN_RUNNER_DEBUG";
|
|
890
|
+
function orphanDebugLog(value, write) {
|
|
891
|
+
if (value === undefined || value === "" || value === "0" || value === "false") {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
return (message) => {
|
|
895
|
+
write(`${message}
|
|
896
|
+
`);
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// src/templates/coverage-preload.ts
|
|
901
|
+
var timings = process.env[PRELOAD_TIMINGS_ENV] ? {} : undefined;
|
|
902
|
+
var nowEpoch = preloadEpochNow;
|
|
903
|
+
if (timings) {
|
|
904
|
+
timings["at.preloadStart"] = nowEpoch();
|
|
905
|
+
}
|
|
906
|
+
guardAgainstOrphaning({
|
|
907
|
+
fdValue: process.env[LIFELINE_FD_ENV],
|
|
908
|
+
getPpid: () => process.ppid,
|
|
909
|
+
log: orphanDebugLog(process.env[ORPHAN_DEBUG_ENV], (text) => process.stderr.write(text)),
|
|
910
|
+
onOrphaned: () => {
|
|
911
|
+
console.warn("[Stryker] Parent process is no longer running \u2014 terminating to avoid an orphaned bun test process");
|
|
912
|
+
process.exit(1);
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
Object.defineProperty(describe2, "concurrent", { value: describe2, writable: true, configurable: true });
|
|
916
|
+
Object.defineProperty(test, "concurrent", { value: test, writable: true, configurable: true });
|
|
917
|
+
Object.defineProperty(it, "concurrent", { value: it, writable: true, configurable: true });
|
|
918
|
+
var config = getPreloadConfig();
|
|
919
|
+
var { syncPort, syncToken, coverageFile, activeMutant, hitLimit, hitLimitToken } = config;
|
|
920
|
+
delete process.env[HIT_LIMIT_TOKEN_ENV];
|
|
921
|
+
delete process.env[SYNC_TOKEN_ENV];
|
|
922
|
+
var planFile = process.env[DRY_RUN_PLAN_ENV];
|
|
923
|
+
delete process.env[DRY_RUN_PLAN_ENV];
|
|
924
|
+
var watchListFile = process.env[WATCH_LIST_ENV];
|
|
925
|
+
delete process.env[WATCH_LIST_ENV];
|
|
926
|
+
var plan = null;
|
|
927
|
+
if (planFile !== undefined && !activeMutant) {
|
|
928
|
+
try {
|
|
929
|
+
plan = readDryRunPlan(planFile);
|
|
930
|
+
} catch (error) {
|
|
931
|
+
preloadFs.writeSync(2, `${formatDryRunPlanMessage(planFile, error instanceof Error ? error.message : String(error))}
|
|
932
|
+
`);
|
|
933
|
+
process.exit(1);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
var discovering = plan?.mode === "discover";
|
|
937
|
+
var shouldCollectCoverage2 = shouldCollectCoverage(config) || discovering;
|
|
938
|
+
var ws = null;
|
|
939
|
+
var DRAIN_ACK_TIMEOUT_MS = 40000;
|
|
940
|
+
var perFileCounters = new Map;
|
|
941
|
+
function extractFilePrefix(bunMain) {
|
|
942
|
+
if (!bunMain) {
|
|
943
|
+
return "unknown";
|
|
944
|
+
}
|
|
945
|
+
const sandboxMatch = /\.stryker-tmp\/sandbox-[^/]+\/(.+)$/.exec(bunMain);
|
|
946
|
+
if (sandboxMatch) {
|
|
947
|
+
return sandboxMatch[1];
|
|
948
|
+
}
|
|
949
|
+
const cwd = process.cwd();
|
|
950
|
+
if (bunMain.startsWith(`${cwd}/`)) {
|
|
951
|
+
return bunMain.slice(cwd.length + 1);
|
|
952
|
+
}
|
|
953
|
+
return bunMain.replace(/^.*\//, "");
|
|
954
|
+
}
|
|
955
|
+
var lastEndedTestId;
|
|
956
|
+
var lastFilePrefix;
|
|
957
|
+
var lateHits = [];
|
|
958
|
+
var lastBunMain;
|
|
959
|
+
var currentFilePrefix = "";
|
|
960
|
+
if (syncPort && !discovering) {
|
|
961
|
+
ws = await awaitRunnerReady({ syncPort, syncToken: syncToken ?? "", keepOpen: shouldCollectCoverage2 });
|
|
962
|
+
if (timings) {
|
|
963
|
+
timings["at.preloadReady"] = nowEpoch();
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
var g = globalThis;
|
|
967
|
+
var strykerGlobal = initializeStrykerNamespace(g);
|
|
968
|
+
var mutantCoverage = strykerGlobal.mutantCoverage;
|
|
969
|
+
var gapTracker = new StaticGapTracker(mutantCoverage);
|
|
970
|
+
if (activeMutant) {
|
|
971
|
+
const instrumentedBefore = watchListFile !== undefined && instrumentedCodeHasRun(strykerGlobal);
|
|
972
|
+
setActiveMutant(strykerGlobal, activeMutant);
|
|
973
|
+
const onFirstHit = watchListFile !== undefined && hitLimitToken ? setUpWitness({ file: watchListFile, token: hitLimitToken, disarmed: instrumentedBefore, cache: moduleCache() }) : undefined;
|
|
974
|
+
if (hitLimitToken && (hitLimit !== undefined || onFirstHit !== undefined)) {
|
|
975
|
+
installHitLimit(strykerGlobal, hitLimit ?? Number.POSITIVE_INFINITY, hitLimitToken, undefined, onFirstHit);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
var sensors = null;
|
|
979
|
+
var eagerFailures = [];
|
|
980
|
+
if (shouldCollectCoverage2 && plan !== null) {
|
|
981
|
+
sensors = plan.candidates === null ? null : startLoadSensors(plan.candidates, strykerGlobal, () => strykerGlobal.currentTestId ?? null);
|
|
982
|
+
const EAGER_MODULES = plan.eager;
|
|
983
|
+
for (const modPath of EAGER_MODULES) {
|
|
984
|
+
try {
|
|
985
|
+
await import(modPath);
|
|
986
|
+
} catch (err) {
|
|
987
|
+
eagerFailures.push({ file: modPath, error: describeImportError(err) });
|
|
988
|
+
console.warn(`[Stryker] Eager import failed for ${modPath}:`, err);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
sensors?.markEagerEnd();
|
|
992
|
+
if (timings) {
|
|
993
|
+
timings["at.eagerImported"] = nowEpoch();
|
|
994
|
+
timings.eagerModules = EAGER_MODULES.length;
|
|
995
|
+
}
|
|
996
|
+
} else if (timings) {
|
|
997
|
+
timings["at.eagerImported"] = nowEpoch();
|
|
998
|
+
timings.eagerModules = 0;
|
|
999
|
+
}
|
|
1000
|
+
var startedTests = 0;
|
|
1001
|
+
var writeDryRunRecord = () => {
|
|
1002
|
+
if (plan === null || plan.recordFile === null) {
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const recordFile = plan.recordFile;
|
|
1006
|
+
try {
|
|
1007
|
+
const report = sensors === null ? null : sensors.finish();
|
|
1008
|
+
if (timings && report !== null) {
|
|
1009
|
+
timings["ms.sensors"] = report.sensorMs;
|
|
1010
|
+
}
|
|
1011
|
+
const record = buildDryRunRecord(plan, { sensors: report, eagerFailures, startedTests, coverage: strykerGlobal.mutantCoverage });
|
|
1012
|
+
const merged = mergeDryRunRecords(readEarlierRecord(recordFile), record);
|
|
1013
|
+
writePrivateFileAtomically(recordFile, JSON.stringify(merged));
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
console.error(`[Stryker Coverage] Failed to write the dry-run record to ${recordFile}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
var writeCoverageData = () => {
|
|
1019
|
+
if (!shouldCollectCoverage2 || !coverageFile) {
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
const data = serializeCoverageData(strykerGlobal.mutantCoverage, lateHits, gapTracker);
|
|
1023
|
+
if (timings) {
|
|
1024
|
+
timings["at.coverageFormatted"] = nowEpoch();
|
|
1025
|
+
timings["bytes.coverage"] = data.length;
|
|
1026
|
+
}
|
|
1027
|
+
try {
|
|
1028
|
+
writeCoverageToFile(coverageFile, data);
|
|
1029
|
+
if (timings) {
|
|
1030
|
+
timings["at.coverageWritten"] = nowEpoch();
|
|
1031
|
+
}
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
console.error(`[Stryker Coverage] Failed to write coverage to ${coverageFile}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
if (shouldCollectCoverage2) {
|
|
1037
|
+
beforeEach(() => {
|
|
1038
|
+
const hookStart = timings ? performance.now() : 0;
|
|
1039
|
+
startedTests++;
|
|
1040
|
+
const bunMain = String(globalThis.Bun?.main ?? "");
|
|
1041
|
+
if (bunMain !== lastBunMain) {
|
|
1042
|
+
lastBunMain = bunMain;
|
|
1043
|
+
currentFilePrefix = extractFilePrefix(bunMain);
|
|
1044
|
+
}
|
|
1045
|
+
const filePrefix = currentFilePrefix;
|
|
1046
|
+
const bledMutantIds = gapTracker.close();
|
|
1047
|
+
if (filePrefix !== lastFilePrefix) {
|
|
1048
|
+
lastEndedTestId = undefined;
|
|
1049
|
+
} else if (lastEndedTestId !== undefined && bledMutantIds.length > 0) {
|
|
1050
|
+
lateHits.push({ testId: lastEndedTestId, mutantIds: bledMutantIds });
|
|
1051
|
+
}
|
|
1052
|
+
const prevCount = perFileCounters.get(filePrefix) ?? 0;
|
|
1053
|
+
const nextCount = prevCount + 1;
|
|
1054
|
+
perFileCounters.set(filePrefix, nextCount);
|
|
1055
|
+
const testId = `${filePrefix}@@test-${nextCount}`;
|
|
1056
|
+
strykerGlobal.currentTestId = testId;
|
|
1057
|
+
mutantCoverage.perTest[testId] ??= {};
|
|
1058
|
+
if (timings) {
|
|
1059
|
+
timings["at.firstTest"] ??= nowEpoch();
|
|
1060
|
+
timings["ms.beforeEach"] = (timings["ms.beforeEach"] ?? 0) + (performance.now() - hookStart);
|
|
1061
|
+
timings.tests = (timings.tests ?? 0) + 1;
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
afterEach(() => {
|
|
1065
|
+
const hookStart = timings ? performance.now() : 0;
|
|
1066
|
+
const endedTestId = strykerGlobal.currentTestId;
|
|
1067
|
+
lastEndedTestId = endedTestId;
|
|
1068
|
+
if (endedTestId) {
|
|
1069
|
+
const sepIdx = endedTestId.lastIndexOf("@@");
|
|
1070
|
+
lastFilePrefix = sepIdx === -1 ? endedTestId : endedTestId.slice(0, sepIdx);
|
|
1071
|
+
}
|
|
1072
|
+
gapTracker.open();
|
|
1073
|
+
strykerGlobal.currentTestId = undefined;
|
|
1074
|
+
if (timings) {
|
|
1075
|
+
timings["ms.afterEach"] = (timings["ms.afterEach"] ?? 0) + (performance.now() - hookStart);
|
|
1076
|
+
}
|
|
1077
|
+
});
|
|
1078
|
+
afterAll(async () => {
|
|
1079
|
+
if (timings) {
|
|
1080
|
+
timings["at.afterAll"] = nowEpoch();
|
|
1081
|
+
timings.afterAlls = (timings.afterAlls ?? 0) + 1;
|
|
1082
|
+
}
|
|
1083
|
+
const trailingBleed = gapTracker.close();
|
|
1084
|
+
if (lastEndedTestId !== undefined && trailingBleed.length > 0) {
|
|
1085
|
+
lateHits.push({ testId: lastEndedTestId, mutantIds: trailingBleed });
|
|
1086
|
+
}
|
|
1087
|
+
writeCoverageData();
|
|
1088
|
+
lateHits.length = 0;
|
|
1089
|
+
writeDryRunRecord();
|
|
1090
|
+
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
1091
|
+
try {
|
|
1092
|
+
await new Promise((resolve) => {
|
|
1093
|
+
const wsForDrain = ws;
|
|
1094
|
+
const timeout = setTimeout(() => {
|
|
1095
|
+
console.warn("[Stryker] Timeout waiting for drain acknowledgment");
|
|
1096
|
+
resolve();
|
|
1097
|
+
}, DRAIN_ACK_TIMEOUT_MS);
|
|
1098
|
+
wsForDrain.onmessage = (event) => {
|
|
1099
|
+
if (event.data === "drained") {
|
|
1100
|
+
clearTimeout(timeout);
|
|
1101
|
+
resolve();
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
wsForDrain.onerror = () => {
|
|
1105
|
+
clearTimeout(timeout);
|
|
1106
|
+
resolve();
|
|
1107
|
+
};
|
|
1108
|
+
try {
|
|
1109
|
+
if (timings) {
|
|
1110
|
+
timings["at.drainRequested"] = nowEpoch();
|
|
1111
|
+
}
|
|
1112
|
+
wsForDrain.send("drain-request");
|
|
1113
|
+
} catch {
|
|
1114
|
+
clearTimeout(timeout);
|
|
1115
|
+
resolve();
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
console.warn("[Stryker] Error during drain handshake:", error);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
if (timings) {
|
|
1123
|
+
timings["at.drained"] = nowEpoch();
|
|
1124
|
+
preloadFs.writeSync(2, formatPreloadTimings(timings));
|
|
1125
|
+
}
|
|
1126
|
+
ws?.close();
|
|
1127
|
+
});
|
|
1128
|
+
}
|