@hughescr/stryker-bun-runner 1.4.0 → 1.5.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.
@@ -1,16 +1,79 @@
1
1
  // @bun
2
2
  // src/coverage/preload-logic.ts
3
- import { appendFileSync } from "fs";
3
+ import { appendFileSync, closeSync, constants, createReadStream, openSync, writeSync } from "fs";
4
+ var preloadFs = { appendFileSync, closeSync, openSync, writeSync };
5
+ var HIT_LIMIT_TOKEN_ENV = "__STRYKER_HIT_LIMIT_TOKEN__";
6
+ var SYNC_TOKEN_ENV = "__STRYKER_SYNC_TOKEN__";
4
7
  function getPreloadConfig() {
5
8
  return {
6
9
  syncPort: process.env.__STRYKER_SYNC_PORT__,
10
+ syncToken: process.env[SYNC_TOKEN_ENV],
7
11
  coverageFile: process.env.__STRYKER_COVERAGE_FILE__,
8
- activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__
12
+ activeMutant: process.env.__STRYKER_ACTIVE_MUTANT__,
13
+ hitLimit: parseHitLimit(process.env.__STRYKER_HIT_LIMIT__),
14
+ hitLimitToken: process.env[HIT_LIMIT_TOKEN_ENV]
9
15
  };
10
16
  }
17
+ function parseHitLimit(raw) {
18
+ const limit = Number(raw);
19
+ return Number.isInteger(limit) && limit > 0 ? limit : undefined;
20
+ }
11
21
  function shouldCollectCoverage(config) {
12
22
  return !config.activeMutant && !!config.coverageFile;
13
23
  }
24
+ function waitForSyncReady(socket) {
25
+ return new Promise((resolve) => {
26
+ socket.addEventListener("message", (event) => {
27
+ if (event.data === "ready") {
28
+ resolve({ ready: true });
29
+ }
30
+ });
31
+ socket.addEventListener("error", () => {
32
+ resolve({ ready: false, problem: "failed with a connection error" });
33
+ });
34
+ socket.addEventListener("close", (event) => {
35
+ const reason = event.reason ? `, reason "${event.reason}"` : "";
36
+ resolve({ ready: false, problem: `closed (code ${event.code ?? "unknown"}${reason})` });
37
+ });
38
+ });
39
+ }
40
+ function syncAddress(syncPort) {
41
+ return `ws://127.0.0.1:${syncPort}/sync`;
42
+ }
43
+ async function awaitRunnerReady(deps) {
44
+ const openSocket = deps.openSocket ?? ((url) => new WebSocket(url));
45
+ const fail = deps.fail ?? ((message) => {
46
+ console.error(message);
47
+ process.exit(1);
48
+ });
49
+ let socket;
50
+ let outcome;
51
+ try {
52
+ socket = openSocket(`${syncAddress(deps.syncPort)}/${deps.syncToken}`);
53
+ outcome = await waitForSyncReady(socket);
54
+ } catch (error) {
55
+ const reason = redactToken(error instanceof Error ? error.message : String(error), deps.syncToken);
56
+ return fail(formatSyncNotReadyMessage(deps.syncPort, `could not be opened (${reason})`));
57
+ }
58
+ if (!outcome.ready) {
59
+ return fail(formatSyncNotReadyMessage(deps.syncPort, outcome.problem));
60
+ }
61
+ if (deps.keepOpen) {
62
+ return socket;
63
+ }
64
+ socket.close();
65
+ return null;
66
+ }
67
+ function redactToken(text, token) {
68
+ return token === "" ? text : text.replaceAll(token, "[redacted]");
69
+ }
70
+ function formatSyncNotReadyMessage(syncPort, problem) {
71
+ return [
72
+ `[Stryker] stryker-bun-runner: the dry run's sync connection to the runner (${syncAddress(syncPort)}) ${problem}`,
73
+ "before the runner signalled that it is ready to observe the tests. Exiting without running any test: tests run now",
74
+ "would not be seen by the runner's inspector, so their results and per-test coverage would be lost."
75
+ ].join(" ");
76
+ }
14
77
  function initializeStrykerNamespace(globalObj) {
15
78
  const g = globalObj;
16
79
  g.__stryker__ ??= { mutantCoverage: { static: {}, perTest: {} } };
@@ -22,6 +85,31 @@ function initializeStrykerNamespace(globalObj) {
22
85
  function setActiveMutant(strykerNamespace, activeMutant) {
23
86
  strykerNamespace.activeMutant = activeMutant;
24
87
  }
88
+ var HIT_LIMIT_SENTINEL = "__STRYKER_HIT_LIMIT_REACHED__";
89
+ function formatHitLimitSentinel(token, hitCount) {
90
+ return `
91
+ ${HIT_LIMIT_SENTINEL} ${token} ${hitCount}
92
+ `;
93
+ }
94
+ function installHitLimit(strykerNamespace, hitLimit, token, report = (line) => {
95
+ preloadFs.writeSync(2, line);
96
+ }) {
97
+ let hitCount = 0;
98
+ let reported = false;
99
+ strykerNamespace.hitLimit = hitLimit;
100
+ Object.defineProperty(strykerNamespace, "hitCount", {
101
+ configurable: true,
102
+ enumerable: true,
103
+ get: () => hitCount,
104
+ set: (value) => {
105
+ hitCount = value;
106
+ if (!reported && hitCount > hitLimit) {
107
+ reported = true;
108
+ report(formatHitLimitSentinel(token, hitCount));
109
+ }
110
+ }
111
+ });
112
+ }
25
113
  function detectGapWindowBleed(staticCountsAtLastBoundary, staticCoverageNow) {
26
114
  if (!staticCoverageNow) {
27
115
  return [];
@@ -37,26 +125,74 @@ function detectGapWindowBleed(staticCountsAtLastBoundary, staticCoverageNow) {
37
125
  }
38
126
  function formatCoverageData(mutantCoverage, counterToName, lateHits = []) {
39
127
  if (!mutantCoverage) {
40
- return { perTest: {}, static: [] };
128
+ return { perTest: {}, static: {} };
41
129
  }
42
130
  const perTest = {};
43
131
  for (const [testId, coverage] of Object.entries(mutantCoverage.perTest ?? {})) {
44
132
  const actualName = counterToName.get(testId) ?? testId;
45
- perTest[actualName] = Object.keys(coverage);
133
+ perTest[actualName] = { ...coverage };
46
134
  }
47
- const staticCoverage = Object.keys(mutantCoverage.static ?? {});
135
+ const staticCoverage = { ...mutantCoverage.static };
48
136
  return {
49
137
  perTest,
50
138
  static: staticCoverage,
51
139
  ...lateHits.length > 0 ? { lateHits: [...lateHits] } : {}
52
140
  };
53
141
  }
142
+ var COVERAGE_APPEND_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW;
54
143
  function writeCoverageToFile(coverageFile, data) {
55
- appendFileSync(coverageFile, `${JSON.stringify(data)}
144
+ const fd = preloadFs.openSync(coverageFile, COVERAGE_APPEND_FLAGS, 384);
145
+ try {
146
+ preloadFs.appendFileSync(fd, `${JSON.stringify(data)}
56
147
  `, "utf8");
148
+ } finally {
149
+ preloadFs.closeSync(fd);
150
+ }
151
+ }
152
+ var LIFELINE_FD_ENV = "__STRYKER_LIFELINE_FD__";
153
+ function describeError(error) {
154
+ const { code, message } = error;
155
+ return String(code ?? message);
156
+ }
157
+ function parseLifelineFd(value) {
158
+ if (value === undefined || !/^\d+$/.test(value)) {
159
+ return;
160
+ }
161
+ const fd = Number(value);
162
+ return Number.isSafeInteger(fd) && fd > 2 ? fd : undefined;
163
+ }
164
+ function watchParentLifeline(deps) {
165
+ let settled = false;
166
+ const unavailable = (reason) => {
167
+ if (!settled) {
168
+ settled = true;
169
+ deps.onUnavailable(reason);
170
+ }
171
+ };
172
+ const fd = parseLifelineFd(deps.fdValue);
173
+ if (fd === undefined) {
174
+ unavailable(`${LIFELINE_FD_ENV}=${deps.fdValue ?? "(unset)"} names no lifeline descriptor`);
175
+ return;
176
+ }
177
+ const open = deps.open ?? ((lifelineFd) => createReadStream("", { fd: lifelineFd }));
178
+ let lifeline;
179
+ try {
180
+ lifeline = open(fd);
181
+ } catch (error) {
182
+ unavailable(`opening fd ${fd} failed: ${describeError(error)}`);
183
+ return;
184
+ }
185
+ lifeline.once("end", () => {
186
+ settled = true;
187
+ deps.onOrphaned();
188
+ });
189
+ lifeline.on("error", (error) => {
190
+ unavailable(`reading fd ${fd} failed: ${describeError(error)}`);
191
+ });
192
+ lifeline.resume();
57
193
  }
58
194
  function startOrphanWatchdog(deps) {
59
- const originalPpid = deps.getPpid();
195
+ const originalPpid = deps.originalPpid ?? deps.getPpid();
60
196
  let fired = false;
61
197
  const intervalId = setInterval(() => {
62
198
  if (fired || deps.getPpid() === originalPpid) {
@@ -70,13 +206,50 @@ function startOrphanWatchdog(deps) {
70
206
  clearInterval(intervalId);
71
207
  };
72
208
  }
209
+ function guardAgainstOrphaning(deps) {
210
+ const originalPpid = deps.getPpid();
211
+ watchParentLifeline({
212
+ fdValue: deps.fdValue,
213
+ onOrphaned: deps.onOrphaned,
214
+ open: deps.open,
215
+ onUnavailable: (reason) => {
216
+ deps.log?.(`[Stryker] parent lifeline unavailable (${reason}); polling the parent PID on a timer instead`);
217
+ startOrphanWatchdog({ getPpid: deps.getPpid, onOrphaned: deps.onOrphaned, intervalMs: deps.intervalMs, originalPpid });
218
+ }
219
+ });
220
+ }
221
+ var ORPHAN_DEBUG_ENV = "STRYKER_BUN_RUNNER_DEBUG";
222
+ function orphanDebugLog(value, write) {
223
+ if (value === undefined || value === "" || value === "0" || value === "false") {
224
+ return;
225
+ }
226
+ return (message) => {
227
+ write(`${message}
228
+ `);
229
+ };
230
+ }
73
231
  export {
232
+ HIT_LIMIT_SENTINEL,
233
+ HIT_LIMIT_TOKEN_ENV,
234
+ LIFELINE_FD_ENV,
235
+ ORPHAN_DEBUG_ENV,
236
+ SYNC_TOKEN_ENV,
237
+ awaitRunnerReady,
74
238
  detectGapWindowBleed,
75
239
  formatCoverageData,
240
+ formatHitLimitSentinel,
241
+ formatSyncNotReadyMessage,
76
242
  getPreloadConfig,
243
+ guardAgainstOrphaning,
77
244
  initializeStrykerNamespace,
245
+ installHitLimit,
246
+ orphanDebugLog,
247
+ parseHitLimit,
248
+ preloadFs,
78
249
  setActiveMutant,
79
250
  shouldCollectCoverage,
80
251
  startOrphanWatchdog,
252
+ waitForSyncReady,
253
+ watchParentLifeline,
81
254
  writeCoverageToFile
82
255
  };