playwright-performance-regression 0.0.0-stage → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2909 @@
1
+ #!/usr/bin/env node
2
+ import { renderHtmlReport, fileExists, readTextFile, resolvePath, writeTextAtomic, loadThresholds, deriveThresholds, thresholdsFilePaths, writeJsonStable, diffThresholds, formatThresholdsDiffMarkdown, formatThresholdsDiff, relativeSlashPath, parseRunReport, schemaIssueToIssue, parseOutcome } from './chunk-JEHUFIY3.js';
3
+ import { CONFIG_FILE_EXTENSIONS, CONFIG_FILE_BASENAME, version, CLI_COMMAND, PACKAGE_NAME, REPOSITORY_URL, generateRunId, peerDependencies, parseRepeat, isEnvLabel, MODE_ENV_NAMES, writeModeState, DOCS_CONFIG_URL, ENV_LABEL_FORMAT, REPEAT_FORMAT } from './chunk-6AB42SPF.js';
4
+ import { DEFAULT_CONFIG, resolveConfig } from './chunk-HES6BVZT.js';
5
+ import { createInterface } from 'readline/promises';
6
+ import { mkdir, writeFile, readdir, stat, rm, readFile } from 'fs/promises';
7
+ import { dirname, resolve, join, extname, basename } from 'path';
8
+ import { fileURLToPath, pathToFileURL } from 'url';
9
+ import { spawn } from 'child_process';
10
+ import { readFileSync } from 'fs';
11
+ import { createRequire } from 'module';
12
+ import { tmpdir } from 'os';
13
+
14
+ // src/cli/help.ts
15
+ var REPEAT_NOTE = [
16
+ "Note: every test runs several times in one worker. Tests that create data with unique",
17
+ "constraints may conflict between repetitions: make the data unique per repetition, or",
18
+ "leave such tests out with --grep-invert."
19
+ ];
20
+ var EXIT_CODES = [
21
+ "Exit codes: 0 ok (failed tests are reported as a warning) \xB7 2 performance regression \xB7",
22
+ "3 tool or config error, or an untrustworthy result (too many failed tests, incomplete run)",
23
+ "\xB7 130/143 interrupted (SIGINT/SIGTERM)"
24
+ ];
25
+ var PASS_THROUGH = [
26
+ 'All other arguments go to "playwright test" unchanged; arguments after "--" are never read',
27
+ `as ${CLI_COMMAND} options. --ui, --debug and --shard are not supported. By default only`,
28
+ "Chromium projects are measured; other projects are left out of the run (option",
29
+ '"run.projects").'
30
+ ];
31
+ var GENERAL = [
32
+ `Usage: ${CLI_COMMAND} <command> [options] [playwright test arguments]`,
33
+ "",
34
+ "Commands:",
35
+ " test Measurement run: measure, evaluate against the thresholds, fail on regression",
36
+ " thresholds Thresholds run: measure without the gate, then write the thresholds files",
37
+ " thresholds --from <file> Derive the thresholds from an existing report.json (no tests)",
38
+ " report Render the HTML report again from report.json",
39
+ " init Guided setup in this project",
40
+ "",
41
+ "Options (test, thresholds):",
42
+ " --env <label> Environment label; selects perf-thresholds.<kind>.<label>.json",
43
+ " --repeat <n> Repetitions per test for this run",
44
+ " --prune (thresholds) Remove unlocked entries of keys not seen in this run",
45
+ "",
46
+ ...PASS_THROUGH,
47
+ "",
48
+ `Run "${CLI_COMMAND} <command> --help" for the options of a command, "${CLI_COMMAND} --version"`,
49
+ "for the version.",
50
+ "",
51
+ ...REPEAT_NOTE,
52
+ "",
53
+ ...EXIT_CODES
54
+ ];
55
+ var TEST = [
56
+ `Usage: ${CLI_COMMAND} test [--env <label>] [--repeat <n>] [playwright test arguments]`,
57
+ "",
58
+ "Runs the tests in perf mode, measures the backend requests and custom measurements, evaluates",
59
+ "them against the thresholds files and fails on a regression.",
60
+ "",
61
+ "Options:",
62
+ " --env <label> Environment label; selects perf-thresholds.<kind>.<label>.json (overrides run.env)",
63
+ " --repeat <n> Repetitions per test for this run (overrides run.repeat.test)",
64
+ " -h, --help Show this help",
65
+ "",
66
+ ...PASS_THROUGH,
67
+ "",
68
+ `Example: ${CLI_COMMAND} test --grep @perf`,
69
+ "",
70
+ ...REPEAT_NOTE,
71
+ "",
72
+ ...EXIT_CODES
73
+ ];
74
+ var THRESHOLDS = [
75
+ `Usage: ${CLI_COMMAND} thresholds [--env <label>] [--repeat <n>] [--prune] [playwright test arguments]`,
76
+ ` ${CLI_COMMAND} thresholds --from <report.json> [--env <label>] [--prune] [--config <file>]`,
77
+ "",
78
+ "Runs the tests in perf mode without the gate and writes the thresholds files, or derives them",
79
+ "from an existing run report without running tests (--from).",
80
+ "",
81
+ "Options:",
82
+ " --env <label> Environment label; the files perf-thresholds.<kind>.<label>.json are written",
83
+ " (with --from: default is the label of the report)",
84
+ " --repeat <n> Repetitions per test for this run (overrides run.repeat.thresholds)",
85
+ " --prune Remove unlocked entries of keys not seen in the run; not with a test filter",
86
+ " --from <file> Derive the thresholds from this report.json; no Playwright arguments",
87
+ " --config <file> (with --from) Package config file; default: pw-perf.config.* in the current",
88
+ " directory or the config directory of the report, else the report snapshot",
89
+ " -h, --help Show this help",
90
+ "",
91
+ ...PASS_THROUGH,
92
+ "",
93
+ ...REPEAT_NOTE,
94
+ "",
95
+ "Exit codes: 0 ok \xB7 3 tool or config error, or an untrustworthy run (nothing is written)",
96
+ "\xB7 130/143 interrupted (SIGINT/SIGTERM)"
97
+ ];
98
+ var REPORT = [
99
+ `Usage: ${CLI_COMMAND} report [--input <report.json>] [--output <report.html>] [--config <file>]`,
100
+ "",
101
+ "Renders the HTML report again from a run report, without running tests.",
102
+ "",
103
+ "Options:",
104
+ " --input <file> Run report; default: report.json in report.dir",
105
+ " --output <file> HTML file; default: report.html next to the input",
106
+ " --config <file> Package config file; default: pw-perf.config.* in the current directory",
107
+ " -h, --help Show this help",
108
+ "",
109
+ "Exit codes: 0 ok \xB7 3 error"
110
+ ];
111
+ var INIT = [
112
+ `Usage: ${CLI_COMMAND} init [--yes] [--dry-run]`,
113
+ "",
114
+ "Guided setup of the package in this project: asks a few questions, shows a diff of every",
115
+ "change and applies it after confirmation. Files it does not recognize are left unchanged",
116
+ "with instructions. Without a terminal and without --yes it only shows the planned changes.",
117
+ "",
118
+ "Options:",
119
+ " -y, --yes Accept the default answers and write the changes",
120
+ " --dry-run Show the planned changes only",
121
+ " -h, --help Show this help",
122
+ "",
123
+ "Exit codes: 0 done (also with manual steps left) \xB7 3 error \xB7 130 interrupted"
124
+ ];
125
+ var TOPICS = {
126
+ test: TEST,
127
+ thresholds: THRESHOLDS,
128
+ report: REPORT,
129
+ init: INIT
130
+ };
131
+ function helpText(command) {
132
+ return `${(command === void 0 ? GENERAL : TOPICS[command]).join("\n")}
133
+ `;
134
+ }
135
+
136
+ // src/cli/init/detect.ts
137
+ var PLAYWRIGHT_CONFIG_NAMES = [
138
+ "ts",
139
+ "mts",
140
+ "cts",
141
+ "js",
142
+ "mjs",
143
+ "cjs"
144
+ ].map((ext) => `playwright.config.${ext}`);
145
+ var PERF_CONFIG_NAMES = CONFIG_FILE_EXTENSIONS.map(
146
+ (ext) => `${CONFIG_FILE_BASENAME}${ext}`
147
+ );
148
+ var INSTALLED_PLAYWRIGHT = "node_modules/@playwright/test/package.json";
149
+ var LOCKFILES = {
150
+ "pnpm-lock.yaml": "pnpm",
151
+ "yarn.lock": "yarn",
152
+ "package-lock.json": "npm"
153
+ };
154
+ var CI_MARKERS = [
155
+ ["github", (p) => p.startsWith(".github/")],
156
+ ["gitlab", (p) => p === ".gitlab-ci.yml"],
157
+ ["jenkins", (p) => p === "Jenkinsfile"],
158
+ ["azure", (p) => p === "azure-pipelines.yml"]
159
+ ];
160
+ var SOURCE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/u;
161
+ var IMPORTS_PLAYWRIGHT_TEST = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*|^\s*import\s*)(['"])@playwright\/test\1/mu;
162
+ var EXTEND_CALL = /(?<!\bexpect)\.extend\s*[<(]/gu;
163
+ var PERF_TAG = /@perf\b/u;
164
+ var WRAPPED_TEST = new RegExp(
165
+ String.raw`\bwithPerfFixtures\s*\(|(['"])${PACKAGE_NAME}/test\1`,
166
+ "u"
167
+ );
168
+ function testDirsOf(configText) {
169
+ const dirs = [...configText.matchAll(/\btestDir\s*:\s*(['"`])([^'"`\n]+)\1/gu)].map(
170
+ (m) => normalizeDir(m[2])
171
+ );
172
+ return dirs.length === 0 ? ["."] : [...new Set(dirs)];
173
+ }
174
+ function normalizeDir(dir) {
175
+ const clean = dir.replaceAll("\\", "/").replace(/^\.\/+/u, "").replace(/\/+$/u, "");
176
+ return clean === "" ? "." : clean;
177
+ }
178
+ function parseJson(text) {
179
+ if (text === void 0) return null;
180
+ try {
181
+ const value = JSON.parse(text);
182
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+ function stringField(obj, ...keys) {
188
+ let value = obj;
189
+ for (const key of keys) {
190
+ if (typeof value !== "object" || value === null) return null;
191
+ value = value[key];
192
+ }
193
+ return typeof value === "string" ? value : null;
194
+ }
195
+ function playwrightVersion(files, pkg) {
196
+ const installed = stringField(parseJson(files.get(INSTALLED_PLAYWRIGHT)), "version");
197
+ if (installed !== null) return installed;
198
+ const range = stringField(pkg, "devDependencies", "@playwright/test") ?? stringField(pkg, "dependencies", "@playwright/test");
199
+ return range === null ? null : /\d+\.\d+\.\d+/u.exec(range)?.[0] ?? null;
200
+ }
201
+ function packageManagerOf(files, pkg) {
202
+ for (const [file, manager] of Object.entries(LOCKFILES)) {
203
+ if (files.has(file)) return manager;
204
+ }
205
+ const declared = /^(npm|pnpm|yarn)@/u.exec(stringField(pkg, "packageManager") ?? "");
206
+ return declared?.[1] ?? "npm";
207
+ }
208
+ function sourceFiles(files, configPath) {
209
+ return [...files.keys()].filter(
210
+ (path) => SOURCE_FILE.test(path) && path !== configPath && !path.startsWith("node_modules/") && !path.includes("/node_modules/") && !PERF_CONFIG_NAMES.includes(path)
211
+ ).sort();
212
+ }
213
+ function detectProject(files) {
214
+ const configPath = PLAYWRIGHT_CONFIG_NAMES.find((name) => files.has(name)) ?? null;
215
+ const configText = configPath === null ? "" : files.get(configPath);
216
+ const pkg = parseJson(files.get("package.json"));
217
+ const sources = sourceFiles(files, configPath);
218
+ const text = (path) => files.get(path) ?? "";
219
+ const moduleType = configPath?.endsWith(".mts") || configPath?.endsWith(".mjs") ? "esm" : configPath?.endsWith(".cts") || configPath?.endsWith(".cjs") ? "cjs" : pkg?.["type"] === "module" ? "esm" : "cjs";
220
+ const baseUrls = [
221
+ ...new Set(
222
+ [...configText.matchAll(/\bbaseURL\s*:[^\n]*?(['"`])(https?:\/\/[^'"`\s]+)\1/gu)].flatMap(
223
+ (m) => {
224
+ try {
225
+ return [new URL(m[2]).origin];
226
+ } catch {
227
+ return [];
228
+ }
229
+ }
230
+ )
231
+ )
232
+ ];
233
+ const projectNames = [
234
+ ...new Set(
235
+ [...configText.matchAll(/\bname\s*:\s*(['"`])([^'"`\n]+)\1/gu)].map((m) => m[2])
236
+ )
237
+ ];
238
+ const scripts = pkg?.["scripts"];
239
+ const paths = [...files.keys()];
240
+ return {
241
+ playwrightConfig: configPath === null ? null : { path: configPath, text: configText },
242
+ playwrightVersion: playwrightVersion(files, pkg),
243
+ packageManager: packageManagerOf(files, pkg),
244
+ moduleType,
245
+ testDir: testDirsOf(configText)[0],
246
+ filesImportingPlaywrightTest: sources.filter((p) => IMPORTS_PLAYWRIGHT_TEST.test(text(p))),
247
+ filesWithExtend: sources.filter((p) => text(p).search(EXTEND_CALL) !== -1),
248
+ taggedPerfTestFiles: sources.filter((p) => PERF_TAG.test(text(p))).length,
249
+ baseUrls,
250
+ projectNames,
251
+ ciPlatform: CI_MARKERS.find(([, test]) => paths.some(test))?.[0] ?? null,
252
+ existing: {
253
+ perfConfig: PERF_CONFIG_NAMES.find((name) => files.has(name)) ?? null,
254
+ wrappedConfig: /\bwithPerf\s*\(/u.test(configText),
255
+ wrappedTest: sources.some((p) => WRAPPED_TEST.test(text(p))),
256
+ scripts: typeof scripts === "object" && scripts !== null ? Object.keys(scripts).sort() : []
257
+ },
258
+ files
259
+ };
260
+ }
261
+
262
+ // src/cli/init/defaults.ts
263
+ var DEFAULT_ANSWERS_REPEAT = DEFAULT_CONFIG.run.repeat.test;
264
+ function defaultLabel(origin, used) {
265
+ const host = new URL(origin).hostname;
266
+ const first = host.split(".")[0] ?? "";
267
+ const base = /^[a-z][a-z0-9-]{0,63}$/u.test(first) && first !== "www" && first !== "localhost" && host.includes(".") ? first : "app";
268
+ let label = base;
269
+ for (let n = 2; used.has(label); n += 1) label = `${base}${n}`;
270
+ return label;
271
+ }
272
+
273
+ // src/cli/init/diff.ts
274
+ var CONTEXT = 3;
275
+ function lines(text) {
276
+ if (text === "") return [];
277
+ const parts = text.split("\n");
278
+ if (parts[parts.length - 1] === "") parts.pop();
279
+ return parts;
280
+ }
281
+ function operations(a, b) {
282
+ let start = 0;
283
+ while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
284
+ let endA = a.length;
285
+ let endB = b.length;
286
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
287
+ endA -= 1;
288
+ endB -= 1;
289
+ }
290
+ const midA = a.slice(start, endA);
291
+ const midB = b.slice(start, endB);
292
+ const n = midA.length;
293
+ const m = midB.length;
294
+ const lcs = new Uint32Array((n + 1) * (m + 1));
295
+ const at = (i2, j2) => lcs[i2 * (m + 1) + j2];
296
+ for (let i2 = n - 1; i2 >= 0; i2 -= 1) {
297
+ for (let j2 = m - 1; j2 >= 0; j2 -= 1) {
298
+ lcs[i2 * (m + 1) + j2] = midA[i2] === midB[j2] ? at(i2 + 1, j2 + 1) + 1 : Math.max(at(i2 + 1, j2), at(i2, j2 + 1));
299
+ }
300
+ }
301
+ const ops = a.slice(0, start).map((line) => ({ kind: " ", line }));
302
+ let i = 0;
303
+ let j = 0;
304
+ while (i < n || j < m) {
305
+ if (i < n && j < m && midA[i] === midB[j]) {
306
+ ops.push({ kind: " ", line: midA[i] });
307
+ i += 1;
308
+ j += 1;
309
+ } else if (i < n && (j === m || at(i + 1, j) >= at(i, j + 1))) {
310
+ ops.push({ kind: "-", line: midA[i] });
311
+ i += 1;
312
+ } else {
313
+ ops.push({ kind: "+", line: midB[j] });
314
+ j += 1;
315
+ }
316
+ }
317
+ for (const line of a.slice(endA)) ops.push({ kind: " ", line });
318
+ return ops;
319
+ }
320
+ function unifiedDiff(change2) {
321
+ const before = change2.before ?? "";
322
+ if (before === change2.after) return "";
323
+ const ops = operations(lines(before), lines(change2.after));
324
+ const out = [
325
+ change2.before === null ? "--- /dev/null" : `--- a/${change2.path}`,
326
+ `+++ b/${change2.path}`
327
+ ];
328
+ const changed = ops.flatMap((op, index) => op.kind === " " ? [] : [index]);
329
+ let h = 0;
330
+ while (h < changed.length) {
331
+ const first = Math.max(0, changed[h] - CONTEXT);
332
+ let last = Math.min(ops.length - 1, changed[h] + CONTEXT);
333
+ h += 1;
334
+ while (h < changed.length && changed[h] - CONTEXT <= last + 1) {
335
+ last = Math.min(ops.length - 1, changed[h] + CONTEXT);
336
+ h += 1;
337
+ }
338
+ let oldStart = 1;
339
+ let newStart = 1;
340
+ for (const op of ops.slice(0, first)) {
341
+ if (op.kind !== "+") oldStart += 1;
342
+ if (op.kind !== "-") newStart += 1;
343
+ }
344
+ const hunk = ops.slice(first, last + 1);
345
+ const oldCount = hunk.filter((op) => op.kind !== "+").length;
346
+ const newCount = hunk.filter((op) => op.kind !== "-").length;
347
+ out.push(
348
+ `@@ -${oldCount === 0 ? oldStart - 1 : oldStart},${oldCount} +${newCount === 0 ? newStart - 1 : newStart},${newCount} @@`
349
+ );
350
+ for (const op of hunk) out.push(`${op.kind}${op.line}`);
351
+ }
352
+ return `${out.join("\n")}
353
+ `;
354
+ }
355
+
356
+ // src/cli/init/files.ts
357
+ var ROOT_FILES = /* @__PURE__ */ new Set([
358
+ "package.json",
359
+ ".gitignore",
360
+ ".gitlab-ci.yml",
361
+ "Jenkinsfile",
362
+ "azure-pipelines.yml",
363
+ ...PLAYWRIGHT_CONFIG_NAMES,
364
+ ...PERF_CONFIG_NAMES
365
+ ]);
366
+ var ROOT_CI_FILE = /^(?:Jenkinsfile\.perf(?:-[a-z0-9-]+)?|azure-pipelines\.perf(?:-[a-z0-9-]+)?\.yml)$/u;
367
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
368
+ "node_modules",
369
+ ".git",
370
+ "dist",
371
+ "build",
372
+ "coverage",
373
+ "test-results",
374
+ "playwright-report",
375
+ "blob-report",
376
+ DEFAULT_CONFIG.report.dir
377
+ ]);
378
+ var MAX_DEPTH = 8;
379
+ var MAX_FILES = 3e3;
380
+ async function readProjectFiles(host, root) {
381
+ const files = /* @__PURE__ */ new Map();
382
+ const join3 = (rel) => host.paths.join(root, rel);
383
+ const read = async (rel) => {
384
+ const text = await host.readText(join3(rel));
385
+ if (text !== null) files.set(rel, text);
386
+ };
387
+ for (const entry of await host.listDir(root)) {
388
+ if (entry.directory) continue;
389
+ if (Object.hasOwn(LOCKFILES, entry.name)) files.set(entry.name, "");
390
+ else if (ROOT_FILES.has(entry.name) || ROOT_CI_FILE.test(entry.name)) await read(entry.name);
391
+ }
392
+ for (const dir of [".github", ".github/workflows", ".gitlab"]) {
393
+ for (const entry of await host.listDir(join3(dir))) {
394
+ if (!entry.directory && /\.ya?ml$/u.test(entry.name)) await read(`${dir}/${entry.name}`);
395
+ }
396
+ }
397
+ const playwright = host.resolvePlaywright(root);
398
+ if (playwright !== null)
399
+ files.set(INSTALLED_PLAYWRIGHT, JSON.stringify({ version: playwright.version }));
400
+ const config = PLAYWRIGHT_CONFIG_NAMES.find((name) => files.has(name));
401
+ if (config === void 0) return files;
402
+ let count2 = 0;
403
+ const walk = async (rel, depth) => {
404
+ if (depth > MAX_DEPTH || rel.split("/").includes("..")) return;
405
+ for (const entry of await host.listDir(rel === "." ? root : join3(rel))) {
406
+ if (count2 >= MAX_FILES) return;
407
+ const path = rel === "." ? entry.name : `${rel}/${entry.name}`;
408
+ if (entry.directory) {
409
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) await walk(path, depth + 1);
410
+ } else if (SOURCE_FILE.test(entry.name) && !files.has(path)) {
411
+ count2 += 1;
412
+ await read(path);
413
+ }
414
+ }
415
+ };
416
+ for (const dir of testDirsOf(files.get(config))) await walk(dir, 0);
417
+ return files;
418
+ }
419
+
420
+ // src/cli/init/generated/ci-templates.ts
421
+ var CI_TEMPLATES = {
422
+ /** examples/ci/github-actions.yml */
423
+ github: "# Performance measurement run with playwright-performance-regression (pw-perf).\n# Save as .github/workflows/perf.yml. Runs on pull requests and every night; the report in\n# perf-results/ is uploaded also when the run fails. Exit codes: 0 ok, 2 performance regression,\n# 3 tool or config error.\nname: Performance\n\non:\n pull_request:\n schedule:\n - cron: '0 3 * * *'\n workflow_dispatch:\n\njobs:\n perf:\n runs-on: ubuntu-latest\n timeout-minutes: 60\n steps:\n - uses: actions/checkout@v7\n - uses: actions/setup-node@v7\n with:\n node-version: 22\n cache: npm\n - run: npm ci\n - run: npx playwright install --with-deps chromium\n - name: Measurement run\n run: npx pw-perf test\n - name: Upload the performance report\n if: always()\n uses: actions/upload-artifact@v7\n with:\n name: perf-results\n path: perf-results/\n retention-days: 30\n",
424
+ /** examples/ci/gitlab-ci.yml */
425
+ gitlab: '# Performance measurement run with playwright-performance-regression (pw-perf).\n# Include this file from .gitlab-ci.yml. Runs in merge request pipelines and scheduled\n# pipelines; exit code 2 (performance regression) is a soft failure, 3 (tool or config error)\n# fails the job. The report in perf-results/ is kept also when the job fails.\nperf:\n image: node:22\n timeout: 1h\n rules:\n - if: $CI_PIPELINE_SOURCE == "merge_request_event"\n - if: $CI_PIPELINE_SOURCE == "schedule"\n script:\n - npm ci\n - npx playwright install --with-deps chromium\n - npx pw-perf test\n allow_failure:\n exit_codes: 2\n artifacts:\n when: always\n paths:\n - perf-results/\n expire_in: 30 days\n',
426
+ /** examples/ci/Jenkinsfile */
427
+ jenkins: `// Performance measurement run with playwright-performance-regression (pw-perf).
428
+ // Use as the script of a pipeline job, e.g. "Jenkinsfile.perf". Exit code 2 (performance
429
+ // regression) marks the build UNSTABLE, 3 (tool or config error) fails it. The report in
430
+ // perf-results/ is archived also when the run fails.
431
+ pipeline {
432
+ agent any
433
+ options {
434
+ timeout(time: 60, unit: 'MINUTES')
435
+ }
436
+ triggers {
437
+ cron('H 3 * * *')
438
+ }
439
+ stages {
440
+ stage('Performance') {
441
+ steps {
442
+ sh 'npm ci'
443
+ sh 'npx playwright install --with-deps chromium'
444
+ script {
445
+ def code = sh(script: 'npx pw-perf test', returnStatus: true)
446
+ if (code == 2) {
447
+ unstable('Performance regression (exit code 2)')
448
+ } else if (code != 0) {
449
+ error("Measurement run failed with exit code \${code}")
450
+ }
451
+ }
452
+ }
453
+ }
454
+ }
455
+ post {
456
+ always {
457
+ archiveArtifacts artifacts: 'perf-results/**', allowEmptyArchive: true
458
+ }
459
+ }
460
+ }
461
+ `,
462
+ /** examples/ci/azure-pipelines.yml */
463
+ azure: `# Performance measurement run with playwright-performance-regression (pw-perf).
464
+ # Register as its own pipeline, e.g. azure-pipelines.perf.yml. Runs on pull requests and every
465
+ # night. Exit code 2 (performance regression) ends the job as "succeeded with issues", 3 (tool or
466
+ # config error) fails it. The report in perf-results/ is published also when the run fails.
467
+ trigger: none
468
+
469
+ pr:
470
+ branches:
471
+ include:
472
+ - '*'
473
+
474
+ schedules:
475
+ - cron: '0 3 * * *'
476
+ displayName: Nightly measurement run
477
+ branches:
478
+ include:
479
+ - main
480
+ always: true
481
+
482
+ pool:
483
+ vmImage: ubuntu-latest
484
+
485
+ jobs:
486
+ - job: perf
487
+ timeoutInMinutes: 60
488
+ steps:
489
+ - task: NodeTool@0
490
+ inputs:
491
+ versionSpec: '22.x'
492
+ - script: npm ci
493
+ displayName: Install dependencies
494
+ - script: npx playwright install --with-deps chromium
495
+ displayName: Install Chromium
496
+ - bash: |
497
+ code=0
498
+ npx pw-perf test || code=$?
499
+ if [ "$code" -eq 2 ]; then
500
+ echo "##vso[task.complete result=SucceededWithIssues;]Performance regression (exit code 2)"
501
+ exit 0
502
+ fi
503
+ exit $code
504
+ displayName: Measurement run
505
+ - publish: perf-results
506
+ artifact: perf-results
507
+ condition: always()
508
+ displayName: Publish the performance report
509
+ `
510
+ };
511
+
512
+ // src/cli/init/ci.ts
513
+ var CI_COMMAND = "npx pw-perf test";
514
+ var suffix = (label) => label === null ? "" : `-${label}`;
515
+ var CI_TARGETS = {
516
+ github: {
517
+ path: (label) => `.github/workflows/perf${suffix(label)}.yml`,
518
+ rename: (text, label) => text.replace(/^name: Performance$/mu, `name: Performance (${label})`)
519
+ },
520
+ gitlab: {
521
+ path: (label) => `.gitlab/perf${suffix(label)}.gitlab-ci.yml`,
522
+ rename: (text, label) => text.replace(/^perf:$/mu, `perf-${label}:`)
523
+ },
524
+ jenkins: { path: (label) => `Jenkinsfile.perf${suffix(label)}`, rename: (text) => text },
525
+ azure: { path: (label) => `azure-pipelines.perf${suffix(label)}.yml`, rename: (text) => text }
526
+ };
527
+ function commandFlags(scope, label) {
528
+ return `${scope === "tagged" ? " --grep @perf" : ""}${label === null ? "" : ` --env ${label}`}`;
529
+ }
530
+ function ciFiles(platform, scope, envLabels) {
531
+ const target = CI_TARGETS[platform];
532
+ const template = CI_TEMPLATES[platform];
533
+ const labels = envLabels.length === 0 ? [null] : [...envLabels];
534
+ return labels.map((label) => {
535
+ let text = template.replace(CI_COMMAND, `${CI_COMMAND}${commandFlags(scope, label)}`);
536
+ if (label !== null) text = target.rename(text, label);
537
+ return { path: target.path(label), text };
538
+ });
539
+ }
540
+
541
+ // src/cli/init/perf-config.ts
542
+ function ts(value) {
543
+ if (typeof value === "string")
544
+ return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
545
+ if (Array.isArray(value)) return `[${value.map(ts).join(", ")}]`;
546
+ if (typeof value === "object" && value !== null) {
547
+ const entries = Object.entries(value).map(
548
+ ([k, v]) => `${/^[A-Za-z_$][\w$]*$/u.test(k) ? k : ts(k)}: ${ts(v)}`
549
+ );
550
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
551
+ }
552
+ return String(value);
553
+ }
554
+ function renderPerfConfig(answers) {
555
+ const d = DEFAULT_CONFIG;
556
+ const body = [];
557
+ const origins = Object.entries(answers.originLabels);
558
+ if (origins.length > 0) {
559
+ body.push(
560
+ " keys: {",
561
+ " // Labels of the backend origins in the endpoint keys.",
562
+ " origins: {"
563
+ );
564
+ for (const [origin, label] of origins) body.push(` ${ts(origin)}: ${ts(label)},`);
565
+ body.push(" },", " },");
566
+ }
567
+ if (answers.repeatTest !== d.run.repeat.test) {
568
+ body.push(
569
+ " run: {",
570
+ ` // Repetitions per test in measurement runs (default ${d.run.repeat.test}).`,
571
+ ` repeat: { test: ${answers.repeatTest} },`,
572
+ " },"
573
+ );
574
+ }
575
+ if (answers.warnOnly !== d.gate.warnOnly) {
576
+ body.push(
577
+ " gate: {",
578
+ answers.warnOnly ? " // Report regressions without failing the run; remove after the first weeks." : " // Fail the run on a regression.",
579
+ ` warnOnly: ${answers.warnOnly},`,
580
+ " },"
581
+ );
582
+ }
583
+ if (body.length > 0) body.push("");
584
+ body.push(
585
+ " // Options changed most often, with their default values:",
586
+ ` // run: ${ts({ repeat: d.run.repeat, projects: d.run.projects, keepReporters: d.run.keepReporters })},`,
587
+ ` // measure: ${ts({ exclude: d.measure.exclude })},`,
588
+ ` // gate: ${ts({ warnOnly: d.gate.warnOnly, tolerance: d.gate.tolerance, maxFailedTestShare: d.gate.maxFailedTestShare })},`,
589
+ ` // thresholds: ${ts({ dir: d.thresholds.dir })},`,
590
+ ` // report: ${ts({ dir: d.report.dir })},`
591
+ );
592
+ return [
593
+ `// Configuration of ${PACKAGE_NAME}, written by "npx pw-perf init".`,
594
+ "// Only the values that differ from the defaults are set. All options:",
595
+ `// ${DOCS_CONFIG_URL}`,
596
+ `import { definePerfConfig } from '${PACKAGE_NAME}';`,
597
+ "",
598
+ "export default definePerfConfig({",
599
+ ...body,
600
+ "});",
601
+ ""
602
+ ].join("\n");
603
+ }
604
+
605
+ // src/cli/init/scan.ts
606
+ var OPEN = { "(": ")", "[": "]", "{": "}" };
607
+ var CLOSE = /* @__PURE__ */ new Set([")", "]", "}"]);
608
+ var REGEX_BEFORE = /* @__PURE__ */ new Set([
609
+ "",
610
+ "(",
611
+ ",",
612
+ "=",
613
+ ":",
614
+ "[",
615
+ "!",
616
+ "&",
617
+ "|",
618
+ "?",
619
+ "{",
620
+ "}",
621
+ ";",
622
+ "+",
623
+ "-",
624
+ "*",
625
+ "%",
626
+ "<",
627
+ ">",
628
+ "~",
629
+ "^"
630
+ ]);
631
+ function skipString(text, i) {
632
+ const quote = text[i];
633
+ let j = i + 1;
634
+ while (j < text.length) {
635
+ const c = text[j];
636
+ if (c === "\\") {
637
+ j += 2;
638
+ continue;
639
+ }
640
+ if (c === quote) return j + 1;
641
+ if (quote === "`" && c === "$" && text[j + 1] === "{") {
642
+ const end = matchBracket(text, j + 1);
643
+ if (end === -1) return text.length;
644
+ j = end;
645
+ continue;
646
+ }
647
+ if (quote !== "`" && c === "\n") return j;
648
+ j += 1;
649
+ }
650
+ return text.length;
651
+ }
652
+ function skipRegex(text, i) {
653
+ let j = i + 1;
654
+ let inClass = false;
655
+ while (j < text.length) {
656
+ const c = text[j];
657
+ if (c === "\\") {
658
+ j += 2;
659
+ continue;
660
+ }
661
+ if (c === "\n") return j;
662
+ if (inClass) {
663
+ if (c === "]") inClass = false;
664
+ } else if (c === "[") {
665
+ inClass = true;
666
+ } else if (c === "/") {
667
+ j += 1;
668
+ while (j < text.length && /[a-z]/u.test(text[j])) j += 1;
669
+ return j;
670
+ }
671
+ j += 1;
672
+ }
673
+ return text.length;
674
+ }
675
+ function skipNonCode(text, i, previous) {
676
+ const c = text[i];
677
+ const next = text[i + 1];
678
+ if (c === "/" && next === "/") {
679
+ const end = text.indexOf("\n", i);
680
+ return end === -1 ? text.length : end;
681
+ }
682
+ if (c === "/" && next === "*") {
683
+ const end = text.indexOf("*/", i + 2);
684
+ return end === -1 ? text.length : end + 2;
685
+ }
686
+ if (c === '"' || c === "'" || c === "`") return skipString(text, i);
687
+ if (c === "/" && REGEX_BEFORE.has(previous)) return skipRegex(text, i);
688
+ return i;
689
+ }
690
+ function matchBracket(text, open) {
691
+ const stack = [];
692
+ let previous = "";
693
+ let i = open;
694
+ while (i < text.length) {
695
+ const skipped = skipNonCode(text, i, previous);
696
+ if (skipped !== i) {
697
+ i = skipped;
698
+ previous = "x";
699
+ continue;
700
+ }
701
+ const c = text[i];
702
+ if (OPEN[c] !== void 0) {
703
+ stack.push(OPEN[c]);
704
+ } else if (CLOSE.has(c)) {
705
+ if (stack.pop() !== c) return -1;
706
+ if (stack.length === 0) return i + 1;
707
+ }
708
+ if (!/\s/u.test(c)) previous = /[\w$]/u.test(c) ? "x" : c;
709
+ i += 1;
710
+ }
711
+ return -1;
712
+ }
713
+ function callParen(text, from) {
714
+ let i = from;
715
+ while (/\s/u.test(text[i] ?? "")) i += 1;
716
+ if (text[i] === "<") {
717
+ let depth = 0;
718
+ for (; i < text.length; i += 1) {
719
+ const c = text[i];
720
+ if (c === "<" || c === "{" || c === "(" || c === "[") depth += 1;
721
+ else if (c === "}" || c === ")" || c === "]") depth -= 1;
722
+ else if (c === ">" && text[i - 1] !== "=") {
723
+ depth -= 1;
724
+ if (depth === 0) break;
725
+ }
726
+ }
727
+ i += 1;
728
+ while (/\s/u.test(text[i] ?? "")) i += 1;
729
+ }
730
+ return text[i] === "(" ? i : -1;
731
+ }
732
+ function onlyTrailing(text, i) {
733
+ let semicolon = false;
734
+ let j = i;
735
+ while (j < text.length) {
736
+ const c = text[j];
737
+ if (/\s/u.test(c)) {
738
+ j += 1;
739
+ } else if (c === ";" && !semicolon) {
740
+ semicolon = true;
741
+ j += 1;
742
+ } else if (c === "/" && (text[j + 1] === "/" || text[j + 1] === "*")) {
743
+ j = skipNonCode(text, j, "");
744
+ } else {
745
+ return false;
746
+ }
747
+ }
748
+ return true;
749
+ }
750
+ function statementEnds(text, i) {
751
+ return /^[ \t]*(?:;|\r?\n|$|\/\/)/u.test(text.slice(i, i + 200));
752
+ }
753
+ var IMPORT_DONE = /(?:\bfrom\s*(['"])[^'"\n]+\1|^\s*import\s*(['"])[^'"\n]+\2)\s*;?\s*$/u;
754
+ var REQUIRE_DONE = /\brequire\(\s*(['"])[^'"\n]+\1\s*\)(?:\.[\w$]+)*\s*;?\s*$/u;
755
+ function importInsertOffset(text) {
756
+ let offset = 0;
757
+ let lastImportEnd = -1;
758
+ let leadingEnd = 0;
759
+ let seenCode = false;
760
+ let inComment = false;
761
+ let pending = null;
762
+ for (const line of text.split("\n")) {
763
+ const start = offset;
764
+ const end = Math.min(offset + line.length + 1, text.length);
765
+ offset += line.length + 1;
766
+ const trimmed = line.trim();
767
+ if (pending !== null) {
768
+ pending.text += `
769
+ ${line}`;
770
+ if (pending.done.test(pending.text)) {
771
+ pending = null;
772
+ lastImportEnd = end;
773
+ }
774
+ continue;
775
+ }
776
+ const header = !seenCode;
777
+ if (inComment || trimmed.startsWith("//") || trimmed.startsWith("/*")) {
778
+ if (inComment) inComment = !trimmed.includes("*/");
779
+ else if (trimmed.startsWith("/*")) inComment = !trimmed.includes("*/");
780
+ if (header) leadingEnd = end;
781
+ continue;
782
+ }
783
+ if (trimmed === "") continue;
784
+ if (/^['"]use strict['"];?$/u.test(trimmed)) {
785
+ leadingEnd = end;
786
+ continue;
787
+ }
788
+ let done = null;
789
+ if (/^import[\s{'"*]/u.test(trimmed)) done = IMPORT_DONE;
790
+ else if (/^(?:const|let|var)\b/u.test(trimmed) && /\brequire\(\s*['"]/u.test(text.slice(start, end + 300).split(";")[0] ?? "")) {
791
+ done = REQUIRE_DONE;
792
+ }
793
+ if (done === null) break;
794
+ seenCode = true;
795
+ if (done.test(line)) lastImportEnd = end;
796
+ else pending = { done, text: line };
797
+ }
798
+ return lastImportEnd >= 0 ? lastImportEnd : leadingEnd;
799
+ }
800
+ function addImports(text, lines2) {
801
+ if (lines2.length === 0) return text;
802
+ const at = importInsertOffset(text);
803
+ const before = text.slice(0, at);
804
+ const block = `${lines2.join("\n")}
805
+ `;
806
+ const sep = before === "" || before.endsWith("\n") ? "" : "\n";
807
+ return `${before}${sep}${block}${text.slice(at)}`;
808
+ }
809
+
810
+ // src/cli/init/patterns.ts
811
+ function wrapPlaywrightConfig(text, perfImport) {
812
+ const esm = [...text.matchAll(/^export\s+default\s+/gmu)];
813
+ const cjs = [...text.matchAll(/^module\.exports\s*=\s*/gmu)];
814
+ if (esm.length + cjs.length !== 1) return null;
815
+ const isEsm = esm.length === 1;
816
+ const match = isEsm ? esm[0] : cjs[0];
817
+ const start = match.index + match[0].length;
818
+ const rest = text.slice(start);
819
+ let open;
820
+ if (rest.startsWith("{")) open = start;
821
+ else {
822
+ const call = /^defineConfig\s*/u.exec(rest);
823
+ if (call === null) return null;
824
+ open = callParen(text, start + "defineConfig".length);
825
+ }
826
+ if (open === -1) return null;
827
+ const end = matchBracket(text, open);
828
+ if (end === -1 || !onlyTrailing(text, end)) return null;
829
+ const value = text.slice(start, end);
830
+ const perfConfig = isEsm ? "perfConfig" : `require('${perfImport}').default`;
831
+ const wrapped = `${text.slice(0, start)}withPerf(${value}, ${perfConfig})${text.slice(end)}`;
832
+ return addImports(
833
+ wrapped,
834
+ isEsm ? [
835
+ `import { withPerf } from '${PACKAGE_NAME}/config';`,
836
+ `import perfConfig from '${perfImport}';`
837
+ ] : [`const { withPerf } = require('${PACKAGE_NAME}/config');`]
838
+ );
839
+ }
840
+ function wrapTestObject(text) {
841
+ const esm = /^export\s+const\s+test\s*=\s*([\w$.]+)\.extend\b/mu.exec(text);
842
+ const cjs = /^(?:module\.)?exports\.test\s*=\s*([\w$.]+)\.extend\b/mu.exec(text);
843
+ const match = esm ?? cjs;
844
+ if (match === null || esm !== null && cjs !== null) return null;
845
+ const exprStart = match.index + match[0].length - match[1].length - ".extend".length;
846
+ const open = callParen(text, match.index + match[0].length);
847
+ if (open === -1) return null;
848
+ const end = matchBracket(text, open);
849
+ if (end === -1 || !statementEnds(text, end)) return null;
850
+ const wrapped = `${text.slice(0, exprStart)}withPerfFixtures(${text.slice(exprStart, end)})${text.slice(end)}`;
851
+ return addImports(wrapped, [
852
+ esm !== null ? `import { withPerfFixtures } from '${PACKAGE_NAME}/fixture';` : `const { withPerfFixtures } = require('${PACKAGE_NAME}/fixture');`
853
+ ]);
854
+ }
855
+ function specifiers(list, separator) {
856
+ const result = [];
857
+ for (const raw of list.split(",")) {
858
+ const text = raw.trim();
859
+ if (text === "") continue;
860
+ const pattern = separator === "as" ? /^(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?$/u : /^()([\w$]+)(?:\s*:\s*([\w$]+))?$/u;
861
+ const m = pattern.exec(text);
862
+ if (m === null) return null;
863
+ result.push({
864
+ text,
865
+ name: m[2],
866
+ alias: m[3] ?? null,
867
+ type: m[1] !== void 0 && m[1] !== ""
868
+ });
869
+ }
870
+ return result;
871
+ }
872
+ var SWAPPED = /* @__PURE__ */ new Set(["test", "expect"]);
873
+ function swapTestImport(text) {
874
+ let changed = false;
875
+ const esm = text.replace(
876
+ /^import\s*\{([^}]*)\}\s*from\s*(['"])@playwright\/test\2(\s*;)?/gmu,
877
+ (whole, list, quote, semi) => {
878
+ const specs = specifiers(list, "as");
879
+ if (specs === null || !specs.some((s) => s.name === "test" && s.alias === null && !s.type)) {
880
+ return whole;
881
+ }
882
+ const swap = specs.filter((s) => SWAPPED.has(s.name) && s.alias === null && !s.type);
883
+ const keep = specs.filter((s) => !swap.includes(s));
884
+ changed = true;
885
+ const end = semi === void 0 ? "" : ";";
886
+ const lines2 = [
887
+ `import { ${swap.map((s) => s.text).join(", ")} } from ${quote}${PACKAGE_NAME}/test${quote}${end}`
888
+ ];
889
+ if (keep.length > 0) {
890
+ lines2.push(
891
+ `import { ${keep.map((s) => s.text).join(", ")} } from ${quote}@playwright/test${quote}${end}`
892
+ );
893
+ }
894
+ return lines2.join("\n");
895
+ }
896
+ );
897
+ const cjs = esm.replace(
898
+ /^(const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*(['"])@playwright\/test\3\s*\)(\s*;)?/gmu,
899
+ (whole, kind, list, quote, semi) => {
900
+ const specs = specifiers(list, ":");
901
+ if (specs === null || !specs.some((s) => s.name === "test" && s.alias === null)) return whole;
902
+ const swap = specs.filter((s) => SWAPPED.has(s.name) && s.alias === null);
903
+ const keep = specs.filter((s) => !swap.includes(s));
904
+ changed = true;
905
+ const end = semi === void 0 ? "" : ";";
906
+ const lines2 = [
907
+ `${kind} { ${swap.map((s) => s.text).join(", ")} } = require(${quote}${PACKAGE_NAME}/test${quote})${end}`
908
+ ];
909
+ if (keep.length > 0) {
910
+ lines2.push(
911
+ `${kind} { ${keep.map((s) => s.text).join(", ")} } = require(${quote}@playwright/test${quote})${end}`
912
+ );
913
+ }
914
+ return lines2.join("\n");
915
+ }
916
+ );
917
+ return changed ? cjs : null;
918
+ }
919
+ function ignores(gitignore, dir) {
920
+ return gitignore.split(/\r?\n/u).some((line) => line.trim().replace(/^\//u, "").replace(/\/$/u, "") === dir);
921
+ }
922
+ function addIgnore(gitignore, dir) {
923
+ if (gitignore === null || gitignore === "") return `${dir}/
924
+ `;
925
+ const nl = gitignore.includes("\r\n") ? "\r\n" : "\n";
926
+ return `${gitignore}${gitignore.endsWith("\n") ? "" : nl}${dir}/${nl}`;
927
+ }
928
+ function addScripts(text, scripts) {
929
+ let pkg;
930
+ try {
931
+ pkg = JSON.parse(text);
932
+ } catch {
933
+ return null;
934
+ }
935
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) return null;
936
+ const obj = pkg;
937
+ const current = obj["scripts"];
938
+ if (current !== void 0 && (typeof current !== "object" || current === null || Array.isArray(current))) {
939
+ return null;
940
+ }
941
+ obj["scripts"] = { ...current, ...scripts };
942
+ const indent = /^[ \t]+(?=")/mu.exec(text)?.[0] ?? " ";
943
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
944
+ const json = JSON.stringify(obj, null, indent).replaceAll("\n", nl);
945
+ return /\r?\n$/u.test(text) ? `${json}${nl}` : json;
946
+ }
947
+
948
+ // src/cli/init/plan.ts
949
+ var PERF_CONFIG_FILE = "pw-perf.config.ts";
950
+ function plannedScripts(answers) {
951
+ const labels = answers.envLabels.length === 0 ? [null] : answers.envLabels;
952
+ const scripts = {};
953
+ for (const label of labels) {
954
+ const name = label === null ? "" : `:${label}`;
955
+ const flags = commandFlags(answers.scope, label);
956
+ scripts[`perf:test${name}`] = `pw-perf test${flags}`;
957
+ scripts[`perf:thresholds${name}`] = `pw-perf thresholds${flags}`;
958
+ }
959
+ return scripts;
960
+ }
961
+ function manual(message2, hint) {
962
+ return { code: "INIT_MANUAL_STEP", message: message2, hint };
963
+ }
964
+ function change(info, path, after) {
965
+ const before = info.files.get(path) ?? null;
966
+ if (before === after) return null;
967
+ return { path, kind: before === null ? "create" : "modify", before, after };
968
+ }
969
+ var CONFIG_HINT = (path) => [
970
+ `Wrap the exported config in withPerf() as the outermost call (also around other wrappers):`,
971
+ ` import { withPerf } from '${PACKAGE_NAME}/config';`,
972
+ ` import perfConfig from './pw-perf.config';`,
973
+ ` export default withPerf(otherWrapper(defineConfig({ ... })), perfConfig);`,
974
+ `In ${path} with module.exports: withPerf(config, require('./pw-perf.config').default).`
975
+ ].join("\n");
976
+ var TEST_HINT = [
977
+ `Wrap every test object used by browser tests in withPerfFixtures() from '${PACKAGE_NAME}/fixture':`,
978
+ " export const test = withPerfFixtures(base.extend({ ... }));",
979
+ " export const adminTest = withPerfFixtures(test.extend({ ... }));",
980
+ " export const merged = withPerfFixtures(mergeTests(a, b));",
981
+ "Wrap the result of mergeTests() and the test passed to createBdd() (playwright-bdd).",
982
+ `Tests that import test from @playwright/test can import it from '${PACKAGE_NAME}/test' instead.`
983
+ ].join("\n");
984
+ function planPerfConfig(info, answers, plan) {
985
+ const existing = info.existing.perfConfig;
986
+ if (existing === null || existing === PERF_CONFIG_FILE) {
987
+ const c = change(info, PERF_CONFIG_FILE, renderPerfConfig(answers));
988
+ if (c !== null) plan.changes.push(c);
989
+ return;
990
+ }
991
+ const values = [
992
+ ...Object.entries(answers.originLabels).map(([o, l]) => `keys.origins["${o}"] = "${l}"`),
993
+ ...answers.repeatTest === DEFAULT_CONFIG.run.repeat.test ? [] : [`run.repeat.test = ${answers.repeatTest}`],
994
+ ...answers.warnOnly === DEFAULT_CONFIG.gate.warnOnly ? [] : [`gate.warnOnly = ${answers.warnOnly}`]
995
+ ];
996
+ if (values.length > 0) {
997
+ plan.manualSteps.push(
998
+ manual(
999
+ `${existing} exists and was not changed.`,
1000
+ `Set these options in it if you want them:
1001
+ ${values.map((v) => ` ${v}`).join("\n")}`
1002
+ )
1003
+ );
1004
+ }
1005
+ }
1006
+ function planPlaywrightConfig(info, plan) {
1007
+ const config = info.playwrightConfig;
1008
+ if (config === null || info.existing.wrappedConfig) return;
1009
+ const existing = info.existing.perfConfig;
1010
+ if (existing !== null && existing.endsWith(".json")) {
1011
+ plan.manualSteps.push(
1012
+ manual(
1013
+ `${config.path} was not changed: the package config is ${existing}.`,
1014
+ CONFIG_HINT(config.path).replaceAll("'./pw-perf.config'", `'./${existing}'`)
1015
+ )
1016
+ );
1017
+ return;
1018
+ }
1019
+ const after = wrapPlaywrightConfig(config.text, "./pw-perf.config");
1020
+ if (after === null) {
1021
+ plan.manualSteps.push(
1022
+ manual(
1023
+ `${config.path} was not changed: its export is not a plain defineConfig({...}) or object (for example another wrapper).`,
1024
+ CONFIG_HINT(config.path)
1025
+ )
1026
+ );
1027
+ return;
1028
+ }
1029
+ plan.changes.push({ path: config.path, kind: "modify", before: config.text, after });
1030
+ }
1031
+ function planTestObject(info, plan) {
1032
+ if (info.existing.wrappedTest) return;
1033
+ const text = (path) => info.files.get(path) ?? "";
1034
+ const extendFiles = info.filesWithExtend;
1035
+ const merges = [...info.files.keys()].filter(
1036
+ (p) => info.filesImportingPlaywrightTest.includes(p) && /\bmergeTests\s*\(/u.test(text(p))
1037
+ );
1038
+ if (extendFiles.length === 0 && merges.length === 0) {
1039
+ const swaps = info.filesImportingPlaywrightTest.flatMap((path) => {
1040
+ const after2 = swapTestImport(text(path));
1041
+ return after2 === null ? [] : [{ path, kind: "modify", before: text(path), after: after2 }];
1042
+ });
1043
+ if (swaps.length === 0) {
1044
+ plan.manualSteps.push(
1045
+ manual(
1046
+ "No test object was found to measure: no file imports test from @playwright/test.",
1047
+ TEST_HINT
1048
+ )
1049
+ );
1050
+ }
1051
+ plan.changes.push(...swaps);
1052
+ return;
1053
+ }
1054
+ const only = extendFiles.length === 1 && merges.length === 0 ? extendFiles[0] : null;
1055
+ const after = only !== null && [...text(only).matchAll(EXTEND_CALL)].length === 1 ? wrapTestObject(text(only)) : null;
1056
+ if (only === null || after === null) {
1057
+ const files = [.../* @__PURE__ */ new Set([...extendFiles, ...merges])].sort();
1058
+ plan.manualSteps.push(
1059
+ manual(
1060
+ `${files.join(", ")} ${files.length === 1 ? "was" : "were"} not changed: the test objects are not one \`export const test = base.extend(...)\` (several test objects, mergeTests() or another layout).`,
1061
+ TEST_HINT
1062
+ )
1063
+ );
1064
+ return;
1065
+ }
1066
+ plan.changes.push({ path: only, kind: "modify", before: text(only), after });
1067
+ }
1068
+ function planGitignore(info, plan) {
1069
+ const dir = DEFAULT_CONFIG.report.dir;
1070
+ const current = info.files.get(".gitignore") ?? null;
1071
+ if (current !== null && ignores(current, dir)) return;
1072
+ const c = change(info, ".gitignore", addIgnore(current, dir));
1073
+ if (c !== null) plan.changes.push(c);
1074
+ }
1075
+ function planScripts(info, answers, plan) {
1076
+ const text = info.files.get("package.json");
1077
+ const wanted = plannedScripts(answers);
1078
+ if (text === void 0) {
1079
+ plan.manualSteps.push(
1080
+ manual(
1081
+ "package.json was not found.",
1082
+ `Add these scripts:
1083
+ ${Object.entries(wanted).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1084
+ )
1085
+ );
1086
+ return;
1087
+ }
1088
+ let current = {};
1089
+ try {
1090
+ const scripts = JSON.parse(text).scripts;
1091
+ if (typeof scripts === "object" && scripts !== null)
1092
+ current = scripts;
1093
+ } catch {
1094
+ }
1095
+ const added = {};
1096
+ for (const [name, command] of Object.entries(wanted)) {
1097
+ if (current[name] === void 0) added[name] = command;
1098
+ else if (current[name] !== command) {
1099
+ plan.manualSteps.push(
1100
+ manual(
1101
+ `package.json: the script "${name}" exists and was not changed.`,
1102
+ `The wizard would add "${name}": "${command}". Rename one of them, or add the command by hand.`
1103
+ )
1104
+ );
1105
+ }
1106
+ }
1107
+ if (Object.keys(added).length === 0) return;
1108
+ const after = addScripts(text, added);
1109
+ if (after === null) {
1110
+ plan.manualSteps.push(
1111
+ manual(
1112
+ 'package.json was not changed: it is not a JSON object with a "scripts" object.',
1113
+ `Add these scripts:
1114
+ ${Object.entries(added).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1115
+ )
1116
+ );
1117
+ return;
1118
+ }
1119
+ plan.changes.push({ path: "package.json", kind: "modify", before: text, after });
1120
+ }
1121
+ var INSTALL = {
1122
+ npm: "npm ci",
1123
+ pnpm: "pnpm install --frozen-lockfile",
1124
+ yarn: "yarn install --immutable"
1125
+ };
1126
+ function planCi(info, answers, plan) {
1127
+ const platform = info.ciPlatform;
1128
+ if (!answers.addCi || platform === null) return;
1129
+ const created = [];
1130
+ for (const file of ciFiles(platform, answers.scope, answers.envLabels)) {
1131
+ const before = info.files.get(file.path) ?? null;
1132
+ if (before === file.text) continue;
1133
+ if (before !== null) {
1134
+ plan.manualSteps.push(
1135
+ manual(
1136
+ `${file.path} exists and was not changed.`,
1137
+ `Compare it with examples/ci/ in the ${PACKAGE_NAME} repository.`
1138
+ )
1139
+ );
1140
+ continue;
1141
+ }
1142
+ plan.changes.push({ path: file.path, kind: "create", before: null, after: file.text });
1143
+ created.push(file.path);
1144
+ }
1145
+ if (platform === "gitlab") {
1146
+ const main2 = info.files.get(".gitlab-ci.yml") ?? "";
1147
+ const missing = ciFiles(platform, answers.scope, answers.envLabels).map((f) => f.path).filter((p) => !main2.includes(p));
1148
+ if (missing.length > 0) {
1149
+ plan.manualSteps.push(
1150
+ manual(
1151
+ ".gitlab-ci.yml was not changed: include the new job file in it.",
1152
+ ["include:", ...missing.map((p) => ` - local: ${p}`)].join("\n")
1153
+ )
1154
+ );
1155
+ }
1156
+ }
1157
+ if (created.length > 0 && info.packageManager !== "npm") {
1158
+ plan.manualSteps.push(
1159
+ manual(
1160
+ `${created.join(", ")} ${created.length === 1 ? "installs" : "install"} the dependencies with npm.`,
1161
+ `This project uses ${info.packageManager}: replace "npm ci" with "${INSTALL[info.packageManager]}" and "npx" with "${info.packageManager === "pnpm" ? "pnpm exec" : "yarn"}".`
1162
+ )
1163
+ );
1164
+ }
1165
+ }
1166
+ function planInitChanges(info, answers) {
1167
+ const plan = { changes: [], manualSteps: [] };
1168
+ planPerfConfig(info, answers, plan);
1169
+ planPlaywrightConfig(info, plan);
1170
+ planTestObject(info, plan);
1171
+ planGitignore(info, plan);
1172
+ planScripts(info, answers, plan);
1173
+ planCi(info, answers, plan);
1174
+ return plan;
1175
+ }
1176
+ function isProtected(info, path) {
1177
+ return PERF_CONFIG_NAMES.includes(path) && info.existing.perfConfig === path;
1178
+ }
1179
+ var PromptAborted = class extends Error {
1180
+ constructor() {
1181
+ super("interrupted");
1182
+ this.name = "PromptAborted";
1183
+ }
1184
+ };
1185
+ function readlinePrompt(input, output, terminal) {
1186
+ const rl = createInterface({ input, output, ...{} });
1187
+ const controller = new AbortController();
1188
+ let closed = false;
1189
+ rl.on("SIGINT", () => controller.abort());
1190
+ rl.on("close", () => {
1191
+ closed = true;
1192
+ controller.abort();
1193
+ });
1194
+ return {
1195
+ async ask(question) {
1196
+ if (controller.signal.aborted) throw new PromptAborted();
1197
+ try {
1198
+ return await rl.question(question, { signal: controller.signal });
1199
+ } catch (error) {
1200
+ if (controller.signal.aborted) {
1201
+ output.write("\n");
1202
+ throw new PromptAborted();
1203
+ }
1204
+ throw error;
1205
+ }
1206
+ },
1207
+ close() {
1208
+ if (!closed) rl.close();
1209
+ }
1210
+ };
1211
+ }
1212
+
1213
+ // src/cli/output.ts
1214
+ var PREFIX = `${PACKAGE_NAME}: `;
1215
+ var ANSI = { red: "\x1B[31m", yellow: "\x1B[33m", green: "\x1B[32m" };
1216
+ var RESET = "\x1B[0m";
1217
+ function paint(text, style2, opts) {
1218
+ return opts.color ? `${ANSI[style2]}${text}${RESET}` : text;
1219
+ }
1220
+ function infoLine(text) {
1221
+ return `${PREFIX}${text}
1222
+ `;
1223
+ }
1224
+ function formatIssue(issue, level, opts) {
1225
+ const label = paint(`${level} ${issue.code}`, level === "error" ? "red" : "yellow", opts);
1226
+ const lines2 = [`${PREFIX}${label}: ${issue.message}`];
1227
+ if (issue.hint !== void 0) {
1228
+ for (const line of issue.hint.split("\n")) lines2.push(` ${line}`);
1229
+ }
1230
+ return `${lines2.join("\n")}
1231
+ `;
1232
+ }
1233
+ function formatIssues(issues, level, opts) {
1234
+ return issues.map((issue) => formatIssue(issue, level, opts)).join("");
1235
+ }
1236
+ var TESTS_TEXT = {
1237
+ passed: "tests passed",
1238
+ failed: "tests failed",
1239
+ timedout: "tests timed out",
1240
+ interrupted: "tests interrupted"
1241
+ };
1242
+ var EVALUATION_TEXT = {
1243
+ passed: "performance passed",
1244
+ warned: "performance passed with warnings",
1245
+ failed: "performance failed",
1246
+ error: "performance not evaluated"
1247
+ };
1248
+ function resultLines(outcome, exitCode, opts) {
1249
+ const parts = [];
1250
+ if (outcome !== null) {
1251
+ parts.push(TESTS_TEXT[outcome.tests.status]);
1252
+ parts.push(
1253
+ outcome.mode === "thresholds" ? outcome.exitCode === 0 ? "thresholds derived" : "thresholds not written" : EVALUATION_TEXT[outcome.evaluation.status]
1254
+ );
1255
+ }
1256
+ const code = paint(`exit code ${exitCode}`, exitCode === 0 ? "green" : "red", opts);
1257
+ parts.push(code);
1258
+ let text = infoLine(parts.join(" \xB7 "));
1259
+ const report = outcome?.paths.reportHtml ?? outcome?.paths.reportJson ?? null;
1260
+ if (report !== null) text += infoLine(`report: ${report}`);
1261
+ const diff = outcome?.paths.thresholdsDiff ?? null;
1262
+ if (diff !== null) text += infoLine(`thresholds diff: ${diff}`);
1263
+ return text;
1264
+ }
1265
+
1266
+ // src/cli/exit.ts
1267
+ var SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
1268
+ function resolveExitCode(input) {
1269
+ if (input.receivedSignal !== void 0) {
1270
+ return { code: SIGNAL_EXIT_CODES[input.receivedSignal], issues: [] };
1271
+ }
1272
+ if (input.listOnly) return { code: input.childExitCode ?? 1, issues: [] };
1273
+ if (input.outcome.ok) return { code: input.outcome.value.exitCode, issues: [] };
1274
+ const playwright = input.childExitCode === null ? "Playwright ended without an exit code (killed by a signal)" : `Playwright exited with code ${input.childExitCode}`;
1275
+ if (input.outcome.reason === "invalid") {
1276
+ return {
1277
+ code: 3,
1278
+ issues: [
1279
+ {
1280
+ code: "CLI_OUTCOME_INVALID",
1281
+ message: `The outcome file of the run is not valid${input.outcome.detail === void 0 ? "" : `: ${input.outcome.detail}`}. ${playwright}.`,
1282
+ hint: "Check that the project uses one version of playwright-performance-regression, then run again."
1283
+ }
1284
+ ]
1285
+ };
1286
+ }
1287
+ return {
1288
+ code: 3,
1289
+ issues: [
1290
+ {
1291
+ code: "CLI_OUTCOME_MISSING",
1292
+ message: `The run wrote no outcome file, so its result is unknown. ${playwright}.`,
1293
+ hint: [
1294
+ "Common causes:",
1295
+ `- playwright.config does not use withPerf() (set it up with "${CLI_COMMAND} init");`,
1296
+ "- a configuration error (see the message above);",
1297
+ "- no test matched the filters (Playwright then reports no tests);",
1298
+ "- Playwright stopped before the reporters finished (onEnd)."
1299
+ ].join("\n")
1300
+ }
1301
+ ]
1302
+ };
1303
+ }
1304
+
1305
+ // src/cli/playwright-args.ts
1306
+ var WITH_VALUE = /* @__PURE__ */ new Set([
1307
+ "--browser",
1308
+ "--config",
1309
+ "--global-timeout",
1310
+ "--grep",
1311
+ "--grep-invert",
1312
+ "--max-failures",
1313
+ "--output",
1314
+ "--repeat-each",
1315
+ "--reporter",
1316
+ "--retries",
1317
+ "--shard",
1318
+ "--test-list",
1319
+ "--test-list-invert",
1320
+ "--timeout",
1321
+ "--trace",
1322
+ "--tsconfig",
1323
+ "--ui-host",
1324
+ "--ui-port",
1325
+ "--update-source-method",
1326
+ "--workers"
1327
+ ]);
1328
+ var OPTIONAL_VALUE = /* @__PURE__ */ new Set(["--only-changed", "--update-snapshots"]);
1329
+ var VARIADIC = /* @__PURE__ */ new Set(["--project"]);
1330
+ var SHORT = {
1331
+ c: "--config",
1332
+ g: "--grep",
1333
+ j: "--workers",
1334
+ u: "--update-snapshots",
1335
+ x: "-x",
1336
+ h: "--help"
1337
+ };
1338
+ function isOptionLike(arg) {
1339
+ return arg.startsWith("-") && arg !== "-";
1340
+ }
1341
+ function scanPlaywrightArgs(args) {
1342
+ const options = [];
1343
+ const positionals = [];
1344
+ let i = 0;
1345
+ while (i < args.length) {
1346
+ const arg = args[i];
1347
+ if (!isOptionLike(arg)) {
1348
+ positionals.push(arg);
1349
+ i += 1;
1350
+ continue;
1351
+ }
1352
+ let name;
1353
+ let inlineValue;
1354
+ if (arg.startsWith("--")) {
1355
+ const eq = arg.indexOf("=");
1356
+ name = eq === -1 ? arg : arg.slice(0, eq);
1357
+ if (eq !== -1) inlineValue = arg.slice(eq + 1);
1358
+ } else {
1359
+ const long = SHORT[arg.charAt(1)];
1360
+ name = long ?? arg;
1361
+ if (long !== void 0 && arg.length > 2) {
1362
+ const rest = arg.slice(2);
1363
+ inlineValue = rest.startsWith("=") ? rest.slice(1) : rest;
1364
+ }
1365
+ }
1366
+ const option = { name, values: [], index: i, inline: false };
1367
+ options.push(option);
1368
+ i += 1;
1369
+ if (inlineValue !== void 0) {
1370
+ option.values.push(inlineValue);
1371
+ option.inline = true;
1372
+ continue;
1373
+ }
1374
+ if (WITH_VALUE.has(name)) {
1375
+ if (i < args.length) {
1376
+ option.values.push(args[i]);
1377
+ i += 1;
1378
+ }
1379
+ } else if (OPTIONAL_VALUE.has(name)) {
1380
+ if (i < args.length && !isOptionLike(args[i])) {
1381
+ option.values.push(args[i]);
1382
+ i += 1;
1383
+ }
1384
+ } else if (VARIADIC.has(name)) {
1385
+ while (i < args.length && !isOptionLike(args[i])) {
1386
+ option.values.push(args[i]);
1387
+ i += 1;
1388
+ }
1389
+ }
1390
+ }
1391
+ return { options, positionals };
1392
+ }
1393
+ var FILTERS = /* @__PURE__ */ new Set([
1394
+ "--grep",
1395
+ "--grep-invert",
1396
+ "--project",
1397
+ "--last-failed",
1398
+ "--only-changed",
1399
+ "--test-list",
1400
+ "--test-list-invert"
1401
+ ]);
1402
+ function testFilters(args) {
1403
+ const scanned = scanPlaywrightArgs(args);
1404
+ return [
1405
+ ...scanned.options.filter((o) => FILTERS.has(o.name)).map((o) => args.slice(o.index, o.index + 1 + (o.inline ? 0 : o.values.length)).join(" ")),
1406
+ ...scanned.positionals
1407
+ ];
1408
+ }
1409
+ var UNSUPPORTED = /* @__PURE__ */ new Set([
1410
+ "--ui",
1411
+ "--ui-host",
1412
+ "--ui-port",
1413
+ "--debug",
1414
+ "--shard"
1415
+ ]);
1416
+ function unsupportedOptions(args) {
1417
+ return scanPlaywrightArgs(args).options.filter((o) => UNSUPPORTED.has(o.name)).map((o) => o.name);
1418
+ }
1419
+ function isListOnly(args) {
1420
+ return scanPlaywrightArgs(args).options.some((o) => o.name === "--list");
1421
+ }
1422
+ function playwrightConfigArg(args) {
1423
+ const configs = scanPlaywrightArgs(args).options.filter(
1424
+ (o) => o.name === "--config" && o.values.length > 0
1425
+ );
1426
+ return configs.length === 0 ? null : configs[configs.length - 1]?.values[0] ?? null;
1427
+ }
1428
+
1429
+ // src/cli/reporter-arg.ts
1430
+ function withPerfReporterArg(args, reporterPath) {
1431
+ const reporters = scanPlaywrightArgs(args).options.filter(
1432
+ (o) => o.name === "--reporter" && o.values.length > 0
1433
+ );
1434
+ const last = reporters[reporters.length - 1];
1435
+ if (last === void 0) return { ok: true, value: [...args] };
1436
+ if (reporterPath.includes(",")) {
1437
+ return {
1438
+ ok: false,
1439
+ issues: [
1440
+ {
1441
+ code: "CLI_REPORTER_PATH_UNSUPPORTED",
1442
+ message: `The package reporter cannot be added to --reporter: its path contains a comma, and Playwright splits the --reporter value at commas (${reporterPath}).`,
1443
+ hint: "Remove --reporter from the arguments (withPerf() then adds the reporter itself), or move the project to a path without a comma."
1444
+ }
1445
+ ]
1446
+ };
1447
+ }
1448
+ const value = `${last.values[0]},${reporterPath}`;
1449
+ const result = [...args];
1450
+ if (last.inline) result[last.index] = `--reporter=${value}`;
1451
+ else result[last.index + 1] = value;
1452
+ return { ok: true, value: result };
1453
+ }
1454
+
1455
+ // src/cli/run.ts
1456
+ var FORCE_KILL_WINDOW_MS = 5 * 1e3;
1457
+ function outcomeFilePath(tmpdir2, runId, join3) {
1458
+ return join3(tmpdir2, `${PACKAGE_NAME}-${runId}.outcome.json`);
1459
+ }
1460
+ function planRun(cmd, input) {
1461
+ const args = withPerfReporterArg(cmd.playwrightArgs, input.reporterPath);
1462
+ if (!args.ok) return args;
1463
+ const warnings = [];
1464
+ const preset = MODE_ENV_NAMES.filter((name) => (input.env[name] ?? "") !== "");
1465
+ if (preset.length > 0) {
1466
+ warnings.push({
1467
+ code: "CLI_MODE_ALREADY_SET",
1468
+ message: `${preset.join(", ")} ${preset.length === 1 ? "is" : "are"} already set in the environment; the CLI replaces ${preset.length === 1 ? "it" : "them"} for this run.`,
1469
+ hint: 'Use the CLI options (--env, --repeat, --prune) instead of the variables, or run "npx playwright test" for the manual mode.'
1470
+ });
1471
+ }
1472
+ const env = {};
1473
+ for (const [name, value] of Object.entries(input.env)) {
1474
+ if (value !== void 0 && !MODE_ENV_NAMES.includes(name)) env[name] = value;
1475
+ }
1476
+ Object.assign(
1477
+ env,
1478
+ writeModeState({
1479
+ mode: cmd.mode,
1480
+ ...cmd.repeat === void 0 ? {} : { repeat: cmd.repeat },
1481
+ ...cmd.env === void 0 ? {} : { env: cmd.env },
1482
+ runId: input.runId,
1483
+ outcomeFile: input.outcomeFile,
1484
+ prune: cmd.prune
1485
+ })
1486
+ );
1487
+ const repeats = cmd.repeat === void 0 ? `repeats per test from run.repeat.${cmd.mode}` : `${cmd.repeat} ${cmd.repeat === 1 ? "repeat" : "repeats"} per test`;
1488
+ const lines2 = [`perf mode "${cmd.mode}", ${repeats}, 1 worker.`];
1489
+ if (!cmd.listOnly && testFilters(cmd.playwrightArgs).length === 0) {
1490
+ lines2.push("tip: measure a subset, e.g. --grep @perf or --project chromium.");
1491
+ }
1492
+ return { ok: true, value: { args: args.value, env, lines: lines2, warnings } };
1493
+ }
1494
+ function versionAtLeast(version2, minimum) {
1495
+ const parts = (v) => v.split(/[.+-]/u).slice(0, 3).map((p) => Number.parseInt(p, 10) || 0);
1496
+ const a = parts(version2);
1497
+ const b = parts(minimum);
1498
+ for (let i = 0; i < 3; i += 1) {
1499
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
1500
+ }
1501
+ return true;
1502
+ }
1503
+ function style(host) {
1504
+ return { color: host.stderr.isTTY === true && (host.env.NO_COLOR ?? "") === "" };
1505
+ }
1506
+ async function playwrightDir(cmd, host) {
1507
+ const config = playwrightConfigArg(cmd.playwrightArgs);
1508
+ if (config === null) return host.cwd;
1509
+ const path = host.paths.resolve(host.cwd, config);
1510
+ return await host.isDirectory(path) ? path : host.paths.dirname(path);
1511
+ }
1512
+ async function readOutcome(host, file, runId) {
1513
+ let text;
1514
+ try {
1515
+ text = await host.readText(file);
1516
+ } catch (error) {
1517
+ return {
1518
+ ok: false,
1519
+ reason: "invalid",
1520
+ detail: error instanceof Error ? error.message : String(error)
1521
+ };
1522
+ }
1523
+ if (text === null) return { ok: false, reason: "missing" };
1524
+ const parsed = parseOutcome(text, file);
1525
+ if (!parsed.ok) {
1526
+ return { ok: false, reason: "invalid", detail: parsed.issues.map((i) => i.message).join("; ") };
1527
+ }
1528
+ if (parsed.value.runId !== runId) {
1529
+ return {
1530
+ ok: false,
1531
+ reason: "invalid",
1532
+ detail: `it belongs to run ${parsed.value.runId}, not to this run (${runId})`
1533
+ };
1534
+ }
1535
+ return { ok: true, value: parsed.value };
1536
+ }
1537
+ function waitForChild(child, host, received) {
1538
+ return new Promise((resolve2) => {
1539
+ let lastSigint = null;
1540
+ const forward = (signal) => {
1541
+ received.signal ??= signal;
1542
+ if (signal === "SIGINT") {
1543
+ const now = host.now().getTime();
1544
+ if (lastSigint !== null && now - lastSigint <= FORCE_KILL_WINDOW_MS) {
1545
+ child.kill("SIGKILL");
1546
+ return;
1547
+ }
1548
+ lastSigint = now;
1549
+ }
1550
+ if (host.platform === "win32") child.kill();
1551
+ else child.kill(signal);
1552
+ };
1553
+ const off = [
1554
+ host.onSignal("SIGINT", () => forward("SIGINT")),
1555
+ host.onSignal("SIGTERM", () => forward("SIGTERM"))
1556
+ ];
1557
+ let finished = false;
1558
+ const done = (result) => {
1559
+ if (finished) return;
1560
+ finished = true;
1561
+ for (const remove of off) remove();
1562
+ resolve2(result);
1563
+ };
1564
+ child.once("error", (error) => done({ code: null, error }));
1565
+ child.once("exit", (code) => done({ code }));
1566
+ });
1567
+ }
1568
+ async function runTests(cmd, host) {
1569
+ const out = style(host);
1570
+ const fail2 = (issues) => {
1571
+ host.stderr.write(formatIssues(issues, "error", out));
1572
+ return 3;
1573
+ };
1574
+ const install = host.resolvePlaywright(await playwrightDir(cmd, host));
1575
+ if (install === null) {
1576
+ return fail2([
1577
+ {
1578
+ code: "CLI_PLAYWRIGHT_NOT_FOUND",
1579
+ message: "@playwright/test is not installed in this project.",
1580
+ hint: 'Install it with "npm i -D @playwright/test", or run the command from the project directory (or pass -c <playwright.config>).'
1581
+ }
1582
+ ]);
1583
+ }
1584
+ const warnings = [];
1585
+ if (!versionAtLeast(install.version, host.minPlaywrightVersion)) {
1586
+ warnings.push({
1587
+ code: "CLI_PLAYWRIGHT_UNSUPPORTED_VERSION",
1588
+ message: `@playwright/test ${install.version} is older than ${host.minPlaywrightVersion}, the lowest supported version; the run continues.`,
1589
+ hint: `Update @playwright/test to ${host.minPlaywrightVersion} or newer.`
1590
+ });
1591
+ }
1592
+ const runId = generateRunId(host.now(), () => host.random());
1593
+ const outcomeFile = outcomeFilePath(host.tmpdir, runId, host.paths.join);
1594
+ const plan = planRun(cmd, { env: host.env, runId, outcomeFile, reporterPath: host.reporterPath });
1595
+ if (!plan.ok) return fail2(plan.issues);
1596
+ warnings.push(...plan.value.warnings);
1597
+ host.stderr.write(formatIssues(warnings, "warning", out));
1598
+ for (const line of plan.value.lines) host.stderr.write(infoLine(line));
1599
+ const received = {};
1600
+ let child;
1601
+ try {
1602
+ child = host.spawnNode([install.cliPath, "test", ...plan.value.args], {
1603
+ cwd: host.cwd,
1604
+ env: plan.value.env,
1605
+ stdio: "inherit",
1606
+ shell: false
1607
+ });
1608
+ } catch (error) {
1609
+ return fail2([spawnFailed(error)]);
1610
+ }
1611
+ const exit = await waitForChild(child, host, received);
1612
+ const outcome = await readOutcome(host, outcomeFile, runId);
1613
+ await host.removeFile(outcomeFile).catch(() => void 0);
1614
+ if (exit.error !== void 0) return fail2([spawnFailed(exit.error)]);
1615
+ const resolved = resolveExitCode({
1616
+ outcome,
1617
+ childExitCode: exit.code,
1618
+ ...received.signal === void 0 ? {} : { receivedSignal: received.signal },
1619
+ listOnly: cmd.listOnly
1620
+ });
1621
+ host.stderr.write(formatIssues(resolved.issues, "error", out));
1622
+ if (!cmd.listOnly) {
1623
+ const value = outcome.ok ? outcome.value : null;
1624
+ host.stderr.write(resultLines(value, resolved.code, out));
1625
+ }
1626
+ return resolved.code;
1627
+ }
1628
+ function spawnFailed(error) {
1629
+ return {
1630
+ code: "CLI_SPAWN_FAILED",
1631
+ message: `The Playwright process could not be started: ${error instanceof Error ? error.message : String(error)}`,
1632
+ hint: "Check that Node can run the Playwright CLI of the project (reinstall the dependencies)."
1633
+ };
1634
+ }
1635
+
1636
+ // src/cli/init/wizard.ts
1637
+ var STEPS = 11;
1638
+ var PLATFORM_NAMES = {
1639
+ github: "GitHub Actions",
1640
+ gitlab: "GitLab CI",
1641
+ jenkins: "Jenkins",
1642
+ azure: "Azure Pipelines"
1643
+ };
1644
+ var DOCS = `${REPOSITORY_URL}/blob/main/docs`;
1645
+ var WriteFailed = class extends Error {
1646
+ };
1647
+ var Dialog = class {
1648
+ #host;
1649
+ #prompt;
1650
+ #style;
1651
+ constructor(host, prompt, style2) {
1652
+ this.#host = host;
1653
+ this.#prompt = prompt;
1654
+ this.#style = style2;
1655
+ }
1656
+ get interactive() {
1657
+ return this.#prompt !== null;
1658
+ }
1659
+ say(...lines2) {
1660
+ this.#host.stdout.write(lines2.map((l) => `${l}
1661
+ `).join(""));
1662
+ }
1663
+ step(n, title, ...lesson) {
1664
+ this.say("", `Step ${n}/${STEPS} \xB7 ${title}`, ...lesson.map((l) => ` ${l}`));
1665
+ }
1666
+ warn(issues) {
1667
+ if (issues.length > 0) this.#host.stderr.write(formatIssues(issues, "warning", this.#style));
1668
+ }
1669
+ /** A question with a default; `parse` returns the value or null to ask again. */
1670
+ async ask(question, shownDefault, fallback, parse, fallbackText = shownDefault) {
1671
+ const text = ` ${question} (${shownDefault}) `;
1672
+ if (this.#prompt === null) {
1673
+ this.say(`${text}\u2192 ${fallbackText}`);
1674
+ return fallback;
1675
+ }
1676
+ for (; ; ) {
1677
+ const answer = (await this.#prompt.ask(text)).trim();
1678
+ if (answer === "") return fallback;
1679
+ const value = parse(answer);
1680
+ if (value !== null) return value;
1681
+ this.say(" Please answer again: that value is not valid here.");
1682
+ }
1683
+ }
1684
+ confirm(question, fallback) {
1685
+ return this.ask(
1686
+ question,
1687
+ fallback ? "Y/n" : "y/N",
1688
+ fallback,
1689
+ (a) => /^(y|yes)$/iu.test(a) ? true : /^(n|no)$/iu.test(a) ? false : null,
1690
+ fallback ? "yes" : "no"
1691
+ );
1692
+ }
1693
+ async pause() {
1694
+ if (this.#prompt !== null) await this.#prompt.ask(" Press Enter to continue. ");
1695
+ }
1696
+ };
1697
+ function count(n, one, many) {
1698
+ return `${n} ${n === 1 ? one : many}`;
1699
+ }
1700
+ function runCommand(manager, script) {
1701
+ return manager === "npm" ? `npm run ${script}` : `${manager} ${script}`;
1702
+ }
1703
+ function describeProject(info) {
1704
+ const config = info.playwrightConfig;
1705
+ const lines2 = [
1706
+ `${config?.path ?? "-"} \xB7 Playwright ${info.playwrightVersion ?? "version unknown"} \xB7 ${info.packageManager} \xB7 ${info.moduleType === "esm" ? "ES modules" : "CommonJS"}`,
1707
+ `Test directory "${info.testDir}": ${count(info.filesImportingPlaywrightTest.length, "file imports", "files import")} @playwright/test, ${count(info.filesWithExtend.length, "file calls", "files call")} .extend()`
1708
+ ];
1709
+ if (info.baseUrls.length > 0 || info.projectNames.length > 0) {
1710
+ lines2.push(
1711
+ [
1712
+ info.baseUrls.length > 0 ? `baseURL ${info.baseUrls.join(", ")}` : null,
1713
+ info.projectNames.length > 0 ? `projects ${info.projectNames.join(", ")}` : null
1714
+ ].filter((part) => part !== null).join(" \xB7 ")
1715
+ );
1716
+ }
1717
+ lines2.push(`CI: ${info.ciPlatform === null ? "none found" : PLATFORM_NAMES[info.ciPlatform]}`);
1718
+ if (info.existing.wrappedConfig || info.existing.wrappedTest || info.existing.perfConfig !== null) {
1719
+ lines2.push(
1720
+ `Already set up: ${[
1721
+ info.existing.wrappedConfig ? "withPerf()" : null,
1722
+ info.existing.wrappedTest ? "measured test object" : null,
1723
+ info.existing.perfConfig
1724
+ ].filter((part) => part !== null).join(", ")}`
1725
+ );
1726
+ }
1727
+ return lines2;
1728
+ }
1729
+ async function askAnswers(dialog, info) {
1730
+ dialog.step(
1731
+ 2,
1732
+ "How it works",
1733
+ `1. Measurement runs are separate from your usual test runs: "${CLI_COMMAND} test" runs the tests in perf mode.`,
1734
+ "2. Every test runs several times in one worker, so each backend request gets enough samples.",
1735
+ '3. Requests are grouped into endpoint keys such as "GET api /users/:id".',
1736
+ `4. "${CLI_COMMAND} thresholds" derives thresholds per key into files you commit to the repository.`,
1737
+ "5. Exit code 0 means ok, 2 a performance regression, 3 a tool or config error."
1738
+ );
1739
+ await dialog.pause();
1740
+ dialog.step(3, "Backend", "Endpoint keys start with a short label of the backend origin.");
1741
+ const originLabels = {};
1742
+ if (info.baseUrls.length === 0) {
1743
+ dialog.say(" No baseURL found in playwright.config: requests are labeled with their host.");
1744
+ }
1745
+ const used = /* @__PURE__ */ new Set();
1746
+ for (const origin of info.baseUrls) {
1747
+ const fallback = defaultLabel(origin, used);
1748
+ const label = await dialog.ask(
1749
+ `Label for ${origin}?`,
1750
+ fallback,
1751
+ fallback,
1752
+ (a) => /^[a-z0-9.-]{1,64}$/u.test(a) ? a : null
1753
+ );
1754
+ used.add(label);
1755
+ originLabels[origin] = label;
1756
+ }
1757
+ const tagged = info.taggedPerfTestFiles > 0;
1758
+ dialog.step(
1759
+ 4,
1760
+ "Which tests",
1761
+ "A measurement run takes about (tests \xD7 repetitions) test runs on 1 worker, so measure the tests",
1762
+ `that call the important backend endpoints. Files with tests tagged @perf: ${info.taggedPerfTestFiles}.`
1763
+ );
1764
+ if (!tagged) {
1765
+ dialog.warn([
1766
+ {
1767
+ code: "INIT_NO_TAGGED_TESTS",
1768
+ message: "No test is tagged @perf, so all tests are proposed.",
1769
+ hint: "Tag the tests to measure with test('title @perf', ...) or test('title', { tag: '@perf' }, ...), then choose @perf."
1770
+ }
1771
+ ]);
1772
+ }
1773
+ const scope = await dialog.ask(
1774
+ "Measure all tests or only tests tagged @perf? [all/@perf]",
1775
+ tagged ? "@perf" : "all",
1776
+ tagged ? "tagged" : "all",
1777
+ (a) => a === "all" ? "all" : a === "@perf" || a === "perf" ? "tagged" : null
1778
+ );
1779
+ dialog.step(
1780
+ 5,
1781
+ "Repetitions",
1782
+ "Each rule needs a minimum number of samples per endpoint (minSamples), and samples are",
1783
+ "calls per test \xD7 tests \xD7 repetitions."
1784
+ );
1785
+ const repeatTest = await dialog.ask(
1786
+ "Repetitions per test in measurement runs?",
1787
+ String(DEFAULT_ANSWERS_REPEAT),
1788
+ DEFAULT_ANSWERS_REPEAT,
1789
+ (a) => {
1790
+ const n = parseRepeat(a);
1791
+ return n !== null && resolveConfig({ run: { repeat: { test: n } } }, {}).ok ? n : null;
1792
+ }
1793
+ );
1794
+ dialog.step(
1795
+ 6,
1796
+ "Trial period",
1797
+ "In warn-only mode regressions are reported but do not fail the run, so you can watch the",
1798
+ "results for a few weeks before they block builds."
1799
+ );
1800
+ const warnOnly = await dialog.confirm("Start in warn-only mode for the first weeks?", true);
1801
+ dialog.step(
1802
+ 7,
1803
+ "Environments",
1804
+ "Each environment gets its own thresholds files (perf-thresholds.<kind>.<label>.json)."
1805
+ );
1806
+ let envLabels = [];
1807
+ if (await dialog.confirm("Do you run against several environments?", false)) {
1808
+ envLabels = await dialog.ask(
1809
+ "Environment labels, separated by commas?",
1810
+ "none",
1811
+ [],
1812
+ (a) => {
1813
+ const labels = [
1814
+ ...new Set(
1815
+ a.split(",").map((l) => l.trim()).filter((l) => l !== "")
1816
+ )
1817
+ ];
1818
+ return labels.length > 0 && labels.every(isEnvLabel) ? labels : null;
1819
+ }
1820
+ );
1821
+ }
1822
+ dialog.step(
1823
+ 8,
1824
+ "CI",
1825
+ "A CI job runs the measurement on pull requests and every night and keeps the report."
1826
+ );
1827
+ let addCi = false;
1828
+ if (info.ciPlatform === null) {
1829
+ dialog.say(
1830
+ ` No CI configuration found. Recipes for GitHub Actions, GitLab CI, Jenkins and Azure Pipelines: ${DOCS}/ci.md`
1831
+ );
1832
+ } else {
1833
+ addCi = await dialog.confirm(
1834
+ `Add a CI job for measurement runs (${PLATFORM_NAMES[info.ciPlatform]})?`,
1835
+ true
1836
+ );
1837
+ }
1838
+ return { originLabels, scope, repeatTest, warnOnly, envLabels, addCi };
1839
+ }
1840
+ function changeTitle(change2) {
1841
+ return `${change2.path} (${change2.kind === "create" ? "new file" : "change"})`;
1842
+ }
1843
+ async function applyChanges(dialog, host, info, changes, write, yes) {
1844
+ const written = [];
1845
+ for (const change2 of changes) {
1846
+ dialog.say(
1847
+ "",
1848
+ ` ${changeTitle(change2)}`,
1849
+ ...unifiedDiff(change2).trimEnd().split("\n").map((l) => ` ${l}`)
1850
+ );
1851
+ let apply;
1852
+ if (isProtected(info, change2.path)) {
1853
+ if (dialog.interactive)
1854
+ apply = await dialog.confirm(`${change2.path} exists. Overwrite it?`, false);
1855
+ else {
1856
+ dialog.say(
1857
+ ` ${change2.path} exists and is kept${yes ? " (--yes does not overwrite it)" : ""}.`
1858
+ );
1859
+ apply = false;
1860
+ }
1861
+ } else {
1862
+ apply = await dialog.confirm("Apply this change?", true);
1863
+ }
1864
+ if (!apply || !write) continue;
1865
+ try {
1866
+ await host.writeText(host.paths.join(host.cwd, change2.path), change2.after);
1867
+ } catch (error) {
1868
+ throw new WriteFailed(
1869
+ `${change2.path}: ${error instanceof Error ? error.message : String(error)}`
1870
+ );
1871
+ }
1872
+ written.push(change2.path);
1873
+ }
1874
+ return written;
1875
+ }
1876
+ function nextSteps(info, answers, written) {
1877
+ const scripts = Object.keys(plannedScripts(answers));
1878
+ const thresholds = scripts.find((s) => s.startsWith("perf:thresholds"));
1879
+ const test = scripts.find((s) => s.startsWith("perf:test"));
1880
+ const steps = [
1881
+ `${runCommand(info.packageManager, thresholds)}: derive the thresholds and commit the perf-thresholds.*.json files (derive them on the CI machines for stable values).`,
1882
+ `${runCommand(info.packageManager, test)}: a measurement run that fails on a regression.`
1883
+ ];
1884
+ const platform = info.ciPlatform;
1885
+ if (answers.addCi && platform !== null) {
1886
+ const ci = CI_TARGETS[platform].path(answers.envLabels[0] ?? null);
1887
+ if (platform === "jenkins")
1888
+ steps.push(`Create a Pipeline job in Jenkins with the script path ${ci}.`);
1889
+ if (platform === "azure") steps.push(`Create a pipeline in Azure DevOps from ${ci}.`);
1890
+ }
1891
+ if (answers.warnOnly)
1892
+ steps.push("After the trial period remove gate.warnOnly from pw-perf.config.ts.");
1893
+ if (written.length === 0 && scripts.length > 0)
1894
+ steps.unshift("Apply the changes above (run init again in a terminal or with --yes).");
1895
+ return steps;
1896
+ }
1897
+ async function runInit(cmd, host, style2) {
1898
+ const interactive = !cmd.yes && !cmd.dryRun && host.stdin.isTTY === true && host.stdout.isTTY === true;
1899
+ const write = !cmd.dryRun && (cmd.yes || interactive);
1900
+ const prompt = interactive ? host.createPrompt() : null;
1901
+ const dialog = new Dialog(host, prompt, style2);
1902
+ try {
1903
+ if (!write) {
1904
+ host.stderr.write(
1905
+ infoLine(
1906
+ cmd.dryRun ? "dry run: the planned changes are shown and nothing is written." : "no terminal: the default answers are used and nothing is written (like --dry-run). Use --yes to write the changes."
1907
+ )
1908
+ );
1909
+ }
1910
+ const info = detectProject(await readProjectFiles(host, host.cwd));
1911
+ dialog.step(1, "Project", ...describeProject(info));
1912
+ if (info.playwrightConfig === null) {
1913
+ host.stderr.write(
1914
+ formatIssues(
1915
+ [
1916
+ {
1917
+ code: "INIT_NO_PLAYWRIGHT_CONFIG",
1918
+ message: `No playwright.config.* in ${host.cwd}.`,
1919
+ hint: `Run "${CLI_COMMAND} init" in the directory of playwright.config (in a monorepo: the package with the Playwright tests).`
1920
+ }
1921
+ ],
1922
+ "error",
1923
+ style2
1924
+ )
1925
+ );
1926
+ return 3;
1927
+ }
1928
+ if (info.playwrightVersion !== null && !versionAtLeast(info.playwrightVersion, host.minPlaywrightVersion)) {
1929
+ host.stderr.write(
1930
+ formatIssues(
1931
+ [
1932
+ {
1933
+ code: "INIT_PLAYWRIGHT_TOO_OLD",
1934
+ message: `@playwright/test ${info.playwrightVersion} is older than ${host.minPlaywrightVersion}, the lowest version ${PACKAGE_NAME} supports.`,
1935
+ hint: `Update @playwright/test to ${host.minPlaywrightVersion} or later, then run "${CLI_COMMAND} init" again.`
1936
+ }
1937
+ ],
1938
+ "error",
1939
+ style2
1940
+ )
1941
+ );
1942
+ return 3;
1943
+ }
1944
+ const answers = await askAnswers(dialog, info);
1945
+ const plan = planInitChanges(info, answers);
1946
+ dialog.step(
1947
+ 9,
1948
+ "Changes",
1949
+ plan.changes.length === 0 ? "Nothing to change: the project is already set up for these answers." : "Each change is shown as a diff before it is applied."
1950
+ );
1951
+ let written;
1952
+ try {
1953
+ written = await applyChanges(dialog, host, info, plan.changes, write, cmd.yes);
1954
+ } catch (error) {
1955
+ if (!(error instanceof WriteFailed)) throw error;
1956
+ host.stderr.write(
1957
+ formatIssues(
1958
+ [
1959
+ {
1960
+ code: "INIT_WRITE_FAILED",
1961
+ message: `Could not write ${error.message}`,
1962
+ hint: "Check the permissions of the file and its directory, then run init again."
1963
+ }
1964
+ ],
1965
+ "error",
1966
+ style2
1967
+ )
1968
+ );
1969
+ return 3;
1970
+ }
1971
+ dialog.warn(plan.manualSteps);
1972
+ dialog.step(
1973
+ 10,
1974
+ "First measurement",
1975
+ `A thresholds run measures the tests and writes the thresholds files and the report (${DEFAULT_CONFIG.report.dir}/).`,
1976
+ "Thresholds measured on a laptop do not fit CI machines: derive the committed ones in CI."
1977
+ );
1978
+ let firstRun = false;
1979
+ if (dialog.interactive && written.length > 0) {
1980
+ firstRun = await dialog.confirm("Run a first thresholds run now?", false);
1981
+ } else {
1982
+ dialog.say(" Skipped.");
1983
+ }
1984
+ dialog.step(11, "Summary");
1985
+ if (written.length > 0) dialog.say(" Changed files:", ...written.map((p) => ` ${p}`));
1986
+ else if (write) dialog.say(" No files were changed.");
1987
+ else
1988
+ dialog.say(
1989
+ " Planned changes (not written):",
1990
+ ...plan.changes.map((c) => ` ${changeTitle(c)}`)
1991
+ );
1992
+ if (plan.manualSteps.length > 0)
1993
+ dialog.say(` Manual steps: ${plan.manualSteps.length} (see the warnings above).`);
1994
+ dialog.say(
1995
+ " Next steps:",
1996
+ ...nextSteps(info, answers, written).map((s, i) => ` ${i + 1}. ${s}`)
1997
+ );
1998
+ dialog.say(` Docs: ${DOCS}/adoption.md \xB7 ${DOCS}/ci.md \xB7 ${DOCS}/configuration.md`);
1999
+ prompt?.close();
2000
+ if (firstRun) {
2001
+ const args = answers.scope === "tagged" ? ["--grep", "@perf"] : [];
2002
+ return await runTests(
2003
+ { kind: "run", mode: "thresholds", prune: false, playwrightArgs: args, listOnly: false },
2004
+ host
2005
+ );
2006
+ }
2007
+ return 0;
2008
+ } catch (error) {
2009
+ if (error instanceof PromptAborted) {
2010
+ host.stderr.write(infoLine("interrupted."));
2011
+ return 130;
2012
+ }
2013
+ throw error;
2014
+ } finally {
2015
+ prompt?.close();
2016
+ }
2017
+ }
2018
+
2019
+ // src/cli/base-dir.ts
2020
+ function parentOf(path) {
2021
+ const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
2022
+ return cut <= 0 ? path.slice(0, cut + 1) || "." : path.slice(0, cut);
2023
+ }
2024
+ function resolveBaseDir(input) {
2025
+ if (input.loadedConfigFile !== void 0) {
2026
+ return { dir: (input.dirname ?? parentOf)(input.loadedConfigFile), issues: [] };
2027
+ }
2028
+ if (input.reportConfigDir !== void 0 && input.exists(input.reportConfigDir)) {
2029
+ return { dir: input.reportConfigDir, issues: [] };
2030
+ }
2031
+ return {
2032
+ dir: input.cwd,
2033
+ issues: [
2034
+ {
2035
+ code: "CLI_CONFIG_DIR_MISSING",
2036
+ message: input.reportConfigDir === void 0 ? `No package config file was loaded; relative paths (thresholds.dir, report.dir) are resolved against the current directory ${input.cwd}.` : `The config directory of the report (${input.reportConfigDir}) does not exist on this machine; relative paths (thresholds.dir, report.dir) are resolved against the current directory ${input.cwd}.`,
2037
+ hint: "Run the command from the directory of playwright.config, or pass the package config with --config."
2038
+ }
2039
+ ]
2040
+ };
2041
+ }
2042
+ function errorText(error) {
2043
+ const message2 = error instanceof Error ? error.message : String(error);
2044
+ return message2.split("\n")[0] ?? message2;
2045
+ }
2046
+ function loadFailureHint(error) {
2047
+ const e = typeof error === "object" && error !== null ? error : {};
2048
+ const message2 = typeof e.message === "string" ? e.message : "";
2049
+ if (e.code === "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
2050
+ return "Node loads the file by stripping the types: replace enums, namespaces with code and constructor parameter properties with erasable syntax.";
2051
+ }
2052
+ if (e.code === "ERR_MODULE_NOT_FOUND" && message2.startsWith("Cannot find module")) {
2053
+ return 'Add the extension to relative imports, e.g. "./helpers.ts" instead of "./helpers".';
2054
+ }
2055
+ if (e.code === "ERR_MODULE_NOT_FOUND" && message2.startsWith("Cannot find package")) {
2056
+ return "Path aliases from tsconfig do not work when Node loads the file: use a relative import.";
2057
+ }
2058
+ return "Fix the error in the file, or pass another package config with --config.";
2059
+ }
2060
+ function loadFailed(path, reason, hint) {
2061
+ return {
2062
+ code: "CONFIG_FILE_LOAD_FAILED",
2063
+ message: `The package config ${path} cannot be loaded: ${reason}`,
2064
+ hint
2065
+ };
2066
+ }
2067
+ function isLoadingWarning(warning) {
2068
+ return warning.name === "ExperimentalWarning" && /type stripping/iu.test(warning.message) || warning.code === "MODULE_TYPELESS_PACKAGE_JSON";
2069
+ }
2070
+ async function importCapturingWarnings(path, importModule, notes) {
2071
+ const listeners = process.listeners("warning");
2072
+ const captured = [];
2073
+ const capture = (warning) => {
2074
+ captured.push(warning);
2075
+ };
2076
+ process.removeAllListeners("warning");
2077
+ process.on("warning", capture);
2078
+ try {
2079
+ return await importModule(pathToFileURL(path).href);
2080
+ } finally {
2081
+ await new Promise((resolve2) => setImmediate(resolve2));
2082
+ process.off("warning", capture);
2083
+ for (const listener of listeners) process.on("warning", listener);
2084
+ const loading = captured.filter(isLoadingWarning);
2085
+ if (loading.length > 0) {
2086
+ notes.push(
2087
+ `note: Node printed ${loading.length === 1 ? "a warning" : `${loading.length} warnings`} while loading ${basename(path)}: ${loading.map((w) => w.message.split("\n")[0]).join("; ")}`
2088
+ );
2089
+ }
2090
+ for (const warning of captured.filter((w) => !isLoadingWarning(w))) {
2091
+ for (const listener of listeners) listener(warning);
2092
+ }
2093
+ }
2094
+ }
2095
+ function defaultExport(module) {
2096
+ if (typeof module !== "object" || module === null || !("default" in module)) return void 0;
2097
+ const value = module.default;
2098
+ if (typeof value === "object" && value !== null && "default" in value) {
2099
+ const keys = Object.keys(value).filter((k) => k !== "__esModule");
2100
+ if (keys.length === 1) return value.default;
2101
+ }
2102
+ return value;
2103
+ }
2104
+ async function loadFile(path, host, notes) {
2105
+ const json = extname(path) === ".json";
2106
+ try {
2107
+ if (json) {
2108
+ return { ok: true, value: { value: JSON.parse(await readFile(path, "utf8")), json } };
2109
+ }
2110
+ const module = await importCapturingWarnings(
2111
+ path,
2112
+ host.importModule ?? ((url) => import(url)),
2113
+ notes
2114
+ );
2115
+ const value = defaultExport(module);
2116
+ if (value === void 0) {
2117
+ return {
2118
+ ok: false,
2119
+ issues: [
2120
+ loadFailed(
2121
+ path,
2122
+ "the file has no default export.",
2123
+ "Export the config as default: export default definePerfConfig({ ... })."
2124
+ )
2125
+ ]
2126
+ };
2127
+ }
2128
+ return { ok: true, value: { value, json } };
2129
+ } catch (error) {
2130
+ return {
2131
+ ok: false,
2132
+ issues: [
2133
+ loadFailed(
2134
+ path,
2135
+ errorText(error),
2136
+ json ? "Fix the JSON syntax of the file." : loadFailureHint(error)
2137
+ )
2138
+ ]
2139
+ };
2140
+ }
2141
+ }
2142
+ async function findConfigFile(dirs, exists) {
2143
+ for (const dir of dirs) {
2144
+ for (const ext of CONFIG_FILE_EXTENSIONS) {
2145
+ const path = join(dir, `${CONFIG_FILE_BASENAME}${ext}`);
2146
+ if (await exists(path)) return path;
2147
+ }
2148
+ }
2149
+ return null;
2150
+ }
2151
+ var IGNORED_OPTIONS = /* @__PURE__ */ new Set([
2152
+ "$schema",
2153
+ "run",
2154
+ "report",
2155
+ "thresholds.dir",
2156
+ "thresholds.filePrefix"
2157
+ ]);
2158
+ function snapshotDifferences(a, b, path = []) {
2159
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2160
+ if (isObject(a) && isObject(b)) {
2161
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort();
2162
+ return keys.filter((k) => !IGNORED_OPTIONS.has([...path, k].join("."))).flatMap((k) => snapshotDifferences(a[k], b[k], [...path, k]));
2163
+ }
2164
+ return JSON.stringify(a) === JSON.stringify(b) ? [] : [path.join(".")];
2165
+ }
2166
+ var MAX_LISTED_DIFFERENCES = 10;
2167
+ function differsWarning(paths) {
2168
+ const listed = paths.slice(0, MAX_LISTED_DIFFERENCES).join(", ");
2169
+ const more = paths.length > MAX_LISTED_DIFFERENCES ? ` and ${paths.length - MAX_LISTED_DIFFERENCES} more` : "";
2170
+ return {
2171
+ code: "CONFIG_SNAPSHOT_DIFFERS",
2172
+ message: `The package config file differs from the config the report was recorded with: ${listed}${more}.`,
2173
+ hint: "The file is used. If the run used other settings on purpose, check the result, or run the measurement again with the current config."
2174
+ };
2175
+ }
2176
+ function configErrors(issues, where) {
2177
+ return issues.map((issue) => ({
2178
+ ...issue,
2179
+ message: `${where}: ${issue.message}`,
2180
+ hint: issue.hint ?? `See ${DOCS_CONFIG_URL} for all options.`
2181
+ }));
2182
+ }
2183
+ async function resolveCliConfig(input, host) {
2184
+ const warnings = [];
2185
+ const notes = [];
2186
+ const overrides = {
2187
+ mode: input.mode,
2188
+ ...input.env === void 0 ? {} : { env: input.env }
2189
+ };
2190
+ let file = null;
2191
+ if (input.explicit !== void 0) {
2192
+ if (!await host.exists(input.explicit)) {
2193
+ return {
2194
+ ok: false,
2195
+ issues: [
2196
+ {
2197
+ code: "CONFIG_FILE_NOT_FOUND",
2198
+ message: `The package config file given with --config does not exist: ${input.explicit}`,
2199
+ hint: "Check the path; it is resolved against the current directory."
2200
+ }
2201
+ ]
2202
+ };
2203
+ }
2204
+ file = { path: input.explicit, explicit: true };
2205
+ } else {
2206
+ const found = await findConfigFile(input.searchDirs, host.exists);
2207
+ if (found !== null) file = { path: found, explicit: false };
2208
+ }
2209
+ if (file !== null) {
2210
+ const loaded = await loadFile(file.path, host, notes);
2211
+ if (loaded.ok) {
2212
+ const resolved2 = resolveConfig(loaded.value.value, {
2213
+ ...overrides,
2214
+ source: loaded.value.json ? "json" : "code"
2215
+ });
2216
+ if (!resolved2.ok) return { ok: false, issues: configErrors(resolved2.issues, file.path) };
2217
+ warnings.push(...resolved2.value.warnings);
2218
+ if (input.report !== void 0) {
2219
+ const differences = snapshotDifferences(resolved2.value.snapshot, input.report.config);
2220
+ if (differences.length > 0) warnings.push(differsWarning(differences));
2221
+ }
2222
+ return {
2223
+ ok: true,
2224
+ value: {
2225
+ config: resolved2.value.config,
2226
+ snapshot: resolved2.value.snapshot,
2227
+ source: { kind: "file", ...file },
2228
+ warnings,
2229
+ notes
2230
+ }
2231
+ };
2232
+ }
2233
+ if (file.explicit) return { ok: false, issues: loaded.issues };
2234
+ warnings.push(
2235
+ ...loaded.issues.map((issue) => ({
2236
+ ...issue,
2237
+ message: `${issue.message} The ${input.report === void 0 ? "default config" : "config snapshot of the report"} is used instead.`
2238
+ }))
2239
+ );
2240
+ }
2241
+ const fromSnapshot = input.report !== void 0;
2242
+ const resolved = resolveConfig(fromSnapshot ? input.report?.config : void 0, {
2243
+ ...overrides,
2244
+ source: fromSnapshot ? "snapshot" : "code"
2245
+ });
2246
+ if (!resolved.ok) {
2247
+ return {
2248
+ ok: false,
2249
+ issues: configErrors(
2250
+ resolved.issues,
2251
+ fromSnapshot ? "config snapshot of the report" : "default config"
2252
+ )
2253
+ };
2254
+ }
2255
+ warnings.push(...resolved.value.warnings);
2256
+ return {
2257
+ ok: true,
2258
+ value: {
2259
+ config: resolved.value.config,
2260
+ snapshot: resolved.value.snapshot,
2261
+ source: fromSnapshot ? { kind: "snapshot" } : { kind: "defaults" },
2262
+ warnings,
2263
+ notes
2264
+ }
2265
+ };
2266
+ }
2267
+ function configSourceLine(source) {
2268
+ switch (source.kind) {
2269
+ case "file":
2270
+ return `config: ${source.path}${source.explicit ? " (--config)" : ""}`;
2271
+ case "snapshot":
2272
+ return "config: the config snapshot in the report";
2273
+ case "defaults":
2274
+ return "config: the defaults";
2275
+ }
2276
+ }
2277
+
2278
+ // src/cli/offline.ts
2279
+ var DEFAULT_WIDTH = 120;
2280
+ function message(error) {
2281
+ return error instanceof Error ? error.message : String(error);
2282
+ }
2283
+ var Printer = class {
2284
+ host;
2285
+ constructor(host) {
2286
+ this.host = host;
2287
+ }
2288
+ get color() {
2289
+ return this.host.stderr.isTTY === true && (this.host.env.NO_COLOR ?? "") === "";
2290
+ }
2291
+ errors(issues) {
2292
+ this.host.stderr.write(formatIssues(issues, "error", this));
2293
+ return 3;
2294
+ }
2295
+ warnings(issues) {
2296
+ this.host.stderr.write(formatIssues(issues, "warning", this));
2297
+ }
2298
+ info(line) {
2299
+ this.host.stderr.write(infoLine(line));
2300
+ }
2301
+ };
2302
+ function reportNotFound(path, how) {
2303
+ return {
2304
+ code: "CLI_REPORT_NOT_FOUND",
2305
+ message: `The run report ${path} does not exist (${how}).`,
2306
+ hint: `Pass the report explicitly, e.g. --input apps/web/${DEFAULT_CONFIG.report.dir}/report.json, or run "${CLI_COMMAND} test" first.`
2307
+ };
2308
+ }
2309
+ async function readReport(path) {
2310
+ let text;
2311
+ try {
2312
+ text = await readTextFile(path);
2313
+ } catch (error) {
2314
+ return {
2315
+ ok: false,
2316
+ missing: false,
2317
+ issues: [
2318
+ {
2319
+ code: "SCHEMA_INVALID_JSON",
2320
+ message: `${path}: the file cannot be read (${message(error)})`,
2321
+ hint: "Check the path and the file permissions."
2322
+ }
2323
+ ]
2324
+ };
2325
+ }
2326
+ if (text === null) return { ok: false, missing: true, issues: [] };
2327
+ const parsed = parseRunReport(text, path);
2328
+ if (!parsed.ok)
2329
+ return { ok: false, missing: false, issues: parsed.issues.map(schemaIssueToIssue) };
2330
+ return { ok: true, report: parsed.value };
2331
+ }
2332
+ async function configFor(host, out, options) {
2333
+ const reportDir = options.report?.configDir;
2334
+ const reportDirExists = reportDir !== void 0 && await host.exists(reportDir);
2335
+ const searchDirs = [host.cwd];
2336
+ if (reportDirExists && reportDir !== host.cwd) searchDirs.push(reportDir);
2337
+ const resolved = await resolveCliConfig(
2338
+ {
2339
+ ...options.explicit === void 0 ? {} : { explicit: host.paths.resolve(host.cwd, options.explicit) },
2340
+ searchDirs,
2341
+ ...options.report === void 0 ? {} : { report: options.report },
2342
+ mode: options.mode,
2343
+ ...options.env === void 0 ? {} : { env: options.env }
2344
+ },
2345
+ { exists: (p) => host.exists(p), importModule: (url) => host.importModule(url) }
2346
+ );
2347
+ if (!resolved.ok) {
2348
+ out.errors(resolved.issues);
2349
+ return null;
2350
+ }
2351
+ const cfg = resolved.value;
2352
+ for (const note of cfg.notes) out.info(note);
2353
+ out.info(configSourceLine(cfg.source));
2354
+ out.warnings(cfg.warnings);
2355
+ const base = resolveBaseDir({
2356
+ ...cfg.source.kind === "file" ? { loadedConfigFile: cfg.source.path } : {},
2357
+ ...reportDir === void 0 ? {} : { reportConfigDir: reportDir },
2358
+ cwd: host.cwd,
2359
+ exists: (dir) => dir === reportDir && reportDirExists,
2360
+ dirname: host.paths.dirname
2361
+ });
2362
+ out.warnings(base.issues);
2363
+ out.info(`base directory: ${base.dir}`);
2364
+ return { cfg, baseDir: base.dir };
2365
+ }
2366
+ async function thresholdsFrom(cmd, host) {
2367
+ const out = new Printer(host);
2368
+ const reportPath = host.paths.resolve(host.cwd, cmd.from);
2369
+ const read = await readReport(reportPath);
2370
+ if (!read.ok) {
2371
+ return out.errors(
2372
+ read.missing ? [reportNotFound(reportPath, "given with --from")] : read.issues
2373
+ );
2374
+ }
2375
+ const report = read.report;
2376
+ const resolved = await configFor(host, out, {
2377
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
2378
+ report,
2379
+ env: cmd.env ?? report.env,
2380
+ mode: "thresholds"
2381
+ });
2382
+ if (resolved === null) return 3;
2383
+ const { cfg, baseDir } = resolved;
2384
+ const config = cfg.config;
2385
+ if (report.tests.status !== "passed") {
2386
+ out.warnings([
2387
+ {
2388
+ code: "CLI_REPORT_TESTS_FAILED",
2389
+ message: `The tests of the source run did not pass (status "${report.tests.status}"); the thresholds are derived anyway.`,
2390
+ hint: "Review the diff before committing the thresholds files."
2391
+ }
2392
+ ]);
2393
+ }
2394
+ const location = {
2395
+ configDir: baseDir,
2396
+ dir: config.thresholds.dir,
2397
+ filePrefix: config.thresholds.filePrefix,
2398
+ env: config.run.env
2399
+ };
2400
+ const loaded = await loadThresholds(location);
2401
+ const derived = deriveThresholds(report, config, loaded, {
2402
+ env: config.run.env,
2403
+ prune: cmd.prune,
2404
+ toolVersion: host.packageVersion
2405
+ });
2406
+ if (!derived.ok) return out.errors(derived.issues);
2407
+ out.warnings(derived.value.warnings);
2408
+ const absolute = thresholdsFilePaths(location);
2409
+ const writeErrors = [];
2410
+ const written = [];
2411
+ for (const file of derived.value.files) {
2412
+ if (file.content === null || !file.changed) continue;
2413
+ try {
2414
+ await writeJsonStable(absolute[file.kind], file.content);
2415
+ written.push(absolute[file.kind]);
2416
+ } catch (error) {
2417
+ writeErrors.push({
2418
+ code: "CLI_WRITE_FAILED",
2419
+ message: `The thresholds file ${absolute[file.kind]} could not be written: ${message(error)}`,
2420
+ hint: "Check that thresholds.dir is writable, then run the command again."
2421
+ });
2422
+ }
2423
+ }
2424
+ const diffs = derived.value.files.map(
2425
+ (file) => diffThresholds(loaded[file.kind], file, report, config)
2426
+ );
2427
+ const diffPath = resolvePath(resolvePath(baseDir, config.report.dir), "thresholds-diff.md");
2428
+ let diffWritten = false;
2429
+ try {
2430
+ await writeTextAtomic(
2431
+ diffPath,
2432
+ formatThresholdsDiffMarkdown(
2433
+ diffs,
2434
+ derived.value.files.map((file) => loaded[file.kind].path)
2435
+ )
2436
+ );
2437
+ diffWritten = true;
2438
+ } catch (error) {
2439
+ out.warnings([
2440
+ {
2441
+ code: "THRESHOLDS_DIFF_WRITE_FAILED",
2442
+ message: `The thresholds diff could not be written to ${diffPath}: ${message(error)}`,
2443
+ hint: "The thresholds files are written; check that report.dir is writable."
2444
+ }
2445
+ ]);
2446
+ }
2447
+ const stdout = host.stdout;
2448
+ const width = stdout.isTTY === true && stdout.columns !== void 0 && stdout.columns > 0 ? stdout.columns : DEFAULT_WIDTH;
2449
+ stdout.write(
2450
+ formatThresholdsDiff(diffs, {
2451
+ paths: derived.value.files.map((file) => relativeSlashPath(host.cwd, absolute[file.kind])),
2452
+ width,
2453
+ color: stdout.isTTY === true && (host.env.NO_COLOR ?? "") === "",
2454
+ prune: cmd.prune,
2455
+ diffPath: diffWritten ? relativeSlashPath(host.cwd, diffPath) : null
2456
+ })
2457
+ );
2458
+ if (writeErrors.length > 0) return out.errors(writeErrors);
2459
+ out.info(
2460
+ written.length === 0 ? "thresholds files unchanged \xB7 exit code 0" : `${written.length === 1 ? "1 thresholds file" : `${written.length} thresholds files`} written \xB7 exit code 0`
2461
+ );
2462
+ return 0;
2463
+ }
2464
+ async function renderReport(cmd, host, renderHtml) {
2465
+ const out = new Printer(host);
2466
+ let report;
2467
+ let inputPath;
2468
+ if (cmd.input !== void 0) {
2469
+ inputPath = host.paths.resolve(host.cwd, cmd.input);
2470
+ const read = await readReport(inputPath);
2471
+ if (!read.ok)
2472
+ return out.errors(
2473
+ read.missing ? [reportNotFound(inputPath, "given with --input")] : read.issues
2474
+ );
2475
+ report = read.report;
2476
+ if (await configFor(host, out, {
2477
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
2478
+ report,
2479
+ mode: report.mode
2480
+ }) === null) {
2481
+ return 3;
2482
+ }
2483
+ } else {
2484
+ const resolved = await configFor(host, out, {
2485
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
2486
+ mode: "test"
2487
+ });
2488
+ if (resolved === null) return 3;
2489
+ inputPath = resolvePath(
2490
+ resolvePath(resolved.baseDir, resolved.cfg.config.report.dir),
2491
+ "report.json"
2492
+ );
2493
+ const read = await readReport(inputPath);
2494
+ if (!read.ok)
2495
+ return out.errors(
2496
+ read.missing ? [reportNotFound(inputPath, "report.dir of the config")] : read.issues
2497
+ );
2498
+ report = read.report;
2499
+ }
2500
+ const outputPath = cmd.output === void 0 ? resolvePath(host.paths.dirname(inputPath), "report.html") : host.paths.resolve(host.cwd, cmd.output);
2501
+ let page;
2502
+ try {
2503
+ page = renderHtml(report);
2504
+ } catch (error) {
2505
+ return out.errors([
2506
+ {
2507
+ code: "HTML_RENDER_FAILED",
2508
+ message: `The HTML report could not be rendered from ${inputPath}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
2509
+ hint: "This is a bug in the package; please report it with the message above."
2510
+ }
2511
+ ]);
2512
+ }
2513
+ try {
2514
+ await writeTextAtomic(outputPath, page);
2515
+ } catch (error) {
2516
+ return out.errors([
2517
+ {
2518
+ code: "CLI_WRITE_FAILED",
2519
+ message: `The HTML report could not be written to ${outputPath}: ${message(error)}`,
2520
+ hint: "Check that the directory is writable, or pass another --output."
2521
+ }
2522
+ ]);
2523
+ }
2524
+ out.info(`report: ${outputPath}`);
2525
+ return 0;
2526
+ }
2527
+
2528
+ // src/cli/parse.ts
2529
+ var COMMANDS = ["test", "thresholds", "report", "init"];
2530
+ var HELP = /* @__PURE__ */ new Set(["--help", "-h"]);
2531
+ var VERSION = /* @__PURE__ */ new Set(["--version", "-v"]);
2532
+ var USAGE_HINT = `Commands: ${COMMANDS.join(", ")}. Run "${CLI_COMMAND} --help" for the usage.`;
2533
+ var RUN_OPTIONS = ["--env", "--repeat", "--prune", "--from"];
2534
+ var FROM_OPTIONS = ["--env", "--prune", "--from", "--config"];
2535
+ var REPORT_OPTIONS = ["--input", "--output", "--config"];
2536
+ var VALUED = /* @__PURE__ */ new Set([
2537
+ "--env",
2538
+ "--repeat",
2539
+ "--from",
2540
+ "--config",
2541
+ "--input",
2542
+ "--output"
2543
+ ]);
2544
+ function ownOption(args, i, names, issues) {
2545
+ const arg = args[i];
2546
+ const eq = arg.indexOf("=");
2547
+ const name = eq === -1 ? arg : arg.slice(0, eq);
2548
+ if (!names.includes(name)) return null;
2549
+ if (!VALUED.has(name)) {
2550
+ if (eq !== -1) {
2551
+ issues.push({
2552
+ code: "CLI_INVALID_OPTION",
2553
+ message: `${name} takes no value, got "${arg}".`,
2554
+ hint: `Write ${name} on its own.`
2555
+ });
2556
+ }
2557
+ return { option: { name }, used: 1 };
2558
+ }
2559
+ const next = args[i + 1];
2560
+ const value = eq !== -1 ? arg.slice(eq + 1) : next;
2561
+ if (value === void 0 || value === "" || eq === -1 && value.startsWith("-")) {
2562
+ issues.push({
2563
+ code: "CLI_MISSING_ARGUMENT",
2564
+ message: `${name} needs a value.`,
2565
+ hint: `Write ${name} <value> or ${name}=<value>.`
2566
+ });
2567
+ return { option: { name }, used: eq === -1 && value === "" ? 2 : 1 };
2568
+ }
2569
+ return { option: { name, value }, used: eq !== -1 ? 1 : 2 };
2570
+ }
2571
+ function invalidValue(name, expected, value) {
2572
+ return {
2573
+ code: "CLI_INVALID_OPTION",
2574
+ message: `${name}: expected ${expected}, got ${JSON.stringify(value)}.`,
2575
+ hint: `Fix the value of ${name}.`
2576
+ };
2577
+ }
2578
+ function checkEnv(value, issues) {
2579
+ if (isEnvLabel(value)) return value;
2580
+ issues.push(invalidValue("--env", ENV_LABEL_FORMAT, value));
2581
+ return void 0;
2582
+ }
2583
+ function checkRepeat(value, mode, issues) {
2584
+ const repeat = parseRepeat(value);
2585
+ if (repeat === null) {
2586
+ issues.push(invalidValue("--repeat", REPEAT_FORMAT, value));
2587
+ return void 0;
2588
+ }
2589
+ const resolved = resolveConfig(void 0, { mode, repeat });
2590
+ if (!resolved.ok) {
2591
+ const reason = resolved.issues[0]?.message ?? "out of range";
2592
+ issues.push({
2593
+ code: "CLI_INVALID_OPTION",
2594
+ message: `--repeat: ${reason}.`,
2595
+ hint: "Fix the value of --repeat."
2596
+ });
2597
+ return void 0;
2598
+ }
2599
+ return repeat;
2600
+ }
2601
+ function fail(issues) {
2602
+ return { ok: false, issues };
2603
+ }
2604
+ function parseRun(mode, args) {
2605
+ const sep = args.indexOf("--");
2606
+ const before = sep === -1 ? args : args.slice(0, sep);
2607
+ const after = sep === -1 ? [] : args.slice(sep + 1);
2608
+ if (before.some((a) => HELP.has(a))) return { ok: true, value: { kind: "help", command: mode } };
2609
+ if (mode === "thresholds" && before.some((a) => a === "--from" || a.startsWith("--from="))) {
2610
+ return parseFrom(before, after);
2611
+ }
2612
+ const issues = [];
2613
+ const playwrightArgs = [];
2614
+ let env;
2615
+ let repeat;
2616
+ let prune = false;
2617
+ for (let i = 0; i < before.length; ) {
2618
+ const own = ownOption(before, i, RUN_OPTIONS, issues);
2619
+ if (own === null) {
2620
+ playwrightArgs.push(before[i]);
2621
+ i += 1;
2622
+ continue;
2623
+ }
2624
+ i += own.used;
2625
+ const { name, value } = own.option;
2626
+ if (mode === "test" && (name === "--prune" || name === "--from")) {
2627
+ issues.push({
2628
+ code: "CLI_INVALID_OPTION",
2629
+ message: `${name} is an option of the thresholds command, not of test.`,
2630
+ hint: name === "--from" ? `Derive thresholds from a report with "${CLI_COMMAND} thresholds --from <report.json>".` : `Remove ${name}, or run "${CLI_COMMAND} thresholds --prune".`
2631
+ });
2632
+ continue;
2633
+ }
2634
+ if (name === "--prune") prune = true;
2635
+ else if (value === void 0) continue;
2636
+ else if (name === "--env") env = checkEnv(value, issues);
2637
+ else if (name === "--repeat") repeat = checkRepeat(value, mode, issues);
2638
+ }
2639
+ playwrightArgs.push(...after);
2640
+ const unsupported = unsupportedOptions(playwrightArgs);
2641
+ if (unsupported.length > 0) {
2642
+ issues.push({
2643
+ code: "CLI_UNSUPPORTED_PLAYWRIGHT_OPTION",
2644
+ message: `${[...new Set(unsupported)].join(", ")} cannot be used in perf mode: ${unsupported.includes("--shard") ? "each shard would see only part of the samples" : "it changes how the tests run and their timings"}.`,
2645
+ hint: 'Remove the option; use "npx playwright test" for UI mode, debugging and sharding.'
2646
+ });
2647
+ }
2648
+ if (prune) {
2649
+ const filters = testFilters(playwrightArgs);
2650
+ if (filters.length > 0) {
2651
+ issues.push({
2652
+ code: "CLI_PRUNE_WITH_FILTER",
2653
+ message: `--prune cannot be used with a test filter (${filters.join(" ")}): entries of the tests left out would be removed from the thresholds files.`,
2654
+ hint: "Run --prune without --grep, --project or file paths, or leave --prune out."
2655
+ });
2656
+ }
2657
+ }
2658
+ if (issues.length > 0) return fail(issues);
2659
+ return {
2660
+ ok: true,
2661
+ value: {
2662
+ kind: "run",
2663
+ mode,
2664
+ ...env === void 0 ? {} : { env },
2665
+ ...repeat === void 0 ? {} : { repeat },
2666
+ prune,
2667
+ playwrightArgs,
2668
+ listOnly: isListOnly(playwrightArgs)
2669
+ }
2670
+ };
2671
+ }
2672
+ function parseFrom(before, after) {
2673
+ const issues = [];
2674
+ const rejected = [];
2675
+ let from;
2676
+ let env;
2677
+ let config;
2678
+ let prune = false;
2679
+ for (let i = 0; i < before.length; ) {
2680
+ const own = ownOption(before, i, FROM_OPTIONS, issues);
2681
+ if (own === null) {
2682
+ const arg = before[i];
2683
+ const name2 = arg.split("=")[0];
2684
+ if (REPORT_OPTIONS.includes(name2)) {
2685
+ issues.push({
2686
+ code: "CLI_INVALID_OPTION",
2687
+ message: `${name2} is an option of the report command, not of thresholds --from.`,
2688
+ hint: `Remove ${name2}.`
2689
+ });
2690
+ if (!arg.includes("=") && before[i + 1] !== void 0) i += 1;
2691
+ } else {
2692
+ rejected.push(arg);
2693
+ }
2694
+ i += 1;
2695
+ continue;
2696
+ }
2697
+ i += own.used;
2698
+ const { name, value } = own.option;
2699
+ if (name === "--prune") prune = true;
2700
+ else if (value === void 0) continue;
2701
+ else if (name === "--from") from = value;
2702
+ else if (name === "--env") env = checkEnv(value, issues);
2703
+ else if (name === "--config") config = value;
2704
+ }
2705
+ rejected.push(...after);
2706
+ if (rejected.length > 0) {
2707
+ issues.push({
2708
+ code: "CLI_FROM_WITH_PLAYWRIGHT_ARGS",
2709
+ message: `thresholds --from runs no tests, so it takes no Playwright arguments and no --repeat; got: ${rejected.join(" ")}.`,
2710
+ hint: `Use only --from, --env, --prune and --config, or run "${CLI_COMMAND} thresholds" without --from to run the tests.`
2711
+ });
2712
+ }
2713
+ if (issues.length > 0 || from === void 0) return fail(issues);
2714
+ return {
2715
+ ok: true,
2716
+ value: {
2717
+ kind: "thresholds-from",
2718
+ from,
2719
+ ...env === void 0 ? {} : { env },
2720
+ prune,
2721
+ ...config === void 0 ? {} : { config }
2722
+ }
2723
+ };
2724
+ }
2725
+ function unexpected(command, arg) {
2726
+ return {
2727
+ code: "CLI_INVALID_OPTION",
2728
+ message: `${command} does not take "${arg}".`,
2729
+ hint: `Run "${CLI_COMMAND} ${command} --help" for its options.`
2730
+ };
2731
+ }
2732
+ function parseReport(args) {
2733
+ if (args.some((a) => HELP.has(a)))
2734
+ return { ok: true, value: { kind: "help", command: "report" } };
2735
+ const issues = [];
2736
+ const found = {};
2737
+ for (let i = 0; i < args.length; ) {
2738
+ const own = ownOption(args, i, REPORT_OPTIONS, issues);
2739
+ if (own === null) {
2740
+ issues.push(unexpected("report", args[i]));
2741
+ i += 1;
2742
+ continue;
2743
+ }
2744
+ i += own.used;
2745
+ if (own.option.value !== void 0) found[own.option.name] = own.option.value;
2746
+ }
2747
+ if (issues.length > 0) return fail(issues);
2748
+ const { "--input": input, "--output": output, "--config": config } = found;
2749
+ return {
2750
+ ok: true,
2751
+ value: {
2752
+ kind: "report",
2753
+ ...input === void 0 ? {} : { input },
2754
+ ...output === void 0 ? {} : { output },
2755
+ ...config === void 0 ? {} : { config }
2756
+ }
2757
+ };
2758
+ }
2759
+ function parseInit(args) {
2760
+ if (args.some((a) => HELP.has(a))) return { ok: true, value: { kind: "help", command: "init" } };
2761
+ const issues = [];
2762
+ let yes = false;
2763
+ let dryRun = false;
2764
+ for (const arg of args) {
2765
+ if (arg === "--yes" || arg === "-y") yes = true;
2766
+ else if (arg === "--dry-run") dryRun = true;
2767
+ else issues.push(unexpected("init", arg));
2768
+ }
2769
+ return issues.length > 0 ? fail(issues) : { ok: true, value: { kind: "init", yes, dryRun } };
2770
+ }
2771
+ function parseArgs(argv) {
2772
+ const first = argv[0];
2773
+ if (first === void 0) {
2774
+ return fail([{ code: "CLI_UNKNOWN_COMMAND", message: "No command given.", hint: USAGE_HINT }]);
2775
+ }
2776
+ if (HELP.has(first)) return { ok: true, value: { kind: "help" } };
2777
+ if (VERSION.has(first)) return { ok: true, value: { kind: "version" } };
2778
+ const rest = argv.slice(1);
2779
+ switch (first) {
2780
+ case "test":
2781
+ case "thresholds":
2782
+ return parseRun(first, rest);
2783
+ case "report":
2784
+ return parseReport(rest);
2785
+ case "init":
2786
+ return parseInit(rest);
2787
+ default:
2788
+ return fail([
2789
+ { code: "CLI_UNKNOWN_COMMAND", message: `Unknown command "${first}".`, hint: USAGE_HINT }
2790
+ ]);
2791
+ }
2792
+ }
2793
+
2794
+ // src/cli/main.ts
2795
+ function color(host) {
2796
+ return { color: host.stderr.isTTY === true && (host.env.NO_COLOR ?? "") === "" };
2797
+ }
2798
+ function internalError(error) {
2799
+ const text = error instanceof Error ? error.stack ?? error.message : String(error);
2800
+ return {
2801
+ code: "CLI_INTERNAL_ERROR",
2802
+ message: `Unexpected error in the CLI: ${text}`,
2803
+ hint: "This is a bug in the package; please report it with the message above."
2804
+ };
2805
+ }
2806
+ async function main(argv, host, options = {}) {
2807
+ try {
2808
+ const parsed = parseArgs(argv);
2809
+ if (!parsed.ok) {
2810
+ host.stderr.write(formatIssues(parsed.issues, "error", color(host)));
2811
+ return 3;
2812
+ }
2813
+ const cmd = parsed.value;
2814
+ switch (cmd.kind) {
2815
+ case "help":
2816
+ host.stdout.write(helpText(cmd.command));
2817
+ return 0;
2818
+ case "version":
2819
+ host.stdout.write(`${host.packageVersion}
2820
+ `);
2821
+ return 0;
2822
+ case "run":
2823
+ return await runTests(cmd, host);
2824
+ case "thresholds-from":
2825
+ return await thresholdsFrom(cmd, host);
2826
+ case "report":
2827
+ return await renderReport(cmd, host, options.renderHtml ?? renderHtmlReport);
2828
+ case "init":
2829
+ return await runInit(cmd, host, color(host));
2830
+ }
2831
+ } catch (error) {
2832
+ host.stderr.write(formatIssues([internalError(error)], "error", color(host)));
2833
+ return 3;
2834
+ }
2835
+ }
2836
+ function isModuleNotFound(error) {
2837
+ return typeof error === "object" && error !== null && "code" in error && error.code === "MODULE_NOT_FOUND";
2838
+ }
2839
+ function resolvePlaywright(dir) {
2840
+ const require2 = createRequire(join(dir, "noop.js"));
2841
+ let manifest;
2842
+ try {
2843
+ manifest = require2.resolve("@playwright/test/package.json");
2844
+ } catch (error) {
2845
+ if (isModuleNotFound(error)) return null;
2846
+ throw error;
2847
+ }
2848
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
2849
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.playwright;
2850
+ if (bin === void 0) throw new Error(`${manifest} has no "bin.playwright" entry`);
2851
+ return { cliPath: resolve(dirname(manifest), bin), version: pkg.version ?? "0.0.0" };
2852
+ }
2853
+ function minimumPlaywright() {
2854
+ const range = peerDependencies["@playwright/test"];
2855
+ return /\d+\.\d+\.\d+/u.exec(range)?.[0] ?? "0.0.0";
2856
+ }
2857
+ function nodeHost() {
2858
+ return {
2859
+ cwd: process.cwd(),
2860
+ paths: { join: join, resolve, dirname },
2861
+ env: process.env,
2862
+ platform: process.platform,
2863
+ tmpdir: tmpdir(),
2864
+ stdin: process.stdin,
2865
+ stdout: process.stdout,
2866
+ stderr: process.stderr,
2867
+ now: () => /* @__PURE__ */ new Date(),
2868
+ random: Math.random,
2869
+ packageVersion: version,
2870
+ minPlaywrightVersion: minimumPlaywright(),
2871
+ // dist/cli.js and dist/reporter.js are siblings (ESM build).
2872
+ reporterPath: fileURLToPath(new URL("./reporter.js", import.meta.url)),
2873
+ resolvePlaywright,
2874
+ spawnNode: (args, options) => spawn(process.execPath, args, options),
2875
+ onSignal: (signal, handler) => {
2876
+ process.on(signal, handler);
2877
+ return () => {
2878
+ process.off(signal, handler);
2879
+ };
2880
+ },
2881
+ readText: readTextFile,
2882
+ removeFile: (path) => rm(path, { force: true }),
2883
+ exists: fileExists,
2884
+ isDirectory: async (path) => {
2885
+ try {
2886
+ return (await stat(path)).isDirectory();
2887
+ } catch {
2888
+ return false;
2889
+ }
2890
+ },
2891
+ importModule: (url) => import(url),
2892
+ listDir: async (path) => {
2893
+ try {
2894
+ const entries = await readdir(path, { withFileTypes: true });
2895
+ return entries.map((e) => ({ name: e.name, directory: e.isDirectory() })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2896
+ } catch {
2897
+ return [];
2898
+ }
2899
+ },
2900
+ writeText: async (path, text) => {
2901
+ await mkdir(dirname(path), { recursive: true });
2902
+ await writeFile(path, text, "utf8");
2903
+ },
2904
+ createPrompt: () => readlinePrompt(process.stdin, process.stdout)
2905
+ };
2906
+ }
2907
+
2908
+ // src/entries/cli.ts
2909
+ process.exitCode = await main(process.argv.slice(2), nodeHost());