playwright-performance-regression 0.1.0-next.3 → 1.0.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 (37) hide show
  1. package/CHANGELOG.md +388 -0
  2. package/README.md +53 -41
  3. package/dist/{chunk-MUZFQKGQ.js → chunk-4WX3Z5MJ.js} +321 -30
  4. package/dist/{chunk-AQ2XKYNV.js → chunk-5Y34Q4DR.js} +37 -9
  5. package/dist/chunk-B4XTLSRN.js +1788 -0
  6. package/dist/{chunk-44ASXVQN.cjs → chunk-PWK5XSP2.cjs} +337 -45
  7. package/dist/{chunk-DYLCGMI2.js → chunk-S6UH6QPK.js} +6 -1
  8. package/dist/{chunk-BAOTUUTV.cjs → chunk-VREOANPX.cjs} +75 -28
  9. package/dist/{chunk-2JO5HVPC.cjs → chunk-W7NEFS5V.cjs} +37 -9
  10. package/dist/{chunk-DX36GFOZ.js → chunk-YKBX6SAT.js} +94 -57
  11. package/dist/cli.js +1922 -3307
  12. package/dist/config.cjs +58 -120
  13. package/dist/config.d.cts +2 -3
  14. package/dist/config.d.ts +2 -3
  15. package/dist/config.js +48 -110
  16. package/dist/fixture.cjs +9 -5
  17. package/dist/fixture.d.cts +10 -4
  18. package/dist/fixture.d.ts +10 -4
  19. package/dist/fixture.js +4 -4
  20. package/dist/index.cjs +3 -3
  21. package/dist/index.d.cts +22 -10
  22. package/dist/index.d.ts +22 -10
  23. package/dist/index.js +1 -1
  24. package/dist/perf-api-2DH_keLh.d.cts +17 -0
  25. package/dist/perf-api-2DH_keLh.d.ts +17 -0
  26. package/dist/reporter.cjs +2046 -835
  27. package/dist/reporter.js +6741 -1737
  28. package/dist/test.cjs +4 -4
  29. package/dist/test.js +4 -4
  30. package/package.json +17 -3
  31. package/schemas/config.schema.json +29 -14
  32. package/schemas/outcome.schema.json +1 -1
  33. package/schemas/run-report.schema.json +16 -2
  34. package/schemas/samples.schema.json +48 -2
  35. package/dist/chunk-LTRHMBVY.js +0 -5592
  36. package/dist/perf-api-Rm1h1O_-.d.cts +0 -12
  37. package/dist/perf-api-Rm1h1O_-.d.ts +0 -12
@@ -0,0 +1,1788 @@
1
+ import { KINDS } from './chunk-YKBX6SAT.js';
2
+ import { str, nullable, constant, obj, bool, msOrNull, epochMs, enumOf, oneOf, int, arr, issue, isoDate, ratio, msLimit, fingerprint, hostFingerprint, derivationSettings, percentileName, count, timestamp, runId, envLabelOrNull, tool, kind, record, key, nul, anyObject, ms, num, packageConfig, mode, evaluationStatus, testsStatus, isRecord, Sink, child, expandSteps, DEFAULT_CONFIG } from './chunk-5Y34Q4DR.js';
3
+ import { rmSync, readFileSync, readdirSync, lstatSync, realpathSync, existsSync } from 'fs';
4
+ import { readFile, mkdir, writeFile, rename, rm, access } from 'fs/promises';
5
+ import { tmpdir, homedir, cpus, availableParallelism } from 'os';
6
+ import { join, resolve, dirname, relative, isAbsolute, basename, sep } from 'path';
7
+ import { randomUUID } from 'crypto';
8
+ import { spawn } from 'child_process';
9
+
10
+ function tempPath(name) {
11
+ return join(tmpdir(), name);
12
+ }
13
+ function removeFileSync(path) {
14
+ rmSync(path, { force: true });
15
+ }
16
+ function isNotFound(error) {
17
+ return typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
18
+ }
19
+ async function readTextFile(path) {
20
+ try {
21
+ return await readFile(path, "utf8");
22
+ } catch (error) {
23
+ if (isNotFound(error)) return null;
24
+ throw error;
25
+ }
26
+ }
27
+ function readTextFileSync(path) {
28
+ try {
29
+ return readFileSync(path, "utf8");
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ function listDirSync(dir) {
35
+ try {
36
+ return readdirSync(dir);
37
+ } catch {
38
+ return [];
39
+ }
40
+ }
41
+ function isDirectorySync(path) {
42
+ try {
43
+ return lstatSync(realpathSync.native(path)).isDirectory();
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+ function realPathSync(path) {
49
+ try {
50
+ return realpathSync.native(path);
51
+ } catch {
52
+ return resolve(path);
53
+ }
54
+ }
55
+ function homeDir() {
56
+ return homedir();
57
+ }
58
+ function scanDirSync(dir, limit) {
59
+ const found = [];
60
+ const pending = [""];
61
+ while (pending.length > 0) {
62
+ const rel = pending.pop();
63
+ let names;
64
+ try {
65
+ names = readdirSync(rel === "" ? dir : join(dir, rel));
66
+ } catch {
67
+ continue;
68
+ }
69
+ for (const name of names) {
70
+ const child2 = rel === "" ? name : `${rel}/${name}`;
71
+ found.push(child2);
72
+ if (found.length > limit) return null;
73
+ try {
74
+ if (lstatSync(join(dir, child2)).isDirectory()) pending.push(child2);
75
+ } catch {
76
+ }
77
+ }
78
+ }
79
+ return found;
80
+ }
81
+ function emptyDirSync(dir) {
82
+ let failure2 = null;
83
+ for (const name of listDirSync(dir)) {
84
+ try {
85
+ rmSync(join(dir, name), { recursive: true, force: true });
86
+ } catch (error) {
87
+ failure2 ??= error;
88
+ }
89
+ }
90
+ if (failure2 !== null) throw failure2;
91
+ }
92
+ async function fileExists(path) {
93
+ try {
94
+ await access(path);
95
+ return true;
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+ function resolvePath(base, path) {
101
+ return resolve(base, path);
102
+ }
103
+ function directoryOf(path) {
104
+ return dirname(path);
105
+ }
106
+ function relativeSlashPath(from, path) {
107
+ const rel = relative(from, path);
108
+ const shown = rel === "" ? "." : isAbsolute(rel) ? path : rel;
109
+ return shown.replaceAll("\\", "/");
110
+ }
111
+
112
+ // src/core/format/round.ts
113
+ function roundRatio(x) {
114
+ return Math.round(x * 1e4) / 1e4 + 0;
115
+ }
116
+ function roundMs(x) {
117
+ return Math.round(x * 10) / 10;
118
+ }
119
+ function snap(x, digits) {
120
+ return Math.round(x * 10 ** (digits + 6)) / 1e6;
121
+ }
122
+ function ceilTo(x, digits) {
123
+ return Math.ceil(snap(x, digits)) / 10 ** digits;
124
+ }
125
+ function floorTo(x, digits) {
126
+ return Math.floor(snap(x, digits)) / 10 ** digits;
127
+ }
128
+
129
+ // src/core/format/json.ts
130
+ var INDENT = " ";
131
+ function fail(pointer, what) {
132
+ throw new TypeError(
133
+ `stringifyStable: value at "${pointer}" is ${what}, which cannot be written to JSON`
134
+ );
135
+ }
136
+ function isPlainObject(value) {
137
+ const proto = Object.getPrototypeOf(value);
138
+ return proto === Object.prototype || proto === null;
139
+ }
140
+ function escapePointer(key2) {
141
+ return key2.replaceAll("~", "~0").replaceAll("/", "~1");
142
+ }
143
+ function write(value, pointer, indent, ancestors) {
144
+ switch (typeof value) {
145
+ case "string":
146
+ case "boolean":
147
+ return JSON.stringify(value);
148
+ case "number":
149
+ if (!Number.isFinite(value)) fail(pointer, String(value));
150
+ return JSON.stringify(value);
151
+ case "undefined":
152
+ return fail(pointer, "undefined");
153
+ case "object":
154
+ break;
155
+ default:
156
+ return fail(pointer, typeof value);
157
+ }
158
+ if (value === null) return "null";
159
+ if (ancestors.has(value)) fail(pointer, "a circular reference");
160
+ const inner = indent + INDENT;
161
+ ancestors.add(value);
162
+ let text;
163
+ if (Array.isArray(value)) {
164
+ const items = value.map((item, i) => inner + write(item, `${pointer}/${i}`, inner, ancestors));
165
+ text = items.length === 0 ? "[]" : `[
166
+ ${items.join(",\n")}
167
+ ${indent}]`;
168
+ } else {
169
+ if (!isPlainObject(value)) fail(pointer, "not a plain object");
170
+ const record2 = value;
171
+ const keys = Object.keys(record2).filter((key2) => record2[key2] !== void 0).sort();
172
+ const entries = keys.map(
173
+ (key2) => `${inner}${JSON.stringify(key2)}: ${write(record2[key2], `${pointer}/${escapePointer(key2)}`, inner, ancestors)}`
174
+ );
175
+ text = entries.length === 0 ? "{}" : `{
176
+ ${entries.join(",\n")}
177
+ ${indent}}`;
178
+ }
179
+ ancestors.delete(value);
180
+ return text;
181
+ }
182
+ function stringifyStable(value) {
183
+ return `${write(value, "", "", /* @__PURE__ */ new Set())}
184
+ `;
185
+ }
186
+
187
+ // src/core/format/violation.ts
188
+ var TIME_RULES = /* @__PURE__ */ new Set([
189
+ "median",
190
+ "percentile",
191
+ "p99"
192
+ ]);
193
+ var SHARE_RULES = /* @__PURE__ */ new Set([
194
+ "apdex",
195
+ "wilson",
196
+ "errors"
197
+ ]);
198
+ function exceedance(check2) {
199
+ if (check2.rule === "apdex") return check2.actual === 0 ? Infinity : check2.limit / check2.actual;
200
+ return check2.limit === 0 ? Infinity : check2.actual / check2.limit;
201
+ }
202
+ function overText(check2) {
203
+ if (SHARE_RULES.has(check2.rule)) {
204
+ const points = Math.max(1, Math.round(Math.abs(check2.actual - check2.limit) * 100));
205
+ return `+${String(points)} pp`;
206
+ }
207
+ const r = exceedance(check2);
208
+ if (!Number.isFinite(r)) return ">999%";
209
+ const over = Math.max(1, Math.round((r - 1) * 100));
210
+ return over > 999 ? ">999%" : `+${String(over)}%`;
211
+ }
212
+ function formatFactor(ratio2, threshold = null) {
213
+ const scaled = Math.round(ratio2 * 1e6) / 1e4;
214
+ let hundredths = Math.round(scaled);
215
+ if (threshold !== null && hundredths / 100 <= threshold && ratio2 > threshold) {
216
+ hundredths = Math.ceil(scaled);
217
+ }
218
+ return (hundredths / 100).toFixed(2);
219
+ }
220
+ function formatMs(ms2) {
221
+ return `${Math.round(ms2)} ms`;
222
+ }
223
+ function formatActual(check2) {
224
+ if (TIME_RULES.has(check2.rule)) return formatMs(check2.actual);
225
+ const observed = check2.observed === null ? "" : ` (${check2.observed.toFixed(3)})`;
226
+ return `${check2.actual.toFixed(3)}${observed}`;
227
+ }
228
+ function formatLimit(check2) {
229
+ return TIME_RULES.has(check2.rule) ? formatMs(check2.limit) : check2.limit.toFixed(3);
230
+ }
231
+
232
+ // src/io/json.ts
233
+ async function writeTextAtomic(path, text) {
234
+ const dir = dirname(path);
235
+ await mkdir(dir, { recursive: true });
236
+ const temp = join(dir, `.${basename(path)}.${randomUUID()}.tmp`);
237
+ try {
238
+ await writeFile(temp, text, "utf8");
239
+ await rename(temp, path);
240
+ } catch (error) {
241
+ await rm(temp, { force: true });
242
+ throw error;
243
+ }
244
+ }
245
+ async function writeJsonStable(path, value) {
246
+ await writeTextAtomic(path, stringifyStable(value));
247
+ }
248
+ function runPass(command, env, cwd) {
249
+ return new Promise((resolveExit) => {
250
+ let settled = false;
251
+ const settle = (exit) => {
252
+ if (settled) return;
253
+ settled = true;
254
+ resolveExit(exit);
255
+ };
256
+ try {
257
+ const child2 = spawn(command.file, [...command.args], {
258
+ cwd,
259
+ env,
260
+ stdio: "inherit",
261
+ shell: false,
262
+ windowsHide: true
263
+ });
264
+ const forward = (signal) => {
265
+ child2.kill(signal);
266
+ };
267
+ const onInt = () => forward("SIGINT");
268
+ const onTerm = () => forward("SIGTERM");
269
+ process.on("SIGINT", onInt);
270
+ process.on("SIGTERM", onTerm);
271
+ const done = (exit) => {
272
+ process.off("SIGINT", onInt);
273
+ process.off("SIGTERM", onTerm);
274
+ settle(exit);
275
+ };
276
+ child2.once("error", (error) => done({ code: null, signal: null, error: error.message }));
277
+ child2.once("exit", (code, signal) => done({ code, signal }));
278
+ } catch (error) {
279
+ settle({
280
+ code: null,
281
+ signal: null,
282
+ error: error instanceof Error ? error.message : String(error)
283
+ });
284
+ }
285
+ });
286
+ }
287
+ function readPackageInfo(dir) {
288
+ for (let current = dir; ; current = dirname(current)) {
289
+ const file = join(current, "package.json");
290
+ if (existsSync(file)) {
291
+ let scripts = {};
292
+ try {
293
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
294
+ if (typeof parsed.scripts === "object" && parsed.scripts !== null) {
295
+ scripts = Object.fromEntries(
296
+ Object.entries(parsed.scripts).filter(([, v]) => typeof v === "string")
297
+ );
298
+ }
299
+ } catch {
300
+ scripts = null;
301
+ }
302
+ return {
303
+ scripts,
304
+ lockFiles: {
305
+ pnpm: existsSync(join(current, "pnpm-lock.yaml")),
306
+ yarn: existsSync(join(current, "yarn.lock"))
307
+ }
308
+ };
309
+ }
310
+ if (dirname(current) === current)
311
+ return { scripts: null, lockFiles: { pnpm: false, yarn: false } };
312
+ }
313
+ }
314
+ function readSuite(configDir, configFile) {
315
+ try {
316
+ const parsed = JSON.parse(readFileSync(join(configDir, "package.json"), "utf8"));
317
+ if (typeof parsed.name === "string" && parsed.name.trim() !== "") {
318
+ return { name: parsed.name.trim(), source: "package" };
319
+ }
320
+ } catch {
321
+ }
322
+ for (let current = configDir; ; current = dirname(current)) {
323
+ if (existsSync(join(current, ".git"))) {
324
+ const path = relative(current, configFile ?? configDir).split(sep).join("/");
325
+ return path === "" ? null : { name: path, source: "config" };
326
+ }
327
+ if (dirname(current) === current) return null;
328
+ }
329
+ }
330
+ function read(env, name) {
331
+ const value = env[name];
332
+ return value === void 0 || value === "" ? null : value;
333
+ }
334
+ function first(env, ...names) {
335
+ for (const name of names) {
336
+ const value = read(env, name);
337
+ if (value !== null) return value;
338
+ }
339
+ return null;
340
+ }
341
+ function compose(env, build, ...names) {
342
+ const values = names.map((name) => read(env, name));
343
+ return values.every((v) => v !== null) ? build(values) : null;
344
+ }
345
+ function readCiInfo(env) {
346
+ if (env.GITHUB_ACTIONS === "true") {
347
+ return {
348
+ provider: "github",
349
+ commit: read(env, "GITHUB_SHA"),
350
+ branch: first(env, "GITHUB_HEAD_REF", "GITHUB_REF_NAME"),
351
+ buildUrl: compose(
352
+ env,
353
+ ([server, repository, runId2]) => `${server}/${repository}/actions/runs/${runId2}`,
354
+ "GITHUB_SERVER_URL",
355
+ "GITHUB_REPOSITORY",
356
+ "GITHUB_RUN_ID"
357
+ )
358
+ };
359
+ }
360
+ if (env.GITLAB_CI === "true") {
361
+ return {
362
+ provider: "gitlab",
363
+ commit: read(env, "CI_COMMIT_SHA"),
364
+ branch: read(env, "CI_COMMIT_REF_NAME"),
365
+ buildUrl: read(env, "CI_JOB_URL")
366
+ };
367
+ }
368
+ if (read(env, "JENKINS_URL") !== null) {
369
+ return {
370
+ provider: "jenkins",
371
+ commit: read(env, "GIT_COMMIT"),
372
+ branch: first(env, "BRANCH_NAME", "GIT_BRANCH"),
373
+ buildUrl: read(env, "BUILD_URL")
374
+ };
375
+ }
376
+ if (env.TF_BUILD === "True") {
377
+ return {
378
+ provider: "azure",
379
+ commit: read(env, "BUILD_SOURCEVERSION"),
380
+ branch: read(env, "BUILD_SOURCEBRANCHNAME"),
381
+ buildUrl: compose(
382
+ env,
383
+ ([collection, project, buildId]) => `${collection}${project}/_build/results?buildId=${buildId}`,
384
+ "SYSTEM_COLLECTIONURI",
385
+ "SYSTEM_TEAMPROJECT",
386
+ "BUILD_BUILDID"
387
+ )
388
+ };
389
+ }
390
+ if (read(env, "CI") !== null)
391
+ return { provider: "other", commit: null, branch: null, buildUrl: null };
392
+ return null;
393
+ }
394
+ function readHostInfo(env) {
395
+ return {
396
+ platform: process.platform,
397
+ arch: process.arch,
398
+ nodeVersion: process.version,
399
+ ci: read(env, "CI") !== null,
400
+ cpuCount: availableParallelism(),
401
+ cpuModel: cpus()[0]?.model.trim() ?? ""
402
+ };
403
+ }
404
+
405
+ // src/core/schema/formats.ts
406
+ var nonEmpty = str({ minLength: 1 });
407
+ var nonEmptyOrNull = nullable(nonEmpty);
408
+ function present(value, pointer, sink, properties) {
409
+ for (const [name, schema] of Object.entries(properties)) {
410
+ if (Object.hasOwn(value, name)) schema.check(value[name], `${pointer}/${name}`, sink);
411
+ }
412
+ }
413
+ var noTiming = {
414
+ duration: nul,
415
+ requestStart: nul,
416
+ ttfb: nul,
417
+ timeSource: constant("browser"),
418
+ fromServiceWorker: constant(false)
419
+ };
420
+ var requestSample = obj(
421
+ {
422
+ method: str({ pattern: /^[A-Z]+$/u }),
423
+ url: nonEmpty,
424
+ resourceType: nonEmpty,
425
+ status: oneOf(int({ minimum: 100, maximum: 599 }), constant("FAILED"), constant("PENDING")),
426
+ failureText: nonEmpty,
427
+ startTime: epochMs,
428
+ duration: msOrNull,
429
+ requestStart: msOrNull,
430
+ ttfb: msOrNull,
431
+ timeSource: enumOf(["browser", "node"]),
432
+ fromServiceWorker: bool
433
+ },
434
+ {
435
+ required: [
436
+ "method",
437
+ "url",
438
+ "resourceType",
439
+ "status",
440
+ "startTime",
441
+ "duration",
442
+ "requestStart",
443
+ "ttfb",
444
+ "timeSource",
445
+ "fromServiceWorker"
446
+ ],
447
+ refine(value, pointer, sink) {
448
+ const status = Object.hasOwn(value, "status") ? value.status : "FAILED";
449
+ if (status === "FAILED" && !Object.hasOwn(value, "failureText")) {
450
+ sink.add(pointer, "must have required property 'failureText' when status is FAILED");
451
+ }
452
+ if (status !== "FAILED" && Object.hasOwn(value, "failureText")) {
453
+ sink.add(`${pointer}/failureText`, "must NOT be present unless status is FAILED");
454
+ }
455
+ if (status === "FAILED" || status === "PENDING" || !Object.hasOwn(value, "status")) {
456
+ present(value, pointer, sink, noTiming);
457
+ }
458
+ }
459
+ }
460
+ );
461
+ var apiRequestSample = obj(
462
+ {
463
+ method: str({ pattern: /^[A-Z]+$/u }),
464
+ url: nonEmpty,
465
+ status: oneOf(int({ minimum: 100, maximum: 599 }), constant("FAILED"), constant("PENDING")),
466
+ failureText: nonEmpty,
467
+ startTime: epochMs,
468
+ duration: msOrNull,
469
+ source: enumOf(["request", "context", "tracked"])
470
+ },
471
+ {
472
+ required: ["method", "url", "status", "startTime", "duration", "source"],
473
+ refine(value, pointer, sink) {
474
+ const status = Object.hasOwn(value, "status") ? value.status : "FAILED";
475
+ if (status === "FAILED" && !Object.hasOwn(value, "failureText")) {
476
+ sink.add(pointer, "must have required property 'failureText' when status is FAILED");
477
+ }
478
+ if (status !== "FAILED" && Object.hasOwn(value, "failureText")) {
479
+ sink.add(`${pointer}/failureText`, "must NOT be present unless status is FAILED");
480
+ }
481
+ if (status === "FAILED" || status === "PENDING" || !Object.hasOwn(value, "status")) {
482
+ present(value, pointer, sink, { duration: nul });
483
+ }
484
+ }
485
+ }
486
+ );
487
+ var sampleBatch = obj(
488
+ {
489
+ schemaVersion: constant(3),
490
+ collector: obj(
491
+ {
492
+ name: str({ pattern: /^[a-z0-9-]+$/u }),
493
+ version: nonEmpty,
494
+ browserName: nonEmptyOrNull
495
+ },
496
+ { required: ["name", "version", "browserName"] }
497
+ ),
498
+ requests: arr(requestSample),
499
+ apiRequests: arr(apiRequestSample),
500
+ diagnostics: arr(issue)
501
+ },
502
+ { required: ["schemaVersion", "collector", "requests", "apiRequests", "diagnostics"] }
503
+ );
504
+ var LIMIT_FIELDS = ["t", "median", "percentile", "p99", "minApdex", "maxWilson", "maxErrorRate"];
505
+ var thresholdsEntry = obj(
506
+ {
507
+ t: nullable(msLimit),
508
+ median: msLimit,
509
+ percentile: msLimit,
510
+ p99: msLimit,
511
+ minApdex: nullable(ratio),
512
+ maxWilson: nullable(ratio),
513
+ maxErrorRate: ratio,
514
+ locked: constant(true),
515
+ note: str({ minLength: 1, maxLength: 500 }),
516
+ gate: constant("warn"),
517
+ until: isoDate
518
+ },
519
+ {
520
+ refine(value, pointer, sink) {
521
+ if (![...LIMIT_FIELDS, "gate"].some((name) => Object.hasOwn(value, name))) {
522
+ sink.add(pointer, "must have at least one limit or gate");
523
+ }
524
+ if (Object.hasOwn(value, "gate")) {
525
+ for (const name of ["note", "until"]) {
526
+ if (!Object.hasOwn(value, name)) {
527
+ sink.add(pointer, `must have property '${name}' when property 'gate' is present`);
528
+ }
529
+ }
530
+ }
531
+ if (Object.hasOwn(value, "until") && !Object.hasOwn(value, "gate")) {
532
+ sink.add(pointer, "must have property 'gate' when property 'until' is present");
533
+ }
534
+ }
535
+ }
536
+ );
537
+ var thresholdsGenerated = obj(
538
+ {
539
+ tool,
540
+ env: envLabelOrNull,
541
+ sourceRunId: runId,
542
+ sourceRunStartedAt: timestamp,
543
+ sourceSampleCount: count,
544
+ evaluatedPercentile: percentileName,
545
+ derivation: derivationSettings,
546
+ browsers: arr(nonEmpty, { uniqueItems: true }),
547
+ playwrightVersion: nonEmpty,
548
+ host: hostFingerprint,
549
+ normalization: fingerprint
550
+ },
551
+ {
552
+ required: [
553
+ "tool",
554
+ "env",
555
+ "sourceRunId",
556
+ "sourceRunStartedAt",
557
+ "sourceSampleCount",
558
+ "evaluatedPercentile",
559
+ "derivation",
560
+ "browsers",
561
+ "playwrightVersion",
562
+ "host",
563
+ "normalization"
564
+ ]
565
+ }
566
+ );
567
+ var thresholdsFile = obj(
568
+ {
569
+ schemaVersion: constant(2),
570
+ kind,
571
+ generated: oneOf(thresholdsGenerated, nul),
572
+ entries: record(key, thresholdsEntry)
573
+ },
574
+ { required: ["schemaVersion", "kind", "generated", "entries"] }
575
+ );
576
+ var evaluationCounts = obj(
577
+ Object.fromEntries(
578
+ [
579
+ "keys",
580
+ "fromFile",
581
+ "fromDefaults",
582
+ "notEvaluated",
583
+ "tooFewSamples",
584
+ "fileEntriesNotEvaluated",
585
+ "medianOnly",
586
+ "unseenThresholdEntries",
587
+ "violations",
588
+ "blockingViolations",
589
+ "muted"
590
+ ].map((name) => [name, count])
591
+ ),
592
+ {
593
+ required: [
594
+ "keys",
595
+ "fromFile",
596
+ "fromDefaults",
597
+ "notEvaluated",
598
+ "tooFewSamples",
599
+ "fileEntriesNotEvaluated",
600
+ "medianOnly",
601
+ "unseenThresholdEntries",
602
+ "violations",
603
+ "blockingViolations",
604
+ "muted"
605
+ ]
606
+ }
607
+ );
608
+ var thresholdFileInfo = obj(
609
+ {
610
+ kind,
611
+ path: nonEmpty,
612
+ status: enumOf(["loaded", "missing", "invalid"]),
613
+ generated: oneOf(anyObject, nul),
614
+ unseenKeys: arr(key)
615
+ },
616
+ { required: ["kind", "path", "status", "generated", "unseenKeys"] }
617
+ );
618
+ var testRef = obj(
619
+ {
620
+ title: str(),
621
+ project: str(),
622
+ file: str(),
623
+ line: int({ minimum: 1 }),
624
+ repeatEachIndex: int({ minimum: 0 })
625
+ },
626
+ { required: ["title", "project", "file", "line", "repeatEachIndex"] }
627
+ );
628
+ var slowSample = obj(
629
+ { duration: ms, startedAt: timestamp, test: testRef, url: nonEmpty },
630
+ { required: ["duration", "startedAt", "test"] }
631
+ );
632
+ var stats = obj(
633
+ {
634
+ min: ms,
635
+ avg: ms,
636
+ max: ms,
637
+ percentiles: record(percentileName, ms, { required: ["p50", "p90", "p95", "p99"] })
638
+ },
639
+ { required: ["min", "avg", "max", "percentiles"] }
640
+ );
641
+ var check = obj(
642
+ {
643
+ rule: enumOf(["median", "percentile", "p99", "apdex", "wilson", "errors"]),
644
+ n: int({ minimum: 1 }),
645
+ actual: num({ minimum: 0 }),
646
+ observed: oneOf(num({ minimum: 0, maximum: 1 }), nul),
647
+ limit: num({ minimum: 0 }),
648
+ passed: bool,
649
+ hardLimitExceeded: bool,
650
+ blocking: bool,
651
+ usage: nullable(num({ minimum: 0 }))
652
+ },
653
+ {
654
+ required: [
655
+ "rule",
656
+ "n",
657
+ "actual",
658
+ "observed",
659
+ "limit",
660
+ "passed",
661
+ "hardLimitExceeded",
662
+ "blocking",
663
+ "usage"
664
+ ]
665
+ }
666
+ );
667
+ var keyEvaluation = obj(
668
+ {
669
+ result: enumOf(["pass", "fail", "not-evaluated"]),
670
+ reason: oneOf(enumOf(["too-few-samples", "no-rules", "thresholds-error"]), nul),
671
+ thresholdSource: enumOf(["file", "default"]),
672
+ limits: obj(
673
+ {
674
+ t: nullable(msLimit),
675
+ median: msLimit,
676
+ percentile: msLimit,
677
+ p99: msLimit,
678
+ minApdex: nullable(ratio),
679
+ maxWilson: nullable(ratio),
680
+ maxErrorRate: ratio
681
+ },
682
+ { required: LIMIT_FIELDS }
683
+ ),
684
+ checks: arr(check),
685
+ muted: oneOf(
686
+ obj(
687
+ { until: isoDate, note: nonEmpty, expired: bool },
688
+ { required: ["until", "note", "expired"] }
689
+ ),
690
+ nul
691
+ )
692
+ },
693
+ { required: ["result", "reason", "thresholdSource", "limits", "checks", "muted"] }
694
+ );
695
+ var HINT_CODES = [
696
+ "HINT_HARD_LIMIT",
697
+ "HINT_SLOWDOWN",
698
+ "HINT_TAIL",
699
+ "HINT_SHIFT",
700
+ "HINT_OUTLIERS",
701
+ "HINT_ERRORS_DOMINANT",
702
+ "HINT_ERRORS_MIXED",
703
+ "HINT_APDEX",
704
+ "HINT_SLOW_SHARE",
705
+ "HINT_MEDIAN_ONLY",
706
+ "HINT_MUTED",
707
+ "HINT_FAILED_TESTS",
708
+ "HINT_NEAR_LIMIT"
709
+ ];
710
+ var HINT_PARAMS = [
711
+ "rule",
712
+ "usage",
713
+ "medianUsage",
714
+ "factor",
715
+ "max",
716
+ "rate",
717
+ "limit",
718
+ "label",
719
+ "count",
720
+ "errors",
721
+ "label1",
722
+ "count1",
723
+ "label2",
724
+ "count2",
725
+ "label3",
726
+ "count3",
727
+ "apdex",
728
+ "share",
729
+ "t",
730
+ "n"
731
+ ];
732
+ var hint = obj(
733
+ { code: enumOf(HINT_CODES), params: record(enumOf(HINT_PARAMS), oneOf(str(), num())) },
734
+ { required: ["code", "params"] }
735
+ );
736
+ var histogram = oneOf(
737
+ obj(
738
+ {
739
+ edges: arr(num({ minimum: 0 }), { minItems: 2, maxItems: 31 }),
740
+ counts: arr(count, { minItems: 1, maxItems: 30 })
741
+ },
742
+ { required: ["edges", "counts"] }
743
+ ),
744
+ nul
745
+ );
746
+ var testCost = obj(
747
+ {
748
+ title: str(),
749
+ project: str(),
750
+ file: str(),
751
+ line: int({ minimum: 1 }),
752
+ executions: int({ minimum: 1 }),
753
+ requestCount: int({ minimum: 1 }),
754
+ errorCount: count,
755
+ totalMs: ms,
756
+ maxRequestMs: msOrNull,
757
+ keyCount: int({ minimum: 1 }),
758
+ topKeys: arr(
759
+ obj(
760
+ { key, count: int({ minimum: 1 }), totalMs: ms },
761
+ { required: ["key", "count", "totalMs"] }
762
+ ),
763
+ { maxItems: 3 }
764
+ ),
765
+ violatedKeys: arr(key, { maxItems: 10 }),
766
+ violatedKeyCount: count
767
+ },
768
+ {
769
+ required: [
770
+ "title",
771
+ "project",
772
+ "file",
773
+ "line",
774
+ "executions",
775
+ "requestCount",
776
+ "errorCount",
777
+ "totalMs",
778
+ "maxRequestMs",
779
+ "keyCount",
780
+ "topKeys",
781
+ "violatedKeys",
782
+ "violatedKeyCount"
783
+ ]
784
+ }
785
+ );
786
+ var waterfallRequest = obj(
787
+ {
788
+ offset: int({ minimum: 0 }),
789
+ duration: msOrNull,
790
+ key,
791
+ status: str({ pattern: /^(?:[1-5][0-9]{2}|FAILED|ABORTED|PENDING)$/u })
792
+ },
793
+ { required: ["offset", "duration", "key", "status"] }
794
+ );
795
+ var waterfall = obj(
796
+ {
797
+ test: testRef,
798
+ totalMs: ms,
799
+ requestCount: int({ minimum: 1 }),
800
+ spanMs: ms,
801
+ requests: arr(waterfallRequest, { maxItems: 200 }),
802
+ omitted: count
803
+ },
804
+ { required: ["test", "totalMs", "requestCount", "spanMs", "requests", "omitted"] }
805
+ );
806
+ var testBreakdown = oneOf(
807
+ obj(
808
+ {
809
+ tests: arr(testCost, { maxItems: 500 }),
810
+ omitted: count,
811
+ waterfalls: arr(waterfall, { maxItems: 5 })
812
+ },
813
+ { required: ["tests", "omitted", "waterfalls"] }
814
+ ),
815
+ nul
816
+ );
817
+ var aggregateProps = {
818
+ count,
819
+ successCount: count,
820
+ errorCount: count,
821
+ fromFailedTests: count,
822
+ testCount: count,
823
+ statuses: record(
824
+ str({ pattern: /^(?:[1-5][0-9]{2}|FAILED|ABORTED|PENDING|ok|error|unfinished)$/u }),
825
+ int({ minimum: 1 })
826
+ ),
827
+ timeSources: obj({ browser: count, node: count }, { required: ["browser", "node"] }),
828
+ stats: oneOf(stats, nul),
829
+ ttfb: oneOf(
830
+ obj({ p50: ms, p95: ms, otherP50: msOrNull }, { required: ["p50", "p95", "otherP50"] }),
831
+ nul
832
+ ),
833
+ slowest: arr(slowSample, { maxItems: 3 }),
834
+ topTests: arr(
835
+ obj(
836
+ {
837
+ title: str(),
838
+ project: str(),
839
+ file: str(),
840
+ line: int({ minimum: 1 }),
841
+ sampleCount: int({ minimum: 1 })
842
+ },
843
+ { required: ["title", "project", "file", "line", "sampleCount"] }
844
+ ),
845
+ { maxItems: 5 }
846
+ ),
847
+ samples: obj({ durations: arr(ms), sampled: bool }, { required: ["durations", "sampled"] }),
848
+ evaluation: keyEvaluation,
849
+ histogram,
850
+ hints: arr(hint, { maxItems: 3 })
851
+ };
852
+ var aggregateRequired = [
853
+ "count",
854
+ "successCount",
855
+ "errorCount",
856
+ "fromFailedTests",
857
+ "testCount",
858
+ "statuses",
859
+ "timeSources",
860
+ "stats",
861
+ "ttfb",
862
+ "slowest",
863
+ "topTests",
864
+ "samples",
865
+ "evaluation",
866
+ "histogram",
867
+ "hints"
868
+ ];
869
+ var aggregate = obj(aggregateProps, { required: aggregateRequired });
870
+ var stepAggregate = obj(
871
+ {
872
+ ...aggregateProps,
873
+ location: oneOf(
874
+ obj({ file: nonEmpty, line: int({ minimum: 1 }) }, { required: ["file", "line"] }),
875
+ nul
876
+ ),
877
+ stepErrorsFromFailedTests: count
878
+ },
879
+ { required: [...aggregateRequired, "location", "stepErrorsFromFailedTests"] }
880
+ );
881
+ var runReport = obj(
882
+ {
883
+ schemaVersion: constant(4),
884
+ tool,
885
+ runId,
886
+ mode,
887
+ startedAt: timestamp,
888
+ finishedAt: timestamp,
889
+ env: envLabelOrNull,
890
+ configDir: nonEmpty,
891
+ // Optional (02-REQ-42): left out when neither a package name nor a repository root is known.
892
+ suite: obj(
893
+ { name: nonEmpty, source: enumOf(["package", "config"]) },
894
+ { required: ["name", "source"] }
895
+ ),
896
+ config: packageConfig,
897
+ normalization: fingerprint,
898
+ stepNormalization: oneOf(fingerprint, nul),
899
+ ci: oneOf(
900
+ obj(
901
+ {
902
+ provider: enumOf(["github", "gitlab", "jenkins", "azure", "other"]),
903
+ commit: nonEmptyOrNull,
904
+ branch: nonEmptyOrNull,
905
+ buildUrl: nonEmptyOrNull
906
+ },
907
+ { required: ["provider", "commit", "branch", "buildUrl"] }
908
+ ),
909
+ nul
910
+ ),
911
+ host: obj(
912
+ {
913
+ platform: str(),
914
+ arch: str(),
915
+ nodeVersion: str(),
916
+ ci: bool,
917
+ cpuCount: int({ minimum: 1 }),
918
+ cpuModel: str()
919
+ },
920
+ { required: ["platform", "arch", "nodeVersion", "ci", "cpuCount", "cpuModel"] }
921
+ ),
922
+ playwright: obj({ version: str() }, { required: ["version"] }),
923
+ passes: obj(
924
+ {
925
+ planned: int({ minimum: 1 }),
926
+ completed: int({ minimum: 1 }),
927
+ failed: arr(int({ minimum: 2 }))
928
+ },
929
+ { required: ["planned", "completed", "failed"] }
930
+ ),
931
+ runConditions: obj(
932
+ {
933
+ workers: int({ minimum: 1 }),
934
+ projects: arr(
935
+ obj(
936
+ {
937
+ name: str(),
938
+ role: enumOf(["measured", "dependency", "teardown"]),
939
+ browserName: oneOf(str(), nul),
940
+ repeatEach: int({ minimum: 1 }),
941
+ retries: int({ minimum: 0 }),
942
+ requestOnly: constant(true)
943
+ },
944
+ { required: ["name", "role", "browserName", "repeatEach", "retries"] }
945
+ )
946
+ ),
947
+ overriddenSettings: arr(str())
948
+ },
949
+ { required: ["workers", "projects", "overriddenSettings"] }
950
+ ),
951
+ tests: obj(
952
+ {
953
+ status: testsStatus,
954
+ expected: count,
955
+ unexpected: count,
956
+ flaky: count,
957
+ skipped: count
958
+ },
959
+ { required: ["status", "expected", "unexpected", "flaky", "skipped"] }
960
+ ),
961
+ evaluation: obj(
962
+ {
963
+ status: evaluationStatus,
964
+ gateEnabled: bool,
965
+ counts: obj(
966
+ { api: evaluationCounts, step: evaluationCounts },
967
+ { required: ["api", "step"] }
968
+ )
969
+ },
970
+ { required: ["status", "gateEnabled", "counts"] }
971
+ ),
972
+ thresholdFiles: arr(thresholdFileInfo),
973
+ warnings: arr(issue),
974
+ toolErrors: arr(issue),
975
+ origins: arr(
976
+ obj(
977
+ { origin: nonEmpty, label: str(), requestCount: count },
978
+ { required: ["origin", "label", "requestCount"] }
979
+ )
980
+ ),
981
+ endpoints: record(key, aggregate),
982
+ steps: record(key, stepAggregate),
983
+ testBreakdown
984
+ },
985
+ {
986
+ required: [
987
+ "schemaVersion",
988
+ "tool",
989
+ "runId",
990
+ "mode",
991
+ "startedAt",
992
+ "finishedAt",
993
+ "env",
994
+ "configDir",
995
+ "config",
996
+ "normalization",
997
+ "stepNormalization",
998
+ "ci",
999
+ "host",
1000
+ "playwright",
1001
+ "passes",
1002
+ "runConditions",
1003
+ "tests",
1004
+ "evaluation",
1005
+ "thresholdFiles",
1006
+ "warnings",
1007
+ "toolErrors",
1008
+ "origins",
1009
+ "endpoints",
1010
+ "steps",
1011
+ "testBreakdown"
1012
+ ]
1013
+ }
1014
+ );
1015
+ obj(
1016
+ {
1017
+ schemaVersion: constant(1),
1018
+ runId,
1019
+ // The outcome has its own modes: a check writes neither a report nor thresholds (02-REQ-34).
1020
+ mode: enumOf(["test", "thresholds", "check"]),
1021
+ exitCode: enumOf([0, 2, 3]),
1022
+ tests: obj({ status: testsStatus }, { required: ["status"] }),
1023
+ evaluation: obj(
1024
+ { status: evaluationStatus, gateEnabled: bool },
1025
+ { required: ["status", "gateEnabled"] }
1026
+ ),
1027
+ toolErrors: arr(issue),
1028
+ paths: obj(
1029
+ {
1030
+ reportJson: nonEmptyOrNull,
1031
+ reportHtml: nonEmptyOrNull,
1032
+ thresholds: arr(nonEmpty),
1033
+ thresholdsDiff: nonEmptyOrNull
1034
+ },
1035
+ { required: ["reportJson", "reportHtml", "thresholds", "thresholdsDiff"] }
1036
+ )
1037
+ },
1038
+ {
1039
+ required: [
1040
+ "schemaVersion",
1041
+ "runId",
1042
+ "mode",
1043
+ "exitCode",
1044
+ "tests",
1045
+ "evaluation",
1046
+ "toolErrors",
1047
+ "paths"
1048
+ ]
1049
+ }
1050
+ );
1051
+
1052
+ // src/core/schema/parse.ts
1053
+ var MAX_PROBLEMS = 5;
1054
+ var SCHEMA_VERSIONS = {
1055
+ samples: 3,
1056
+ runReport: 4,
1057
+ thresholds: 2,
1058
+ outcome: 1
1059
+ };
1060
+ var HINTS = {
1061
+ SCHEMA_INVALID_JSON: "Fix the JSON syntax, or delete the file and let the package write it again.",
1062
+ SCHEMA_VERSION_MISSING: 'Add the "schemaVersion" of the format at the top level, or let the package write the file again.',
1063
+ SCHEMA_VERSION_TOO_NEW: "The file was written by a newer version of the package; update the package to read it.",
1064
+ SCHEMA_VERSION_MISMATCH: "The attachment was written by another version of the package; use one package version in a run.",
1065
+ SCHEMA_VALIDATION_FAILED: "Fix the listed fields; the JSON Schemas in the package's schemas/ directory describe the format.",
1066
+ THRESHOLDS_KIND_MISMATCH: 'Each kind has its own file (pw-perf-thresholds[.steps]…); move the entries to the right file or fix "kind".'
1067
+ };
1068
+ function describeProblems(problems, more) {
1069
+ const list = problems.map((p) => `${p.pointer === "" ? "(root)" : p.pointer} ${p.message}`).join("; ");
1070
+ return more ? `${list}; …` : list;
1071
+ }
1072
+ function issueOf(code, source, summary, problems = []) {
1073
+ const shown = problems.slice(0, MAX_PROBLEMS).map(({ pointer, message }) => ({ pointer, message }));
1074
+ const details = shown.length === 0 ? "" : `: ${describeProblems(shown, problems.length > shown.length)}`;
1075
+ return { code, source, message: `${source}: ${summary}${details}`, problems: shown };
1076
+ }
1077
+ function failure(issue2) {
1078
+ return { ok: false, issues: [issue2] };
1079
+ }
1080
+ function parseJson(text, source, format) {
1081
+ try {
1082
+ return { ok: true, value: JSON.parse(text) };
1083
+ } catch (error) {
1084
+ const reason = error instanceof Error ? error.message : String(error);
1085
+ return failure(
1086
+ issueOf("SCHEMA_INVALID_JSON", source, `${format.name} is not valid JSON (${reason})`)
1087
+ );
1088
+ }
1089
+ }
1090
+ function migrate(document, from, to, migrations) {
1091
+ let current = document;
1092
+ for (let version = from; version < to; version++) {
1093
+ const step = migrations[version];
1094
+ if (step === void 0) throw new Error(`no migration from schemaVersion ${version}`);
1095
+ current = { ...step(current), schemaVersion: version + 1 };
1096
+ }
1097
+ return current;
1098
+ }
1099
+ function validate(document, source, format) {
1100
+ const sink = new Sink(MAX_PROBLEMS + 1);
1101
+ format.schema.check(document, "", sink);
1102
+ if (sink.problems.length === 0) format.extraChecks?.(document, sink);
1103
+ if (sink.problems.length === 0) return null;
1104
+ return issueOf(
1105
+ "SCHEMA_VALIDATION_FAILED",
1106
+ source,
1107
+ `${format.name} does not match the format`,
1108
+ sink.problems
1109
+ );
1110
+ }
1111
+ function parseVersioned(text, source, format, options = {}) {
1112
+ const parsed = parseJson(text, source, format);
1113
+ if (!parsed.ok) return parsed;
1114
+ const document = parsed.value;
1115
+ if (!isRecord(document)) {
1116
+ return failure(
1117
+ issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
1118
+ { pointer: "", message: "must be object" }
1119
+ ])
1120
+ );
1121
+ }
1122
+ const version = document.schemaVersion;
1123
+ if (typeof version !== "number" || !Number.isInteger(version)) {
1124
+ const found = Object.hasOwn(document, "schemaVersion") ? `schemaVersion must be an integer, found ${JSON.stringify(version)}` : "schemaVersion is missing";
1125
+ return failure(issueOf("SCHEMA_VERSION_MISSING", source, `${format.name}: ${found}`));
1126
+ }
1127
+ if (options.exactVersion === true && version !== format.current) {
1128
+ return failure(
1129
+ issueOf(
1130
+ "SCHEMA_VERSION_MISMATCH",
1131
+ source,
1132
+ `${format.name} has schemaVersion ${version}, but this package version reads only ${format.current}`
1133
+ )
1134
+ );
1135
+ }
1136
+ if (version > format.current) {
1137
+ return failure(
1138
+ issueOf(
1139
+ "SCHEMA_VERSION_TOO_NEW",
1140
+ source,
1141
+ `${format.name} has schemaVersion ${version}, newer than ${format.current} supported by this package version`
1142
+ )
1143
+ );
1144
+ }
1145
+ if (version < 1) {
1146
+ return failure(
1147
+ issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
1148
+ { pointer: "/schemaVersion", message: "must be >= 1" }
1149
+ ])
1150
+ );
1151
+ }
1152
+ const current = version < format.current ? migrate(document, version, format.current, format.migrations) : document;
1153
+ const invalid = validate(current, source, format);
1154
+ if (invalid !== null) return failure(invalid);
1155
+ return {
1156
+ ok: true,
1157
+ value: { document: current, migratedFrom: version < format.current ? version : null }
1158
+ };
1159
+ }
1160
+ function isCalendarDate(text) {
1161
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(text);
1162
+ if (match === null) return false;
1163
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
1164
+ if (month < 1 || month > 12 || day < 1) return false;
1165
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
1166
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
1167
+ return day <= days;
1168
+ }
1169
+ var SAMPLES_FORMAT = {
1170
+ name: "sample batch",
1171
+ schemaFile: "samples.schema.json",
1172
+ current: SCHEMA_VERSIONS.samples,
1173
+ migrations: {},
1174
+ schema: sampleBatch
1175
+ };
1176
+ function migrateRunReportV1(document) {
1177
+ const aggregates = (value) => {
1178
+ if (!isRecord(value)) return value;
1179
+ return Object.fromEntries(
1180
+ Object.entries(value).map(([name, aggregate2]) => {
1181
+ if (!isRecord(aggregate2)) return [name, aggregate2];
1182
+ const evaluation = aggregate2.evaluation;
1183
+ const ttfb = aggregate2.ttfb;
1184
+ return [
1185
+ name,
1186
+ {
1187
+ ...aggregate2,
1188
+ ttfb: isRecord(ttfb) ? { ...ttfb, otherP50: null } : ttfb,
1189
+ evaluation: isRecord(evaluation) && Array.isArray(evaluation.checks) ? {
1190
+ ...evaluation,
1191
+ checks: evaluation.checks.map(
1192
+ (check2) => isRecord(check2) ? { ...check2, usage: null } : check2
1193
+ )
1194
+ } : evaluation,
1195
+ histogram: null,
1196
+ hints: []
1197
+ }
1198
+ ];
1199
+ })
1200
+ );
1201
+ };
1202
+ return {
1203
+ ...document,
1204
+ endpoints: aggregates(document.endpoints),
1205
+ custom: aggregates(document.custom),
1206
+ testBreakdown: null
1207
+ };
1208
+ }
1209
+ function withoutCustomOptions(config) {
1210
+ if (!isRecord(config) || !isRecord(config.checks)) return config;
1211
+ const drop = (value) => {
1212
+ if (!isRecord(value)) return value;
1213
+ const { custom: _removed, ...rest } = value;
1214
+ return rest;
1215
+ };
1216
+ const checks = Object.fromEntries(
1217
+ Object.entries(config.checks).map(([group, rules]) => {
1218
+ if (!isRecord(rules)) return [group, rules];
1219
+ if (group === "errors") return [group, { ...rules, limit: drop(rules.limit) }];
1220
+ return [
1221
+ group,
1222
+ Object.fromEntries(
1223
+ Object.entries(rules).map(([name, rule]) => {
1224
+ if (group === "slowShare" && name === "t") return [name, drop(rule)];
1225
+ if (!isRecord(rule) || !Object.hasOwn(rule, "limit")) return [name, rule];
1226
+ return [name, { ...rule, limit: drop(rule.limit) }];
1227
+ })
1228
+ )
1229
+ ];
1230
+ })
1231
+ );
1232
+ return { ...config, checks };
1233
+ }
1234
+ function withStepOptions(config) {
1235
+ if (!isRecord(config)) return config;
1236
+ const out = { ...config };
1237
+ if (isRecord(config.measure) && !Object.hasOwn(config.measure, "steps")) {
1238
+ out.measure = { ...config.measure, steps: expandSteps(false) };
1239
+ }
1240
+ if (isRecord(config.checks)) {
1241
+ const defaults = DEFAULT_CONFIG.checks;
1242
+ const withStep = (value, fallback) => isRecord(value) && !Object.hasOwn(value, "step") && isRecord(fallback) ? { ...value, step: structuredClone(fallback.step) } : value;
1243
+ out.checks = Object.fromEntries(
1244
+ Object.entries(config.checks).map(([group, rules]) => {
1245
+ const groupDefaults = defaults[group];
1246
+ if (!isRecord(rules) || !isRecord(groupDefaults)) return [group, rules];
1247
+ if (group === "errors") {
1248
+ return [group, { ...rules, limit: withStep(rules.limit, groupDefaults.limit) }];
1249
+ }
1250
+ return [
1251
+ group,
1252
+ Object.fromEntries(
1253
+ Object.entries(rules).map(([name, rule]) => {
1254
+ const ruleDefaults = groupDefaults[name];
1255
+ if (group === "slowShare" && name === "t")
1256
+ return [name, withStep(rule, ruleDefaults)];
1257
+ if (!isRecord(rule) || !isRecord(ruleDefaults)) return [name, rule];
1258
+ if (!Object.hasOwn(rule, "limit")) return [name, rule];
1259
+ return [name, { ...rule, limit: withStep(rule.limit, ruleDefaults.limit) }];
1260
+ })
1261
+ )
1262
+ ];
1263
+ })
1264
+ );
1265
+ }
1266
+ return out;
1267
+ }
1268
+ function withPassesOption(config) {
1269
+ if (!isRecord(config) || !isRecord(config.run)) return config;
1270
+ const { repeat, ...run } = config.run;
1271
+ return repeat === void 0 ? config : { ...config, run: { ...run, passes: repeat } };
1272
+ }
1273
+ function withGateAndPresetOptions(config) {
1274
+ if (!isRecord(config)) return config;
1275
+ const out = { ...config };
1276
+ if (isRecord(config.gate)) {
1277
+ const { warnOnly: _warnOnly, ...gate } = config.gate;
1278
+ out.gate = gate;
1279
+ }
1280
+ if (isRecord(config.thresholds) && !Object.hasOwn(config.thresholds, "preset")) {
1281
+ out.thresholds = { preset: "normal", ...config.thresholds };
1282
+ }
1283
+ if (isRecord(config.run) && !Object.hasOwn(config.run, "grep")) {
1284
+ out.run = { ...config.run, grep: null };
1285
+ }
1286
+ return out;
1287
+ }
1288
+ function migrateRunReportV2(document) {
1289
+ const { custom: _custom, ...rest } = document;
1290
+ const evaluation = document.evaluation;
1291
+ const counts = isRecord(evaluation) ? evaluation.counts : void 0;
1292
+ const files = document.thresholdFiles;
1293
+ return {
1294
+ ...rest,
1295
+ stepNormalization: null,
1296
+ steps: {},
1297
+ // A run before D-39 ran its repetitions in one pass (02-REQ-37).
1298
+ passes: { planned: 1, completed: 1, failed: [] },
1299
+ config: withGateAndPresetOptions(
1300
+ withPassesOption(withStepOptions(withoutCustomOptions(document.config)))
1301
+ ),
1302
+ evaluation: isRecord(evaluation) && isRecord(counts) ? {
1303
+ ...evaluation,
1304
+ counts: {
1305
+ ...Object.fromEntries(Object.entries(counts).filter(([k]) => k !== "custom")),
1306
+ step: Object.fromEntries(Object.keys(counts.api ?? {}).map((name) => [name, 0]))
1307
+ }
1308
+ } : evaluation,
1309
+ thresholdFiles: Array.isArray(files) ? files.filter((file) => !(isRecord(file) && file.kind === "custom")) : files
1310
+ };
1311
+ }
1312
+ function sum(values) {
1313
+ return values.reduce((total, v) => total + (typeof v === "number" ? v : Number.NaN), 0);
1314
+ }
1315
+ function checkRunReport(document, sink) {
1316
+ for (const kind2 of ["endpoints"]) {
1317
+ const map = document[kind2];
1318
+ for (const [name, aggregate2] of Object.entries(map)) {
1319
+ const histogram2 = aggregate2.histogram;
1320
+ if (histogram2 === null) continue;
1321
+ const pointer = child(child(`/${kind2}`, name), "histogram");
1322
+ const { edges, counts } = histogram2;
1323
+ if (edges.some((edge, i) => i > 0 && edge <= (edges[i - 1] ?? 0))) {
1324
+ sink.add(child(pointer, "edges"), "must be strictly ascending");
1325
+ }
1326
+ if (counts.length !== edges.length - 1) {
1327
+ sink.add(child(pointer, "counts"), "must have one item fewer than edges");
1328
+ }
1329
+ const retained = aggregate2.samples.durations.length;
1330
+ if (sum(counts) !== retained) {
1331
+ sink.add(child(pointer, "counts"), "must sum to the number of samples.durations");
1332
+ }
1333
+ }
1334
+ }
1335
+ const breakdown = document.testBreakdown;
1336
+ if (breakdown === null) return;
1337
+ breakdown.tests.forEach((test, i) => {
1338
+ if (test.violatedKeys.length !== Math.min(10, test.violatedKeyCount)) {
1339
+ sink.add(
1340
+ `/testBreakdown/tests/${i}/violatedKeys`,
1341
+ "must have min(10, violatedKeyCount) items"
1342
+ );
1343
+ }
1344
+ });
1345
+ breakdown.waterfalls.forEach((waterfall2, i) => {
1346
+ if (waterfall2.requests.length + waterfall2.omitted !== waterfall2.requestCount) {
1347
+ sink.add(`/testBreakdown/waterfalls/${i}`, "requests plus omitted must equal requestCount");
1348
+ }
1349
+ });
1350
+ }
1351
+ function migrateRunReportV3(document) {
1352
+ const config = document.config;
1353
+ if (!isRecord(config) || !isRecord(config.run)) return document;
1354
+ const { projects: _projects, ...run } = config.run;
1355
+ const measure = isRecord(config.measure) ? { api: true, ...config.measure } : config.measure;
1356
+ const report = isRecord(config.report) ? { ...config.report, junit: false } : config.report;
1357
+ return {
1358
+ ...document,
1359
+ config: { ...config, run: { ...run, overrideSlowMo: false }, measure, report }
1360
+ };
1361
+ }
1362
+ var RUN_REPORT_FORMAT = {
1363
+ name: "run report",
1364
+ schemaFile: "run-report.schema.json",
1365
+ current: SCHEMA_VERSIONS.runReport,
1366
+ migrations: { 1: migrateRunReportV1, 2: migrateRunReportV2, 3: migrateRunReportV3 },
1367
+ schema: runReport,
1368
+ extraChecks: checkRunReport
1369
+ };
1370
+ var THRESHOLDS_FORMAT = {
1371
+ name: "thresholds file",
1372
+ schemaFile: "thresholds.schema.json",
1373
+ current: SCHEMA_VERSIONS.thresholds,
1374
+ // v1 → v2 changes no content (02-REQ-33): a v1 file of kind custom fails validation after it.
1375
+ migrations: { 1: (document) => document },
1376
+ schema: thresholdsFile,
1377
+ extraChecks(document, sink) {
1378
+ const entries = document.entries;
1379
+ for (const [name, entry] of Object.entries(entries)) {
1380
+ if (typeof entry.until === "string" && !isCalendarDate(entry.until)) {
1381
+ sink.add(child(child("/entries", name), "until"), "must be an existing calendar date");
1382
+ }
1383
+ }
1384
+ }
1385
+ };
1386
+ ({
1387
+ current: SCHEMA_VERSIONS.outcome});
1388
+ function parseSampleBatch(text, source) {
1389
+ const parsed = parseVersioned(text, source, SAMPLES_FORMAT, { exactVersion: true });
1390
+ return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
1391
+ }
1392
+ function parseRunReport(text, source) {
1393
+ const parsed = parseVersioned(text, source, RUN_REPORT_FORMAT);
1394
+ return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
1395
+ }
1396
+ function parseThresholdsFile(text, source, expectedKind) {
1397
+ const parsed = parseVersioned(text, source, THRESHOLDS_FORMAT);
1398
+ if (!parsed.ok) return parsed;
1399
+ const file = parsed.value.document;
1400
+ if (file.kind !== expectedKind) {
1401
+ return failure(
1402
+ issueOf(
1403
+ "THRESHOLDS_KIND_MISMATCH",
1404
+ source,
1405
+ `thresholds file has kind "${file.kind}", but this path holds "${expectedKind}" thresholds`,
1406
+ [{ pointer: "/kind", message: `must be "${expectedKind}"` }]
1407
+ )
1408
+ );
1409
+ }
1410
+ return { ok: true, value: { file, migratedFrom: parsed.value.migratedFrom } };
1411
+ }
1412
+ function schemaIssueToIssue(issue2) {
1413
+ return { code: issue2.code, message: issue2.message, hint: HINTS[issue2.code] };
1414
+ }
1415
+
1416
+ // src/io/thresholds.ts
1417
+ var NAME_PART = { api: null, step: "steps" };
1418
+ function thresholdsFileName(prefix, kind2, env) {
1419
+ const part = NAME_PART[kind2];
1420
+ return `${prefix}${part === null ? "" : `.${part}`}${env === null ? "" : `.${env}`}.json`;
1421
+ }
1422
+ function thresholdsFilePaths(location) {
1423
+ const dir = resolvePath(location.configDir, location.dir);
1424
+ const path = (kind2) => resolvePath(dir, thresholdsFileName(location.filePrefix, kind2, location.env));
1425
+ return Object.fromEntries(KINDS.map((kind2) => [kind2, path(kind2)]));
1426
+ }
1427
+ async function loadFile(location, kind2) {
1428
+ const absolute = thresholdsFilePaths(location)[kind2];
1429
+ const path = relativeSlashPath(location.configDir, absolute);
1430
+ if (kind2 === "step" ? !location.steps : location.api === false) {
1431
+ return { status: "missing", kind: kind2, path, envlessFileExists: false };
1432
+ }
1433
+ let text;
1434
+ try {
1435
+ text = await readTextFile(absolute);
1436
+ } catch (error) {
1437
+ const reason = error instanceof Error ? error.message : String(error);
1438
+ return {
1439
+ status: "invalid",
1440
+ kind: kind2,
1441
+ path,
1442
+ issues: [
1443
+ {
1444
+ code: "SCHEMA_INVALID_JSON",
1445
+ source: path,
1446
+ message: `${path}: the file cannot be read (${reason})`,
1447
+ problems: []
1448
+ }
1449
+ ]
1450
+ };
1451
+ }
1452
+ if (text === null) {
1453
+ const envless = location.env !== null && await fileExists(
1454
+ resolvePath(
1455
+ resolvePath(location.configDir, location.dir),
1456
+ thresholdsFileName(location.filePrefix, kind2, null)
1457
+ )
1458
+ );
1459
+ return { status: "missing", kind: kind2, path, envlessFileExists: envless };
1460
+ }
1461
+ const parsed = parseThresholdsFile(text, path, kind2);
1462
+ if (!parsed.ok) return { status: "invalid", kind: kind2, path, issues: parsed.issues };
1463
+ const { file, migratedFrom } = parsed.value;
1464
+ return {
1465
+ status: "loaded",
1466
+ kind: kind2,
1467
+ path,
1468
+ file,
1469
+ ...migratedFrom === null ? {} : { migratedFrom }
1470
+ };
1471
+ }
1472
+ async function loadThresholds(location) {
1473
+ const files = await Promise.all(KINDS.map((kind2) => loadFile(location, kind2)));
1474
+ return Object.fromEntries(KINDS.map((kind2, i) => [kind2, files[i]]));
1475
+ }
1476
+
1477
+ // src/console/color.ts
1478
+ var ANSI = {
1479
+ green: "\x1B[32m",
1480
+ red: "\x1B[31m",
1481
+ yellow: "\x1B[33m",
1482
+ magenta: "\x1B[35m",
1483
+ cyan: "\x1B[36m",
1484
+ dim: "\x1B[2m",
1485
+ bold: "\x1B[1m",
1486
+ // Black on the light backgrounds, bright white on the dark ones.
1487
+ "badge-green": "\x1B[1;30;42m",
1488
+ "badge-yellow": "\x1B[1;30;43m",
1489
+ "badge-red": "\x1B[1;97;41m",
1490
+ "badge-magenta": "\x1B[1;97;45m"
1491
+ };
1492
+ var RESET = "\x1B[0m";
1493
+ function colorEnabled(stream, env) {
1494
+ if ((env.NO_COLOR ?? "") !== "") return false;
1495
+ const force = env.FORCE_COLOR;
1496
+ if (force !== void 0) return force !== "0";
1497
+ return stream.isTTY === true && env.TERM !== "dumb";
1498
+ }
1499
+ function paint(text, style, enabled) {
1500
+ return enabled && text !== "" ? `${ANSI[style]}${text}${RESET}` : text;
1501
+ }
1502
+ function painter(enabled) {
1503
+ return (text, style) => paint(text, style, enabled);
1504
+ }
1505
+
1506
+ // src/console/text.ts
1507
+ function compareText(a, b) {
1508
+ return a < b ? -1 : a > b ? 1 : 0;
1509
+ }
1510
+ function plural(n, word, many = `${word}s`) {
1511
+ return `${n} ${n === 1 ? word : many}`;
1512
+ }
1513
+ function truncateMiddle(text, width) {
1514
+ if (textWidth(text) <= width) return text;
1515
+ if (width <= 1) return "…".slice(0, width);
1516
+ const chars = clusters(text);
1517
+ const headRoom = Math.ceil((width - 1) / 2);
1518
+ const tailRoom = width - 1 - headRoom;
1519
+ let head = "";
1520
+ let used = 0;
1521
+ for (const c of chars) {
1522
+ if (used + c.width > headRoom) break;
1523
+ head += c.text;
1524
+ used += c.width;
1525
+ }
1526
+ let tail = "";
1527
+ used = 0;
1528
+ for (let i = chars.length - 1; i >= 0; i -= 1) {
1529
+ const c = chars[i];
1530
+ if (c === void 0 || used + c.width > tailRoom) break;
1531
+ tail = c.text + tail;
1532
+ used += c.width;
1533
+ }
1534
+ return `${head}…${tail}`;
1535
+ }
1536
+ var WIDE = [
1537
+ [8986, 8987],
1538
+ [9193, 9196],
1539
+ [9200, 9200],
1540
+ [9203, 9203],
1541
+ [9725, 9726],
1542
+ [9748, 9749],
1543
+ [9800, 9811],
1544
+ [9855, 9855],
1545
+ [9875, 9875],
1546
+ [9889, 9889],
1547
+ [9898, 9899],
1548
+ [9917, 9918],
1549
+ [9924, 9925],
1550
+ [9934, 9934],
1551
+ [9940, 9940],
1552
+ [9962, 9962],
1553
+ [9970, 9971],
1554
+ [9973, 9973],
1555
+ [9978, 9978],
1556
+ [9981, 9981],
1557
+ [9989, 9989],
1558
+ [9994, 9995],
1559
+ [10024, 10024],
1560
+ [10060, 10060],
1561
+ [10062, 10062],
1562
+ [10067, 10069],
1563
+ [10071, 10071],
1564
+ [10133, 10135],
1565
+ [10160, 10160],
1566
+ [10175, 10175],
1567
+ [11035, 11036],
1568
+ [11088, 11088],
1569
+ [11093, 11093],
1570
+ [127744, 129791]
1571
+ ];
1572
+ var ZERO = [
1573
+ [768, 879],
1574
+ [8203, 8205],
1575
+ [8400, 8447],
1576
+ [65024, 65039],
1577
+ [127995, 127999],
1578
+ [917760, 917999]
1579
+ ];
1580
+ var VS16 = 65039;
1581
+ var ZWJ = 8205;
1582
+ function inRanges(cp, ranges) {
1583
+ return ranges.some(([from, to]) => cp >= from && cp <= to);
1584
+ }
1585
+ function charWidth(char) {
1586
+ const cp = char.codePointAt(0) ?? 0;
1587
+ if (inRanges(cp, ZERO)) return 0;
1588
+ return inRanges(cp, WIDE) ? 2 : 1;
1589
+ }
1590
+ function clusters(text) {
1591
+ const out = [];
1592
+ let joined = false;
1593
+ for (const char of text) {
1594
+ const cp = char.codePointAt(0) ?? 0;
1595
+ const last = out[out.length - 1];
1596
+ if (last !== void 0 && (joined || charWidth(char) === 0)) {
1597
+ last.text += char;
1598
+ if (cp === VS16) last.width = 2;
1599
+ joined = cp === ZWJ;
1600
+ continue;
1601
+ }
1602
+ out.push({ text: char, width: charWidth(char) });
1603
+ joined = false;
1604
+ }
1605
+ return out;
1606
+ }
1607
+ function textWidth(text) {
1608
+ return clusters(text).reduce((sum2, c) => sum2 + c.width, 0);
1609
+ }
1610
+ function padEnd(text, width) {
1611
+ return text + " ".repeat(Math.max(0, width - textWidth(text)));
1612
+ }
1613
+ function padStart(text, width) {
1614
+ return " ".repeat(Math.max(0, width - textWidth(text))) + text;
1615
+ }
1616
+
1617
+ // src/console/box.ts
1618
+ function asciiTerminal(env) {
1619
+ return env.TERM === "dumb";
1620
+ }
1621
+ function marks(ascii) {
1622
+ return ascii ? { ok: "✔", warn: "!", error: "✖" } : { ok: "✅", warn: "⚠", error: "❌" };
1623
+ }
1624
+ function cellsOf(line) {
1625
+ const spans = line.spans ?? [{ text: line.text ?? "", style: line.style }];
1626
+ const cells = [];
1627
+ for (const span of spans) {
1628
+ for (const c of clusters(span.text))
1629
+ cells.push({ char: c.text, style: span.style, width: c.width });
1630
+ }
1631
+ return cells;
1632
+ }
1633
+ function widthOf(cells) {
1634
+ return cells.reduce((sum2, c) => sum2 + c.width, 0);
1635
+ }
1636
+ function cutCells(cells, width) {
1637
+ if (widthOf(cells) <= width) return cells;
1638
+ const out = [];
1639
+ let used = 0;
1640
+ for (const cell of cells) {
1641
+ if (used + cell.width > width - 1) break;
1642
+ out.push(cell);
1643
+ used += cell.width;
1644
+ }
1645
+ out.push({ char: "…", style: out[out.length - 1]?.style, width: 1 });
1646
+ return out;
1647
+ }
1648
+ function wrapCells(cells, width, indent) {
1649
+ const lines = [];
1650
+ const pad = Array.from({ length: indent }, () => ({
1651
+ char: " ",
1652
+ style: void 0,
1653
+ width: 1
1654
+ }));
1655
+ let rest = cells;
1656
+ for (let first2 = true; ; first2 = false) {
1657
+ const room = Math.max(1, first2 ? width : width - indent);
1658
+ let used = 0;
1659
+ let i = 0;
1660
+ let space = -1;
1661
+ while (i < rest.length && used + (rest[i]?.width ?? 0) <= room) {
1662
+ if (rest[i]?.char === " ") space = i;
1663
+ used += rest[i]?.width ?? 0;
1664
+ i += 1;
1665
+ }
1666
+ const lead = first2 ? [] : pad;
1667
+ if (i >= rest.length) {
1668
+ lines.push([...lead, ...rest]);
1669
+ return lines;
1670
+ }
1671
+ const cut = rest[i]?.char === " " ? i : space > 0 ? space : Math.max(1, i);
1672
+ lines.push([...lead, ...rest.slice(0, cut)]);
1673
+ rest = rest.slice(cut);
1674
+ while (rest[0]?.char === " ") rest = rest.slice(1);
1675
+ if (rest.length === 0) return lines;
1676
+ }
1677
+ }
1678
+ function render(cells, color) {
1679
+ let out = "";
1680
+ let run = "";
1681
+ let style;
1682
+ const flush = () => {
1683
+ out += style === void 0 ? run : paint(run, style, color);
1684
+ run = "";
1685
+ };
1686
+ for (const cell of cells) {
1687
+ if (cell.style !== style) {
1688
+ flush();
1689
+ style = cell.style;
1690
+ }
1691
+ run += cell.char;
1692
+ }
1693
+ flush();
1694
+ return out;
1695
+ }
1696
+ function boxLines(lines, opts) {
1697
+ const g = opts.ascii ? { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" } : { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│" };
1698
+ const all = lines.map(cellsOf);
1699
+ const title = opts.title ?? "";
1700
+ const titleWidth = title === "" ? 0 : textWidth(title) + 3;
1701
+ const longest = Math.max(titleWidth, ...all.map(widthOf));
1702
+ const inner = Math.max(1, Math.min(longest, opts.width - 4));
1703
+ const border = (text) => paint(text, opts.border, opts.color);
1704
+ const top = title === "" ? border(`${g.tl}${g.h.repeat(inner + 2)}${g.tr}`) : `${border(`${g.tl}${g.h} `)}${paint(title, "bold", opts.color)}${border(
1705
+ ` ${g.h.repeat(Math.max(0, inner + 2 - titleWidth))}${g.tr}`
1706
+ )}`;
1707
+ const out = [top];
1708
+ all.forEach((cells, index) => {
1709
+ const parts = opts.wrap === true ? wrapCells(cells, inner, lines[index]?.indent ?? 0) : [cutCells(cells, inner)];
1710
+ for (const part of parts) {
1711
+ const fill = " ".repeat(Math.max(0, inner - widthOf(part)));
1712
+ out.push(`${border(g.v)} ${render(part, opts.color)}${fill} ${border(g.v)}`);
1713
+ }
1714
+ });
1715
+ out.push(border(`${g.bl}${g.h.repeat(inner + 2)}${g.br}`));
1716
+ return out;
1717
+ }
1718
+ function box(lines, opts) {
1719
+ return `${boxLines(lines, opts).join("\n")}
1720
+ `;
1721
+ }
1722
+ function cutText(text, width) {
1723
+ if (textWidth(text) <= width) return text;
1724
+ let out = "";
1725
+ let used = 0;
1726
+ for (const c of clusters(text)) {
1727
+ if (used + c.width > width - 1) break;
1728
+ out += c.text;
1729
+ used += c.width;
1730
+ }
1731
+ return `${out}…`;
1732
+ }
1733
+ function table(columns, rows, opts) {
1734
+ const g = opts.ascii ? { v: "|", h: "-", top: ["+", "+", "+"], mid: ["+", "+", "+"], bottom: ["+", "+", "+"] } : { v: "│", h: "─", top: ["┌", "┬", "┐"], mid: ["├", "┼", "┤"], bottom: ["└", "┴", "┘"] };
1735
+ const header = opts.header !== false;
1736
+ const natural = columns.map(
1737
+ (c, i) => Math.max(header ? textWidth(c.header) : 0, ...rows.map((r) => textWidth(r.cells[i] ?? "")))
1738
+ );
1739
+ const overhead = 3 * columns.length + 1;
1740
+ const widths = columns.map((c, i) => {
1741
+ if (c.flex !== true) return natural[i] ?? 0;
1742
+ const others = natural.reduce((sum2, w, j) => j === i ? sum2 : sum2 + w, 0);
1743
+ return Math.max(c.minWidth ?? 1, Math.min(natural[i] ?? 0, opts.width - overhead - others));
1744
+ });
1745
+ let title = opts.title ?? "";
1746
+ if (title !== "") {
1747
+ const inner = () => widths.reduce((sum2, w) => sum2 + w + 3, -1);
1748
+ const room = Math.max(1, opts.width - 2 - 4);
1749
+ title = cutText(title, room);
1750
+ const need = textWidth(title) + 4 - inner();
1751
+ const last = widths.length - 1;
1752
+ if (need > 0 && last >= 0) widths[last] = (widths[last] ?? 0) + need;
1753
+ }
1754
+ const border = opts.border ?? "dim";
1755
+ const edge = (text) => paint(text, border, opts.color);
1756
+ const ruleText = ([left, cross, right]) => `${left}${widths.map((w) => g.h.repeat(w + 2)).join(cross)}${right}`;
1757
+ const rule = (marks2) => edge(ruleText(marks2));
1758
+ const top = () => {
1759
+ if (title === "") return rule(g.top);
1760
+ const rest = ruleText(g.top).slice(textWidth(title) + 4);
1761
+ return `${edge(`${g.top[0] ?? ""}${g.h} `)}${paint(title, "bold", opts.color)}${edge(` ${rest}`)}`;
1762
+ };
1763
+ const line = (cells, style, cellStyles = []) => {
1764
+ const texts = columns.map((c, i) => {
1765
+ const w = widths[i] ?? 0;
1766
+ const raw = cells[i] ?? "";
1767
+ const text = c.flex === true ? truncateMiddle(raw, w) : raw;
1768
+ const padded = c.align === "right" ? padStart(text, w) : padEnd(text, w);
1769
+ const cellStyle = cellStyles[i] ?? style ?? c.style;
1770
+ return cellStyle === void 0 ? padded : paint(padded, cellStyle, opts.color);
1771
+ });
1772
+ return `${edge(g.v)} ${texts.join(` ${edge(g.v)} `)} ${edge(g.v)}`;
1773
+ };
1774
+ return [
1775
+ top(),
1776
+ ...header ? [
1777
+ line(
1778
+ columns.map((c) => c.header),
1779
+ "bold"
1780
+ ),
1781
+ rule(g.mid)
1782
+ ] : [],
1783
+ ...rows.map((r) => line(r.cells, r.style, r.cellStyles)),
1784
+ rule(g.bottom)
1785
+ ];
1786
+ }
1787
+
1788
+ export { SCHEMA_VERSIONS, asciiTerminal, box, boxLines, ceilTo, colorEnabled, compareText, directoryOf, emptyDirSync, exceedance, floorTo, formatActual, formatFactor, formatLimit, formatMs, homeDir, isDirectorySync, listDirSync, loadThresholds, marks, overText, padEnd, paint, painter, parseRunReport, parseSampleBatch, plural, readCiInfo, readHostInfo, readPackageInfo, readSuite, readTextFile, readTextFileSync, realPathSync, relativeSlashPath, removeFileSync, resolvePath, roundMs, roundRatio, runPass, scanDirSync, schemaIssueToIssue, stringifyStable, table, tempPath, textWidth, thresholdsFilePaths, truncateMiddle, writeJsonStable, writeTextAtomic };