playwright-performance-regression 0.1.0-next.1 → 0.1.0-next.4

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 (41) hide show
  1. package/CHANGELOG.md +431 -0
  2. package/README.md +96 -64
  3. package/dist/{chunk-L5C63HEF.js → chunk-CISGJCFW.js} +378 -48
  4. package/dist/chunk-CXE5IWZY.js +1648 -0
  5. package/dist/{chunk-B64P2D5A.js → chunk-E2IX265O.js} +395 -206
  6. package/dist/chunk-IUI4AFE5.cjs +658 -0
  7. package/dist/{chunk-WZVQK7CQ.cjs → chunk-KELMALEG.cjs} +408 -218
  8. package/dist/{chunk-GCA73FFP.cjs → chunk-LUA4WRIQ.cjs} +382 -47
  9. package/dist/chunk-RL27E3AB.js +595 -0
  10. package/dist/{chunk-DYLCGMI2.js → chunk-S6UH6QPK.js} +6 -1
  11. package/dist/cli.js +2761 -2339
  12. package/dist/config.cjs +122 -137
  13. package/dist/config.d.cts +3 -2
  14. package/dist/config.d.ts +3 -2
  15. package/dist/config.js +117 -132
  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 +121 -25
  22. package/dist/index.d.ts +121 -25
  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 +5713 -1237
  27. package/dist/reporter.js +6905 -693
  28. package/dist/test.cjs +4 -4
  29. package/dist/test.js +4 -4
  30. package/package.json +19 -1
  31. package/schemas/common.schema.json +2 -2
  32. package/schemas/config.schema.json +72 -26
  33. package/schemas/outcome.schema.json +2 -2
  34. package/schemas/run-report.schema.json +549 -20
  35. package/schemas/samples.schema.json +48 -37
  36. package/schemas/thresholds.schema.json +1 -1
  37. package/dist/chunk-3CLCMD2Q.js +0 -3411
  38. package/dist/chunk-4SFI55HF.cjs +0 -319
  39. package/dist/chunk-HBGADXLP.js +0 -254
  40. package/dist/perf-api-V4PeHVE0.d.cts +0 -22
  41. package/dist/perf-api-V4PeHVE0.d.ts +0 -22
@@ -1,3411 +0,0 @@
1
- import { CONTEXT_CLOSED_FAILURE_TEXT, PACKAGE_NAME, CLI_COMMAND, DIFF_CATEGORIES, diffCountsText, LISTED_CATEGORIES, diffValuesText, diffMarker, REPOSITORY_URL, LIMIT_NAMES, diffChangeText } from './chunk-HBGADXLP.js';
2
- import { str, nullable, constant, obj, bool, msOrNull, epochMs, enumOf, oneOf, int, nul, num, arr, issue, isoDate, ratio, msLimit, fingerprint, hostFingerprint, derivationSettings, percentileName, count, timestamp, runId, envLabelOrNull, tool, kind, record, key, anyObject, ms, packageConfig, mode, evaluationStatus, testsStatus, isRecord, Sink, child } from './chunk-L5C63HEF.js';
3
- import { readFile, access, mkdir, writeFile, rename, rm } from 'fs/promises';
4
- import { resolve, dirname, relative, isAbsolute, join, basename } from 'path';
5
- import { randomUUID } from 'crypto';
6
- import { cpus, availableParallelism } from 'os';
7
-
8
- function isNotFound(error) {
9
- return typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
10
- }
11
- async function readTextFile(path) {
12
- try {
13
- return await readFile(path, "utf8");
14
- } catch (error) {
15
- if (isNotFound(error)) return null;
16
- throw error;
17
- }
18
- }
19
- async function fileExists(path) {
20
- try {
21
- await access(path);
22
- return true;
23
- } catch {
24
- return false;
25
- }
26
- }
27
- function resolvePath(base, path) {
28
- return resolve(base, path);
29
- }
30
- function directoryOf(path) {
31
- return dirname(path);
32
- }
33
- function relativeSlashPath(from, path) {
34
- const rel = relative(from, path);
35
- const shown = rel === "" ? "." : isAbsolute(rel) ? path : rel;
36
- return shown.replaceAll("\\", "/");
37
- }
38
-
39
- // src/core/format/round.ts
40
- function roundRatio(x) {
41
- return Math.round(x * 1e4) / 1e4 + 0;
42
- }
43
- function roundMs(x) {
44
- return Math.round(x * 10) / 10;
45
- }
46
- function snap(x, digits) {
47
- return Math.round(x * 10 ** (digits + 6)) / 1e6;
48
- }
49
- function ceilTo(x, digits) {
50
- return Math.ceil(snap(x, digits)) / 10 ** digits;
51
- }
52
- function floorTo(x, digits) {
53
- return Math.floor(snap(x, digits)) / 10 ** digits;
54
- }
55
-
56
- // src/core/format/json.ts
57
- var INDENT = " ";
58
- function fail(pointer, what) {
59
- throw new TypeError(
60
- `stringifyStable: value at "${pointer}" is ${what}, which cannot be written to JSON`
61
- );
62
- }
63
- function isPlainObject(value) {
64
- const proto = Object.getPrototypeOf(value);
65
- return proto === Object.prototype || proto === null;
66
- }
67
- function escapePointer(key2) {
68
- return key2.replaceAll("~", "~0").replaceAll("/", "~1");
69
- }
70
- function write(value, pointer, indent, ancestors) {
71
- switch (typeof value) {
72
- case "string":
73
- case "boolean":
74
- return JSON.stringify(value);
75
- case "number":
76
- if (!Number.isFinite(value)) fail(pointer, String(value));
77
- return JSON.stringify(value);
78
- case "undefined":
79
- return fail(pointer, "undefined");
80
- case "object":
81
- break;
82
- default:
83
- return fail(pointer, typeof value);
84
- }
85
- if (value === null) return "null";
86
- if (ancestors.has(value)) fail(pointer, "a circular reference");
87
- const inner = indent + INDENT;
88
- ancestors.add(value);
89
- let text;
90
- if (Array.isArray(value)) {
91
- const items = value.map((item, i) => inner + write(item, `${pointer}/${i}`, inner, ancestors));
92
- text = items.length === 0 ? "[]" : `[
93
- ${items.join(",\n")}
94
- ${indent}]`;
95
- } else {
96
- if (!isPlainObject(value)) fail(pointer, "not a plain object");
97
- const record2 = value;
98
- const keys = Object.keys(record2).filter((key2) => record2[key2] !== void 0).sort();
99
- const entries = keys.map(
100
- (key2) => `${inner}${JSON.stringify(key2)}: ${write(record2[key2], `${pointer}/${escapePointer(key2)}`, inner, ancestors)}`
101
- );
102
- text = entries.length === 0 ? "{}" : `{
103
- ${entries.join(",\n")}
104
- ${indent}}`;
105
- }
106
- ancestors.delete(value);
107
- return text;
108
- }
109
- function stringifyStable(value) {
110
- return `${write(value, "", "", /* @__PURE__ */ new Set())}
111
- `;
112
- }
113
-
114
- // src/io/json.ts
115
- async function writeTextAtomic(path, text) {
116
- const dir = dirname(path);
117
- await mkdir(dir, { recursive: true });
118
- const temp = join(dir, `.${basename(path)}.${randomUUID()}.tmp`);
119
- try {
120
- await writeFile(temp, text, "utf8");
121
- await rename(temp, path);
122
- } catch (error) {
123
- await rm(temp, { force: true });
124
- throw error;
125
- }
126
- }
127
- async function writeJsonStable(path, value) {
128
- await writeTextAtomic(path, stringifyStable(value));
129
- }
130
- function read(env, name) {
131
- const value = env[name];
132
- return value === void 0 || value === "" ? null : value;
133
- }
134
- function first(env, ...names) {
135
- for (const name of names) {
136
- const value = read(env, name);
137
- if (value !== null) return value;
138
- }
139
- return null;
140
- }
141
- function compose(env, build, ...names) {
142
- const values = names.map((name) => read(env, name));
143
- return values.every((v) => v !== null) ? build(values) : null;
144
- }
145
- function readCiInfo(env) {
146
- if (env.GITHUB_ACTIONS === "true") {
147
- return {
148
- provider: "github",
149
- commit: read(env, "GITHUB_SHA"),
150
- branch: first(env, "GITHUB_HEAD_REF", "GITHUB_REF_NAME"),
151
- buildUrl: compose(
152
- env,
153
- ([server, repository, runId2]) => `${server}/${repository}/actions/runs/${runId2}`,
154
- "GITHUB_SERVER_URL",
155
- "GITHUB_REPOSITORY",
156
- "GITHUB_RUN_ID"
157
- )
158
- };
159
- }
160
- if (env.GITLAB_CI === "true") {
161
- return {
162
- provider: "gitlab",
163
- commit: read(env, "CI_COMMIT_SHA"),
164
- branch: read(env, "CI_COMMIT_REF_NAME"),
165
- buildUrl: read(env, "CI_JOB_URL")
166
- };
167
- }
168
- if (read(env, "JENKINS_URL") !== null) {
169
- return {
170
- provider: "jenkins",
171
- commit: read(env, "GIT_COMMIT"),
172
- branch: first(env, "BRANCH_NAME", "GIT_BRANCH"),
173
- buildUrl: read(env, "BUILD_URL")
174
- };
175
- }
176
- if (env.TF_BUILD === "True") {
177
- return {
178
- provider: "azure",
179
- commit: read(env, "BUILD_SOURCEVERSION"),
180
- branch: read(env, "BUILD_SOURCEBRANCHNAME"),
181
- buildUrl: compose(
182
- env,
183
- ([collection, project, buildId]) => `${collection}${project}/_build/results?buildId=${buildId}`,
184
- "SYSTEM_COLLECTIONURI",
185
- "SYSTEM_TEAMPROJECT",
186
- "BUILD_BUILDID"
187
- )
188
- };
189
- }
190
- if (read(env, "CI") !== null)
191
- return { provider: "other", commit: null, branch: null, buildUrl: null };
192
- return null;
193
- }
194
- function readHostInfo(env) {
195
- return {
196
- platform: process.platform,
197
- arch: process.arch,
198
- nodeVersion: process.version,
199
- ci: read(env, "CI") !== null,
200
- cpuCount: availableParallelism(),
201
- cpuModel: cpus()[0]?.model.trim() ?? ""
202
- };
203
- }
204
-
205
- // src/core/schema/formats.ts
206
- var nonEmpty = str({ minLength: 1 });
207
- var nonEmptyOrNull = nullable(nonEmpty);
208
- function present(value, pointer, sink, properties) {
209
- for (const [name, schema] of Object.entries(properties)) {
210
- if (Object.hasOwn(value, name)) schema.check(value[name], `${pointer}/${name}`, sink);
211
- }
212
- }
213
- var noTiming = {
214
- duration: nul,
215
- requestStart: nul,
216
- ttfb: nul,
217
- timeSource: constant("browser"),
218
- fromServiceWorker: constant(false)
219
- };
220
- var requestSample = obj(
221
- {
222
- method: str({ pattern: /^[A-Z]+$/u }),
223
- url: nonEmpty,
224
- resourceType: nonEmpty,
225
- status: oneOf(int({ minimum: 100, maximum: 599 }), constant("FAILED"), constant("PENDING")),
226
- failureText: nonEmpty,
227
- startTime: epochMs,
228
- duration: msOrNull,
229
- requestStart: msOrNull,
230
- ttfb: msOrNull,
231
- timeSource: enumOf(["browser", "node"]),
232
- fromServiceWorker: bool
233
- },
234
- {
235
- required: [
236
- "method",
237
- "url",
238
- "resourceType",
239
- "status",
240
- "startTime",
241
- "duration",
242
- "requestStart",
243
- "ttfb",
244
- "timeSource",
245
- "fromServiceWorker"
246
- ],
247
- refine(value, pointer, sink) {
248
- const status = Object.hasOwn(value, "status") ? value.status : "FAILED";
249
- if (status === "FAILED" && !Object.hasOwn(value, "failureText")) {
250
- sink.add(pointer, "must have required property 'failureText' when status is FAILED");
251
- }
252
- if (status !== "FAILED" && Object.hasOwn(value, "failureText")) {
253
- sink.add(`${pointer}/failureText`, "must NOT be present unless status is FAILED");
254
- }
255
- if (status === "FAILED" || status === "PENDING" || !Object.hasOwn(value, "status")) {
256
- present(value, pointer, sink, noTiming);
257
- }
258
- }
259
- }
260
- );
261
- var customSample = obj(
262
- {
263
- name: str({
264
- minLength: 1,
265
- maxLength: 200,
266
- // Same pattern as the schema: no control characters (06-REQ-03).
267
- // eslint-disable-next-line no-control-regex
268
- pattern: /^[^\s\u0000-\u001F\u007F](?:[^\u0000-\u001F\u007F]*[^\s\u0000-\u001F\u007F])?$/u
269
- }),
270
- outcome: enumOf(["ok", "error", "unfinished"]),
271
- duration: msOrNull,
272
- endTime: oneOf(epochMs, nul)
273
- },
274
- {
275
- required: ["name", "outcome", "duration", "endTime"],
276
- refine(value, pointer, sink) {
277
- const unfinished = !Object.hasOwn(value, "outcome") || value.outcome === "unfinished";
278
- present(
279
- value,
280
- pointer,
281
- sink,
282
- unfinished ? { duration: nul, endTime: nul } : { duration: num(), endTime: int() }
283
- );
284
- }
285
- }
286
- );
287
- var sampleBatch = obj(
288
- {
289
- schemaVersion: constant(1),
290
- collector: obj(
291
- {
292
- name: str({ pattern: /^[a-z0-9-]+$/u }),
293
- version: nonEmpty,
294
- browserName: nonEmptyOrNull
295
- },
296
- { required: ["name", "version", "browserName"] }
297
- ),
298
- requests: arr(requestSample),
299
- custom: arr(customSample),
300
- diagnostics: arr(issue)
301
- },
302
- { required: ["schemaVersion", "collector", "requests", "custom", "diagnostics"] }
303
- );
304
- var LIMIT_FIELDS = ["t", "median", "percentile", "p99", "minApdex", "maxWilson", "maxErrorRate"];
305
- var thresholdsEntry = obj(
306
- {
307
- t: nullable(msLimit),
308
- median: msLimit,
309
- percentile: msLimit,
310
- p99: msLimit,
311
- minApdex: nullable(ratio),
312
- maxWilson: nullable(ratio),
313
- maxErrorRate: ratio,
314
- locked: constant(true),
315
- note: str({ minLength: 1, maxLength: 500 }),
316
- gate: constant("warn"),
317
- until: isoDate
318
- },
319
- {
320
- refine(value, pointer, sink) {
321
- if (![...LIMIT_FIELDS, "gate"].some((name) => Object.hasOwn(value, name))) {
322
- sink.add(pointer, "must have at least one limit or gate");
323
- }
324
- if (Object.hasOwn(value, "gate")) {
325
- for (const name of ["note", "until"]) {
326
- if (!Object.hasOwn(value, name)) {
327
- sink.add(pointer, `must have property '${name}' when property 'gate' is present`);
328
- }
329
- }
330
- }
331
- if (Object.hasOwn(value, "until") && !Object.hasOwn(value, "gate")) {
332
- sink.add(pointer, "must have property 'gate' when property 'until' is present");
333
- }
334
- }
335
- }
336
- );
337
- var thresholdsGenerated = obj(
338
- {
339
- tool,
340
- env: envLabelOrNull,
341
- sourceRunId: runId,
342
- sourceRunStartedAt: timestamp,
343
- sourceSampleCount: count,
344
- evaluatedPercentile: percentileName,
345
- derivation: derivationSettings,
346
- browsers: arr(nonEmpty, { uniqueItems: true }),
347
- playwrightVersion: nonEmpty,
348
- host: hostFingerprint,
349
- normalization: fingerprint
350
- },
351
- {
352
- required: [
353
- "tool",
354
- "env",
355
- "sourceRunId",
356
- "sourceRunStartedAt",
357
- "sourceSampleCount",
358
- "evaluatedPercentile",
359
- "derivation",
360
- "browsers",
361
- "playwrightVersion",
362
- "host",
363
- "normalization"
364
- ]
365
- }
366
- );
367
- var thresholdsFile = obj(
368
- {
369
- schemaVersion: constant(1),
370
- kind,
371
- generated: oneOf(thresholdsGenerated, nul),
372
- entries: record(key, thresholdsEntry)
373
- },
374
- { required: ["schemaVersion", "kind", "generated", "entries"] }
375
- );
376
- var evaluationCounts = obj(
377
- Object.fromEntries(
378
- [
379
- "keys",
380
- "fromFile",
381
- "fromDefaults",
382
- "notEvaluated",
383
- "tooFewSamples",
384
- "fileEntriesNotEvaluated",
385
- "medianOnly",
386
- "unseenThresholdEntries",
387
- "violations",
388
- "blockingViolations",
389
- "muted"
390
- ].map((name) => [name, count])
391
- ),
392
- {
393
- required: [
394
- "keys",
395
- "fromFile",
396
- "fromDefaults",
397
- "notEvaluated",
398
- "tooFewSamples",
399
- "fileEntriesNotEvaluated",
400
- "medianOnly",
401
- "unseenThresholdEntries",
402
- "violations",
403
- "blockingViolations",
404
- "muted"
405
- ]
406
- }
407
- );
408
- var thresholdFileInfo = obj(
409
- {
410
- kind,
411
- path: nonEmpty,
412
- status: enumOf(["loaded", "missing", "invalid"]),
413
- generated: oneOf(anyObject, nul),
414
- unseenKeys: arr(key)
415
- },
416
- { required: ["kind", "path", "status", "generated", "unseenKeys"] }
417
- );
418
- var testRef = obj(
419
- {
420
- title: str(),
421
- project: str(),
422
- file: str(),
423
- line: int({ minimum: 1 }),
424
- repeatEachIndex: int({ minimum: 0 })
425
- },
426
- { required: ["title", "project", "file", "line", "repeatEachIndex"] }
427
- );
428
- var slowSample = obj(
429
- { duration: ms, startedAt: timestamp, test: testRef, url: nonEmpty },
430
- { required: ["duration", "startedAt", "test"] }
431
- );
432
- var stats = obj(
433
- {
434
- min: ms,
435
- avg: ms,
436
- max: ms,
437
- percentiles: record(percentileName, ms, { required: ["p50", "p90", "p95", "p99"] })
438
- },
439
- { required: ["min", "avg", "max", "percentiles"] }
440
- );
441
- var check = obj(
442
- {
443
- rule: enumOf(["median", "percentile", "p99", "apdex", "wilson", "errors"]),
444
- n: int({ minimum: 1 }),
445
- actual: num({ minimum: 0 }),
446
- observed: oneOf(num({ minimum: 0, maximum: 1 }), nul),
447
- limit: num({ minimum: 0 }),
448
- passed: bool,
449
- hardLimitExceeded: bool,
450
- blocking: bool
451
- },
452
- {
453
- required: [
454
- "rule",
455
- "n",
456
- "actual",
457
- "observed",
458
- "limit",
459
- "passed",
460
- "hardLimitExceeded",
461
- "blocking"
462
- ]
463
- }
464
- );
465
- var keyEvaluation = obj(
466
- {
467
- result: enumOf(["pass", "fail", "not-evaluated"]),
468
- reason: oneOf(enumOf(["too-few-samples", "no-rules", "thresholds-error"]), nul),
469
- thresholdSource: enumOf(["file", "default"]),
470
- limits: obj(
471
- {
472
- t: nullable(msLimit),
473
- median: msLimit,
474
- percentile: msLimit,
475
- p99: msLimit,
476
- minApdex: nullable(ratio),
477
- maxWilson: nullable(ratio),
478
- maxErrorRate: ratio
479
- },
480
- { required: LIMIT_FIELDS }
481
- ),
482
- checks: arr(check),
483
- muted: oneOf(
484
- obj(
485
- { until: isoDate, note: nonEmpty, expired: bool },
486
- { required: ["until", "note", "expired"] }
487
- ),
488
- nul
489
- )
490
- },
491
- { required: ["result", "reason", "thresholdSource", "limits", "checks", "muted"] }
492
- );
493
- var aggregate = obj(
494
- {
495
- count,
496
- successCount: count,
497
- errorCount: count,
498
- fromFailedTests: count,
499
- testCount: count,
500
- statuses: record(
501
- str({ pattern: /^(?:[1-5][0-9]{2}|FAILED|ABORTED|PENDING|ok|error|unfinished)$/u }),
502
- int({ minimum: 1 })
503
- ),
504
- timeSources: obj({ browser: count, node: count }, { required: ["browser", "node"] }),
505
- stats: oneOf(stats, nul),
506
- ttfb: oneOf(obj({ p50: ms, p95: ms }, { required: ["p50", "p95"] }), nul),
507
- slowest: arr(slowSample, { maxItems: 3 }),
508
- topTests: arr(
509
- obj(
510
- {
511
- title: str(),
512
- project: str(),
513
- file: str(),
514
- line: int({ minimum: 1 }),
515
- sampleCount: int({ minimum: 1 })
516
- },
517
- { required: ["title", "project", "file", "line", "sampleCount"] }
518
- ),
519
- { maxItems: 5 }
520
- ),
521
- samples: obj({ durations: arr(ms), sampled: bool }, { required: ["durations", "sampled"] }),
522
- evaluation: keyEvaluation
523
- },
524
- {
525
- required: [
526
- "count",
527
- "successCount",
528
- "errorCount",
529
- "fromFailedTests",
530
- "testCount",
531
- "statuses",
532
- "timeSources",
533
- "stats",
534
- "ttfb",
535
- "slowest",
536
- "topTests",
537
- "samples",
538
- "evaluation"
539
- ]
540
- }
541
- );
542
- var runReport = obj(
543
- {
544
- schemaVersion: constant(1),
545
- tool,
546
- runId,
547
- mode,
548
- startedAt: timestamp,
549
- finishedAt: timestamp,
550
- env: envLabelOrNull,
551
- configDir: nonEmpty,
552
- config: packageConfig,
553
- normalization: fingerprint,
554
- ci: oneOf(
555
- obj(
556
- {
557
- provider: enumOf(["github", "gitlab", "jenkins", "azure", "other"]),
558
- commit: nonEmptyOrNull,
559
- branch: nonEmptyOrNull,
560
- buildUrl: nonEmptyOrNull
561
- },
562
- { required: ["provider", "commit", "branch", "buildUrl"] }
563
- ),
564
- nul
565
- ),
566
- host: obj(
567
- {
568
- platform: str(),
569
- arch: str(),
570
- nodeVersion: str(),
571
- ci: bool,
572
- cpuCount: int({ minimum: 1 }),
573
- cpuModel: str()
574
- },
575
- { required: ["platform", "arch", "nodeVersion", "ci", "cpuCount", "cpuModel"] }
576
- ),
577
- playwright: obj({ version: str() }, { required: ["version"] }),
578
- runConditions: obj(
579
- {
580
- workers: int({ minimum: 1 }),
581
- projects: arr(
582
- obj(
583
- {
584
- name: str(),
585
- role: enumOf(["measured", "dependency", "teardown"]),
586
- browserName: oneOf(str(), nul),
587
- repeatEach: int({ minimum: 1 }),
588
- retries: int({ minimum: 0 })
589
- },
590
- { required: ["name", "role", "browserName", "repeatEach", "retries"] }
591
- )
592
- ),
593
- overriddenSettings: arr(str())
594
- },
595
- { required: ["workers", "projects", "overriddenSettings"] }
596
- ),
597
- tests: obj(
598
- {
599
- status: testsStatus,
600
- expected: count,
601
- unexpected: count,
602
- flaky: count,
603
- skipped: count
604
- },
605
- { required: ["status", "expected", "unexpected", "flaky", "skipped"] }
606
- ),
607
- evaluation: obj(
608
- {
609
- status: evaluationStatus,
610
- gateEnabled: bool,
611
- counts: obj(
612
- { api: evaluationCounts, custom: evaluationCounts },
613
- { required: ["api", "custom"] }
614
- )
615
- },
616
- { required: ["status", "gateEnabled", "counts"] }
617
- ),
618
- thresholdFiles: arr(thresholdFileInfo),
619
- warnings: arr(issue),
620
- toolErrors: arr(issue),
621
- origins: arr(
622
- obj(
623
- { origin: nonEmpty, label: str(), requestCount: count },
624
- { required: ["origin", "label", "requestCount"] }
625
- )
626
- ),
627
- endpoints: record(key, aggregate),
628
- custom: record(key, aggregate)
629
- },
630
- {
631
- required: [
632
- "schemaVersion",
633
- "tool",
634
- "runId",
635
- "mode",
636
- "startedAt",
637
- "finishedAt",
638
- "env",
639
- "configDir",
640
- "config",
641
- "normalization",
642
- "ci",
643
- "host",
644
- "playwright",
645
- "runConditions",
646
- "tests",
647
- "evaluation",
648
- "thresholdFiles",
649
- "warnings",
650
- "toolErrors",
651
- "origins",
652
- "endpoints",
653
- "custom"
654
- ]
655
- }
656
- );
657
- var outcomeFile = obj(
658
- {
659
- schemaVersion: constant(1),
660
- runId,
661
- mode,
662
- exitCode: enumOf([0, 2, 3]),
663
- tests: obj({ status: testsStatus }, { required: ["status"] }),
664
- evaluation: obj(
665
- { status: evaluationStatus, gateEnabled: bool },
666
- { required: ["status", "gateEnabled"] }
667
- ),
668
- toolErrors: arr(issue),
669
- paths: obj(
670
- {
671
- reportJson: nonEmptyOrNull,
672
- reportHtml: nonEmptyOrNull,
673
- thresholds: arr(nonEmpty),
674
- thresholdsDiff: nonEmptyOrNull
675
- },
676
- { required: ["reportJson", "reportHtml", "thresholds", "thresholdsDiff"] }
677
- )
678
- },
679
- {
680
- required: [
681
- "schemaVersion",
682
- "runId",
683
- "mode",
684
- "exitCode",
685
- "tests",
686
- "evaluation",
687
- "toolErrors",
688
- "paths"
689
- ]
690
- }
691
- );
692
-
693
- // src/core/schema/parse.ts
694
- var MAX_PROBLEMS = 5;
695
- var SCHEMA_VERSIONS = {
696
- samples: 1,
697
- runReport: 1,
698
- thresholds: 1,
699
- outcome: 1
700
- };
701
- var HINTS = {
702
- SCHEMA_INVALID_JSON: "Fix the JSON syntax, or delete the file and let the package write it again.",
703
- SCHEMA_VERSION_MISSING: 'Add the "schemaVersion" of the format at the top level, or let the package write the file again.',
704
- SCHEMA_VERSION_TOO_NEW: "The file was written by a newer version of the package; update the package to read it.",
705
- SCHEMA_VERSION_MISMATCH: "The attachment was written by another version of the package; use one package version in a run.",
706
- SCHEMA_VALIDATION_FAILED: "Fix the listed fields; the JSON Schemas in the package's schemas/ directory describe the format.",
707
- THRESHOLDS_KIND_MISMATCH: 'Each kind has its own file (perf-thresholds.api… and perf-thresholds.custom…); move the entries to the right file or fix "kind".'
708
- };
709
- function describeProblems(problems, more) {
710
- const list = problems.map((p) => `${p.pointer === "" ? "(root)" : p.pointer} ${p.message}`).join("; ");
711
- return more ? `${list}; …` : list;
712
- }
713
- function issueOf(code2, source, summary, problems = []) {
714
- const shown = problems.slice(0, MAX_PROBLEMS).map(({ pointer, message }) => ({ pointer, message }));
715
- const details2 = shown.length === 0 ? "" : `: ${describeProblems(shown, problems.length > shown.length)}`;
716
- return { code: code2, source, message: `${source}: ${summary}${details2}`, problems: shown };
717
- }
718
- function failure(issue2) {
719
- return { ok: false, issues: [issue2] };
720
- }
721
- function parseJson(text, source, format) {
722
- try {
723
- return { ok: true, value: JSON.parse(text) };
724
- } catch (error) {
725
- const reason = error instanceof Error ? error.message : String(error);
726
- return failure(
727
- issueOf("SCHEMA_INVALID_JSON", source, `${format.name} is not valid JSON (${reason})`)
728
- );
729
- }
730
- }
731
- function migrate(document, from, to, migrations) {
732
- let current = document;
733
- for (let version = from; version < to; version++) {
734
- const step = migrations[version];
735
- if (step === void 0) throw new Error(`no migration from schemaVersion ${version}`);
736
- current = { ...step(current), schemaVersion: version + 1 };
737
- }
738
- return current;
739
- }
740
- function validate(document, source, format) {
741
- const sink = new Sink(MAX_PROBLEMS + 1);
742
- format.schema.check(document, "", sink);
743
- if (sink.problems.length === 0) format.extraChecks?.(document, sink);
744
- if (sink.problems.length === 0) return null;
745
- return issueOf(
746
- "SCHEMA_VALIDATION_FAILED",
747
- source,
748
- `${format.name} does not match the format`,
749
- sink.problems
750
- );
751
- }
752
- function parseVersioned(text, source, format, options = {}) {
753
- const parsed = parseJson(text, source, format);
754
- if (!parsed.ok) return parsed;
755
- const document = parsed.value;
756
- if (!isRecord(document)) {
757
- return failure(
758
- issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
759
- { pointer: "", message: "must be object" }
760
- ])
761
- );
762
- }
763
- const version = document.schemaVersion;
764
- if (typeof version !== "number" || !Number.isInteger(version)) {
765
- const found = Object.hasOwn(document, "schemaVersion") ? `schemaVersion must be an integer, found ${JSON.stringify(version)}` : "schemaVersion is missing";
766
- return failure(issueOf("SCHEMA_VERSION_MISSING", source, `${format.name}: ${found}`));
767
- }
768
- if (options.exactVersion === true && version !== format.current) {
769
- return failure(
770
- issueOf(
771
- "SCHEMA_VERSION_MISMATCH",
772
- source,
773
- `${format.name} has schemaVersion ${version}, but this package version reads only ${format.current}`
774
- )
775
- );
776
- }
777
- if (version > format.current) {
778
- return failure(
779
- issueOf(
780
- "SCHEMA_VERSION_TOO_NEW",
781
- source,
782
- `${format.name} has schemaVersion ${version}, newer than ${format.current} supported by this package version`
783
- )
784
- );
785
- }
786
- if (version < 1) {
787
- return failure(
788
- issueOf("SCHEMA_VALIDATION_FAILED", source, `${format.name} does not match the format`, [
789
- { pointer: "/schemaVersion", message: "must be >= 1" }
790
- ])
791
- );
792
- }
793
- const current = version < format.current ? migrate(document, version, format.current, format.migrations) : document;
794
- const invalid = validate(current, source, format);
795
- if (invalid !== null) return failure(invalid);
796
- return {
797
- ok: true,
798
- value: { document: current, migratedFrom: version < format.current ? version : null }
799
- };
800
- }
801
- function isCalendarDate(text) {
802
- const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(text);
803
- if (match === null) return false;
804
- const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
805
- if (month < 1 || month > 12 || day < 1) return false;
806
- const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
807
- const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
808
- return day <= days;
809
- }
810
- var SAMPLES_FORMAT = {
811
- name: "sample batch",
812
- schemaFile: "samples.schema.json",
813
- current: SCHEMA_VERSIONS.samples,
814
- migrations: {},
815
- schema: sampleBatch
816
- };
817
- var RUN_REPORT_FORMAT = {
818
- name: "run report",
819
- schemaFile: "run-report.schema.json",
820
- current: SCHEMA_VERSIONS.runReport,
821
- migrations: {},
822
- schema: runReport
823
- };
824
- var THRESHOLDS_FORMAT = {
825
- name: "thresholds file",
826
- schemaFile: "thresholds.schema.json",
827
- current: SCHEMA_VERSIONS.thresholds,
828
- migrations: {},
829
- schema: thresholdsFile,
830
- extraChecks(document, sink) {
831
- const entries = document.entries;
832
- for (const [name, entry] of Object.entries(entries)) {
833
- if (typeof entry.until === "string" && !isCalendarDate(entry.until)) {
834
- sink.add(child(child("/entries", name), "until"), "must be an existing calendar date");
835
- }
836
- }
837
- }
838
- };
839
- var OUTCOME_FORMAT = {
840
- name: "outcome file",
841
- schemaFile: "outcome.schema.json",
842
- current: SCHEMA_VERSIONS.outcome,
843
- migrations: {},
844
- schema: outcomeFile
845
- };
846
- function parseSampleBatch(text, source) {
847
- const parsed = parseVersioned(text, source, SAMPLES_FORMAT, { exactVersion: true });
848
- return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
849
- }
850
- function parseRunReport(text, source) {
851
- const parsed = parseVersioned(text, source, RUN_REPORT_FORMAT);
852
- return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
853
- }
854
- function parseThresholdsFile(text, source, expectedKind) {
855
- const parsed = parseVersioned(text, source, THRESHOLDS_FORMAT);
856
- if (!parsed.ok) return parsed;
857
- const file = parsed.value.document;
858
- if (file.kind !== expectedKind) {
859
- return failure(
860
- issueOf(
861
- "THRESHOLDS_KIND_MISMATCH",
862
- source,
863
- `thresholds file has kind "${file.kind}", but this path holds "${expectedKind}" thresholds`,
864
- [{ pointer: "/kind", message: `must be "${expectedKind}"` }]
865
- )
866
- );
867
- }
868
- return { ok: true, value: { file, migratedFrom: parsed.value.migratedFrom } };
869
- }
870
- function parseOutcome(text, source) {
871
- const parsed = parseVersioned(text, source, OUTCOME_FORMAT);
872
- return parsed.ok ? { ok: true, value: parsed.value.document } : parsed;
873
- }
874
- function schemaIssueToIssue(issue2) {
875
- return { code: issue2.code, message: issue2.message, hint: HINTS[issue2.code] };
876
- }
877
-
878
- // src/io/thresholds.ts
879
- var KINDS = ["api", "custom"];
880
- function thresholdsFileName(prefix, kind2, env) {
881
- return `${prefix}.${kind2}${env === null ? "" : `.${env}`}.json`;
882
- }
883
- function thresholdsFilePaths(location) {
884
- const dir = resolvePath(location.configDir, location.dir);
885
- const path = (kind2) => resolvePath(dir, thresholdsFileName(location.filePrefix, kind2, location.env));
886
- return { api: path("api"), custom: path("custom") };
887
- }
888
- async function loadFile(location, kind2) {
889
- const absolute = thresholdsFilePaths(location)[kind2];
890
- const path = relativeSlashPath(location.configDir, absolute);
891
- let text;
892
- try {
893
- text = await readTextFile(absolute);
894
- } catch (error) {
895
- const reason = error instanceof Error ? error.message : String(error);
896
- return {
897
- status: "invalid",
898
- kind: kind2,
899
- path,
900
- issues: [
901
- {
902
- code: "SCHEMA_INVALID_JSON",
903
- source: path,
904
- message: `${path}: the file cannot be read (${reason})`,
905
- problems: []
906
- }
907
- ]
908
- };
909
- }
910
- if (text === null) {
911
- const envless = location.env !== null && await fileExists(
912
- resolvePath(
913
- resolvePath(location.configDir, location.dir),
914
- thresholdsFileName(location.filePrefix, kind2, null)
915
- )
916
- );
917
- return { status: "missing", kind: kind2, path, envlessFileExists: envless };
918
- }
919
- const parsed = parseThresholdsFile(text, path, kind2);
920
- if (!parsed.ok) return { status: "invalid", kind: kind2, path, issues: parsed.issues };
921
- const { file, migratedFrom } = parsed.value;
922
- return {
923
- status: "loaded",
924
- kind: kind2,
925
- path,
926
- file,
927
- ...migratedFrom === null ? {} : { migratedFrom }
928
- };
929
- }
930
- async function loadThresholds(location) {
931
- const [api, custom] = await Promise.all(KINDS.map((kind2) => loadFile(location, kind2)));
932
- return { api, custom };
933
- }
934
-
935
- // src/html/escape.ts
936
- var SAFE = /* @__PURE__ */ Symbol("SafeHtml");
937
- var ESCAPES = {
938
- "&": "&amp;",
939
- "<": "&lt;",
940
- ">": "&gt;",
941
- '"': "&quot;",
942
- "'": "&#39;"
943
- };
944
- function escapeHtml(value) {
945
- return value.replace(/[&<>"']/gu, (c) => ESCAPES[c] ?? c);
946
- }
947
- function isSafe(value) {
948
- return typeof value === "object" && value !== null && SAFE in value;
949
- }
950
- function trustedHtml(text) {
951
- return { [SAFE]: true, text };
952
- }
953
- function render(value) {
954
- if (value === null || value === void 0 || value === false) return "";
955
- if (typeof value === "string") return escapeHtml(value);
956
- if (typeof value === "number") return escapeHtml(String(value));
957
- if (isSafe(value)) return value.text;
958
- return value.map(render).join("");
959
- }
960
- function html(strings, ...values) {
961
- let text = strings[0] ?? "";
962
- for (let i = 0; i < values.length; i++) {
963
- text += render(values[i]) + (strings[i + 1] ?? "");
964
- }
965
- return trustedHtml(text);
966
- }
967
-
968
- // src/html/format.ts
969
- function formatMs(value) {
970
- if (value >= 1e4) return `${(Math.round(value / 100) / 10).toFixed(1)} s`;
971
- if (value < 10) return `${(Math.round(value * 10) / 10).toFixed(1)} ms`;
972
- return `${Math.round(value)} ms`;
973
- }
974
- function formatRatio(value) {
975
- return value.toFixed(3);
976
- }
977
- function pad(n) {
978
- return String(n).padStart(2, "0");
979
- }
980
- function formatDate(iso) {
981
- const time = Date.parse(iso);
982
- if (Number.isNaN(time)) return iso;
983
- const d = new Date(time);
984
- return `${String(d.getUTCFullYear())}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`;
985
- }
986
- function formatRunDuration(startedAt, finishedAt) {
987
- const ms2 = Date.parse(finishedAt) - Date.parse(startedAt);
988
- if (!Number.isFinite(ms2) || ms2 < 0) return "—";
989
- const total = Math.round(ms2 / 1e3);
990
- const h = Math.floor(total / 3600);
991
- const min = Math.floor(total % 3600 / 60);
992
- const s = total % 60;
993
- if (h > 0) return `${String(h)} h ${String(min)} min ${String(s)} s`;
994
- if (min > 0) return `${String(min)} min ${String(s)} s`;
995
- return `${String(s)} s`;
996
- }
997
- function plural(n, word, many = `${word}s`) {
998
- return `${String(n)} ${n === 1 ? word : many}`;
999
- }
1000
- function truncateMiddle(text, max) {
1001
- const points = Array.from(text);
1002
- if (points.length <= max) return text;
1003
- const keep = max - 1;
1004
- const head = Math.ceil(keep / 2);
1005
- return `${points.slice(0, head).join("")}…${points.slice(points.length - (keep - head)).join("")}`;
1006
- }
1007
-
1008
- // src/html/bar.ts
1009
- var WIDTH = 640;
1010
- var LEFT = 24;
1011
- var RIGHT = 616;
1012
- var ROW = 13;
1013
- var CHAR = 6.2;
1014
- var GAP = 8;
1015
- function coordinate(value, axisMax) {
1016
- return Math.round((LEFT + (RIGHT - LEFT) * value / axisMax) * 10) / 10;
1017
- }
1018
- function merge(marks) {
1019
- const out = [];
1020
- for (const mark of marks) {
1021
- const same = out.find((m) => m.value === mark.value);
1022
- if (same === void 0) out.push({ ...mark });
1023
- else same.label = `${same.label}, ${mark.label}`;
1024
- }
1025
- return out;
1026
- }
1027
- function place(marks, axisMax) {
1028
- const rowsEnd = [];
1029
- return [...marks].sort((a, b) => a.value - b.value).map((mark) => {
1030
- const x = coordinate(mark.value, axisMax);
1031
- const text = `${mark.label} ${formatMs(mark.value)}`;
1032
- const width = text.length * CHAR;
1033
- const anchor = x - width / 2 < 0 ? "start" : x + width / 2 > WIDTH ? "end" : "middle";
1034
- const from = anchor === "start" ? x : anchor === "end" ? x - width : x - width / 2;
1035
- let row = rowsEnd.findIndex((end) => end + GAP <= from);
1036
- if (row === -1) row = rowsEnd.length;
1037
- rowsEnd[row] = from + width;
1038
- return { text, x, row, anchor };
1039
- });
1040
- }
1041
- function percentileBar(stats2, limits, level) {
1042
- if (stats2 === null) return null;
1043
- const p = stats2.percentiles;
1044
- const markers = [];
1045
- for (const name of ["p50", "p90", "p95", "p99"]) {
1046
- const value = p[name];
1047
- if (value !== void 0) markers.push({ label: name, value });
1048
- }
1049
- markers.push({ label: "max", value: stats2.max });
1050
- const lines = [];
1051
- if (limits.t !== null) lines.push({ label: "T", value: limits.t });
1052
- lines.push({ label: "median limit", value: limits.median });
1053
- lines.push({ label: `${level} limit`, value: limits.percentile });
1054
- lines.push({ label: "p99 limit", value: limits.p99 });
1055
- const axisMax = Math.max(stats2.max, limits.p99) > 0 ? Math.max(stats2.max, limits.p99) : 1;
1056
- const top = place(merge(markers), axisMax);
1057
- const bottom = place(merge(lines), axisMax);
1058
- const topRows = Math.max(1, ...top.map((m) => m.row + 1));
1059
- const bottomRows = Math.max(1, ...bottom.map((m) => m.row + 1));
1060
- const axisY = 12 + ROW * topRows;
1061
- const height = axisY + 22 + ROW * bottomRows + 14;
1062
- const markerSvg = top.map((m) => {
1063
- const y = axisY - 12 - ROW * m.row;
1064
- return html`<line class="bar-mark" x1="${m.x}" y1="${axisY - 8}" x2="${m.x}" y2="${axisY + 8}"/><text x="${m.x}" y="${y}" text-anchor="${m.anchor}">${m.text}</text>`;
1065
- });
1066
- const lineSvg = bottom.map((m) => {
1067
- const y = axisY + 24 + ROW * m.row;
1068
- return html`<line class="bar-limit" x1="${m.x}" y1="${axisY - 4}" x2="${m.x}" y2="${y - 10}"/><text class="bar-limit-text" x="${m.x}" y="${y}" text-anchor="${m.anchor}">${m.text}</text>`;
1069
- });
1070
- const p50 = p["p50"];
1071
- const p99 = p["p99"];
1072
- let range = null;
1073
- if (p50 !== void 0 && p99 !== void 0) {
1074
- const x1 = coordinate(p50, axisMax);
1075
- const width = Math.max(0, Math.round((coordinate(p99, axisMax) - x1) * 10) / 10);
1076
- range = html`<rect class="bar-range" x="${x1}" y="${axisY - 4}" width="${width}" height="8"/>`;
1077
- }
1078
- const describe = [...markers, ...lines].map((m) => `${m.label} ${formatMs(m.value)}`).join(", ");
1079
- const label = `Percentiles and limits: ${describe}`;
1080
- return html`<svg class="bar" viewBox="0 0 ${WIDTH} ${height}" role="img" aria-label="${label}"><line class="bar-axis" x1="${LEFT}" y1="${axisY}" x2="${RIGHT}" y2="${axisY}"/>${range}${lineSvg}${markerSvg}<text class="bar-scale" x="${LEFT}" y="${height - 2}">0</text><text class="bar-scale" x="${RIGHT}" y="${height - 2}" text-anchor="end">${formatMs(axisMax)}</text></svg>`;
1081
- }
1082
-
1083
- // src/html/data.ts
1084
- function withoutDurations(aggregates) {
1085
- const out = {};
1086
- for (const key2 of Object.keys(aggregates).sort()) {
1087
- const { samples, ...rest } = aggregates[key2];
1088
- out[key2] = {
1089
- ...rest,
1090
- samples: { retained: samples.durations.length, sampled: samples.sampled }
1091
- };
1092
- }
1093
- return out;
1094
- }
1095
- function toHtmlReportData(report) {
1096
- return {
1097
- ...report,
1098
- endpoints: withoutDurations(report.endpoints),
1099
- custom: withoutDurations(report.custom)
1100
- };
1101
- }
1102
- function stable(value, indent, depth) {
1103
- if (value === null || typeof value !== "object") {
1104
- return JSON.stringify(value) ?? "null";
1105
- }
1106
- const inner = indent === null ? "" : depth + indent;
1107
- const open = indent === null ? "" : `
1108
- ${inner}`;
1109
- const close = indent === null ? "" : `
1110
- ${depth}`;
1111
- const sep = indent === null ? "," : `,
1112
- ${inner}`;
1113
- if (Array.isArray(value)) {
1114
- if (value.length === 0) return "[]";
1115
- return `[${open}${value.map((v) => stable(v, indent, inner)).join(sep)}${close}]`;
1116
- }
1117
- const record2 = value;
1118
- const keys = Object.keys(record2).filter((k) => record2[k] !== void 0).sort();
1119
- if (keys.length === 0) return "{}";
1120
- const colon = indent === null ? ":" : ": ";
1121
- const entries = keys.map(
1122
- (k) => `${JSON.stringify(k)}${colon}${stable(record2[k], indent, inner)}`
1123
- );
1124
- return `{${open}${entries.join(sep)}${close}}`;
1125
- }
1126
- function stableJson(value, indent = null) {
1127
- return stable(value, indent, "");
1128
- }
1129
- function embeddedJson(data) {
1130
- return stableJson(data).replaceAll("<", "\\u003c");
1131
- }
1132
-
1133
- // src/html/generated/assets.ts
1134
- var STYLES = ':root{color-scheme:light dark;--bg: #ffffff;--fg: #1b1f24;--muted: #57606a;--border: #d0d7de;--panel: #f6f8fa;--ok: #116329;--warn: #7d4e00;--bad: #b3261e;--link: #0550ae;--mark: #1b1f24;--range: #9fb4cc}@media(prefers-color-scheme:dark){:root{--bg: #0d1117;--fg: #e6edf3;--muted: #9da7b3;--border: #3d444d;--panel: #161b22;--ok: #56d364;--warn: #e3b341;--bad: #ff8e88;--link: #79c0ff;--mark: #e6edf3;--range: #3b5070}}*{box-sizing:border-box}html{background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}body{margin:0;overflow-x:hidden}main,footer{max-width:1280px;margin:0 auto;padding:0 16px}h1{margin:0 0 12px;font-size:24px}h2{margin:32px 0 12px;font-size:19px;border-bottom:1px solid var(--border);padding-bottom:4px}h2.sub{border:0;font-size:15px;margin:16px 0 4px}h3{margin:0 0 4px;font-size:15px}h4{margin:12px 0 4px;font-size:14px}p{margin:4px 0}a{color:var(--link)}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px}pre{background:var(--panel);border:1px solid var(--border);padding:12px;overflow-x:auto}.page-header{padding-top:24px}.tool,.muted-text,.limit,.hint{color:var(--muted)}.meta{display:flex;flex-wrap:wrap;gap:4px 24px;margin:0}.meta dt{color:var(--muted);font-size:12px}.meta dd{margin:0;overflow-wrap:anywhere}.origins,.plain{margin:0;padding-left:20px}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.verdict{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.card{border:1px solid var(--border);border-left-width:6px;border-radius:6px;padding:12px;background:var(--panel);color:var(--fg)}.card.ok{border-left-color:var(--ok)}.card.warn{border-left-color:var(--warn)}.card.bad{border-left-color:var(--bad)}.card .status{font-size:18px;font-weight:700;text-transform:uppercase}.card.ok .status{color:var(--ok)}.card.warn .status{color:var(--warn)}.card.bad .status{color:var(--bad)}.note{font-style:italic}.toolbar{margin-top:12px}.issues{list-style:none;padding:0;margin:0}.issues li{border-left:4px solid currentColor;padding:4px 12px;margin:8px 0}.issues li p{color:var(--fg)}.issues li p.hint{color:var(--muted)}.highlight{border:2px solid var(--bad);border-radius:6px;padding:0 12px 12px}.scroll{overflow-x:auto;max-width:100%}table{border-collapse:collapse;width:100%;margin:4px 0 12px}caption{text-align:left;color:var(--muted);padding:4px 0}th,td{border-bottom:1px solid var(--border);padding:4px 8px;text-align:left;vertical-align:top}thead th{background:var(--panel);white-space:nowrap}th[scope=row]{font-weight:400}.num{text-align:right;white-space:nowrap}table.keys th.key{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px;white-space:nowrap}th button{font:inherit;font-weight:700;color:inherit;background:none;border:0;padding:0;cursor:default}.js th button{cursor:pointer;text-decoration:underline dotted}.js th[aria-sort=ascending] button:after{content:" ▲"}.js th[aria-sort=descending] button:after{content:" ▼"}table.keys tr:first-child>td:first-of-type{white-space:nowrap}.details-row>td{padding-top:0}details>summary{cursor:pointer;color:var(--link)}.details-body{padding:4px 0 12px;max-width:960px}.full-key code,.url{overflow-wrap:anywhere;word-break:break-all}.facts{display:grid;grid-template-columns:max-content 1fr;gap:2px 16px;margin:8px 0}.facts div{display:contents}.facts dt{color:var(--muted)}.facts dd{margin:0}.slowest,.top-tests{margin:0;padding-left:20px}table.checks{width:auto}.bar{width:100%;max-width:640px;height:auto;display:block;margin:8px 0}.bar text{fill:var(--fg);font-size:11px}.bar .bar-limit-text{fill:var(--bad)}.bar-axis{stroke:var(--muted);stroke-width:1}.bar-range{fill:var(--range)}.bar-mark{stroke:var(--mark);stroke-width:2}.bar-limit{stroke:var(--bad);stroke-width:1.5;stroke-dasharray:4 3}.filters{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;margin:8px 0}.filters[hidden],[hidden]{display:none!important}input[type=search]{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--border);border-radius:4px;padding:2px 6px;margin-left:4px}#download{font:inherit;color:var(--fg);background:var(--panel);border:1px solid var(--border);border-radius:6px;padding:4px 12px;cursor:pointer}button:focus-visible,input:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid var(--link);outline-offset:2px}.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}footer{margin:40px auto 24px;color:var(--muted);border-top:1px solid var(--border);padding-top:12px}@media print{:root{color-scheme:light;--bg: #ffffff;--fg: #000000;--muted: #444444;--border: #bbbbbb;--panel: #ffffff;--ok: #0b5e20;--warn: #6a4200;--bad: #a1150e;--link: #000000;--mark: #000000;--range: #c8d3e0}.filters,.toolbar,th button:after{display:none!important}.scroll{overflow:visible}tbody,tr{break-inside:avoid}details[data-violation]::details-content{content-visibility:visible;display:block}}';
1135
- var STYLES_SHA256 = "rMj6c+jgU9bq6OVZSVVT3M4IvsOeXLSFzdizre4Z7Bc=";
1136
- var SCRIPT = `(()=>{const D=document.getElementById("report-data"),b=D?.textContent??'{"endpoints":{},"custom":{}}',C=JSON.parse(b);document.documentElement.classList.add("js");function H(e,a,d,f){if(e===void 0)return null;switch(a){case"result":return f;case"samples":return e.successCount;case"errors":return e.errorCount;case"p50":return e.stats?.percentiles.p50??null;case"percentile":return e.stats?.percentiles[d]??null;case"p99":return e.stats?.percentiles.p99??null;case"max":return e.stats?.max??null;case"ttfb":return e.ttfb?.p50??null;case"tests":return e.testCount;default:return null}}function T(e,a){return e<a?-1:e>a?1:0}function M(e){const a=e.dataset.kind==="custom"?"custom":"endpoints",d=e.dataset.percentile??"p95",f=C[a],m=Array.from(e.tBodies),v=Array.from(e.querySelectorAll("th[data-sort]"));let u=null;function w(r,o){const s=o==="ascending"?1:-1,l=m.map(t=>{const n=t.dataset.key??"",A=Number(t.dataset.group??"3");return{body:t,key:n,value:H(f[n],r,d,A)}});l.sort((t,n)=>{if(r!=="key"){if(t.value===null||n.value===null){if(t.value!==n.value)return t.value===null?1:-1}else if(t.value!==n.value)return(t.value-n.value)*s;return T(t.key,n.key)}return T(t.key,n.key)*s});for(const t of l)e.appendChild(t.body);for(const t of v)t.dataset.sort===r?t.setAttribute("aria-sort",o):t.removeAttribute("aria-sort")}for(const r of v){const o=r.dataset.sort??"key";r.querySelector("button")?.addEventListener("click",()=>{const s=o==="key"||o==="result"?"ascending":"descending",l=u!==null&&u.column===o?u.direction==="ascending"?"descending":"ascending":s;u={column:o,direction:l},w(o,l)})}const c=document.querySelector(\`[data-filters-for="\${e.id}"]\`);if(c===null)return;const g=c.querySelector('[data-filter="text"]'),L=c.querySelector('[data-filter="violations"]'),E=c.querySelector('[data-filter="not-evaluated"]'),k=c.querySelector("[data-count]");function h(){const r=(g?.value??"").toLowerCase();let o=0;for(const s of m){const l=(s.dataset.key??"").toLowerCase(),t=s.dataset.result??"",n=l.includes(r)&&!(L?.checked===!0&&t!=="fail")&&!(E?.checked===!0&&t==="not-evaluated");s.hidden=!n,n&&o++}k!==null&&(k.textContent=\`showing \${o} of \${m.length}\`)}for(const r of[g,L,E])r?.addEventListener("input",h),r?.addEventListener("change",h);c.hidden=!1}for(const e of Array.from(document.querySelectorAll("table.keys")))M(e);const p=document.getElementById("download"),y=document.getElementById("download-link");p instanceof HTMLButtonElement&&y instanceof HTMLAnchorElement&&(p.addEventListener("click",()=>{const e=URL.createObjectURL(new Blob([b],{type:"application/json"}));y.href=e,y.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)}),p.hidden=!1);let i=[];window.addEventListener("beforeprint",()=>{i=Array.from(document.querySelectorAll("details[data-violation]:not([open])"));for(const e of i)e.open=!0});window.addEventListener("afterprint",()=>{for(const e of i)e.open=!1;i=[]});})();`;
1137
- var SCRIPT_SHA256 = "NczooZoEwk0CPgfuEFUbnRFp9bbi8jrYYzyk+WNBTEc=";
1138
-
1139
- // src/html/render.ts
1140
- var KEY_COLUMN_MAX = 80;
1141
- var DEFAULT_PERCENTILE = "p95";
1142
- var TIME_RULES = /* @__PURE__ */ new Set([
1143
- "median",
1144
- "percentile",
1145
- "p99"
1146
- ]);
1147
- var DASH = "—";
1148
- function join2(...parts) {
1149
- return html`${parts}`;
1150
- }
1151
- function percentileLevel(report) {
1152
- return report.config.checks?.time?.percentile?.level ?? DEFAULT_PERCENTILE;
1153
- }
1154
- function isBlocking(evaluation) {
1155
- return evaluation.result === "fail" && evaluation.checks.some((c) => c.blocking);
1156
- }
1157
- function rowGroup(evaluation) {
1158
- if (evaluation.result === "fail") return isBlocking(evaluation) ? 0 : 1;
1159
- return evaluation.result === "pass" ? 2 : 3;
1160
- }
1161
- function limitRatio(agg, level) {
1162
- const value = agg.stats?.percentiles[level];
1163
- if (value === void 0) return -Infinity;
1164
- const limit = agg.evaluation.limits.percentile;
1165
- if (limit === 0) return value === 0 ? 0 : Infinity;
1166
- return value / limit;
1167
- }
1168
- function defaultOrder(aggregates, level) {
1169
- const rows = Object.keys(aggregates).map((key2) => {
1170
- const agg = aggregates[key2];
1171
- return { key: key2, group: rowGroup(agg.evaluation), ratio: limitRatio(agg, level) };
1172
- });
1173
- rows.sort((a, b) => {
1174
- if (a.group !== b.group) return a.group - b.group;
1175
- if (a.ratio !== b.ratio) return a.ratio > b.ratio ? -1 : 1;
1176
- return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
1177
- });
1178
- return rows.map((r) => r.key);
1179
- }
1180
- function reasonText(reason) {
1181
- switch (reason) {
1182
- case "too-few-samples":
1183
- return "too few samples";
1184
- case "no-rules":
1185
- return "no applicable rules";
1186
- case "thresholds-error":
1187
- return "thresholds file invalid";
1188
- default:
1189
- return null;
1190
- }
1191
- }
1192
- function resultText(evaluation) {
1193
- if (evaluation.result === "fail") return isBlocking(evaluation) ? "fail (blocking)" : "fail";
1194
- return evaluation.result === "pass" ? "pass" : "not evaluated";
1195
- }
1196
- function resultClass(evaluation) {
1197
- if (evaluation.result === "fail") return isBlocking(evaluation) ? "bad" : "warn";
1198
- return evaluation.result === "pass" ? "ok" : "muted-text";
1199
- }
1200
- function mutedText(muted) {
1201
- if (muted === null) return null;
1202
- const until = muted.until.slice(0, 10);
1203
- return muted.expired ? `mute expired ${until}` : `muted until ${until}`;
1204
- }
1205
- function ruleName(rule, level) {
1206
- return rule === "percentile" ? level : rule;
1207
- }
1208
- function checkValue(check2, value) {
1209
- return TIME_RULES.has(check2.rule) ? formatMs(value) : formatRatio(value);
1210
- }
1211
- function lowestMinSamples(report) {
1212
- const checks = report.config.checks;
1213
- if (checks === void 0) return null;
1214
- const rules = [
1215
- ["median", checks.time?.median],
1216
- [percentileLevel(report), checks.time?.percentile],
1217
- ["p99", checks.time?.p99],
1218
- ["apdex", checks.slowShare?.apdex],
1219
- ["wilson", checks.slowShare?.wilson],
1220
- ["errors", checks.errors]
1221
- ];
1222
- let best = null;
1223
- for (const [rule, cfg] of rules) {
1224
- if (cfg?.enabled === false || cfg?.minSamples === void 0) continue;
1225
- if (best === null || cfg.minSamples < best.n) best = { rule, n: cfg.minSamples };
1226
- }
1227
- return best;
1228
- }
1229
- function buildLink(url) {
1230
- if (url === null) return DASH;
1231
- return /^https?:\/\//iu.test(url.trimStart()) ? html`<a href="${url}" rel="noopener noreferrer">${url}</a>` : html`<code>${url}</code>`;
1232
- }
1233
- function header(report) {
1234
- const { ci, host } = report;
1235
- const items = [
1236
- ["Run ID", html`<code>${report.runId}</code>`],
1237
- ["Started", formatDate(report.startedAt)],
1238
- ["Duration", formatRunDuration(report.startedAt, report.finishedAt)],
1239
- ["Mode", report.mode],
1240
- ["Environment", report.env ?? DASH],
1241
- ["Playwright", report.playwright.version],
1242
- ["Node.js", host.nodeVersion],
1243
- ["System", `${host.platform} ${host.arch}`],
1244
- [
1245
- "CPU",
1246
- `${host.cpuModel === "" ? "unknown" : host.cpuModel} (${plural(host.cpuCount, "core")})`
1247
- ]
1248
- ];
1249
- if (ci !== null) {
1250
- items.push(
1251
- ["CI", ci.provider],
1252
- ["Commit", ci.commit === null ? DASH : html`<code>${ci.commit}</code>`],
1253
- ["Branch", ci.branch ?? DASH],
1254
- ["Build", buildLink(ci.buildUrl)]
1255
- );
1256
- }
1257
- const origin = (o) => join2(
1258
- html`<li><code>${o.origin}</code> `,
1259
- o.label === "" ? html`<span class="muted-text">(base)</span>` : html`label <code>${o.label}</code>`,
1260
- html` · ${plural(o.requestCount, "request")}</li>`
1261
- );
1262
- return join2(
1263
- html`<header class="page-header">`,
1264
- html`<p class="tool">${report.tool.name} v${report.tool.version}</p>`,
1265
- html`<h1>Performance report</h1>`,
1266
- html`<dl class="meta">${items.map(([k, v]) => html`<div><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>`,
1267
- report.origins.length === 0 ? null : html`<h2 class="sub">Measured origins</h2><ul class="origins">${report.origins.map(origin)}</ul>`,
1268
- html`</header>`
1269
- );
1270
- }
1271
- function card(title, cls, status, ...notes) {
1272
- return html`<div class="card ${cls}"><h3>${title}</h3><p class="status">${status}</p>${notes}</div>`;
1273
- }
1274
- function verdict(report) {
1275
- const t = report.tests;
1276
- const untrustworthy = report.toolErrors.some((i) => i.code === "TESTS_FAILED_TOO_MANY");
1277
- const perf = report.evaluation.status;
1278
- const errors = report.toolErrors.length;
1279
- return join2(
1280
- html`<section aria-labelledby="verdict-h"><h2 id="verdict-h">Verdict</h2><div class="verdict">`,
1281
- card(
1282
- "Tests",
1283
- t.status === "passed" ? "ok" : "warn",
1284
- t.status === "timedout" ? "timed out" : t.status,
1285
- html`<p>${t.expected} expected · ${t.unexpected} unexpected · ${t.flaky} flaky · ${t.skipped} skipped</p>`,
1286
- untrustworthy ? html`<p class="note">Too many tests failed: the performance result is not trustworthy.</p>` : t.unexpected > 0 ? html`<p class="note">Failed tests are information, not the performance verdict.</p>` : null
1287
- ),
1288
- card(
1289
- "Performance",
1290
- perf === "passed" ? "ok" : perf === "warned" ? "warn" : "bad",
1291
- perf,
1292
- report.evaluation.gateEnabled ? null : html`<p class="note">gate off (thresholds mode)</p>`
1293
- ),
1294
- card("Tool errors", errors === 0 ? "ok" : "bad", errors === 0 ? "none" : String(errors)),
1295
- html`</div></section>`
1296
- );
1297
- }
1298
- function mutedSection(report) {
1299
- const rows = [];
1300
- let active = 0;
1301
- for (const [kind2, map] of [
1302
- ["API", report.endpoints],
1303
- ["Custom", report.custom]
1304
- ]) {
1305
- for (const key2 of Object.keys(map).sort()) {
1306
- const evaluation = map[key2]?.evaluation;
1307
- const muted = evaluation?.muted ?? null;
1308
- if (evaluation === void 0 || muted === null) continue;
1309
- if (!muted.expired) active++;
1310
- rows.push(
1311
- join2(
1312
- html`<tr><th scope="row" class="key">${key2}</th><td>${kind2}</td><td>${muted.until}</td>`,
1313
- html`<td>${muted.expired ? html`<span class="warn">expired</span>` : "active"}</td>`,
1314
- html`<td>${evaluation.result === "fail" ? html`<span class="warn">yes</span>` : "no"}</td>`,
1315
- html`<td>${muted.note}</td></tr>`
1316
- )
1317
- );
1318
- }
1319
- }
1320
- if (rows.length === 0) return null;
1321
- return join2(
1322
- html`<section aria-labelledby="muted-h"><h2 id="muted-h">Muted keys</h2>`,
1323
- html`<p>${plural(active, "active muting")}, ${plural(rows.length - active, "expired muting")}.</p>`,
1324
- html`<div class="scroll"><table><caption>Keys muted in the thresholds files</caption>`,
1325
- html`<thead><tr><th scope="col">Key</th><th scope="col">Kind</th><th scope="col">Until</th>`,
1326
- html`<th scope="col">State</th><th scope="col">Violation</th><th scope="col">Note</th></tr></thead>`,
1327
- html`<tbody>${rows}</tbody></table></div></section>`
1328
- );
1329
- }
1330
- var COUNTERS = [
1331
- ["keys", "Keys"],
1332
- ["fromFile", "Evaluated with thresholds from the file"],
1333
- ["fromDefaults", "Evaluated with default thresholds"],
1334
- ["notEvaluated", "Not evaluated"],
1335
- ["tooFewSamples", "Not evaluated: too few samples"],
1336
- ["fileEntriesNotEvaluated", "File entries not evaluated (small n)"],
1337
- ["medianOnly", "Evaluated by the median only"],
1338
- ["unseenThresholdEntries", "File entries not seen in this run"],
1339
- ["violations", "Violations"],
1340
- ["blockingViolations", "Blocking violations"],
1341
- ["muted", "Muted (active)"]
1342
- ];
1343
- function counters(report) {
1344
- const { api, custom } = report.evaluation.counts;
1345
- return join2(
1346
- html`<section aria-labelledby="counters-h"><h2 id="counters-h">Counters</h2>`,
1347
- html`<div class="scroll"><table class="counters"><caption>Keys per kind</caption>`,
1348
- html`<thead><tr><th scope="col">Counter</th><th scope="col" class="num">API</th><th scope="col" class="num">Custom</th></tr></thead>`,
1349
- html`<tbody>${COUNTERS.map(
1350
- ([field2, label]) => html`<tr><th scope="row">${label}</th><td class="num">${api[field2]}</td><td class="num">${custom[field2]}</td></tr>`
1351
- )}</tbody></table></div></section>`
1352
- );
1353
- }
1354
- function issueList(issues, level) {
1355
- const item = (i) => join2(
1356
- html`<li class="${level === "error" ? "bad" : "warn"}"><p><strong>${level}</strong> <code>${i.code}</code>`,
1357
- i.count !== void 0 && i.count > 1 ? html` <span class="count">×${i.count}</span>` : null,
1358
- html`</p><p>${i.message}</p>`,
1359
- i.hint === void 0 ? null : html`<p class="hint">Hint: ${i.hint}</p>`,
1360
- html`</li>`
1361
- );
1362
- return html`<ul class="issues">${issues.map(item)}</ul>`;
1363
- }
1364
- function issuesSection(report) {
1365
- const { warnings, toolErrors } = report;
1366
- if (warnings.length === 0 && toolErrors.length === 0) return null;
1367
- const cls = report.evaluation.status === "error" ? "issues-section highlight" : "issues-section";
1368
- return join2(
1369
- html`<section aria-labelledby="issues-h" class="${cls}"><h2 id="issues-h">Warnings and errors</h2>`,
1370
- toolErrors.length === 0 ? null : html`<h3>Tool errors (${toolErrors.length})</h3>${issueList(toolErrors, "error")}`,
1371
- warnings.length === 0 ? null : html`<h3>Warnings (${warnings.length})</h3>${issueList(warnings, "warning")}`,
1372
- html`</section>`
1373
- );
1374
- }
1375
- function checksTable(agg, level, report) {
1376
- const ev = agg.evaluation;
1377
- if (ev.result === "not-evaluated") {
1378
- const reason = reasonText(ev.reason);
1379
- const lowest = lowestMinSamples(report);
1380
- return join2(
1381
- html`<p>Not evaluated${reason === null ? "" : `: ${reason}`}.`,
1382
- lowest === null ? null : ` The lowest rule (${lowest.rule}) needs ${plural(lowest.n, "sample")}; this key has ${String(agg.successCount)} successful of ${plural(agg.count, "sample")}.`,
1383
- html`</p>`
1384
- );
1385
- }
1386
- const row = (c) => join2(
1387
- html`<tr><th scope="row">${ruleName(c.rule, level)}</th><td class="num">${c.n}</td>`,
1388
- html`<td class="num">${checkValue(c, c.actual)}</td>`,
1389
- html`<td class="num">${c.observed === null ? DASH : formatRatio(c.observed)}</td>`,
1390
- html`<td class="num">${checkValue(c, c.limit)}</td>`,
1391
- html`<td><span class="${c.passed ? "ok" : "bad"}">${c.passed ? "pass" : "fail"}</span></td>`,
1392
- html`<td>${c.blocking ? "yes" : "no"}</td><td>${c.hardLimitExceeded ? "yes" : "no"}</td></tr>`
1393
- );
1394
- return join2(
1395
- html`<table class="checks"><caption>Checks</caption><thead><tr>`,
1396
- html`<th scope="col">Rule</th><th scope="col" class="num">n</th>`,
1397
- html`<th scope="col" class="num">Compared value</th><th scope="col" class="num">Observed</th>`,
1398
- html`<th scope="col" class="num">Limit</th><th scope="col">Result</th><th scope="col">Blocking</th>`,
1399
- html`<th scope="col">Hard limit exceeded</th></tr></thead><tbody>${ev.checks.map(row)}</tbody></table>`
1400
- );
1401
- }
1402
- function testRef2(t) {
1403
- const project = t.project === "" ? "default project" : t.project;
1404
- return html`${t.title} <span class="muted-text">(${project}, <code>${t.file}:${t.line}</code>)</span>`;
1405
- }
1406
- function fact(label, value) {
1407
- return html`<div><dt>${label}</dt><dd>${value}</dd></div>`;
1408
- }
1409
- function details(key2, agg, kind2, report, level) {
1410
- const statuses = Object.keys(agg.statuses).sort();
1411
- const bar = percentileBar(agg.stats, agg.evaluation.limits, level);
1412
- const statusList = statuses.map(
1413
- (s, i) => html`${i > 0 ? ", " : ""}<code>${s}</code> → ${agg.statuses[s] ?? 0}`
1414
- );
1415
- const sampling = agg.samples.sampled ? " (sampled: the key had more successful samples than the limit)" : " (all successful samples)";
1416
- return join2(
1417
- html`<p class="full-key"><code>${key2}</code></p>`,
1418
- checksTable(agg, level, report),
1419
- bar ?? html`<p>No successful samples, so there are no time statistics.</p>`,
1420
- html`<dl class="facts">`,
1421
- fact("Statuses", statuses.length === 0 ? DASH : statusList),
1422
- fact("Samples from failed tests", agg.fromFailedTests),
1423
- agg.timeSources.node > 0 ? fact(
1424
- "Time sources",
1425
- `browser ${String(agg.timeSources.browser)}, node ${String(agg.timeSources.node)}`
1426
- ) : null,
1427
- kind2 === "endpoints" ? fact(
1428
- "TTFB",
1429
- agg.ttfb === null ? DASH : `p50 ${formatMs(agg.ttfb.p50)}, p95 ${formatMs(agg.ttfb.p95)}`
1430
- ) : null,
1431
- fact("Retained samples", `${String(agg.samples.retained)}${sampling}`),
1432
- html`</dl>`,
1433
- agg.slowest.length === 0 ? null : html`<h4>Slowest samples</h4><ol class="slowest">${agg.slowest.map(
1434
- (s) => join2(
1435
- html`<li><strong>${formatMs(s.duration)}</strong> at ${formatDate(s.startedAt)} · `,
1436
- html`${testRef2(s.test)} · repeat ${s.test.repeatEachIndex}`,
1437
- s.url === void 0 ? null : html`<br><span class="url">${s.url}</span>`,
1438
- html`</li>`
1439
- )
1440
- )}</ol>`,
1441
- agg.topTests.length === 0 ? null : html`<h4>Tests calling this key most often</h4><ol class="top-tests">${agg.topTests.map(
1442
- (t) => html`<li>${testRef2(t)} · ${plural(t.sampleCount, "sample")}</li>`
1443
- )}</ol>`
1444
- );
1445
- }
1446
- function percentileCell(value, limit) {
1447
- return value === void 0 ? html`${DASH}` : html`${formatMs(value)} <span class="limit">/ ${formatMs(limit)}</span>`;
1448
- }
1449
- function keyRow(key2, agg, kind2, report, level, columns) {
1450
- const ev = agg.evaluation;
1451
- const s = agg.stats;
1452
- const reason = reasonText(ev.reason);
1453
- const muted = mutedText(ev.muted);
1454
- const group = rowGroup(ev);
1455
- const short = truncateMiddle(key2, KEY_COLUMN_MAX);
1456
- const time = (value) => value === void 0 ? DASH : formatMs(value);
1457
- return join2(
1458
- html`<tbody class="key-group" data-key="${key2}" data-result="${ev.result}" data-group="${group}"><tr>`,
1459
- html`<th scope="row" class="key"${short === key2 ? null : html` title="${key2}"`}>${short}</th>`,
1460
- html`<td><span class="${resultClass(ev)}">${resultText(ev)}</span> <span class="muted-text">· ${ev.thresholdSource}</span>`,
1461
- reason === null ? null : html`<br><span class="muted-text">${reason}</span>`,
1462
- muted === null ? null : html`<br><span class="${ev.muted?.expired === true ? "warn" : "muted-text"}">${muted}</span>`,
1463
- html`</td><td class="num">${agg.successCount} / ${agg.count}</td>`,
1464
- html`<td class="num">${agg.errorCount === 0 ? null : agg.errorCount}</td>`,
1465
- html`<td class="num">${time(s?.percentiles["p50"])}</td>`,
1466
- html`<td class="num">${s === null ? DASH : percentileCell(s.percentiles[level], ev.limits.percentile)}</td>`,
1467
- html`<td class="num">${s === null ? DASH : percentileCell(s.percentiles["p99"], ev.limits.p99)}</td>`,
1468
- html`<td class="num">${time(s?.max)}</td>`,
1469
- kind2 === "endpoints" ? html`<td class="num">${time(agg.ttfb?.p50)}</td>` : null,
1470
- html`<td class="num">${agg.testCount}</td></tr>`,
1471
- html`<tr class="details-row"><td colspan="${columns}"><details${group <= 1 ? html` data-violation=""` : null}>`,
1472
- html`<summary>Details <span class="visually-hidden">of ${short}</span></summary>`,
1473
- html`<div class="details-body">${details(key2, agg, kind2, report, level)}</div></details></td></tr></tbody>`
1474
- );
1475
- }
1476
- function keyTable(kind2, aggregates, report, level) {
1477
- const title = kind2 === "endpoints" ? "Endpoints" : "Custom measurements";
1478
- const id = `${kind2}-table`;
1479
- const cols = [
1480
- ["key", "Key", false],
1481
- ["result", "Result", false],
1482
- ["samples", "Samples", true],
1483
- ["errors", "Errors", true],
1484
- ["p50", "p50", true],
1485
- ["percentile", `${level} / limit`, true],
1486
- ["p99", "p99 / limit", true],
1487
- ["max", "Max", true],
1488
- ...kind2 === "endpoints" ? [["ttfb", "TTFB p50", true]] : [],
1489
- ["tests", "Tests", true]
1490
- ];
1491
- const keys = defaultOrder(aggregates, level);
1492
- const headerCell = ([column, label, numeric]) => html`<th scope="col" data-sort="${column}"${numeric ? html` class="num"` : null}><button type="button">${label}</button></th>`;
1493
- return join2(
1494
- html`<section aria-labelledby="${kind2}-h"><h2 id="${kind2}-h">${title}</h2>`,
1495
- html`<div class="filters" data-filters-for="${id}" hidden>`,
1496
- html`<label>Filter keys <input type="search" data-filter="text" autocomplete="off"></label>`,
1497
- html`<label><input type="checkbox" data-filter="violations"> Only violations</label>`,
1498
- html`<label><input type="checkbox" data-filter="not-evaluated"> Hide not evaluated</label>`,
1499
- html`<span class="count" role="status" data-count>showing ${keys.length} of ${keys.length}</span></div>`,
1500
- html`<div class="scroll"><table id="${id}" class="keys" data-kind="${kind2}" data-percentile="${level}">`,
1501
- html`<caption>${title}: ${plural(keys.length, "key")}, violations first</caption>`,
1502
- html`<thead><tr>${cols.map(headerCell)}</tr></thead>`,
1503
- keys.map(
1504
- (key2) => keyRow(key2, aggregates[key2], kind2, report, level, cols.length)
1505
- ),
1506
- html`</table></div></section>`
1507
- );
1508
- }
1509
- function field(object, name) {
1510
- return typeof object === "object" && object !== null ? object[name] : void 0;
1511
- }
1512
- function textOf(value) {
1513
- if (typeof value === "string") return value;
1514
- return typeof value === "number" ? String(value) : null;
1515
- }
1516
- function generatedSource(file) {
1517
- const generated = file.generated;
1518
- if (generated === null) return file.status === "loaded" ? "hand-written" : DASH;
1519
- const tool2 = field(generated, "tool");
1520
- const run = textOf(field(generated, "sourceRunId"));
1521
- const at2 = textOf(field(generated, "sourceRunStartedAt"));
1522
- const count2 = field(generated, "sourceSampleCount");
1523
- return [
1524
- `generated by ${textOf(field(tool2, "name")) ?? "unknown"} v${textOf(field(tool2, "version")) ?? "?"}`,
1525
- run === null ? "" : ` from run ${run}`,
1526
- at2 === null ? "" : ` (${formatDate(at2)})`,
1527
- typeof count2 === "number" ? `, ${plural(count2, "sample")}` : ""
1528
- ].join("");
1529
- }
1530
- function thresholdsFileRow(file, report) {
1531
- const percentile2 = textOf(field(file.generated, "evaluatedPercentile"));
1532
- const fingerprint2 = textOf(field(file.generated, "normalization"));
1533
- let normalization;
1534
- if (fingerprint2 === null) normalization = html`run <code>${report.normalization}</code>`;
1535
- else if (fingerprint2 === report.normalization)
1536
- normalization = html`<code>${fingerprint2}</code> <span class="ok">matches this run</span>`;
1537
- else
1538
- normalization = html`file <code>${fingerprint2}</code>, run <code>${report.normalization}</code> <strong class="warn">differs: keys may not match</strong>`;
1539
- const statusClass = file.status === "loaded" ? "ok" : file.status === "invalid" ? "bad" : "muted-text";
1540
- const unseen = file.unseenKeys;
1541
- return join2(
1542
- html`<tr><td>${file.kind}</td><td><code>${file.path}</code></td>`,
1543
- html`<td><span class="${statusClass}">${file.status}</span></td><td>${percentile2 ?? DASH}</td>`,
1544
- html`<td>${generatedSource(file)}</td><td>${normalization}</td><td>`,
1545
- unseen.length === 0 ? "0" : html`<details><summary>${plural(unseen.length, "key")}</summary><ul class="plain">${unseen.map((k) => html`<li><code>${k}</code></li>`)}</ul></details>`,
1546
- html`</td></tr>`
1547
- );
1548
- }
1549
- function thresholdsSection(report) {
1550
- const files = report.thresholdFiles;
1551
- return join2(
1552
- html`<section aria-labelledby="thresholds-h"><h2 id="thresholds-h">Thresholds files</h2>`,
1553
- files.length === 0 ? html`<p>No thresholds files were loaded in this run.</p>` : join2(
1554
- html`<div class="scroll"><table><caption>Thresholds files of this run</caption><thead><tr>`,
1555
- html`<th scope="col">Kind</th><th scope="col">Path</th><th scope="col">Status</th>`,
1556
- html`<th scope="col">Percentile</th><th scope="col">Source</th>`,
1557
- html`<th scope="col">Normalization fingerprint</th><th scope="col">Unseen keys</th>`,
1558
- html`</tr></thead><tbody>${files.map((f) => thresholdsFileRow(f, report))}</tbody></table></div>`
1559
- ),
1560
- html`</section>`
1561
- );
1562
- }
1563
- function runConditions(report) {
1564
- const rc = report.runConditions;
1565
- const overridden = rc.overriddenSettings.length === 0 ? "none" : rc.overriddenSettings.map((s, i) => html`${i > 0 ? ", " : ""}<code>${s}</code>`);
1566
- const project = (p) => join2(
1567
- html`<tr><th scope="row">${p.name === "" ? "(default)" : p.name}</th><td>${p.role}</td>`,
1568
- html`<td>${p.browserName ?? DASH}</td><td class="num">${p.repeatEach}</td><td class="num">${p.retries}</td></tr>`
1569
- );
1570
- return join2(
1571
- html`<section aria-labelledby="conditions-h"><h2 id="conditions-h">Run conditions</h2>`,
1572
- html`<p>${plural(rc.workers, "worker")}. Settings overridden by withPerf(): ${overridden}.</p>`,
1573
- rc.projects.length === 0 ? null : join2(
1574
- html`<div class="scroll"><table><caption>Projects</caption><thead><tr>`,
1575
- html`<th scope="col">Project</th><th scope="col">Role</th><th scope="col">Browser</th>`,
1576
- html`<th scope="col" class="num">repeatEach</th><th scope="col" class="num">retries</th>`,
1577
- html`</tr></thead><tbody>${rc.projects.map(project)}</tbody></table></div>`
1578
- ),
1579
- html`</section>`
1580
- );
1581
- }
1582
- function configuration(report) {
1583
- return join2(
1584
- html`<section aria-labelledby="config-h"><h2 id="config-h">Configuration</h2>`,
1585
- html`<details><summary>Configuration snapshot</summary>`,
1586
- html`<pre><code>${stableJson(report.config, " ")}</code></pre></details></section>`
1587
- );
1588
- }
1589
- function footer(report) {
1590
- return html`<footer>Generated by <a href="${REPOSITORY_URL}" rel="noopener noreferrer">${report.tool.name}</a> v${report.tool.version}</footer>`;
1591
- }
1592
- function keySections(data, report) {
1593
- const level = percentileLevel(report);
1594
- const hasEndpoints = Object.keys(data.endpoints).length > 0;
1595
- const hasCustom = Object.keys(data.custom).length > 0;
1596
- if (!hasEndpoints && !hasCustom) {
1597
- return join2(
1598
- html`<section aria-labelledby="endpoints-h"><h2 id="endpoints-h">Endpoints</h2>`,
1599
- html`<p>No requests or custom measurements were recorded. See the `,
1600
- html`<a href="${`${REPOSITORY_URL}#readme`}" rel="noopener noreferrer">documentation</a>`,
1601
- html` for setting up the measured tests.</p></section>`
1602
- );
1603
- }
1604
- return [
1605
- hasEndpoints ? keyTable("endpoints", data.endpoints, report, level) : html`<section aria-labelledby="endpoints-h"><h2 id="endpoints-h">Endpoints</h2><p>No backend requests were recorded.</p></section>`,
1606
- hasCustom ? keyTable("custom", data.custom, report, level) : null
1607
- ];
1608
- }
1609
- var CONTENT_SECURITY_POLICY = `default-src 'none'; script-src 'sha256-${SCRIPT_SHA256}'; style-src 'sha256-${STYLES_SHA256}'; img-src data:`;
1610
- function renderHtmlReport(report) {
1611
- const data = toHtmlReportData(report);
1612
- const head = join2(
1613
- html`<head><meta charset="utf-8">`,
1614
- html`<meta http-equiv="Content-Security-Policy" content="${CONTENT_SECURITY_POLICY}">`,
1615
- html`<meta name="viewport" content="width=device-width, initial-scale=1">`,
1616
- html`<meta name="color-scheme" content="light dark">`,
1617
- html`<meta name="generator" content="${`${PACKAGE_NAME} ${report.tool.version}`}">`,
1618
- html`<link rel="icon" href="data:,"><title>Performance report ${report.runId}</title>`,
1619
- html`<style>${trustedHtml(STYLES)}</style></head>`
1620
- );
1621
- const download = join2(
1622
- html`<div class="toolbar"><button type="button" id="download" hidden>Download JSON (aggregates, without raw samples)</button>`,
1623
- html`<a id="download-link" download="report-data.json" hidden tabindex="-1"></a></div>`
1624
- );
1625
- const main = join2(
1626
- header(report),
1627
- download,
1628
- verdict(report),
1629
- mutedSection(report),
1630
- counters(report),
1631
- issuesSection(report),
1632
- keySections(data, report),
1633
- thresholdsSection(report),
1634
- runConditions(report),
1635
- configuration(report)
1636
- );
1637
- const page = join2(
1638
- html`<!doctype html>\n<html lang="en">${head}\n<body><main>${main}</main>${footer(report)}\n`,
1639
- html`<script type="application/json" id="report-data">${trustedHtml(embeddedJson(data))}</script>\n`,
1640
- html`<script>${trustedHtml(SCRIPT)}</script>\n</body></html>\n`
1641
- );
1642
- return page.text;
1643
- }
1644
-
1645
- // src/core/random/index.ts
1646
- var FIXED_HASH_SEED = 0;
1647
- function hash53(input, seed) {
1648
- let h1 = 3735928559 ^ seed;
1649
- let h2 = 1103547991 ^ seed;
1650
- for (let i = 0; i < input.length; i++) {
1651
- const ch = input.charCodeAt(i);
1652
- h1 = Math.imul(h1 ^ ch, 2654435761);
1653
- h2 = Math.imul(h2 ^ ch, 1597334677);
1654
- }
1655
- h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
1656
- h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
1657
- h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
1658
- h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
1659
- return 4294967296 * (2097151 & h2) + (h1 >>> 0);
1660
- }
1661
- function hashHex(input) {
1662
- return hash53(input, FIXED_HASH_SEED).toString(16).padStart(14, "0");
1663
- }
1664
-
1665
- // src/core/stats/classification.ts
1666
- var ABORT_FAILURE_TEXTS = Object.freeze([
1667
- "net::ERR_ABORTED",
1668
- "NS_BINDING_ABORTED",
1669
- "NS_ERROR_ABORT",
1670
- "cancelled",
1671
- CONTEXT_CLOSED_FAILURE_TEXT
1672
- ]);
1673
- var ABORT_TEXTS = new Set(ABORT_FAILURE_TEXTS);
1674
- function requestStatusLabel(sample) {
1675
- const { status } = sample;
1676
- if (typeof status === "number") return String(status);
1677
- if (status === "FAILED" && sample.failureText !== void 0 && ABORT_TEXTS.has(sample.failureText)) {
1678
- return "ABORTED";
1679
- }
1680
- return status;
1681
- }
1682
- var STATUS_CLASS = /^([1-9])xx$/u;
1683
- var HTTP_CODE = /^[1-9]\d\d$/u;
1684
- function compileStatusMatcher(patterns) {
1685
- const classes = /* @__PURE__ */ new Set();
1686
- const exact = /* @__PURE__ */ new Set();
1687
- for (const pattern of patterns) {
1688
- const match = STATUS_CLASS.exec(pattern);
1689
- if (match?.[1] !== void 0) classes.add(match[1]);
1690
- else exact.add(pattern);
1691
- }
1692
- return (label) => exact.has(label) || HTTP_CODE.test(label) && classes.has(label.charAt(0));
1693
- }
1694
-
1695
- // src/core/stats/identity.ts
1696
- function testIdentity(project, file, title) {
1697
- return `${project}\0${file}\0${title}`;
1698
- }
1699
- function resultId(testId, repeatEachIndex, retry) {
1700
- return `${testId}\0${repeatEachIndex}\0${retry}`;
1701
- }
1702
- function sampleId(result, kind2, ordinal) {
1703
- return `${result}\0${kind2}\0${ordinal}`;
1704
- }
1705
- function isFailedTest(status, expectedStatus) {
1706
- return status !== expectedStatus && status !== "skipped";
1707
- }
1708
-
1709
- // src/core/stats/percentile.ts
1710
- function percentile(sorted, p) {
1711
- const n = sorted.length;
1712
- if (n === 0) return null;
1713
- const scaled = (n - 1) * p;
1714
- const lo = Math.min(Math.floor(scaled / 100), n - 1);
1715
- const x = sorted[lo] ?? Number.NaN;
1716
- if (lo + 1 >= n) return x;
1717
- const next = sorted[lo + 1] ?? Number.NaN;
1718
- return x + (scaled - lo * 100) / 100 * (next - x);
1719
- }
1720
- var ALWAYS = ["p50", "p90", "p95", "p99"];
1721
- function parsePercentileName(name) {
1722
- if (!/^p\d+(?:\.\d)?$/u.test(name)) {
1723
- throw new Error(`Invalid percentile name "${name}"; expected a name like "p95".`);
1724
- }
1725
- const value = Number(name.slice(1));
1726
- if (value > 100) throw new Error(`Invalid percentile name "${name}"; at most "p100".`);
1727
- return value;
1728
- }
1729
- function percentileNames(evaluated) {
1730
- const names = /* @__PURE__ */ new Set([...ALWAYS, evaluated]);
1731
- return [...names].map((name) => [name, parsePercentileName(name)]).sort((a, b) => a[1] - b[1]);
1732
- }
1733
-
1734
- // src/core/stats/sampling.ts
1735
- function at(array, i) {
1736
- return array[i] ?? 0;
1737
- }
1738
- function compareText(a, b) {
1739
- return a < b ? -1 : a > b ? 1 : 0;
1740
- }
1741
- var INITIAL_CAPACITY = 16;
1742
- var BottomK = class {
1743
- capacity;
1744
- size = 0;
1745
- idOf;
1746
- priority;
1747
- duration;
1748
- ttfb;
1749
- result;
1750
- ordinal;
1751
- constructor(capacity, idOf) {
1752
- this.capacity = capacity;
1753
- this.idOf = idOf;
1754
- const initial = Math.min(capacity, INITIAL_CAPACITY);
1755
- this.priority = new Float64Array(initial);
1756
- this.duration = new Int32Array(initial);
1757
- this.ttfb = new Int32Array(initial);
1758
- this.result = new Int32Array(initial);
1759
- this.ordinal = new Int32Array(initial);
1760
- }
1761
- /** Adds a sample: priority from hash53, duration and TTFB in tenths of a ms (TTFB −1: none). */
1762
- add(priority, duration, ttfb, resultIndex, ordinal) {
1763
- if (this.size < this.capacity) {
1764
- if (this.size === this.priority.length) this.grow();
1765
- this.set(this.size, priority, duration, ttfb, resultIndex, ordinal);
1766
- this.size += 1;
1767
- this.siftUp(this.size - 1);
1768
- return;
1769
- }
1770
- if (this.capacity === 0) return;
1771
- if (this.compareWith(priority, resultIndex, ordinal, 0) >= 0) return;
1772
- this.set(0, priority, duration, ttfb, resultIndex, ordinal);
1773
- this.siftDown(0);
1774
- }
1775
- /** Kept durations in tenths of a ms, ascending. */
1776
- durations() {
1777
- return Array.from(this.duration.subarray(0, this.size)).sort((a, b) => a - b);
1778
- }
1779
- /** Known TTFB values of the kept samples in tenths of a ms, ascending. */
1780
- ttfbs() {
1781
- return Array.from(this.ttfb.subarray(0, this.size)).filter((t) => t >= 0).sort((a, b) => a - b);
1782
- }
1783
- grow() {
1784
- const size = Math.min(this.capacity, this.priority.length * 2);
1785
- const copy = (from, to) => {
1786
- to.set(from);
1787
- return to;
1788
- };
1789
- this.priority = copy(this.priority, new Float64Array(size));
1790
- this.duration = copy(this.duration, new Int32Array(size));
1791
- this.ttfb = copy(this.ttfb, new Int32Array(size));
1792
- this.result = copy(this.result, new Int32Array(size));
1793
- this.ordinal = copy(this.ordinal, new Int32Array(size));
1794
- }
1795
- set(i, priority, duration, ttfb, resultIndex, ordinal) {
1796
- this.priority[i] = priority;
1797
- this.duration[i] = duration;
1798
- this.ttfb[i] = ttfb;
1799
- this.result[i] = resultIndex;
1800
- this.ordinal[i] = ordinal;
1801
- }
1802
- /** Order of (priority, resultIndex, ordinal) relative to the kept sample j. */
1803
- compareWith(priority, resultIndex, ordinal, j) {
1804
- const diff = priority - at(this.priority, j);
1805
- if (diff !== 0) return diff;
1806
- return compareText(
1807
- this.idOf(resultIndex, ordinal),
1808
- this.idOf(at(this.result, j), at(this.ordinal, j))
1809
- );
1810
- }
1811
- compare(i, j) {
1812
- return this.compareWith(at(this.priority, i), at(this.result, i), at(this.ordinal, i), j);
1813
- }
1814
- swap(i, j) {
1815
- for (const array of [this.priority, this.duration, this.ttfb, this.result, this.ordinal]) {
1816
- const value = at(array, i);
1817
- array[i] = at(array, j);
1818
- array[j] = value;
1819
- }
1820
- }
1821
- siftUp(start) {
1822
- let i = start;
1823
- while (i > 0) {
1824
- const parent = i - 1 >>> 1;
1825
- if (this.compare(i, parent) <= 0) return;
1826
- this.swap(i, parent);
1827
- i = parent;
1828
- }
1829
- }
1830
- siftDown(start) {
1831
- let i = start;
1832
- for (; ; ) {
1833
- const left = 2 * i + 1;
1834
- if (left >= this.size) return;
1835
- const right = left + 1;
1836
- const larger = right < this.size && this.compare(right, left) > 0 ? right : left;
1837
- if (this.compare(larger, i) <= 0) return;
1838
- this.swap(i, larger);
1839
- i = larger;
1840
- }
1841
- }
1842
- };
1843
-
1844
- // src/core/stats/aggregator.ts
1845
- var SLOWEST = 3;
1846
- var TOP_TESTS = 5;
1847
- function compareText2(a, b) {
1848
- return a < b ? -1 : a > b ? 1 : 0;
1849
- }
1850
- function toTenths(ms2) {
1851
- return Math.round(ms2 * 10);
1852
- }
1853
- function compareSlow(a, b) {
1854
- return b.tenths - a.tenths || compareText2(a.test.file, b.test.file) || a.test.line - b.test.line || a.test.repeatEachIndex - b.test.repeatEachIndex || a.ordinal - b.ordinal || compareText2(a.sampleId, b.sampleId);
1855
- }
1856
- function compareTopTests(a, b) {
1857
- return b.sampleCount - a.sampleCount || compareText2(a.file, b.file) || a.line - b.line || compareText2(a.title, b.title) || compareText2(a.project, b.project);
1858
- }
1859
- var KeyState = class {
1860
- kind;
1861
- count = 0;
1862
- successCount = 0;
1863
- errorCount = 0;
1864
- fromFailedTests = 0;
1865
- browser = 0;
1866
- node = 0;
1867
- statuses = /* @__PURE__ */ new Map();
1868
- /** Test identity → sample count (08-REQ-29). */
1869
- tests = /* @__PURE__ */ new Map();
1870
- minTenths = Infinity;
1871
- maxTenths = -Infinity;
1872
- /** Exact integer sum in tenths of a ms (08-REQ-16). */
1873
- sumTenths = 0;
1874
- slowest = [];
1875
- sample;
1876
- constructor(kind2, sample) {
1877
- this.kind = kind2;
1878
- this.sample = sample;
1879
- }
1880
- countSample(label, test, isError) {
1881
- this.count += 1;
1882
- this.statuses.set(label, (this.statuses.get(label) ?? 0) + 1);
1883
- if (isError) this.errorCount += 1;
1884
- if (test.failed) this.fromFailedTests += 1;
1885
- const counter = this.tests.get(test.identity);
1886
- if (counter === void 0) {
1887
- this.tests.set(test.identity, {
1888
- title: test.title,
1889
- project: test.project,
1890
- file: test.file,
1891
- line: test.line,
1892
- sampleCount: 1
1893
- });
1894
- } else {
1895
- counter.sampleCount += 1;
1896
- }
1897
- }
1898
- addSlow(candidate) {
1899
- const list = this.slowest;
1900
- const last = list[SLOWEST - 1];
1901
- if (last !== void 0 && compareSlow(candidate, last) >= 0) return;
1902
- list.push(candidate);
1903
- list.sort(compareSlow);
1904
- if (list.length > SLOWEST) list.pop();
1905
- }
1906
- };
1907
- var Aggregator = class {
1908
- opts;
1909
- isSuccess;
1910
- isError;
1911
- percentiles;
1912
- endpoints = /* @__PURE__ */ new Map();
1913
- custom = /* @__PURE__ */ new Map();
1914
- /** Interned resultIds: the heap stores an index instead of the text (08-REQ-29). */
1915
- resultIndex = /* @__PURE__ */ new Map();
1916
- resultIds = [];
1917
- origins = /* @__PURE__ */ new Map();
1918
- browsers = /* @__PURE__ */ new Set();
1919
- outsideProjects = /* @__PURE__ */ new Set();
1920
- outsideSamples = 0;
1921
- withoutBrowserTiming = 0;
1922
- keysWithoutBrowserTiming = /* @__PURE__ */ new Set();
1923
- finalized = false;
1924
- constructor(opts) {
1925
- this.opts = opts;
1926
- this.isSuccess = compileStatusMatcher(opts.successStatuses);
1927
- this.isError = compileStatusMatcher(opts.errors.statuses);
1928
- this.percentiles = percentileNames(opts.evaluatedPercentile);
1929
- }
1930
- /**
1931
- * Adds a request sample under `key`. `origin` and `label` come from the KeyResult (07); null
1932
- * when the URL could not be parsed (07-REQ-23), then the sample is not counted in origins.
1933
- * `browserName` is the batch's collector.browserName (08-REQ-32).
1934
- */
1935
- addRequest(key2, sample, origin, label, browserName) {
1936
- if (!this.accept(sample.test)) return;
1937
- if (browserName !== null) this.browsers.add(browserName);
1938
- if (origin !== null) {
1939
- const entry = this.origins.get(origin);
1940
- const text = label ?? "";
1941
- if (entry === void 0) this.origins.set(origin, { label: text, requestCount: 1 });
1942
- else {
1943
- entry.requestCount += 1;
1944
- if (compareText2(text, entry.label) < 0) entry.label = text;
1945
- }
1946
- }
1947
- const state = this.state(this.endpoints, "request", key2);
1948
- const statusLabel = requestStatusLabel(sample);
1949
- state.countSample(statusLabel, sample.test, this.isError(statusLabel));
1950
- if (sample.timeSource === "node") state.node += 1;
1951
- else state.browser += 1;
1952
- if (typeof sample.status !== "number" || !this.isSuccess(statusLabel)) return;
1953
- if (sample.timeSource === "node") {
1954
- this.withoutBrowserTiming += 1;
1955
- this.keysWithoutBrowserTiming.add(key2);
1956
- }
1957
- if (sample.timeSource !== "browser" || sample.fromServiceWorker || sample.duration === null) {
1958
- return;
1959
- }
1960
- this.addTime(state, key2, sample.test, sample.ordinal, {
1961
- duration: sample.duration,
1962
- ttfb: sample.ttfb,
1963
- startedAt: sample.startTime,
1964
- ...this.opts.rawUrls ? { url: sample.url } : {}
1965
- });
1966
- }
1967
- /** Adds a custom measurement sample under its name (08-REQ-04). */
1968
- addCustom(name, sample) {
1969
- if (!this.accept(sample.test)) return;
1970
- const state = this.state(this.custom, "custom", name);
1971
- state.countSample(sample.outcome, sample.test, sample.outcome !== "ok");
1972
- state.node += 1;
1973
- if (sample.outcome !== "ok" || sample.duration === null || sample.endTime === null) return;
1974
- this.addTime(state, name, sample.test, sample.ordinal, {
1975
- duration: sample.duration,
1976
- ttfb: null,
1977
- startedAt: Math.round(sample.endTime - sample.duration)
1978
- });
1979
- }
1980
- /** Builds the aggregates; may be called once. */
1981
- finalize() {
1982
- if (this.finalized) throw new Error("Aggregator.finalize() may be called once.");
1983
- this.finalized = true;
1984
- return {
1985
- endpoints: this.build(this.endpoints),
1986
- custom: this.build(this.custom),
1987
- origins: [...this.origins.keys()].sort(compareText2).map((origin) => {
1988
- const entry = this.origins.get(origin) ?? { label: "", requestCount: 0 };
1989
- return { origin, label: entry.label, requestCount: entry.requestCount };
1990
- }),
1991
- issues: this.issues()
1992
- };
1993
- }
1994
- /** False for samples of projects that are not measured (08-REQ-31). */
1995
- accept(test) {
1996
- if (this.finalized) throw new Error("Aggregator: samples added after finalize().");
1997
- if (this.opts.measuredProjects.has(test.project)) return true;
1998
- this.outsideSamples += 1;
1999
- this.outsideProjects.add(test.project);
2000
- return false;
2001
- }
2002
- state(states, kind2, key2) {
2003
- let state = states.get(key2);
2004
- if (state === void 0) {
2005
- const ids = this.resultIds;
2006
- state = new KeyState(
2007
- kind2,
2008
- new BottomK(
2009
- this.opts.advanced.maxSamplesPerKey,
2010
- (r, ordinal) => sampleId(ids[r] ?? "", kind2, ordinal)
2011
- )
2012
- );
2013
- states.set(key2, state);
2014
- }
2015
- return state;
2016
- }
2017
- addTime(state, key2, test, ordinal, time) {
2018
- const tenths = toTenths(time.duration);
2019
- state.successCount += 1;
2020
- state.sumTenths += tenths;
2021
- if (tenths < state.minTenths) state.minTenths = tenths;
2022
- if (tenths > state.maxTenths) state.maxTenths = tenths;
2023
- let r = this.resultIndex.get(test.resultId);
2024
- if (r === void 0) {
2025
- r = this.resultIds.length;
2026
- this.resultIds.push(test.resultId);
2027
- this.resultIndex.set(test.resultId, r);
2028
- }
2029
- const id = sampleId(test.resultId, state.kind, ordinal);
2030
- const priority = hash53(`${key2}\0${id}`, this.opts.advanced.seed);
2031
- state.sample.add(priority, tenths, time.ttfb === null ? -1 : toTenths(time.ttfb), r, ordinal);
2032
- state.addSlow({
2033
- tenths,
2034
- startedAt: time.startedAt,
2035
- test,
2036
- ordinal,
2037
- sampleId: id,
2038
- ...time.url === void 0 ? {} : { url: time.url }
2039
- });
2040
- }
2041
- build(states) {
2042
- const result = {};
2043
- for (const key2 of [...states.keys()].sort(compareText2)) {
2044
- const state = states.get(key2);
2045
- if (state !== void 0) result[key2] = this.aggregate(state);
2046
- }
2047
- return result;
2048
- }
2049
- aggregate(state) {
2050
- const durations = state.sample.durations().map((t) => t / 10);
2051
- const ttfbs = state.sample.ttfbs().map((t) => t / 10);
2052
- const at2 = (sorted, p) => roundMs(percentile(sorted, p) ?? 0);
2053
- const statuses = {};
2054
- for (const label of [...state.statuses.keys()].sort(compareText2)) {
2055
- statuses[label] = state.statuses.get(label) ?? 0;
2056
- }
2057
- const usable = state.successCount > 0;
2058
- return {
2059
- count: state.count,
2060
- successCount: state.successCount,
2061
- errorCount: state.errorCount,
2062
- fromFailedTests: state.fromFailedTests,
2063
- testCount: state.tests.size,
2064
- statuses,
2065
- timeSources: { browser: state.browser, node: state.node },
2066
- stats: usable ? {
2067
- min: state.minTenths / 10,
2068
- avg: Math.round(state.sumTenths / state.successCount) / 10,
2069
- max: state.maxTenths / 10,
2070
- percentiles: Object.fromEntries(
2071
- this.percentiles.map(([name, p]) => [name, at2(durations, p)])
2072
- )
2073
- } : null,
2074
- ttfb: ttfbs.length === 0 ? null : { p50: at2(ttfbs, 50), p95: at2(ttfbs, 95) },
2075
- slowest: state.slowest.map((s) => ({
2076
- duration: s.tenths / 10,
2077
- startedAt: new Date(s.startedAt).toISOString(),
2078
- test: {
2079
- title: s.test.title,
2080
- project: s.test.project,
2081
- file: s.test.file,
2082
- line: s.test.line,
2083
- repeatEachIndex: s.test.repeatEachIndex
2084
- },
2085
- ...s.url === void 0 ? {} : { url: s.url }
2086
- })),
2087
- topTests: [...state.tests.values()].map(({ title, project, file, line, sampleCount }) => ({
2088
- title,
2089
- project,
2090
- file,
2091
- line,
2092
- sampleCount
2093
- })).sort(compareTopTests).slice(0, TOP_TESTS),
2094
- samples: {
2095
- durations,
2096
- sampled: state.successCount > this.opts.advanced.maxSamplesPerKey
2097
- }
2098
- };
2099
- }
2100
- issues() {
2101
- const issues = [];
2102
- const plural4 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2103
- if (this.withoutBrowserTiming > 0) {
2104
- const n = this.withoutBrowserTiming;
2105
- issues.push({
2106
- code: "STATS_SAMPLES_WITHOUT_BROWSER_TIMING",
2107
- message: `${plural4(n, "successful request sample")} in ${plural4(this.keysWithoutBrowserTiming.size, "endpoint key")} had no browser timing (timeSource "node") and ${n === 1 ? "was" : "were"} left out of the time statistics.`,
2108
- hint: "Browser timing is missing for some requests (e.g. when the browser reports no timing for them); they still count in count and statuses."
2109
- });
2110
- }
2111
- if (this.outsideSamples > 0) {
2112
- const projects = [...this.outsideProjects].sort(compareText2).join(", ");
2113
- issues.push({
2114
- code: "STATS_SAMPLES_OUTSIDE_MEASURED_PROJECTS",
2115
- message: `${plural4(this.outsideSamples, "sample")} from projects that are not measured (${projects}) were not aggregated.`,
2116
- hint: "Setup and teardown projects run once and are not measured; move the calls you want to measure into tests of a measured project."
2117
- });
2118
- }
2119
- if (this.browsers.size > 1) {
2120
- const names = [...this.browsers].sort(compareText2).join(", ");
2121
- issues.push({
2122
- code: "STATS_MULTIPLE_BROWSERS",
2123
- message: `Request samples come from more than one browser (${names}); timings of different engines are mixed in the same keys.`,
2124
- hint: "Measure one browser engine per run (option run.projects)."
2125
- });
2126
- }
2127
- return issues;
2128
- }
2129
- };
2130
- function addKeyedRequest(aggregator, keyOf, sample, browserName) {
2131
- const result = keyOf(sample);
2132
- if (result.ok) {
2133
- aggregator.addRequest(result.key, sample, result.origin, result.label, browserName);
2134
- }
2135
- return result;
2136
- }
2137
-
2138
- // src/core/stats/functions.ts
2139
- var WILSON_Z = 1.96;
2140
- function countAtMost(sorted, t) {
2141
- let lo = 0;
2142
- let hi = sorted.length;
2143
- while (lo < hi) {
2144
- const mid = lo + hi >>> 1;
2145
- if ((sorted[mid] ?? Number.NaN) <= t) lo = mid + 1;
2146
- else hi = mid;
2147
- }
2148
- return lo;
2149
- }
2150
- function apdexCounts(sorted, t) {
2151
- const s = countAtMost(sorted, t);
2152
- const u = countAtMost(sorted, 4 * t) - s;
2153
- return { s, u, n: sorted.length };
2154
- }
2155
- function apdex(sorted, t) {
2156
- const { s, u, n } = apdexCounts(sorted, t);
2157
- return n === 0 ? null : roundRatio((s + u / 2) / n);
2158
- }
2159
- function exceedingShare(sorted, t) {
2160
- return { k: sorted.length - countAtMost(sorted, t), n: sorted.length };
2161
- }
2162
- function wilsonBounds(k, n) {
2163
- if (n === 0) return null;
2164
- const z2 = WILSON_Z * WILSON_Z;
2165
- const share = k / n;
2166
- const center = share + z2 / (2 * n);
2167
- const margin = WILSON_Z * Math.sqrt(share * (1 - share) / n + z2 / (4 * n * n));
2168
- const denominator = 1 + z2 / n;
2169
- const clamp2 = (x) => Math.min(1, Math.max(0, roundRatio(x)));
2170
- return {
2171
- lower: clamp2((center - margin) / denominator),
2172
- upper: clamp2((center + margin) / denominator)
2173
- };
2174
- }
2175
-
2176
- // src/core/evaluate/files.ts
2177
- function compareText3(a, b) {
2178
- return a < b ? -1 : a > b ? 1 : 0;
2179
- }
2180
- function plural2(n, word, many = `${word}s`) {
2181
- return `${n} ${n === 1 ? word : many}`;
2182
- }
2183
- var KIND_NOUN = { api: "endpoint", custom: "custom measurement" };
2184
- function envlessPath(path, env) {
2185
- const suffix = `.${env}.json`;
2186
- return path.endsWith(suffix) ? `${path.slice(0, -suffix.length)}.json` : path;
2187
- }
2188
- function missingFileWarning(file, env) {
2189
- const derive = `Derive thresholds with \`${CLI_COMMAND} thresholds\`${env === null ? "" : ` (environment "${env}")`}.`;
2190
- const envless = env !== null && file.envlessFileExists ? ` ${envlessPath(file.path, env)} exists but is not used for environment "${env}": thresholds of another environment would give false alarms or hide regressions.` : "";
2191
- return {
2192
- code: "THRESHOLDS_FILE_MISSING",
2193
- message: `Thresholds file ${file.path} not found; ${KIND_NOUN[file.kind]} keys are evaluated with default thresholds.`,
2194
- hint: `${derive}${envless}`
2195
- };
2196
- }
2197
- function majorMinor(version) {
2198
- return version.split(".").slice(0, 2).join(".");
2199
- }
2200
- function sameList(a, b) {
2201
- const x = [...new Set(a)].sort(compareText3);
2202
- const y = [...new Set(b)].sort(compareText3);
2203
- return x.length === y.length && x.every((v, i) => v === y[i]);
2204
- }
2205
- function listText(list) {
2206
- const unique = [...new Set(list)].sort(compareText3);
2207
- return unique.length === 0 ? "(none)" : unique.join(", ");
2208
- }
2209
- function sourceDifferences(generated, source) {
2210
- const diffs = [];
2211
- let timing = false;
2212
- let keys = false;
2213
- if (!sameList(generated.browsers, source.browsers)) {
2214
- diffs.push(`browsers ${listText(generated.browsers)} / ${listText(source.browsers)}`);
2215
- timing = true;
2216
- }
2217
- if (majorMinor(generated.playwrightVersion) !== majorMinor(source.playwrightVersion)) {
2218
- diffs.push(`playwrightVersion ${generated.playwrightVersion} / ${source.playwrightVersion}`);
2219
- timing = true;
2220
- }
2221
- const hostFields = ["platform", "arch", "ci", "cpuCount", "cpuModel"];
2222
- for (const field2 of hostFields) {
2223
- const a = generated.host[field2];
2224
- const b = source.host[field2];
2225
- if (a !== b) {
2226
- diffs.push(`host.${field2} ${JSON.stringify(a)} / ${JSON.stringify(b)}`);
2227
- timing = true;
2228
- }
2229
- }
2230
- if (generated.normalization !== source.normalization) {
2231
- diffs.push(`normalization ${generated.normalization} / ${source.normalization}`);
2232
- keys = true;
2233
- }
2234
- return { diffs, timing, keys };
2235
- }
2236
- function generatedWarnings(path, generated, cfg, env, source) {
2237
- const issues = [];
2238
- const level = cfg.checks.time.percentile.level;
2239
- if (generated.evaluatedPercentile !== level) {
2240
- issues.push({
2241
- code: "EVAL_PERCENTILE_MISMATCH",
2242
- message: `Thresholds in ${path} were derived for ${generated.evaluatedPercentile}, but this run evaluates ${level}; the percentile limits are compared with ${level}.`,
2243
- hint: `Derive thresholds again with \`${CLI_COMMAND} thresholds\` after changing checks.time.percentile.level.`
2244
- });
2245
- }
2246
- if (generated.env !== env) {
2247
- const show = (v) => v === null ? "none" : `"${v}"`;
2248
- issues.push({
2249
- code: "THRESHOLDS_ENV_MISMATCH",
2250
- message: `Thresholds in ${path} were derived for environment ${show(generated.env)}, but this run uses environment ${show(env)}.`,
2251
- hint: "The file was probably copied or renamed by hand; derive thresholds for this environment."
2252
- });
2253
- }
2254
- const { diffs, timing, keys } = sourceDifferences(generated, source);
2255
- if (diffs.length > 0) {
2256
- const hints = [];
2257
- if (timing) {
2258
- hints.push(
2259
- "Another machine, browser or Playwright version changes the timings: derive thresholds on the same infrastructure as the evaluation."
2260
- );
2261
- }
2262
- if (keys) {
2263
- hints.push(
2264
- `Another normalization changes the keys: derive thresholds again with \`${CLI_COMMAND} thresholds\`.`
2265
- );
2266
- }
2267
- issues.push({
2268
- code: "THRESHOLDS_SOURCE_MISMATCH",
2269
- message: `Thresholds in ${path} come from a run with other conditions (thresholds / this run): ${diffs.join("; ")}.`,
2270
- hint: hints.join(" ")
2271
- });
2272
- }
2273
- return issues;
2274
- }
2275
- function unseenWarning(path, unseen) {
2276
- return {
2277
- code: "THRESHOLDS_UNSEEN_ENTRIES",
2278
- message: `${plural2(unseen.length, "entry", "entries")} in ${path} ${unseen.length === 1 ? "was" : "were"} not seen in this run.`,
2279
- hint: `Run the full suite, or remove stale entries with \`${CLI_COMMAND} thresholds --prune\`.`
2280
- };
2281
- }
2282
- function outdatedWarning(path, from, current) {
2283
- return {
2284
- code: "THRESHOLDS_FILE_OUTDATED",
2285
- message: `Thresholds file ${path} has format version ${from}; it was read after migration to version ${current}.`,
2286
- hint: `The next \`${CLI_COMMAND} thresholds\` writes it in the current version and keeps locked entries.`
2287
- };
2288
- }
2289
- function fileInfo(file, unseenKeys) {
2290
- return {
2291
- kind: file.kind,
2292
- path: file.path,
2293
- status: file.status,
2294
- generated: file.status === "loaded" && file.file.generated !== null ? structuredClone(file.file.generated) : null,
2295
- unseenKeys
2296
- };
2297
- }
2298
-
2299
- // src/core/evaluate/limits.ts
2300
- function defaultLimits(checks, kind2) {
2301
- return {
2302
- t: null,
2303
- median: checks.time.median.limit[kind2],
2304
- percentile: checks.time.percentile.limit[kind2],
2305
- p99: checks.time.p99.limit[kind2],
2306
- minApdex: null,
2307
- maxWilson: null,
2308
- maxErrorRate: checks.errors.limit[kind2]
2309
- };
2310
- }
2311
- function entryLimits(entry, checks, kind2) {
2312
- const defaults = defaultLimits(checks, kind2);
2313
- const t = entry.t ?? null;
2314
- return {
2315
- t,
2316
- median: entry.median ?? defaults.median,
2317
- percentile: entry.percentile ?? defaults.percentile,
2318
- p99: entry.p99 ?? defaults.p99,
2319
- minApdex: t === null ? null : entry.minApdex === void 0 ? checks.slowShare.apdex.limit[kind2] : entry.minApdex,
2320
- maxWilson: t === null ? null : entry.maxWilson === void 0 ? checks.slowShare.wilson.limit[kind2] : entry.maxWilson,
2321
- maxErrorRate: entry.maxErrorRate ?? defaults.maxErrorRate
2322
- };
2323
- }
2324
-
2325
- // src/core/evaluate/muting.ts
2326
- var MUTE_EXPIRY_WARN_DAYS = 7;
2327
- var DAY_MS = 864e5;
2328
- function dayOf(timestamp2) {
2329
- const time = Date.parse(timestamp2);
2330
- if (Number.isNaN(time)) throw new Error(`evaluate: invalid startedAt "${timestamp2}"`);
2331
- return new Date(time).toISOString().slice(0, 10);
2332
- }
2333
- function daysBetween(from, to) {
2334
- return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS);
2335
- }
2336
- function keyMuting(entry, runDay) {
2337
- if (entry.gate !== "warn" || entry.until === void 0) return null;
2338
- return {
2339
- until: entry.until,
2340
- note: entry.note ?? "",
2341
- expired: daysBetween(entry.until, runDay) > 0
2342
- };
2343
- }
2344
- function isMuteActive(muted) {
2345
- return muted !== null && !muted.expired;
2346
- }
2347
- function keyList(keys) {
2348
- return keys.map(({ kind: kind2, key: key2, muted }) => `${kind2} ${key2} (until ${muted.until})`).join(", ");
2349
- }
2350
- function mutingWarnings(keys, runDay) {
2351
- const active = keys.filter((k) => !k.muted.expired);
2352
- const expiring = active.filter(
2353
- (k) => daysBetween(runDay, k.muted.until) <= MUTE_EXPIRY_WARN_DAYS
2354
- );
2355
- const expired = keys.filter((k) => k.muted.expired);
2356
- const issues = [];
2357
- if (active.length > 0) {
2358
- issues.push({
2359
- code: "THRESHOLDS_MUTED",
2360
- message: `${plural2(active.length, "key is", "keys are")} muted; ${active.length === 1 ? "its" : "their"} violations do not block.`,
2361
- hint: "Muted keys are listed with their note and end date; remove gate and until from the entry once the cause is fixed."
2362
- });
2363
- }
2364
- if (expiring.length > 0) {
2365
- issues.push({
2366
- code: "THRESHOLDS_MUTE_EXPIRING",
2367
- message: `Muting ends within ${MUTE_EXPIRY_WARN_DAYS} days for ${plural2(expiring.length, "key")}: ${keyList(expiring)}.`,
2368
- hint: "Fix the cause before the end date, or extend until in the thresholds file on purpose."
2369
- });
2370
- }
2371
- if (expired.length > 0) {
2372
- issues.push({
2373
- code: "THRESHOLDS_MUTE_EXPIRED",
2374
- message: `Muting expired for ${plural2(expired.length, "key")}, so ${expired.length === 1 ? "it blocks" : "they block"} again: ${keyList(expired)}.`,
2375
- hint: "Remove gate and until from the entry, or extend until on purpose."
2376
- });
2377
- }
2378
- return issues;
2379
- }
2380
-
2381
- // src/core/evaluate/rules.ts
2382
- var TIME_RULES2 = /* @__PURE__ */ new Set(["median", "percentile", "p99"]);
2383
- function timeCheck(rule, actual, limit, m) {
2384
- return { rule, n: m, actual, observed: null, limit, passed: !(actual > limit) };
2385
- }
2386
- function runRules(stats2, limits, cfg) {
2387
- const { time, slowShare, errors } = cfg.checks;
2388
- const n = stats2.successCount;
2389
- const bigN = stats2.count;
2390
- const durations = [...stats2.samples.durations].sort((a, b) => a - b);
2391
- const m = durations.length;
2392
- const percentiles = stats2.stats?.percentiles ?? {};
2393
- const at2 = (name) => {
2394
- const value = percentiles[name];
2395
- if (value === void 0) {
2396
- throw new Error(`evaluate: aggregate has no percentile "${name}"`);
2397
- }
2398
- return value;
2399
- };
2400
- const t = limits.t;
2401
- const inputs = [
2402
- {
2403
- ...time.median,
2404
- hasLimits: true,
2405
- count: n,
2406
- run: () => timeCheck("median", at2("p50"), limits.median, m)
2407
- },
2408
- {
2409
- ...time.percentile,
2410
- hasLimits: true,
2411
- count: n,
2412
- run: () => timeCheck("percentile", at2(time.percentile.level), limits.percentile, m)
2413
- },
2414
- {
2415
- ...time.p99,
2416
- hasLimits: true,
2417
- count: n,
2418
- run: () => timeCheck("p99", at2("p99"), limits.p99, m)
2419
- },
2420
- {
2421
- ...slowShare.apdex,
2422
- hasLimits: t !== null && limits.minApdex !== null,
2423
- count: n,
2424
- run: () => {
2425
- const tt = t ?? 0;
2426
- const limit = limits.minApdex ?? 0;
2427
- const { s, u } = apdexCounts(durations, tt);
2428
- const actual = wilsonBounds(s + u / 2, m)?.upper ?? 0;
2429
- return {
2430
- rule: "apdex",
2431
- n: m,
2432
- actual,
2433
- observed: apdex(durations, tt),
2434
- limit,
2435
- passed: !(actual < limit)
2436
- };
2437
- }
2438
- },
2439
- {
2440
- ...slowShare.wilson,
2441
- hasLimits: t !== null && limits.maxWilson !== null,
2442
- count: n,
2443
- run: () => {
2444
- const limit = limits.maxWilson ?? 0;
2445
- const { k } = exceedingShare(durations, t ?? 0);
2446
- const actual = wilsonBounds(k, m)?.lower ?? 0;
2447
- return {
2448
- rule: "wilson",
2449
- n: m,
2450
- actual,
2451
- observed: roundRatio(k / m),
2452
- limit,
2453
- passed: !(actual > limit)
2454
- };
2455
- }
2456
- },
2457
- {
2458
- ...errors,
2459
- hasLimits: true,
2460
- count: bigN,
2461
- run: () => {
2462
- const actual = wilsonBounds(stats2.errorCount, bigN)?.lower ?? 0;
2463
- return {
2464
- rule: "errors",
2465
- n: bigN,
2466
- actual,
2467
- observed: roundRatio(stats2.errorCount / bigN),
2468
- limit: limits.maxErrorRate,
2469
- passed: !(actual > limits.maxErrorRate)
2470
- };
2471
- }
2472
- }
2473
- ];
2474
- const hardLimitFactor = cfg.gate.hardLimitFactor;
2475
- const checks = [];
2476
- let applicable = false;
2477
- for (const input of inputs) {
2478
- if (!input.enabled || !input.hasLimits) continue;
2479
- applicable = true;
2480
- if (input.count < Math.max(1, input.minSamples)) continue;
2481
- const check2 = input.run();
2482
- const hardLimitExceeded = !check2.passed && TIME_RULES2.has(check2.rule) && hardLimitFactor !== null && check2.actual > check2.limit * hardLimitFactor;
2483
- checks.push({ ...check2, hardLimitExceeded, blocking: false });
2484
- }
2485
- return { checks, applicable };
2486
- }
2487
-
2488
- // src/core/evaluate/evaluate.ts
2489
- var KINDS2 = ["api", "custom"];
2490
- function allowedViolations(tolerance, evaluated) {
2491
- if (typeof tolerance === "number") return tolerance;
2492
- const match = /^(\d+)(?:\.(\d+))?%$/u.exec(tolerance);
2493
- if (match === null) throw new Error(`evaluate: invalid gate.tolerance "${tolerance}"`);
2494
- const decimals = match[2] ?? "";
2495
- const scale = 10 ** decimals.length;
2496
- const scaledPercent = Number(match[1]) * scale + (decimals === "" ? 0 : Number(decimals));
2497
- return Math.floor(scaledPercent * evaluated / (100 * scale));
2498
- }
2499
- function evaluateKey(key2, stats2, kind2, thresholds, cfg, runDay) {
2500
- const file = thresholds[kind2];
2501
- if (file.status === "invalid") {
2502
- return {
2503
- result: "not-evaluated",
2504
- reason: "thresholds-error",
2505
- thresholdSource: "default",
2506
- limits: defaultLimits(cfg.checks, kind2),
2507
- checks: [],
2508
- muted: null
2509
- };
2510
- }
2511
- const entries = file.status === "loaded" ? file.file.entries : {};
2512
- const entry = Object.hasOwn(entries, key2) ? entries[key2] : void 0;
2513
- const limits = entry === void 0 ? defaultLimits(cfg.checks, kind2) : entryLimits(entry, cfg.checks, kind2);
2514
- const { checks, applicable } = runRules(stats2, limits, cfg);
2515
- return {
2516
- result: checks.length === 0 ? "not-evaluated" : checks.some((c) => !c.passed) ? "fail" : "pass",
2517
- reason: checks.length > 0 ? null : applicable ? "too-few-samples" : "no-rules",
2518
- thresholdSource: entry === void 0 ? "default" : "file",
2519
- limits,
2520
- checks,
2521
- muted: entry === void 0 ? null : keyMuting(entry, runDay)
2522
- };
2523
- }
2524
- function qualifies(evaluation, gate) {
2525
- if (gate.warnOnly) return false;
2526
- if (evaluation.thresholdSource === "default" && gate.defaultThresholds === "warn") return false;
2527
- return !isMuteActive(evaluation.muted);
2528
- }
2529
- function applyGate(perKey, gate) {
2530
- const all = KINDS2.flatMap((kind2) => Object.values(perKey[kind2]));
2531
- const qualified = all.filter(
2532
- (e) => qualifies(e, gate) && e.checks.some((check2) => !check2.passed)
2533
- );
2534
- const evaluated = all.filter((e) => e.result !== "not-evaluated").length;
2535
- const overTolerance = qualified.length > allowedViolations(gate.tolerance, evaluated);
2536
- for (const evaluation of qualified) {
2537
- for (const check2 of evaluation.checks) {
2538
- check2.blocking = !check2.passed && (overTolerance || check2.hardLimitExceeded);
2539
- }
2540
- }
2541
- }
2542
- function countKind(perKey, unseenThresholdEntries) {
2543
- const counts = {
2544
- keys: 0,
2545
- fromFile: 0,
2546
- fromDefaults: 0,
2547
- notEvaluated: 0,
2548
- tooFewSamples: 0,
2549
- fileEntriesNotEvaluated: 0,
2550
- medianOnly: 0,
2551
- unseenThresholdEntries,
2552
- violations: 0,
2553
- blockingViolations: 0,
2554
- muted: 0
2555
- };
2556
- for (const e of Object.values(perKey)) {
2557
- counts.keys += 1;
2558
- if (isMuteActive(e.muted)) counts.muted += 1;
2559
- if (e.result === "not-evaluated") {
2560
- counts.notEvaluated += 1;
2561
- if (e.reason === "too-few-samples") {
2562
- counts.tooFewSamples += 1;
2563
- if (e.thresholdSource === "file") counts.fileEntriesNotEvaluated += 1;
2564
- }
2565
- continue;
2566
- }
2567
- if (e.thresholdSource === "file") counts.fromFile += 1;
2568
- else counts.fromDefaults += 1;
2569
- const timeRules = e.checks.filter((c) => TIME_RULES2.has(c.rule)).map((c) => c.rule);
2570
- if (timeRules.length === 1 && timeRules[0] === "median") counts.medianOnly += 1;
2571
- if (e.result === "fail") counts.violations += 1;
2572
- if (e.checks.some((c) => c.blocking)) counts.blockingViolations += 1;
2573
- }
2574
- return counts;
2575
- }
2576
- function evaluationStatus2(perKey, thresholds, fatalToolError) {
2577
- if (fatalToolError || KINDS2.some((kind2) => thresholds[kind2].status === "invalid")) {
2578
- return "error";
2579
- }
2580
- const checks = KINDS2.flatMap((kind2) => Object.values(perKey[kind2])).flatMap((e) => e.checks);
2581
- if (checks.some((c) => c.blocking)) return "failed";
2582
- if (checks.some((c) => !c.passed)) return "warned";
2583
- return "passed";
2584
- }
2585
- function evaluate(aggregates, thresholds, cfg, opts) {
2586
- const runDay = dayOf(opts.startedAt);
2587
- const byKind = {
2588
- api: aggregates.endpoints,
2589
- custom: aggregates.custom
2590
- };
2591
- const perKey = { api: {}, custom: {} };
2592
- for (const kind2 of KINDS2) {
2593
- for (const key2 of Object.keys(byKind[kind2]).sort(compareText3)) {
2594
- const stats2 = byKind[kind2][key2];
2595
- if (stats2 !== void 0) {
2596
- perKey[kind2][key2] = evaluateKey(key2, stats2, kind2, thresholds, cfg, runDay);
2597
- }
2598
- }
2599
- }
2600
- applyGate(perKey, cfg.gate);
2601
- const warnings = [];
2602
- const toolErrors = [];
2603
- const thresholdFiles = [];
2604
- const unseenCount = { api: 0, custom: 0 };
2605
- for (const kind2 of KINDS2) {
2606
- const file = thresholds[kind2];
2607
- if (file.kind !== kind2) {
2608
- throw new Error(`evaluate: thresholds.${kind2} has kind "${file.kind}"`);
2609
- }
2610
- let unseen = [];
2611
- if (file.status === "missing") {
2612
- warnings.push(missingFileWarning(file, opts.env));
2613
- } else if (file.status === "invalid") {
2614
- toolErrors.push(...file.issues.map(schemaIssueToIssue));
2615
- } else {
2616
- if (file.migratedFrom !== void 0) {
2617
- warnings.push(outdatedWarning(file.path, file.migratedFrom, SCHEMA_VERSIONS.thresholds));
2618
- }
2619
- if (file.file.generated !== null) {
2620
- warnings.push(
2621
- ...generatedWarnings(file.path, file.file.generated, cfg, opts.env, opts.source)
2622
- );
2623
- }
2624
- unseen = Object.keys(file.file.entries).filter((key2) => !Object.hasOwn(byKind[kind2], key2)).sort(compareText3);
2625
- if (unseen.length > 0) warnings.push(unseenWarning(file.path, unseen));
2626
- }
2627
- unseenCount[kind2] = unseen.length;
2628
- thresholdFiles.push(fileInfo(file, unseen));
2629
- }
2630
- const counts = {
2631
- api: countKind(perKey.api, unseenCount.api),
2632
- custom: countKind(perKey.custom, unseenCount.custom)
2633
- };
2634
- if (KINDS2.every((kind2) => Object.keys(byKind[kind2]).length === 0)) {
2635
- warnings.push({
2636
- code: "EVAL_NO_SAMPLES",
2637
- message: "The run recorded no samples, so nothing was evaluated.",
2638
- hint: "Check the integration: tests must use the fixtures from withPerfFixtures, and the measure options (include, exclude, resourceTypes) must not filter out every request."
2639
- });
2640
- }
2641
- const notEvaluated = counts.api.fileEntriesNotEvaluated + counts.custom.fileEntriesNotEvaluated;
2642
- if (notEvaluated > 0) {
2643
- warnings.push({
2644
- code: "THRESHOLDS_ENTRIES_NOT_EVALUATED",
2645
- message: `${plural2(notEvaluated, "key")} with an entry in the thresholds file had too few samples and ${notEvaluated === 1 ? "was" : "were"} not evaluated.`,
2646
- hint: `Run more repetitions (run.repeat or \`${CLI_COMMAND} test --repeat\`), or accept that the endpoint is called rarely.`
2647
- });
2648
- }
2649
- const mutedKeys = KINDS2.flatMap(
2650
- (kind2) => Object.entries(perKey[kind2]).flatMap(
2651
- ([key2, e]) => e.muted === null ? [] : [{ kind: kind2, key: key2, muted: e.muted }]
2652
- )
2653
- );
2654
- warnings.push(...mutingWarnings(mutedKeys, runDay));
2655
- return {
2656
- status: evaluationStatus2(perKey, thresholds, opts.fatalToolError),
2657
- gateEnabled: opts.mode === "test",
2658
- counts,
2659
- perKey,
2660
- thresholdFiles,
2661
- warnings,
2662
- toolErrors
2663
- };
2664
- }
2665
-
2666
- // src/core/evaluate/outcome.ts
2667
- function percent(share) {
2668
- return `${Math.round(share * 1e3) / 10}%`;
2669
- }
2670
- function assessRun(input, gate) {
2671
- const { tests, maxFailures, sharded } = input;
2672
- const warnings = [];
2673
- const toolErrors = [];
2674
- const executions = tests.expected + tests.unexpected + tests.flaky;
2675
- const share = executions === 0 ? 0 : tests.unexpected / executions;
2676
- const failedText = `${tests.unexpected} of ${plural2(executions, "test execution")} failed`;
2677
- if (share > gate.maxFailedTestShare) {
2678
- toolErrors.push({
2679
- code: "TESTS_FAILED_TOO_MANY",
2680
- message: `${failedText} (${percent(share)}, more than gate.maxFailedTestShare ${percent(gate.maxFailedTestShare)}); samples of a large part of the tests are missing, so the performance result is not trustworthy.`,
2681
- hint: "Fix the failing tests (run them without perf mode), or raise gate.maxFailedTestShare if the failures are expected."
2682
- });
2683
- } else if (tests.unexpected > 0) {
2684
- warnings.push({
2685
- code: "TESTS_FAILED",
2686
- message: `${failedText}; the performance result still decides.`,
2687
- hint: "Functional failures are reported by your regular test run."
2688
- });
2689
- }
2690
- const stoppedByMaxFailures = maxFailures > 0 && tests.unexpected >= maxFailures;
2691
- if (tests.status === "timedout" || tests.status === "interrupted" || stoppedByMaxFailures) {
2692
- const why = stoppedByMaxFailures ? `it stopped after ${plural2(tests.unexpected, "failure")} (maxFailures ${maxFailures})` : tests.status === "timedout" ? "it timed out" : "it was interrupted";
2693
- toolErrors.push({
2694
- code: "RUN_INCOMPLETE",
2695
- message: `The run did not execute all tests: ${why}. The evaluation covers only the samples collected.`,
2696
- hint: "Raise the global timeout or maxFailures for perf runs, or measure a smaller subset of tests."
2697
- });
2698
- }
2699
- if (sharded) {
2700
- toolErrors.push({
2701
- code: "RUN_SHARDED",
2702
- message: "The perf-mode run is sharded (--shard): each machine would evaluate only part of the keys.",
2703
- hint: "Run perf mode on one machine without --shard."
2704
- });
2705
- }
2706
- return { warnings, toolErrors };
2707
- }
2708
- function buildOutcome(report, paths) {
2709
- const exitCode = report.toolErrors.length > 0 ? 3 : report.mode === "test" && report.evaluation.gateEnabled && report.evaluation.status === "failed" ? 2 : 0;
2710
- return {
2711
- schemaVersion: SCHEMA_VERSIONS.outcome,
2712
- runId: report.runId,
2713
- mode: report.mode,
2714
- exitCode,
2715
- tests: { status: report.tests.status },
2716
- evaluation: { status: report.evaluation.status, gateEnabled: report.evaluation.gateEnabled },
2717
- toolErrors: report.toolErrors.map((issue2) => ({ ...issue2 })),
2718
- paths: { ...paths, thresholds: [...paths.thresholds] }
2719
- };
2720
- }
2721
-
2722
- // src/core/thresholds/constants.ts
2723
- var WILSON_SELF_GAP = 0.01;
2724
- var ERR_SELF_GAP = 0.01;
2725
-
2726
- // src/core/thresholds/formulas.ts
2727
- function minDeriveSamples(checks) {
2728
- return Math.max(1, checks.time.median.minSamples);
2729
- }
2730
- function isDerivable(stats2, checks) {
2731
- return stats2.stats !== null && stats2.successCount >= minDeriveSamples(checks);
2732
- }
2733
- function withPercentile(stats2, level) {
2734
- if (stats2.stats === null || stats2.stats.percentiles[level] !== void 0) return stats2;
2735
- const p = percentileNames(level).find(([name]) => name === level)?.[1];
2736
- const durations = [...stats2.samples.durations].sort((a, b) => a - b);
2737
- const value = p === void 0 ? null : percentile(durations, p);
2738
- if (value === null) return stats2;
2739
- return {
2740
- ...stats2,
2741
- stats: { ...stats2.stats, percentiles: { ...stats2.stats.percentiles, [level]: roundMs(value) } }
2742
- };
2743
- }
2744
- function clamp(x, min, max) {
2745
- return Math.min(max, Math.max(min, x));
2746
- }
2747
- function derivationSettings2(cfg, kind2) {
2748
- const { time, slowShare, errors } = cfg.checks;
2749
- return structuredClone({
2750
- t: slowShare.t[kind2],
2751
- smallSampleN: cfg.thresholds.smallSampleN,
2752
- margins: {
2753
- median: time.median.margin,
2754
- percentile: time.percentile.margin,
2755
- p99: time.p99.margin,
2756
- apdex: slowShare.apdex.margin,
2757
- wilson: slowShare.wilson.margin,
2758
- errors: errors.margin
2759
- }
2760
- });
2761
- }
2762
- function deriveEntry(stats2, kind2, cfg) {
2763
- const level = cfg.checks.time.percentile.level;
2764
- const source = withPercentile(stats2, level).stats;
2765
- if (source === null) throw new Error("deriveEntry: aggregate has no successful samples");
2766
- const at2 = (name) => {
2767
- const value = source.percentiles[name];
2768
- if (value === void 0) throw new Error(`deriveEntry: aggregate has no percentile "${name}"`);
2769
- return value;
2770
- };
2771
- const { time, slowShare, errors } = cfg.checks;
2772
- const T = slowShare.t[kind2];
2773
- const n = stats2.successCount;
2774
- const small = n < cfg.thresholds.smallSampleN;
2775
- const p50 = at2("p50");
2776
- const p90 = at2("p90");
2777
- const p99 = at2("p99");
2778
- const pE = at2(level);
2779
- const durations = [...stats2.samples.durations].sort((a, b) => a - b);
2780
- const t = p50 > T.max ? null : ceilTo(clamp(Math.min(p90, T.medianFactor * p50), T.min, T.max), 0);
2781
- const rMedian = small ? time.median.margin.smallSampleRelative : time.median.margin.relative;
2782
- const median = ceilTo(Math.max(p50 * (1 + rMedian), p50 + time.median.margin.minMs), 0);
2783
- const pMargin = time.percentile.margin;
2784
- const rPercentile = small ? pMargin.smallSampleRelative : pMargin.relative;
2785
- const percentileLimit = ceilTo(Math.max(pE * (1 + rPercentile), pE + pMargin.minMs, median), 0);
2786
- const p99Margin = time.p99.margin;
2787
- const p99Limit = ceilTo(
2788
- Math.max(
2789
- p99 * (1 + p99Margin.relative),
2790
- percentileLimit + Math.max(p99Margin.minGapMs, p99Margin.minGapRelative * percentileLimit)
2791
- ),
2792
- 0
2793
- );
2794
- let minApdex = null;
2795
- let maxWilson = null;
2796
- if (t !== null) {
2797
- const apdexMargin = slowShare.apdex.margin;
2798
- const score = apdex(durations, t) ?? 0;
2799
- minApdex = floorTo(
2800
- Math.max(0, score - (small ? apdexMargin.smallSampleAbsolute : apdexMargin.absolute)),
2801
- 3
2802
- );
2803
- const w = slowShare.wilson.margin;
2804
- const { k, n: m } = exceedingShare(durations, t);
2805
- const s = m === 0 ? 0 : k / m;
2806
- const wLow = wilsonBounds(k, m)?.lower ?? 0;
2807
- maxWilson = ceilTo(
2808
- Math.min(
2809
- 1,
2810
- Math.max(
2811
- clamp(s * w.factor + w.add, w.min, w.max),
2812
- small ? w.smallSampleMin : 0,
2813
- wLow + WILSON_SELF_GAP
2814
- )
2815
- ),
2816
- 3
2817
- );
2818
- }
2819
- const bigN = stats2.count;
2820
- const e = bigN === 0 ? 0 : stats2.errorCount / bigN;
2821
- const eLow = wilsonBounds(stats2.errorCount, bigN)?.lower ?? 0;
2822
- const em = errors.margin;
2823
- const maxErrorRate = ceilTo(
2824
- Math.min(1, Math.max(e * em.factor + em.add, em.min, eLow + ERR_SELF_GAP)),
2825
- 3
2826
- );
2827
- return {
2828
- t,
2829
- median,
2830
- percentile: percentileLimit,
2831
- p99: p99Limit,
2832
- minApdex,
2833
- maxWilson,
2834
- maxErrorRate
2835
- };
2836
- }
2837
-
2838
- // src/core/thresholds/consistency.ts
2839
- function allRulesOn(checks) {
2840
- const on = (rule) => ({
2841
- ...rule,
2842
- enabled: true,
2843
- minSamples: 0
2844
- });
2845
- return {
2846
- time: {
2847
- median: on(checks.time.median),
2848
- percentile: on(checks.time.percentile),
2849
- p99: on(checks.time.p99)
2850
- },
2851
- slowShare: {
2852
- t: checks.slowShare.t,
2853
- apdex: on(checks.slowShare.apdex),
2854
- wilson: on(checks.slowShare.wilson)
2855
- },
2856
- errors: on(checks.errors)
2857
- };
2858
- }
2859
- function entrySelfConsistent(entry, aggregate2, kind2, cfg) {
2860
- const checks = allRulesOn(cfg.checks);
2861
- const stats2 = withPercentile(aggregate2, checks.time.percentile.level);
2862
- const { checks: results } = runRules(stats2, entryLimits(entry, cfg.checks, kind2), {
2863
- checks,
2864
- gate: cfg.gate
2865
- });
2866
- return results.every((check2) => check2.passed);
2867
- }
2868
-
2869
- // src/core/thresholds/entries.ts
2870
- var MS_LIMITS = /* @__PURE__ */ new Set(["t", "median", "percentile", "p99"]);
2871
- var TIME_LIMITS = ["median", "percentile", "p99"];
2872
- function isComplete(entry) {
2873
- return LIMIT_NAMES.every((name) => entry[name] !== void 0);
2874
- }
2875
- function limitsOf(entry) {
2876
- return {
2877
- t: entry.t ?? null,
2878
- median: entry.median ?? null,
2879
- percentile: entry.percentile ?? null,
2880
- p99: entry.p99 ?? null,
2881
- minApdex: entry.minApdex ?? null,
2882
- maxWilson: entry.maxWilson ?? null,
2883
- maxErrorRate: entry.maxErrorRate ?? null
2884
- };
2885
- }
2886
- function atMost(a, b) {
2887
- return Math.round(a * 1e6) <= Math.round(b * 1e6);
2888
- }
2889
- function withinHysteresis(before, after, hysteresis) {
2890
- return LIMIT_NAMES.every((name) => {
2891
- const a = before[name];
2892
- const b = after[name];
2893
- if (a === null || b === null) return a === b;
2894
- const allowed = MS_LIMITS.has(name) ? hysteresis.relative * a : hysteresis.ratio;
2895
- return atMost(Math.abs(b - a), allowed);
2896
- });
2897
- }
2898
- function changeDirection(limit, before, after) {
2899
- if (before === after) return null;
2900
- if (after === null) return "looser";
2901
- if (before === null) return "stricter";
2902
- const higher = after > before;
2903
- return (limit === "minApdex" ? !higher : higher) ? "looser" : "stricter";
2904
- }
2905
- function grewMuch(limit, before, after, loosenWarnRelative) {
2906
- if (!TIME_LIMITS.includes(limit) || before === null || after === null) return false;
2907
- return !atMost(after - before, loosenWarnRelative * before);
2908
- }
2909
- function loosenedMuch(before, after, loosenWarnRelative) {
2910
- const a = limitsOf(before);
2911
- const b = limitsOf(after);
2912
- return TIME_LIMITS.some((name) => grewMuch(name, a[name], b[name], loosenWarnRelative));
2913
- }
2914
-
2915
- // src/core/thresholds/derive.ts
2916
- var KINDS3 = ["api", "custom"];
2917
- var KIND_NOUN2 = { api: "endpoint", custom: "custom measurement" };
2918
- function aggregatesOf(report, kind2) {
2919
- return kind2 === "api" ? report.endpoints : report.custom;
2920
- }
2921
- function reportSource(report) {
2922
- const browsers = report.runConditions.projects.filter((p) => p.role === "measured" && p.browserName !== null).map((p) => p.browserName ?? "");
2923
- const { platform, arch, ci, cpuCount, cpuModel } = report.host;
2924
- return {
2925
- browsers: [...new Set(browsers)].sort(compareText3),
2926
- playwrightVersion: report.playwright.version,
2927
- host: { platform, arch, ci, cpuCount, cpuModel },
2928
- normalization: report.normalization
2929
- };
2930
- }
2931
- function refusal(report, cfg, existing) {
2932
- const incomplete = [];
2933
- if (report.tests.status === "interrupted" || report.tests.status === "timedout") {
2934
- incomplete.push(`tests ${report.tests.status}`);
2935
- }
2936
- if (report.toolErrors.length > 0) {
2937
- const codes = [...new Set(report.toolErrors.map((issue2) => issue2.code))];
2938
- incomplete.push(`tool errors: ${codes.join(", ")}`);
2939
- }
2940
- if (incomplete.length > 0) {
2941
- return [
2942
- {
2943
- code: "THRESHOLDS_SOURCE_INCOMPLETE",
2944
- message: `The source report is incomplete or untrustworthy (${incomplete.join("; ")}); no thresholds file was written.`,
2945
- hint: `Fix the cause and derive again with \`${CLI_COMMAND} thresholds\`: thresholds are derived from complete runs only.`
2946
- }
2947
- ];
2948
- }
2949
- if (KINDS3.every((kind2) => Object.keys(aggregatesOf(report, kind2)).length === 0)) {
2950
- return [
2951
- {
2952
- code: "THRESHOLDS_EMPTY_REPORT",
2953
- message: "The source report has no samples; no thresholds file was written.",
2954
- hint: "Check the integration: tests must use the fixtures from withPerfFixtures, and the measure options must not filter out every request."
2955
- }
2956
- ];
2957
- }
2958
- const derivable = KINDS3.some(
2959
- (kind2) => Object.values(aggregatesOf(report, kind2)).some((stats2) => isDerivable(stats2, cfg.checks))
2960
- );
2961
- if (!derivable) {
2962
- return [
2963
- {
2964
- code: "THRESHOLDS_NOTHING_TO_DERIVE",
2965
- message: `No key has at least ${minDeriveSamples(cfg.checks)} successful samples (checks.time.median.minSamples); no thresholds file was written.`,
2966
- hint: `Run more repetitions (run.repeat.thresholds or \`${CLI_COMMAND} thresholds --repeat\`).`
2967
- }
2968
- ];
2969
- }
2970
- const invalid = KINDS3.flatMap((kind2) => {
2971
- const file = existing[kind2];
2972
- return file.status === "invalid" ? file.issues.map(schemaIssueToIssue) : [];
2973
- });
2974
- return invalid.length > 0 ? invalid : null;
2975
- }
2976
- function generatedBlock(report, cfg, kind2, opts) {
2977
- const source = reportSource(report);
2978
- const sampleCount = Object.values(aggregatesOf(report, kind2)).reduce(
2979
- (sum, stats2) => sum + stats2.successCount,
2980
- 0
2981
- );
2982
- return {
2983
- tool: { name: PACKAGE_NAME, version: opts.toolVersion },
2984
- env: opts.env,
2985
- sourceRunId: report.runId,
2986
- sourceRunStartedAt: report.startedAt,
2987
- sourceSampleCount: sampleCount,
2988
- evaluatedPercentile: cfg.checks.time.percentile.level,
2989
- derivation: derivationSettings2(cfg, kind2),
2990
- browsers: source.browsers,
2991
- playwrightVersion: source.playwrightVersion,
2992
- host: source.host,
2993
- normalization: source.normalization
2994
- };
2995
- }
2996
- function generatedChanged(before, after) {
2997
- return before.env !== after.env || before.evaluatedPercentile !== after.evaluatedPercentile || stringifyStable(before.derivation) !== stringifyStable(after.derivation) || !sameList(before.browsers, after.browsers) || majorMinor(before.playwrightVersion) !== majorMinor(after.playwrightVersion) || stringifyStable(before.host) !== stringifyStable(after.host) || before.normalization !== after.normalization;
2998
- }
2999
- function humanFields(entry) {
3000
- const fields = {};
3001
- if (entry.note !== void 0) fields.note = entry.note;
3002
- if (entry.gate !== void 0) fields.gate = entry.gate;
3003
- if (entry.until !== void 0) fields.until = entry.until;
3004
- return fields;
3005
- }
3006
- function deriveKind(report, cfg, file, opts) {
3007
- const kind2 = file.kind;
3008
- const aggregates = aggregatesOf(report, kind2);
3009
- const keys = Object.keys(aggregates).sort(compareText3);
3010
- const derivable = new Set(
3011
- keys.filter((key2) => {
3012
- const stats2 = aggregates[key2];
3013
- return stats2 !== void 0 && isDerivable(stats2, cfg.checks);
3014
- })
3015
- );
3016
- const warnings = [];
3017
- if (derivable.size === 0) {
3018
- if (keys.length > 0) {
3019
- warnings.push({
3020
- code: "THRESHOLDS_KIND_SKIPPED",
3021
- message: `No ${KIND_NOUN2[kind2]} key has at least ${minDeriveSamples(cfg.checks)} successful samples; ${file.path} was not written.`,
3022
- hint: `Run more repetitions (run.repeat.thresholds or \`${CLI_COMMAND} thresholds --repeat\`).`
3023
- });
3024
- }
3025
- return { file: { kind: kind2, content: null, changed: false }, warnings, loosenedMuch: 0 };
3026
- }
3027
- const loaded = file.status === "loaded" ? file : null;
3028
- if (loaded !== null && loaded.file.generated === null) {
3029
- warnings.push({
3030
- code: "THRESHOLDS_MANUAL_FILE",
3031
- message: `${loaded.path} was written by hand (generated: null); its complete entries that are not locked are recomputed.`,
3032
- hint: 'Mark entries you want to keep as they are with "locked": true.'
3033
- });
3034
- }
3035
- if (loaded !== null && loaded.file.generated !== null) {
3036
- const {
3037
- diffs,
3038
- timing,
3039
- keys: keysDiffer
3040
- } = sourceDifferences(loaded.file.generated, reportSource(report));
3041
- if (diffs.length > 0) {
3042
- const hints = [];
3043
- if (timing) {
3044
- hints.push(
3045
- `Deriving on another machine, browser or Playwright version shifts all limits at once: derive on the CI infrastructure that evaluates the runs (\`${CLI_COMMAND} thresholds --from\` with the report from CI).`
3046
- );
3047
- }
3048
- if (keysDiffer) {
3049
- hints.push(
3050
- `Another normalization changes the keys: entries of old keys are kept as unseen until removed with \`${CLI_COMMAND} thresholds --prune\`.`
3051
- );
3052
- }
3053
- warnings.push({
3054
- code: "THRESHOLDS_SOURCE_MISMATCH",
3055
- message: `Thresholds in ${loaded.path} were derived under other conditions than the source report (file / source report): ${diffs.join("; ")}.`,
3056
- hint: hints.join(" ")
3057
- });
3058
- }
3059
- }
3060
- const before = loaded?.file.entries ?? {};
3061
- const entries = {};
3062
- let much = 0;
3063
- for (const key2 of Object.keys(before).sort(compareText3)) {
3064
- const old = before[key2];
3065
- if (old === void 0) continue;
3066
- const stats2 = Object.hasOwn(aggregates, key2) ? aggregates[key2] : void 0;
3067
- if (old.locked === true || !isComplete(old)) {
3068
- entries[key2] = structuredClone(old);
3069
- continue;
3070
- }
3071
- if (stats2 === void 0) {
3072
- if (!opts.prune) entries[key2] = structuredClone(old);
3073
- continue;
3074
- }
3075
- if (!derivable.has(key2) || cfg.thresholds.update === "new-only") {
3076
- entries[key2] = structuredClone(old);
3077
- continue;
3078
- }
3079
- const fresh = deriveEntry(stats2, kind2, cfg);
3080
- if (withinHysteresis(old, fresh, cfg.thresholds.hysteresis) && entrySelfConsistent(old, stats2, kind2, cfg)) {
3081
- entries[key2] = structuredClone(old);
3082
- continue;
3083
- }
3084
- entries[key2] = { ...fresh, ...humanFields(old) };
3085
- if (loosenedMuch(old, fresh, cfg.thresholds.loosenWarnRelative)) much += 1;
3086
- }
3087
- for (const key2 of derivable) {
3088
- const stats2 = aggregates[key2];
3089
- if (Object.hasOwn(before, key2) || stats2 === void 0) continue;
3090
- entries[key2] = deriveEntry(stats2, kind2, cfg);
3091
- }
3092
- const generated = generatedBlock(report, cfg, kind2, opts);
3093
- const content = {
3094
- schemaVersion: SCHEMA_VERSIONS.thresholds,
3095
- kind: kind2,
3096
- generated,
3097
- entries: Object.fromEntries(
3098
- Object.keys(entries).sort(compareText3).map((key2) => [key2, entries[key2] ?? {}])
3099
- )
3100
- };
3101
- const changed = loaded === null || loaded.migratedFrom !== void 0 || loaded.file.generated === null || stringifyStable(loaded.file.entries) !== stringifyStable(content.entries) || generatedChanged(loaded.file.generated, generated);
3102
- return {
3103
- file: { kind: kind2, content: changed ? content : structuredClone(loaded.file), changed },
3104
- warnings,
3105
- loosenedMuch: much
3106
- };
3107
- }
3108
- function deriveThresholds(report, cfg, existing, opts) {
3109
- for (const kind2 of KINDS3) {
3110
- if (existing[kind2].kind !== kind2) {
3111
- throw new Error(`deriveThresholds: existing.${kind2} has kind "${existing[kind2].kind}"`);
3112
- }
3113
- }
3114
- const refused = refusal(report, cfg, existing);
3115
- if (refused !== null) return { ok: false, issues: refused };
3116
- const warnings = [];
3117
- if (report.env !== opts.env) {
3118
- const show = (v) => v === null ? "none" : `"${v}"`;
3119
- warnings.push({
3120
- code: "THRESHOLDS_ENV_MISMATCH",
3121
- message: `The source report was recorded for environment ${show(report.env)}, but the thresholds are written for environment ${show(opts.env)}.`,
3122
- hint: "Check the --env flag and run.env: the files are written for the current environment label."
3123
- });
3124
- }
3125
- if (report.tests.unexpected > 0) {
3126
- warnings.push({
3127
- code: "THRESHOLDS_SOURCE_TESTS_FAILED",
3128
- message: `The source report has ${plural2(report.tests.unexpected, "failed test execution")}; samples of failed tests may raise the thresholds.`,
3129
- hint: "Review the diff before committing, or fix the tests and derive again."
3130
- });
3131
- }
3132
- if (report.mode === "test") {
3133
- warnings.push({
3134
- code: "THRESHOLDS_SOURCE_TEST_MODE",
3135
- message: "The source report comes from test mode, which runs fewer repetitions than a thresholds run.",
3136
- hint: `Prefer a report of \`${CLI_COMMAND} thresholds\` as the source.`
3137
- });
3138
- }
3139
- const files = [];
3140
- let much = 0;
3141
- for (const kind2 of KINDS3) {
3142
- const file = existing[kind2];
3143
- if (file.status === "invalid") throw new Error("deriveThresholds: unreachable invalid file");
3144
- const result = deriveKind(report, cfg, file, opts);
3145
- files.push(result.file);
3146
- warnings.push(...result.warnings);
3147
- much += result.loosenedMuch;
3148
- }
3149
- if (much > 0) {
3150
- const percent2 = Math.round(cfg.thresholds.loosenWarnRelative * 100);
3151
- warnings.push({
3152
- code: "THRESHOLDS_LOOSENED_MUCH",
3153
- message: `${plural2(much, "entry has", "entries have")} a time limit that grew by more than ${percent2}% in this derivation.`,
3154
- hint: "Check that the new thresholds do not accept a regression; the entries are marked with ! in the diff."
3155
- });
3156
- }
3157
- return { ok: true, value: { files, warnings } };
3158
- }
3159
-
3160
- // src/core/thresholds/diff.ts
3161
- function limitChanges(before, after, loosenWarnRelative) {
3162
- const a = limitsOf(before);
3163
- const b = limitsOf(after);
3164
- const changes = [];
3165
- for (const limit of LIMIT_NAMES) {
3166
- const direction = changeDirection(limit, a[limit], b[limit]);
3167
- if (direction === null) continue;
3168
- const change = { limit, before: a[limit], after: b[limit], direction };
3169
- if (grewMuch(limit, a[limit], b[limit], loosenWarnRelative)) change.large = true;
3170
- changes.push(change);
3171
- }
3172
- return changes;
3173
- }
3174
- function keptKey(key2, before, after, stats2, kind2, cfg) {
3175
- if (stats2 === void 0) return { key: key2, category: "unseen", changes: [] };
3176
- if (before.locked === true || !isComplete(before)) {
3177
- return {
3178
- key: key2,
3179
- category: "locked",
3180
- changes: [],
3181
- ...isComplete(before) ? {} : { incomplete: true }
3182
- };
3183
- }
3184
- if (!isDerivable(stats2, cfg.checks)) return { key: key2, category: "skipped", changes: [] };
3185
- const changes = limitChanges(before, after, cfg.thresholds.loosenWarnRelative);
3186
- if (changes.length > 0) {
3187
- const looser = changes.some((c) => c.direction === "looser");
3188
- const stricter = changes.some((c) => c.direction === "stricter");
3189
- const category = looser && stricter ? "mixed" : looser ? "loosened" : "tightened";
3190
- return { key: key2, category, changes };
3191
- }
3192
- const fresh = cfg.thresholds.update === "all" ? deriveEntry(stats2, kind2, cfg) : null;
3193
- const old = limitsOf(before);
3194
- const kept = fresh !== null && LIMIT_NAMES.some((name) => fresh[name] !== old[name]);
3195
- return { key: key2, category: "unchanged", changes: [], ...kept ? { withinHysteresis: true } : {} };
3196
- }
3197
- function diffThresholds(before, after, report, cfg) {
3198
- const kind2 = after.kind;
3199
- const old = before.status === "loaded" ? before.file.entries : {};
3200
- const now = after.content === null ? old : after.content.entries;
3201
- const aggregates = aggregatesOf(report, kind2);
3202
- const runDay = dayOf(report.startedAt);
3203
- const keys = /* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(now)]);
3204
- for (const [key2, stats2] of Object.entries(aggregates)) {
3205
- if (!isDerivable(stats2, cfg.checks)) keys.add(key2);
3206
- }
3207
- const diffs = [];
3208
- for (const key2 of [...keys].sort(compareText3)) {
3209
- const b = Object.hasOwn(old, key2) ? old[key2] : void 0;
3210
- const a = Object.hasOwn(now, key2) ? now[key2] : void 0;
3211
- const stats2 = Object.hasOwn(aggregates, key2) ? aggregates[key2] : void 0;
3212
- let diff;
3213
- if (b !== void 0 && a !== void 0) {
3214
- diff = keptKey(key2, b, a, stats2, kind2, cfg);
3215
- } else if (a !== void 0) {
3216
- diff = { key: key2, category: "added", changes: [], limits: limitsOf(a) };
3217
- } else if (b !== void 0) {
3218
- diff = { key: key2, category: "removed", changes: [], limits: limitsOf(b) };
3219
- } else {
3220
- diff = { key: key2, category: "skipped", changes: [] };
3221
- }
3222
- const entry = a ?? b;
3223
- const muting = entry === void 0 ? null : keyMuting(entry, runDay);
3224
- if (muting !== null) diff.muted = { until: muting.until, expired: muting.expired };
3225
- diffs.push(diff);
3226
- }
3227
- const counts = Object.fromEntries(DIFF_CATEGORIES.map((c) => [c, 0]));
3228
- for (const diff of diffs) counts[diff.category] += 1;
3229
- return {
3230
- kind: kind2,
3231
- fileStatus: after.content === null ? "not-written" : !after.changed ? "unchanged" : before.status === "loaded" ? "updated" : "created",
3232
- level: cfg.checks.time.percentile.level,
3233
- keys: diffs,
3234
- counts
3235
- };
3236
- }
3237
-
3238
- // src/core/thresholds/markdown.ts
3239
- function cell(text) {
3240
- return text.replace(/\\/gu, "\\\\").replace(/\|/gu, "\\|").replace(/\r?\n/gu, " ");
3241
- }
3242
- function code(key2) {
3243
- return key2.includes("`") ? cell(key2) : `\`${cell(key2)}\``;
3244
- }
3245
- function formatThresholdsDiffMarkdown(diffs, paths) {
3246
- const lines = ["# Thresholds diff"];
3247
- diffs.forEach((diff, i) => {
3248
- const path = paths[i] ?? `${diff.kind} thresholds`;
3249
- lines.push(
3250
- "",
3251
- `## ${cell(path)} (${diff.fileStatus === "not-written" ? "not written" : diff.fileStatus})`,
3252
- "",
3253
- diffCountsText(diff)
3254
- );
3255
- const listed = diff.keys.filter((k) => LISTED_CATEGORIES.has(k.category));
3256
- if (listed.length > 0) {
3257
- lines.push("", "| | Key | Before | After |", "|---|---|---|---|");
3258
- for (const k of listed) {
3259
- const before = diffValuesText(k, "before", diff.level, " · ");
3260
- const after = diffValuesText(k, "after", diff.level, " · ");
3261
- lines.push(`| ${diffMarker(k)} | ${code(k.key)} | ${cell(before)} | ${cell(after)} |`);
3262
- }
3263
- }
3264
- const expired = diff.keys.filter((k) => k.muted?.expired === true);
3265
- if (expired.length > 0) {
3266
- lines.push("");
3267
- for (const k of expired) {
3268
- lines.push(`- ${code(k.key)} muted (expired ${k.muted?.until ?? ""})`);
3269
- }
3270
- }
3271
- const large = listed.filter((k) => k.changes.some((c) => c.large === true)).length;
3272
- if (large > 0) {
3273
- lines.push(
3274
- "",
3275
- `Entries marked with ! loosened a time limit by a large step; check that they do not accept a regression.`
3276
- );
3277
- }
3278
- });
3279
- return `${lines.join("\n")}
3280
- `;
3281
- }
3282
-
3283
- // src/console/color.ts
3284
- var ANSI = {
3285
- green: "\x1B[32m",
3286
- red: "\x1B[31m",
3287
- yellow: "\x1B[33m",
3288
- cyan: "\x1B[36m",
3289
- dim: "\x1B[2m",
3290
- bold: "\x1B[1m"
3291
- };
3292
- var RESET = "\x1B[0m";
3293
- function colorEnabled(stream, env) {
3294
- if ((env.NO_COLOR ?? "") !== "") return false;
3295
- const force = env.FORCE_COLOR;
3296
- if (force !== void 0) return force !== "0";
3297
- return stream.isTTY === true && env.TERM !== "dumb";
3298
- }
3299
- function paint(text, style, enabled) {
3300
- return enabled && text !== "" ? `${ANSI[style]}${text}${RESET}` : text;
3301
- }
3302
- function painter(enabled) {
3303
- return (text, style) => paint(text, style, enabled);
3304
- }
3305
-
3306
- // src/console/text.ts
3307
- function compareText4(a, b) {
3308
- return a < b ? -1 : a > b ? 1 : 0;
3309
- }
3310
- function plural3(n, word, many = `${word}s`) {
3311
- return `${n} ${n === 1 ? word : many}`;
3312
- }
3313
- function truncateMiddle2(text, width) {
3314
- const chars = Array.from(text);
3315
- if (chars.length <= width) return text;
3316
- if (width <= 1) return "…".slice(0, width);
3317
- const head = Math.ceil((width - 1) / 2);
3318
- const tail = width - 1 - head;
3319
- return `${chars.slice(0, head).join("")}…${tail === 0 ? "" : chars.slice(-tail).join("")}`;
3320
- }
3321
- function textWidth(text) {
3322
- return Array.from(text).length;
3323
- }
3324
- function padEnd(text, width) {
3325
- return text + " ".repeat(Math.max(0, width - textWidth(text)));
3326
- }
3327
- function padStart(text, width) {
3328
- return " ".repeat(Math.max(0, width - textWidth(text))) + text;
3329
- }
3330
-
3331
- // src/console/thresholds-diff.ts
3332
- var MAX_DIFF_ROWS = 30;
3333
- var MIN_KEY_WIDTH = 30;
3334
- var MARKER_STYLE = {
3335
- "+": "green",
3336
- "-": "red",
3337
- "↑": "yellow",
3338
- "↓": "green",
3339
- "±": "yellow"
3340
- };
3341
- function fileLines(diff, path, opts, paint2) {
3342
- const lines = [`Thresholds: ${path} (${fileStatusText(diff)})`];
3343
- const listed = diff.keys.filter((k) => LISTED_CATEGORIES.has(k.category));
3344
- const expired = diff.keys.filter((k) => k.muted?.expired === true);
3345
- if (diff.fileStatus !== "unchanged") lines.push(` ${diffCountsText(diff)}`);
3346
- if (listed.length > 0) {
3347
- const shown = listed.slice(0, MAX_DIFF_ROWS);
3348
- const rows = shown.map((k) => ({
3349
- marker: diffMarker(k),
3350
- key: k.key,
3351
- change: diffChangeText(k, diff.level, " ") + mutedSuffix(k)
3352
- }));
3353
- const markerWidth = Math.max(...rows.map((r) => textWidth(r.marker)));
3354
- const changeWidth = Math.max(...rows.map((r) => textWidth(r.change)));
3355
- const longest = Math.max(...rows.map((r) => textWidth(r.key)));
3356
- const rest = opts.width - 2 - markerWidth - 1 - 2 - changeWidth;
3357
- const keyWidth = Math.max(MIN_KEY_WIDTH, Math.min(longest, rest));
3358
- lines.push("");
3359
- for (const r of rows) {
3360
- const head = r.marker.slice(0, 1);
3361
- const style = MARKER_STYLE[head] ?? "yellow";
3362
- const marker = paint2(head, style) + (r.marker.length > 1 ? paint2(r.marker.slice(1), "red") : "");
3363
- const pad2 = " ".repeat(markerWidth - textWidth(r.marker));
3364
- lines.push(
3365
- ` ${marker}${pad2} ${padEnd(truncateMiddle2(r.key, keyWidth), keyWidth)} ${r.change}`.trimEnd()
3366
- );
3367
- }
3368
- if (listed.length > shown.length) {
3369
- lines.push(` … and ${listed.length - shown.length} more`);
3370
- }
3371
- }
3372
- if (expired.length > 0) {
3373
- lines.push("");
3374
- for (const k of expired) {
3375
- lines.push(` ${paint2("!", "yellow")} ${k.key} muted (expired ${k.muted?.until ?? ""})`);
3376
- }
3377
- }
3378
- const unseen = diff.counts.unseen;
3379
- if (unseen > 0) {
3380
- const entries = plural3(unseen, "entry", "entries");
3381
- const verb = unseen === 1 ? "was" : "were";
3382
- lines.push(
3383
- "",
3384
- opts.prune ? ` ${entries} not seen in this run ${verb} kept because ${unseen === 1 ? "it is" : "they are"} locked.` : ` ${entries} ${verb} not seen in this run and ${verb} kept. Use --prune to remove them.`
3385
- );
3386
- }
3387
- return lines;
3388
- }
3389
- function fileStatusText(diff) {
3390
- return diff.fileStatus === "not-written" ? "not written" : diff.fileStatus;
3391
- }
3392
- function mutedSuffix(k) {
3393
- return k.muted !== void 0 && !k.muted.expired ? ` (muted until ${k.muted.until})` : "";
3394
- }
3395
- function formatThresholdsDiff(diffs, opts) {
3396
- const paint2 = painter(opts.color);
3397
- const lines = [];
3398
- diffs.forEach((diff, i) => {
3399
- lines.push(...fileLines(diff, opts.paths[i] ?? `${diff.kind} thresholds`, opts, paint2));
3400
- });
3401
- const written = diffs.some((d) => d.fileStatus === "created" || d.fileStatus === "updated");
3402
- lines.push("");
3403
- lines.push(
3404
- written ? "Review the changes and commit the thresholds files." : "The thresholds files are up to date."
3405
- );
3406
- if (opts.diffPath !== null) lines.push(`Diff: ${opts.diffPath}`);
3407
- return `${lines.join("\n")}
3408
- `;
3409
- }
3410
-
3411
- export { Aggregator, SCHEMA_VERSIONS, addKeyedRequest, assessRun, buildOutcome, colorEnabled, compareText4 as compareText, deriveThresholds, diffThresholds, directoryOf, evaluate, fileExists, formatThresholdsDiff, formatThresholdsDiffMarkdown, hashHex, isFailedTest, loadThresholds, padEnd, padStart, paint, painter, parseOutcome, parseRunReport, parseSampleBatch, plural3 as plural, readCiInfo, readHostInfo, readTextFile, relativeSlashPath, renderHtmlReport, resolvePath, resultId, roundMs, schemaIssueToIssue, stringifyStable, testIdentity, textWidth, thresholdsFilePaths, truncateMiddle2 as truncateMiddle, writeJsonStable, writeTextAtomic };