@provino/dialect-jest 0.0.0-stage → 0.1.0-rc.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.
@@ -0,0 +1,844 @@
1
+ import { i as hideProvinoFrames, n as formatRetryError, r as formatTestFailures, t as formatFileError } from "../failure-message.js";
2
+ import { join } from "node:path";
3
+
4
+ // src/results/helpers.ts
5
+ /**
6
+ * An empty run (`makeEmptyAggregatedTestResult`, helpers.ts L16-L47).
7
+ * @public
8
+ */
9
+ function makeEmptyAggregatedTestResult() {
10
+ return {
11
+ numFailedTestSuites: 0,
12
+ numFailedTests: 0,
13
+ numPassedTestSuites: 0,
14
+ numPassedTests: 0,
15
+ numPendingTestSuites: 0,
16
+ numPendingTests: 0,
17
+ numRuntimeErrorTestSuites: 0,
18
+ numTodoTests: 0,
19
+ numTotalTestSuites: 0,
20
+ numTotalTests: 0,
21
+ openHandles: [],
22
+ snapshot: {
23
+ added: 0,
24
+ didUpdate: false,
25
+ failure: false,
26
+ filesAdded: 0,
27
+ filesRemoved: 0,
28
+ filesRemovedList: [],
29
+ filesUnmatched: 0,
30
+ filesUpdated: 0,
31
+ matched: 0,
32
+ total: 0,
33
+ unchecked: 0,
34
+ uncheckedKeysByFile: [],
35
+ unmatched: 0,
36
+ updated: 0
37
+ },
38
+ startTime: 0,
39
+ success: true,
40
+ testResults: [],
41
+ wasInterrupted: false
42
+ };
43
+ }
44
+ /** The zeroed `perfStats` and `snapshot` of an empty file result (helpers.ts L93-L115). */
45
+ function emptyParts() {
46
+ return {
47
+ perfStats: {
48
+ end: 0,
49
+ loadTestEnvironmentEnd: 0,
50
+ loadTestEnvironmentStart: 0,
51
+ runtime: 0,
52
+ setupAfterEnvEnd: 0,
53
+ setupAfterEnvStart: 0,
54
+ setupFilesEnd: 0,
55
+ setupFilesStart: 0,
56
+ slow: false,
57
+ start: 0
58
+ },
59
+ snapshot: {
60
+ added: 0,
61
+ fileDeleted: false,
62
+ matched: 0,
63
+ unchecked: 0,
64
+ uncheckedKeys: [],
65
+ unmatched: 0,
66
+ updated: 0
67
+ }
68
+ };
69
+ }
70
+ /**
71
+ * A file's empty result (`createEmptyTestResult`, helpers.ts L89-L117).
72
+ * @public
73
+ */
74
+ function createEmptyTestResult() {
75
+ return {
76
+ leaks: false,
77
+ numFailingTests: 0,
78
+ numPassingTests: 0,
79
+ numPendingTests: 0,
80
+ numTodoTests: 0,
81
+ openHandles: [],
82
+ ...emptyParts(),
83
+ skipped: false,
84
+ testFilePath: "",
85
+ testResults: []
86
+ };
87
+ }
88
+ /**
89
+ * The result of a file that failed to run (`buildFailureTestResult`, helpers.ts L49-L77).
90
+ * @public
91
+ */
92
+ function buildFailureTestResult(testPath, err) {
93
+ return {
94
+ console: void 0,
95
+ displayName: void 0,
96
+ failureMessage: null,
97
+ leaks: false,
98
+ numFailingTests: 0,
99
+ numPassingTests: 0,
100
+ numPendingTests: 0,
101
+ numTodoTests: 0,
102
+ openHandles: [],
103
+ ...emptyParts(),
104
+ skipped: false,
105
+ testExecError: err,
106
+ testFilePath: testPath,
107
+ testResults: []
108
+ };
109
+ }
110
+ /**
111
+ * Adds a file's result to the run's (`addResult`, helpers.ts L79-L151). Mutates `aggregated` and
112
+ * sets `testResult.numTodoTests` to 0 when it is missing, as Jest does.
113
+ * @public
114
+ */
115
+ function addResult(aggregated, testResult) {
116
+ if (!testResult.numTodoTests) testResult.numTodoTests = 0;
117
+ aggregated.testResults.push(testResult);
118
+ aggregated.numTotalTests += testResult.numPassingTests + testResult.numFailingTests + testResult.numPendingTests + testResult.numTodoTests;
119
+ aggregated.numFailedTests += testResult.numFailingTests;
120
+ aggregated.numPassedTests += testResult.numPassingTests;
121
+ aggregated.numPendingTests += testResult.numPendingTests;
122
+ aggregated.numTodoTests += testResult.numTodoTests;
123
+ if (testResult.testExecError) aggregated.numRuntimeErrorTestSuites++;
124
+ if (testResult.skipped) aggregated.numPendingTestSuites++;
125
+ else if (testResult.numFailingTests > 0 || testResult.testExecError) aggregated.numFailedTestSuites++;
126
+ else aggregated.numPassedTestSuites++;
127
+ const { snapshot } = testResult;
128
+ if (snapshot.added) aggregated.snapshot.filesAdded++;
129
+ if (snapshot.fileDeleted) aggregated.snapshot.filesRemoved++;
130
+ if (snapshot.unmatched) aggregated.snapshot.filesUnmatched++;
131
+ if (snapshot.updated) aggregated.snapshot.filesUpdated++;
132
+ aggregated.snapshot.added += snapshot.added;
133
+ aggregated.snapshot.matched += snapshot.matched;
134
+ aggregated.snapshot.unchecked += snapshot.unchecked;
135
+ if (snapshot.uncheckedKeys?.length > 0) aggregated.snapshot.uncheckedKeysByFile.push({
136
+ filePath: testResult.testFilePath,
137
+ keys: snapshot.uncheckedKeys
138
+ });
139
+ aggregated.snapshot.unmatched += snapshot.unmatched;
140
+ aggregated.snapshot.updated += snapshot.updated;
141
+ aggregated.snapshot.total += snapshot.added + snapshot.matched + snapshot.unmatched + snapshot.updated;
142
+ }
143
+ /**
144
+ * A file's result built from its tests' results, with the counts by status
145
+ * (`makeCollectedTestResult`, helpers.ts L153-L185, used by `--collectTests`).
146
+ * @public
147
+ */
148
+ function makeCollectedTestResult(testResults, options) {
149
+ const count = (status) => testResults.filter((result) => result.status === status).length;
150
+ const numFailingTests = count("failed");
151
+ const numPassingTests = count("passed");
152
+ const numTodoTests = count("todo");
153
+ return {
154
+ ...createEmptyTestResult(),
155
+ displayName: options.displayName,
156
+ numFailingTests,
157
+ numPassingTests,
158
+ numPendingTests: testResults.length - numFailingTests - numPassingTests - numTodoTests,
159
+ numTodoTests,
160
+ testFilePath: options.testFilePath,
161
+ testResults
162
+ };
163
+ }
164
+
165
+ // src/results/build.ts
166
+ /**
167
+ * `flattenErrorStack` (jest-message-util 30.5.2, index.ts L504-L551) over a serialized error: the
168
+ * stack (or the message when it has none, or is missing the message), then each `cause` and each
169
+ * of an aggregate's `errors` as `\n\n[cause]: …` and `\n\n[errors]: …`.
170
+ * @public
171
+ */
172
+ function flattenSerializedError(error) {
173
+ return flatten(error, /* @__PURE__ */ new Set());
174
+ }
175
+ function flatten(error, seen) {
176
+ const { message, stack } = error;
177
+ let flattened;
178
+ if (typeof stack === "string" && stack !== "") flattened = message && !stack.includes(message) ? message + stack.replace(/^Error:?\s*\n/, "\n") : stack;
179
+ else flattened = message;
180
+ seen.add(error);
181
+ if (error.cause !== void 0) flattened += `\n\n[cause]: ${seen.has(error.cause) ? "[Circular cause]" : flatten(error.cause, seen)}`;
182
+ for (const nested of error.errors ?? []) flattened += `\n\n[errors]: ${seen.has(nested) ? "[Circular errors]" : flatten(nested, seen)}`;
183
+ seen.delete(error);
184
+ return flattened;
185
+ }
186
+ /** The status Jest reports for a test that ended in `state` (utils.ts L507-L516). */
187
+ function statusOf(state) {
188
+ switch (state) {
189
+ case "skip": return "pending";
190
+ case "todo": return "todo";
191
+ case "fail":
192
+ case "running": return "failed";
193
+ case "pass":
194
+ case "queued": return "passed";
195
+ default: return state;
196
+ }
197
+ }
198
+ /**
199
+ * One test's result. A test that never ended is `failed` with no message (its file's error says
200
+ * why). Jest counts a skipped test's invocations as 1 (`cli/json-vscode-contract`), so does this.
201
+ * @public
202
+ */
203
+ function toAssertionResult(record, options) {
204
+ const { task, result } = record;
205
+ const status = result === void 0 ? "failed" : statusOf(result.state);
206
+ const errors = result?.errors ?? [];
207
+ const { location } = task;
208
+ const title = task.fullName.at(-1) ?? task.name;
209
+ const ran = status === "passed" || status === "failed";
210
+ if (options.collectOnly === true) return {
211
+ ancestorTitles: task.fullName.slice(0, -1),
212
+ duration: null,
213
+ failing: task.expectFail,
214
+ failureDetails: [],
215
+ failureMessages: [],
216
+ fullName: task.fullName.join(" "),
217
+ invocations: 0,
218
+ location: null,
219
+ numPassingAsserts: 0,
220
+ retryReasons: [],
221
+ startAt: null,
222
+ status,
223
+ title,
224
+ ...result?.state === "queued" ? { wouldRun: true } : {}
225
+ };
226
+ return {
227
+ ancestorTitles: task.fullName.slice(0, -1),
228
+ duration: ran && result !== void 0 ? Math.round(result.durationMs) : null,
229
+ failing: task.expectFail,
230
+ failureDetails: errors.map(failureDetailOf),
231
+ failureMessages: errors.map(flattenSerializedError),
232
+ fullName: task.fullName.join(" "),
233
+ invocations: Math.max(1, result?.attempts ?? 0),
234
+ location: options.locations && location !== null ? {
235
+ column: location.column,
236
+ line: location.line
237
+ } : null,
238
+ numPassingAsserts: result?.passingAssertions ?? 0,
239
+ retryMessages: [],
240
+ retryReasons: (result?.retryErrors ?? []).map(flattenSerializedError),
241
+ startAt: record.startedAt,
242
+ status,
243
+ title
244
+ };
245
+ }
246
+ /**
247
+ * The tests of a tree in declaration order (depth first), each with what the events said of it.
248
+ * The assertions of `toTestResult` are in this order. A suite a randomized run shuffled lists its
249
+ * children as it ran them (`orders`, by suite id; the file's under its own id), as jest-circus's
250
+ * results walk the block's shuffled `children`.
251
+ * @public
252
+ */
253
+ function testsInOrder(tree, records, orders = /* @__PURE__ */ new Map()) {
254
+ const byId = new Map(tree.map((node) => [node.id, node]));
255
+ const out = [];
256
+ const visit = (node) => {
257
+ if (node === void 0) return;
258
+ if (node.type === "test") {
259
+ const record = records.get(node.id);
260
+ out.push(record ?? {
261
+ task: node,
262
+ result: void 0,
263
+ startedAt: null
264
+ });
265
+ return;
266
+ }
267
+ for (const child of orders.get(node.id) ?? node.children) visit(byId.get(child));
268
+ };
269
+ for (const node of tree) if (node.type === "file") visit(node);
270
+ return out;
271
+ }
272
+ /** The shuffled child orders of a file: its suites' and its own. */
273
+ function ordersOf(file) {
274
+ const root = file.tree?.find((node) => node.type === "file");
275
+ if (root === void 0 || file.result.childOrder === void 0) return file.orders ?? /* @__PURE__ */ new Map();
276
+ return new Map([...file.orders ?? [], [root.id, file.result.childOrder]]);
277
+ }
278
+ /** The file's own errors as Jest's `SerializableError`. */
279
+ function execErrorOf(errors) {
280
+ const [first] = errors;
281
+ if (first === void 0) return void 0;
282
+ return {
283
+ message: first.message,
284
+ stack: first.stack ?? null,
285
+ ...first.code === void 0 ? {} : { code: first.code }
286
+ };
287
+ }
288
+ /**
289
+ * What an empty file is reported as: Jest fails a file with no test (TestScheduler.ts L176-L184).
290
+ * @public
291
+ */
292
+ const NO_TESTS_MESSAGE = "Your test suite must contain at least one test.";
293
+ /**
294
+ * The stack of `new Error(NO_TESTS_MESSAGE)` as Jest has it (TestScheduler.ts L144-L150): one
295
+ * frame, in Jest's own package under `node_modules`, so no code frame is printed for it. A real
296
+ * stack would point into this package, which prints one wherever it is not installed.
297
+ */
298
+ function noTestsStack() {
299
+ return `Error: ${NO_TESTS_MESSAGE}\n at TestScheduler.onResult (node_modules/@jest/core/build/index.js:1:1)`;
300
+ }
301
+ /**
302
+ * What a file that leaks is failed with under `--detectLeaks` (TestScheduler.ts L153-L169): the
303
+ * message `onResult` builds, plain (Jest paints `EXPERIMENTAL FEATURE!` bold red, which a
304
+ * reporter's style can't reach from here), with one frame in Jest's own package, as for
305
+ * `NO_TESTS_MESSAGE`.
306
+ * @public
307
+ */
308
+ const LEAK_MESSAGE = "EXPERIMENTAL FEATURE!\nYour test suite is leaking memory. Please ensure all references are cleaned.\n\nThere is a number of things that can leak memory:\n - Async operations that have not finished (e.g. fs.readFile).\n - Timers not properly mocked (e.g. setInterval, setTimeout).\n - Keeping references to the global scope.";
309
+ function noTestsResult(testFilePath) {
310
+ return buildFailureTestResult(testFilePath, {
311
+ message: NO_TESTS_MESSAGE,
312
+ stack: noTestsStack()
313
+ });
314
+ }
315
+ /**
316
+ * A file whose results the worker took with it, or a runner that failed it whole: Jest's runner
317
+ * fails the whole file (`TestScheduler.ts` `onFailure`, L185-L200), so even tests that ended before
318
+ * a crash leave no counts and no assertion.
319
+ */
320
+ function discardedResult(file) {
321
+ const error = execErrorOf([...file.result.errors, ...file.unhandled]) ?? {
322
+ message: `the worker running the file exited (${JSON.stringify(file.result.workerExit)})`,
323
+ stack: null
324
+ };
325
+ return buildFailureTestResult(file.testFilePath, error);
326
+ }
327
+ /**
328
+ * What `runTest.ts` L313-L337 sets on every file's result, a collected one too: `perfStats`,
329
+ * `skipped` and `displayName`.
330
+ */
331
+ function withPerfStats(result, file, options) {
332
+ const runtime = file.endedAt - file.startedAt;
333
+ const testCount = result.numPassingTests + result.numFailingTests + result.numPendingTests + result.numTodoTests;
334
+ return {
335
+ ...result,
336
+ displayName: options.displayName,
337
+ perfStats: {
338
+ ...result.perfStats,
339
+ end: file.endedAt,
340
+ runtime,
341
+ slow: runtime / 1e3 > (options.slowTestThreshold ?? 5),
342
+ start: file.startedAt
343
+ },
344
+ skipped: testCount === result.numPendingTests
345
+ };
346
+ }
347
+ /**
348
+ * One file's `TestResult`, with `failureMessage` left `null` (the text comes from
349
+ * `jest-message-util`, asynchronously: `collect.ts` fills it).
350
+ *
351
+ * - A file that loaded and has no test result fails with `Your test suite must contain at least one
352
+ * test.`, whatever errors or leaks it holds (`onResult`, which tests only the results' length),
353
+ * unless the worker's runner failed it after it ran (`runnerFailed`): `runTest` rejected then.
354
+ * - A file that ended with errors and no test that ran, or never loaded, is a runtime error:
355
+ * `testExecError` is its first error.
356
+ * - A file with errors beside tests that ran has `testExecError` `{ message: '', stack }` with the
357
+ * errors joined by newlines, as Jest does for `unhandledErrors` (jestAdapterInit.ts L314-L319).
358
+ * @public
359
+ */
360
+ function toTestResult(file, options) {
361
+ if (file.result.workerExit !== void 0) return discardedResult(file);
362
+ const tests = file.tree === void 0 ? [] : testsInOrder(file.tree, file.records, ordersOf(file));
363
+ const assertionResults = tests.map((record) => toAssertionResult(record, options));
364
+ const count = (status) => assertionResults.filter((result) => result.status === status).length;
365
+ if (assertionResults.length === 0 && file.tree !== void 0 && file.loadFailed !== true && file.runnerFailed !== true) return noTestsResult(file.testFilePath);
366
+ if (file.result.leaks === true) return buildFailureTestResult(file.testFilePath, {
367
+ message: LEAK_MESSAGE,
368
+ stack: `Error: ${LEAK_MESSAGE}\n at TestScheduler.onResult (node_modules/@jest/core/build/index.js:1:1)`
369
+ });
370
+ if (file.result.resultsDiscarded === true) return discardedResult(file);
371
+ const numFailingTests = count("failed");
372
+ const numPassingTests = count("passed");
373
+ const numPendingTests = count("pending");
374
+ const numTodoTests = count("todo");
375
+ const fileErrors = [...file.result.errors, ...file.unhandled];
376
+ const collected = file.tree?.some((node) => node.type !== "file") === true;
377
+ if (options.collectOnly === true && collected) return withPerfStats(makeCollectedTestResult(assertionResults, {
378
+ displayName: options.displayName,
379
+ testFilePath: file.testFilePath
380
+ }), file, options);
381
+ const ran = tests.some((record) => record.result !== void 0);
382
+ let testExecError;
383
+ if (!ran) testExecError = execErrorOf(fileErrors);
384
+ else if (fileErrors.length > 0) testExecError = {
385
+ message: "",
386
+ stack: fileErrors.map(flattenSerializedError).join("\n")
387
+ };
388
+ const failed = testExecError !== void 0 && !ran;
389
+ const results = failed ? [] : assertionResults;
390
+ const runtime = file.endedAt - file.startedAt;
391
+ const { snapshot } = file.result;
392
+ const testCount = numPassingTests + numFailingTests + numPendingTests + numTodoTests;
393
+ return {
394
+ ...createEmptyTestResult(),
395
+ console: void 0,
396
+ displayName: options.displayName,
397
+ failureMessage: null,
398
+ numFailingTests,
399
+ numPassingTests,
400
+ numPendingTests,
401
+ numTodoTests,
402
+ perfStats: {
403
+ end: file.endedAt,
404
+ loadTestEnvironmentEnd: 0,
405
+ loadTestEnvironmentStart: 0,
406
+ runtime,
407
+ setupAfterEnvEnd: 0,
408
+ setupAfterEnvStart: 0,
409
+ setupFilesEnd: 0,
410
+ setupFilesStart: 0,
411
+ slow: runtime / 1e3 > (options.slowTestThreshold ?? 5),
412
+ start: file.startedAt
413
+ },
414
+ skipped: !failed && testCount === numPendingTests,
415
+ ...file.result.heapUsedBytes === void 0 ? {} : { memoryUsage: file.result.heapUsedBytes },
416
+ snapshot: snapshot === void 0 ? createEmptyTestResult().snapshot : {
417
+ added: snapshot.added,
418
+ fileDeleted: snapshot.fileDeleted,
419
+ matched: snapshot.matched,
420
+ unchecked: snapshot.unchecked,
421
+ uncheckedKeys: [...snapshot.uncheckedKeys],
422
+ unmatched: snapshot.unmatched,
423
+ updated: snapshot.updated
424
+ },
425
+ ...testExecError === void 0 ? {} : { testExecError },
426
+ testFilePath: file.testFilePath,
427
+ testResults: results
428
+ };
429
+ }
430
+ /**
431
+ * The aggregate's closing fields (TestScheduler.ts L87-L95 and L198-L212): `didUpdate`, snapshot
432
+ * `failure`, `wasInterrupted` and `success`. Mutates `aggregated`.
433
+ * @public
434
+ */
435
+ function finishAggregated(aggregated, end) {
436
+ const updateAll = end.snapshots?.update === "all";
437
+ const { snapshot } = aggregated;
438
+ const removed = end.snapshots?.filesRemovedList ?? [];
439
+ snapshot.filesRemoved += removed.length;
440
+ snapshot.filesRemovedList = [...snapshot.filesRemovedList, ...removed];
441
+ snapshot.didUpdate = updateAll;
442
+ snapshot.failure = !!(!updateAll && (snapshot.unchecked || snapshot.unmatched || snapshot.filesRemoved));
443
+ aggregated.wasInterrupted = end.reason === "interrupted" || end.reason === "terminated" || end.reason === "hangup";
444
+ aggregated.success = !(!(aggregated.numFailedTests === 0 && aggregated.numRuntimeErrorTestSuites === 0) || snapshot.failure || end.reporterFailed || end.unownedError === true);
445
+ }
446
+ /**
447
+ * What a reporter finds in `failureDetails[i]`: Jest hands it the error itself, so a hook reads
448
+ * `detail.message` (jest-junit's `noStackTrace` does). `--json` writes only the own enumerable keys
449
+ * (`details`, the JSON of the thrown value: only an assertion error keeps `matcherResult`), since
450
+ * an `Error`'s `message`, `stack` and `name` don't enumerate; here they are set the same way, on a
451
+ * plain object.
452
+ */
453
+ function failureDetailOf(error) {
454
+ const details = error.details ?? {};
455
+ if (typeof details !== "object" || details === null || Array.isArray(details)) return details;
456
+ const detail = { ...details };
457
+ const field = (key, value) => {
458
+ const enumerable = error.enumerableFields?.includes(key) === true && (error.details === void 0 || Object.hasOwn(detail, key));
459
+ const kept = enumerable && Object.hasOwn(detail, key) ? detail[key] : value;
460
+ Object.defineProperty(detail, key, {
461
+ writable: true,
462
+ configurable: true,
463
+ enumerable,
464
+ value: key !== "name" && typeof kept === "string" ? hideProvinoFrames(kept) : kept
465
+ });
466
+ };
467
+ field("name", error.name);
468
+ field("message", error.message);
469
+ if (error.stack !== void 0) field("stack", error.stack);
470
+ return detail;
471
+ }
472
+
473
+ // src/results/collect.ts
474
+ /**
475
+ * Builds the collector. `file:end` formats the file's failure text with `jest-message-util`, so the
476
+ * handler is async and the bus waits for it.
477
+ * @public
478
+ */
479
+ function createJestResults(options) {
480
+ const now = options.now ?? Date.now;
481
+ const { globalConfig, projectConfigs } = options;
482
+ let aggregated = makeEmptyAggregatedTestResult();
483
+ /** How the run ended, kept for `reportersFailed`. */
484
+ let ended;
485
+ /** Whether an unhandled error no file owns reached the run (`RunEnd.unownedError`). */
486
+ let unownedError = false;
487
+ aggregated.success = false;
488
+ const files = /* @__PURE__ */ new Map();
489
+ const results = /* @__PURE__ */ new Map();
490
+ const failureBlocks = /* @__PURE__ */ new Map();
491
+ const contexts = /* @__PURE__ */ new Map();
492
+ const configOf = (info) => {
493
+ const config = projectConfigs[info.projectIndex ?? 0] ?? projectConfigs[0];
494
+ if (config === void 0) throw new Error("createJestResults needs a project config");
495
+ return config;
496
+ };
497
+ const contextOf = (config) => {
498
+ let context = contexts.get(config);
499
+ if (context === void 0) {
500
+ context = { config };
501
+ contexts.set(config, context);
502
+ }
503
+ return context;
504
+ };
505
+ const pathOf = (info) => join(configOf(info).rootDir, info.path);
506
+ const newFile = (info) => ({
507
+ info,
508
+ startedAt: now(),
509
+ tree: void 0,
510
+ nodes: /* @__PURE__ */ new Map(),
511
+ loadFailed: false,
512
+ runnerFailed: false,
513
+ records: /* @__PURE__ */ new Map(),
514
+ orders: /* @__PURE__ */ new Map(),
515
+ unhandled: [],
516
+ late: /* @__PURE__ */ new Map(),
517
+ console: []
518
+ });
519
+ const stateOf = (info) => {
520
+ let file = files.get(info.fileId);
521
+ if (file === void 0) {
522
+ file = newFile(info);
523
+ files.set(info.fileId, file);
524
+ }
525
+ return file;
526
+ };
527
+ const record = (file, id) => {
528
+ const known = file.records.get(id);
529
+ if (known !== void 0) return known;
530
+ const node = file.nodes.get(id);
531
+ if (node?.type !== "test") return void 0;
532
+ const fresh = {
533
+ task: node,
534
+ result: void 0,
535
+ startedAt: null
536
+ };
537
+ file.records.set(id, fresh);
538
+ return fresh;
539
+ };
540
+ /**
541
+ * Puts the errors charged to each test after it ended on its result: the test fails (jest-circus
542
+ * reads `test.errors` when the run ends, so an error pushed after `test_done` still fails it). A
543
+ * test with no result keeps them as the file's. `late` holds only the file's tests, so each has a
544
+ * record.
545
+ */
546
+ const chargeLate = (file) => {
547
+ for (const [id, errors] of file.late) {
548
+ const known = record(file, id);
549
+ if (known?.result === void 0) {
550
+ file.unhandled.push(...errors);
551
+ continue;
552
+ }
553
+ const { result } = known;
554
+ file.records.set(id, {
555
+ ...known,
556
+ result: {
557
+ ...result,
558
+ state: result.state === "pass" ? "fail" : result.state,
559
+ errors: [...result.errors, ...errors]
560
+ }
561
+ });
562
+ }
563
+ };
564
+ return {
565
+ reporter: {
566
+ name: "jest-results",
567
+ "run:start": (_info, all) => {
568
+ aggregated = makeEmptyAggregatedTestResult();
569
+ aggregated.success = false;
570
+ ended = void 0;
571
+ unownedError = false;
572
+ aggregated.numTotalTestSuites = all.length;
573
+ aggregated.startTime = now();
574
+ files.clear();
575
+ results.clear();
576
+ failureBlocks.clear();
577
+ contexts.clear();
578
+ },
579
+ "file:start": (info) => {
580
+ files.set(info.fileId, newFile(info));
581
+ },
582
+ console: (info, event) => {
583
+ if (globalConfig.silent === true || globalConfig.verbose === true) return;
584
+ if (event.level === null) return;
585
+ stateOf(info).console.push({
586
+ message: event.text.replace(/\n$/, ""),
587
+ origin: event.origin ?? "",
588
+ type: event.level
589
+ });
590
+ },
591
+ "file:collected": (info, event) => {
592
+ const file = stateOf(info);
593
+ file.tree = event.tasks;
594
+ file.nodes = new Map(event.tasks.map((task) => [task.id, task]));
595
+ file.loadFailed = event.loadFailed === true;
596
+ },
597
+ "task:start": (task) => {
598
+ if (task.type !== "test") return;
599
+ const file = files.get(task.fileId);
600
+ if (file === void 0) return;
601
+ const known = record(file, task.id);
602
+ if (known !== void 0) file.records.set(task.id, {
603
+ ...known,
604
+ startedAt: now()
605
+ });
606
+ },
607
+ "task:end": (task, event) => {
608
+ if (event.type === "suite-end") {
609
+ const order = event.result.childOrder;
610
+ if (order !== void 0) files.get(task.fileId)?.orders.set(task.id, order);
611
+ return;
612
+ }
613
+ if (task.type !== "test" || event.type !== "test-end") return;
614
+ const file = files.get(task.fileId);
615
+ const known = file === void 0 ? void 0 : record(file, task.id);
616
+ if (file === void 0 || known === void 0) return;
617
+ file.records.set(task.id, {
618
+ ...known,
619
+ result: event.result
620
+ });
621
+ },
622
+ unhandled: (info, event) => {
623
+ if (info === null) {
624
+ unownedError = true;
625
+ return;
626
+ }
627
+ const file = stateOf(info);
628
+ const { ownerId } = event;
629
+ const owner = ownerId === null ? void 0 : file.nodes.get(ownerId);
630
+ if (ownerId !== null && ownerId !== info.fileId && owner === void 0) {
631
+ unownedError = true;
632
+ return;
633
+ }
634
+ if (event.origin === "runner") file.runnerFailed = true;
635
+ if (owner?.type === "test") {
636
+ const late = file.late.get(owner.id);
637
+ if (late === void 0) file.late.set(owner.id, [event.error]);
638
+ else late.push(event.error);
639
+ return;
640
+ }
641
+ file.unhandled.push(event.error);
642
+ },
643
+ "file:end": async (fileResult) => {
644
+ const info = fileResult.file;
645
+ const file = stateOf(info);
646
+ chargeLate(file);
647
+ const config = configOf(info);
648
+ const build = {
649
+ locations: config.testLocationInResults,
650
+ displayName: config.displayName,
651
+ ...options.collectOnly === true ? { collectOnly: true } : {},
652
+ ...config.slowTestThreshold === void 0 ? {} : { slowTestThreshold: config.slowTestThreshold }
653
+ };
654
+ const events = {
655
+ info,
656
+ testFilePath: pathOf(info),
657
+ tree: file.tree,
658
+ ...file.loadFailed ? { loadFailed: true } : {},
659
+ ...file.runnerFailed ? { runnerFailed: true } : {},
660
+ records: file.records,
661
+ orders: file.orders,
662
+ result: fileResult,
663
+ unhandled: file.unhandled,
664
+ startedAt: file.startedAt,
665
+ endedAt: now()
666
+ };
667
+ const testResult = toTestResult(events, build);
668
+ testResult.console = file.console.length > 0 ? file.console : void 0;
669
+ const stack = { noStackTrace: globalConfig.noStackTrace };
670
+ const ordered = file.tree === void 0 ? [] : testsInOrder(file.tree, file.records, ordersOf(events));
671
+ for (const [index, assertion] of testResult.testResults.entries()) {
672
+ const errors = ordered[index]?.result?.retryErrors ?? [];
673
+ if (errors.length === 0) continue;
674
+ assertion.retryMessages = await Promise.all(errors.map((error) => formatRetryError(error.stack ?? error.message, config, stack, events.testFilePath)));
675
+ }
676
+ const { testExecError } = testResult;
677
+ if (options.collectOnly === true && testExecError === void 0) {} else if (testExecError !== void 0 && testResult.testResults.length === 0) {
678
+ const text = await formatFileError(testExecError, config, stack, events.testFilePath);
679
+ testResult.failureMessage = text;
680
+ failureBlocks.set(info.fileId, [{ text }]);
681
+ } else {
682
+ const blocks = [];
683
+ for (const [index, assertion] of testResult.testResults.entries()) {
684
+ const text = await formatTestFailures([assertion], config, stack, events.testFilePath);
685
+ if (text === null) continue;
686
+ const taskId = ordered[index]?.task.id;
687
+ blocks.push(taskId === void 0 ? { text } : {
688
+ taskId,
689
+ text
690
+ });
691
+ }
692
+ if (testExecError !== void 0) {
693
+ const errors = [...fileResult.errors, ...file.unhandled];
694
+ const text = await Promise.all(errors.map((error) => formatFileError({
695
+ message: error.message,
696
+ stack: error.stack ?? null
697
+ }, config, stack, events.testFilePath)));
698
+ blocks.push({ text: `${blocks.length === 0 ? "\n\n" : "\n"}${text.join("\n")}` });
699
+ }
700
+ testResult.failureMessage = blocks.length === 0 ? null : blocks.map((block) => block.text).join("\n");
701
+ if (blocks.length > 0) failureBlocks.set(info.fileId, blocks);
702
+ }
703
+ results.set(info.fileId, testResult);
704
+ addResult(aggregated, testResult);
705
+ contextOf(config);
706
+ },
707
+ "run:end": (summary) => {
708
+ ended = {
709
+ reason: summary.reason,
710
+ snapshots: summary.snapshots,
711
+ unownedError
712
+ };
713
+ finishAggregated(aggregated, {
714
+ ...ended,
715
+ reporterFailed: false
716
+ });
717
+ aggregated.success = false;
718
+ aggregated.openHandles = (summary.openHandles ?? []).map((handle) => Object.assign(new Error(handle.type), { stack: [`Error: ${handle.type}`, ...handle.frames].join("\n") }));
719
+ }
720
+ },
721
+ aggregated: () => aggregated,
722
+ testResultOf: (fileId) => results.get(fileId),
723
+ failureTextOf: (fileId) => failureBlocks.get(fileId),
724
+ testOf: (info) => ({
725
+ context: contextOf(configOf(info)),
726
+ path: pathOf(info)
727
+ }),
728
+ contexts: () => new Set(contexts.values()),
729
+ assertionOf: (test, retried) => {
730
+ const file = files.get(test.fileId);
731
+ const known = file === void 0 ? void 0 : record(file, test.id);
732
+ if (file === void 0 || known === void 0) return void 0;
733
+ const config = configOf(file.info);
734
+ const shown = retried === void 0 ? known : {
735
+ ...known,
736
+ result: {
737
+ state: retried.state,
738
+ durationMs: 0,
739
+ startTime: 0,
740
+ errors: retried.errors,
741
+ retryErrors: [],
742
+ attempts: retried.attempt + 1,
743
+ repeatIndex: 0,
744
+ assertions: 0,
745
+ passingAssertions: retried.passingAssertions ?? 0
746
+ }
747
+ };
748
+ return toAssertionResult(shown, {
749
+ locations: config.testLocationInResults,
750
+ displayName: config.displayName
751
+ });
752
+ },
753
+ startInfoOf: (test) => {
754
+ const file = files.get(test.fileId);
755
+ return {
756
+ ancestorTitles: test.fullName.slice(0, -1),
757
+ fullName: test.fullName.join(" "),
758
+ mode: test.mode === "run" ? void 0 : test.mode,
759
+ startedAt: file?.records.get(test.id)?.startedAt ?? null,
760
+ title: test.fullName.at(-1) ?? test.name
761
+ };
762
+ },
763
+ reportersFailed: (failed) => {
764
+ if (ended !== void 0) finishAggregated(aggregated, {
765
+ ...ended,
766
+ reporterFailed: failed
767
+ });
768
+ }
769
+ };
770
+ }
771
+
772
+ // src/results/format-json.ts
773
+ /** One file's entry in the JSON (`formatTestResult`, formatTestResults.ts L18-L69). */
774
+ function formatTestResult(testResult) {
775
+ if (testResult.testExecError) {
776
+ const now = Date.now();
777
+ return {
778
+ assertionResults: testResult.testResults,
779
+ coverage: {},
780
+ endTime: now,
781
+ message: testResult.failureMessage ?? testResult.testExecError.message,
782
+ name: testResult.testFilePath,
783
+ startTime: now,
784
+ status: "failed",
785
+ summary: ""
786
+ };
787
+ }
788
+ if (testResult.skipped) {
789
+ const now = Date.now();
790
+ return {
791
+ assertionResults: testResult.testResults,
792
+ coverage: {},
793
+ endTime: now,
794
+ message: testResult.failureMessage ?? "",
795
+ name: testResult.testFilePath,
796
+ startTime: now,
797
+ status: "skipped",
798
+ summary: ""
799
+ };
800
+ }
801
+ const allTestsExecuted = testResult.numPendingTests === 0;
802
+ const allTestsPassed = testResult.numFailingTests === 0;
803
+ return {
804
+ assertionResults: testResult.testResults,
805
+ coverage: testResult.coverage,
806
+ endTime: testResult.perfStats.end,
807
+ message: testResult.failureMessage ?? "",
808
+ name: testResult.testFilePath,
809
+ startTime: testResult.perfStats.start,
810
+ status: allTestsPassed ? allTestsExecuted ? "passed" : "focused" : "failed",
811
+ summary: ""
812
+ };
813
+ }
814
+ /**
815
+ * The run's results with each file formatted (`formatTestResults`, formatTestResults.ts L71-L81).
816
+ * @public
817
+ */
818
+ function formatJson(results) {
819
+ return {
820
+ ...results,
821
+ testResults: results.testResults.map(formatTestResult)
822
+ };
823
+ }
824
+ /**
825
+ * `JSON.stringify` with what `serializeToJSON` adds: an error as `{ message, name, stack }` and a
826
+ * `bigint` as its literal (`1n`).
827
+ * @public
828
+ */
829
+ function serializeToJson(value, space) {
830
+ return JSON.stringify(value, (_key, inner) => {
831
+ if (inner instanceof Error || Object.prototype.toString.call(inner) === "[object Error]") {
832
+ const error = inner;
833
+ return {
834
+ message: error.message,
835
+ name: error.name,
836
+ stack: error.stack
837
+ };
838
+ }
839
+ if (typeof inner === "bigint") return `${inner}n`;
840
+ return inner;
841
+ }, space);
842
+ }
843
+
844
+ export { LEAK_MESSAGE, NO_TESTS_MESSAGE, addResult, buildFailureTestResult, createEmptyTestResult, createJestResults, finishAggregated, flattenSerializedError, formatFileError, formatJson, formatRetryError, formatTestFailures, makeCollectedTestResult, makeEmptyAggregatedTestResult, serializeToJson, toAssertionResult, toTestResult };