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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,3833 @@
1
+ #!/usr/bin/env node
2
+ import { renderHtmlReport, fileExists, readTextFile, resolvePath, writeTextAtomic, loadThresholds, deriveThresholds, thresholdsFilePaths, writeJsonStable, diffThresholds, formatThresholdsDiffMarkdown, formatThresholdsDiff, relativeSlashPath, colorEnabled, painter, parseRunReport, schemaIssueToIssue, parseOutcome, paint } from './chunk-3CLCMD2Q.js';
3
+ import { CONFIG_FILE_EXTENSIONS, CONFIG_FILE_BASENAME, version, PACKAGE_NAME, CLI_COMMAND, REPOSITORY_URL, generateRunId, peerDependencies, parseRepeat, isEnvLabel, MODE_ENV_NAMES, writeModeState, ENV_LABEL_FORMAT, REPEAT_FORMAT, DOCS_CONFIG_URL } from './chunk-HBGADXLP.js';
4
+ import { DEFAULT_CONFIG, resolveConfig } from './chunk-L5C63HEF.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/init/messages.ts
15
+ var LANGUAGES = ["en", "es", "fr", "pl", "it", "uk", "ru"];
16
+ var LANGUAGE_NAMES = {
17
+ en: "English",
18
+ es: "Español",
19
+ fr: "Français",
20
+ pl: "Polski",
21
+ it: "Italiano",
22
+ uk: "Українська",
23
+ ru: "Русский"
24
+ };
25
+ function isWizardLanguage(value) {
26
+ return LANGUAGES.includes(value);
27
+ }
28
+ var en = {
29
+ declinedInstalled: "{pkg} is installed; no file was changed.",
30
+ declinedSteps: "To set it up by hand:",
31
+ declinedConfig: "Wrap the exported config in playwright.config with withPerf() from {config}.",
32
+ declinedTest: "Wrap your test object with withPerfFixtures() from {fixture}, or import test from {test} instead of @playwright/test.",
33
+ declinedRun: "Run {thresholds} and commit the perf-thresholds.*.json files, then {test} runs the measurement.",
34
+ declinedDocs: "Guide: {url}",
35
+ declinedLater: "Run {init} any time for the guided setup.",
36
+ noTerminal: "no terminal: the default answers are used and nothing is written (like --dry-run). Use --yes to write the changes.",
37
+ dryRun: "dry run: the planned changes are shown and nothing is written.",
38
+ interrupted: "interrupted.",
39
+ answerAgain: "Please answer again: that value is not valid here.",
40
+ pressEnter: "Press Enter to continue.",
41
+ yes: "yes",
42
+ no: "no",
43
+ yesShort: "y",
44
+ noShort: "n",
45
+ stepProject: "Project",
46
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
47
+ versionUnknown: "version unknown",
48
+ testDirLine: 'Test directory "{dir}" · files importing @playwright/test: {imports} · files calling .extend(): {extend}',
49
+ projectsPart: "projects {names}",
50
+ ciLine: "CI: {platform}",
51
+ ciNone: "none found",
52
+ alreadySetUp: "Already set up: {items}",
53
+ measuredTestObject: "measured test object",
54
+ stepHow: "How it works",
55
+ how1: 'Measurement runs are separate from your usual test runs: "{test}" runs the tests in perf mode.',
56
+ how2: "Every test runs several times in one worker, so each backend request gets enough samples.",
57
+ how3: 'Requests are grouped into endpoint keys such as "GET api /users/:id".',
58
+ how4: '"{thresholds}" derives thresholds per key into files you commit to the repository.',
59
+ how5: "Exit code 0 means ok, 2 a performance regression, 3 a tool or config error.",
60
+ stepBackend: "Backend",
61
+ backendLesson: "Endpoint keys start with a short label of the backend origin.",
62
+ noBaseUrl: "No baseURL found in playwright.config: requests are labeled with their host.",
63
+ labelQuestion: "Label for {origin}?",
64
+ stepTests: "Which tests",
65
+ testsLesson: "A measurement run takes about (tests × repetitions) test runs on 1 worker, so measure the tests that call the important backend endpoints.",
66
+ taggedFiles: "Files with tests tagged @perf: {count}.",
67
+ noTaggedMessage: "No test is tagged @perf, so all tests are proposed.",
68
+ noTaggedHint: "Tag the tests to measure with test('title', { tag: '@perf' }, ...), then choose @perf.",
69
+ scopeQuestion: "Measure all tests or only tests tagged @perf? [{all}/@perf]",
70
+ scopeAll: "all",
71
+ stepRepeat: "Repetitions",
72
+ repeatLesson: "Each rule needs a minimum number of samples per endpoint (minSamples), and samples are calls per test × tests × repetitions.",
73
+ repeatQuestion: "Repetitions per test in measurement runs?",
74
+ stepTrial: "Trial period",
75
+ trialLesson: "In warn-only mode regressions are reported but do not fail the run, so you can watch the results for a few weeks before they block builds.",
76
+ warnOnlyQuestion: "Start in warn-only mode for the first weeks?",
77
+ stepEnvs: "Environments",
78
+ envsLesson: "Each environment gets its own thresholds files (perf-thresholds.<kind>.<label>.json).",
79
+ envsQuestion: "Do you run against several environments?",
80
+ envLabelsQuestion: "Environment labels, separated by commas?",
81
+ none: "none",
82
+ stepCi: "CI",
83
+ ciLesson: "A CI job runs the measurement on pull requests and every night and keeps the report.",
84
+ noCi: "No CI configuration found. Recipes for GitHub Actions, GitLab CI, Jenkins and Azure Pipelines: {url}",
85
+ ciQuestion: "Add a CI job for measurement runs ({platform})?",
86
+ stepChanges: "Changes",
87
+ nothingToChange: "Nothing to change: the project is already set up for these answers.",
88
+ changesLesson: "Each change is shown as a diff before it is applied.",
89
+ newFile: "new file",
90
+ modifiedFile: "change",
91
+ overwriteQuestion: "{path} exists. Overwrite it?",
92
+ keptWithYes: "{path} exists and is kept (--yes does not overwrite it).",
93
+ kept: "{path} exists and is kept.",
94
+ applyQuestion: "Apply this change?",
95
+ fileWritten: "Written: {path}",
96
+ stepFirstRun: "First measurement",
97
+ firstRunLesson: "A thresholds run measures the tests and writes the thresholds files and the report ({dir}/).",
98
+ firstRunLaptop: "Thresholds measured on a laptop do not fit CI machines: derive the committed ones in CI.",
99
+ firstRunQuestion: "Run a first thresholds run now?",
100
+ skipped: "Skipped.",
101
+ stepSummary: "Summary",
102
+ changedFiles: "Changed files:",
103
+ noFilesChanged: "No files were changed.",
104
+ plannedChanges: "Planned changes (not written):",
105
+ manualSteps: "Manual steps: {count} (see the warnings above).",
106
+ nextSteps: "Next steps:",
107
+ nextThresholds: "{command}: derive the thresholds and commit the perf-thresholds.*.json files (derive them on the CI machines for stable values).",
108
+ nextTest: "{command}: a measurement run that fails on a regression.",
109
+ nextJenkins: "Create a Pipeline job in Jenkins with the script path {path}.",
110
+ nextAzure: "Create a pipeline in Azure DevOps from {path}.",
111
+ nextWarnOnly: "After the trial period remove gate.warnOnly from pw-perf.config.ts.",
112
+ nextApply: "Apply the changes above (run init again in a terminal or with --yes).",
113
+ docs: "Docs: {links}",
114
+ finished: "Setup finished.",
115
+ noConfigMessage: "No playwright.config.* in {dir}.",
116
+ noConfigHint: 'Run "{command} init" in the directory of playwright.config (in a monorepo: the package with the Playwright tests).',
117
+ tooOldMessage: "@playwright/test {version} is older than {min}, the lowest version {pkg} supports.",
118
+ tooOldHint: 'Update @playwright/test to {min} or later, then run "{command} init" again.',
119
+ writeFailedMessage: "Could not write {detail}",
120
+ writeFailedHint: "Check the permissions of the file and its directory, then run init again.",
121
+ manualPerfConfigKept: "{file} exists and was not changed.",
122
+ manualPerfConfigHint: "Set these options in it if you want them:",
123
+ manualConfigJson: "{config} was not changed: the package config is {file}.",
124
+ manualConfigPattern: "{config} was not changed: its export is not a plain defineConfig({...}) or object (for example another wrapper).",
125
+ configHintIntro: "Wrap the exported config in withPerf() as the outermost call (also around other wrappers):",
126
+ configHintCjs: "In {path} with module.exports: {call}.",
127
+ testHintIntro: "Wrap every test object used by browser tests in withPerfFixtures() from '{entry}':",
128
+ testHintMerge: "Wrap the result of mergeTests() and the test passed to createBdd() (playwright-bdd).",
129
+ testHintImport: "Tests that import test from @playwright/test can import it from '{entry}' instead.",
130
+ manualNoTestObject: "No test object was found to measure: no file imports test from @playwright/test.",
131
+ manualTestObjectOne: "{files} was not changed:",
132
+ manualTestObjectMany: "{files} were not changed:",
133
+ testObjectsReason: "the test objects are not one `export const test = base.extend(...)` (several test objects, mergeTests() or another layout).",
134
+ manualNoPackageJson: "package.json was not found.",
135
+ addScripts: "Add these scripts:",
136
+ manualScriptExists: 'package.json: the script "{name}" exists and was not changed.',
137
+ manualScriptHint: 'The wizard would add "{name}": "{command}". Rename one of them, or add the command by hand.',
138
+ manualPackageJsonInvalid: 'package.json was not changed: it is not a JSON object with a "scripts" object.',
139
+ manualCiKept: "{file} exists and was not changed.",
140
+ manualCiHint: "Compare it with examples/ci/ in the {pkg} repository.",
141
+ manualGitlabInclude: ".gitlab-ci.yml was not changed: include the new job file in it.",
142
+ manualNpmOne: "{files} installs the dependencies with npm.",
143
+ manualNpmMany: "{files} install the dependencies with npm.",
144
+ manualNpmHint: 'This project uses {manager}: replace "npm ci" with "{install}" and "npx" with "{npx}".'
145
+ };
146
+ var pl = {
147
+ declinedInstalled: "{pkg} jest zainstalowana; żaden plik nie został zmieniony.",
148
+ declinedSteps: "Konfiguracja ręczna:",
149
+ declinedConfig: "Owiń eksportowaną konfigurację w playwright.config w withPerf() z {config}.",
150
+ declinedTest: "Owiń swój obiekt test w withPerfFixtures() z {fixture} albo importuj test z {test} zamiast z @playwright/test.",
151
+ declinedRun: "Uruchom {thresholds} i zacommituj pliki perf-thresholds.*.json, potem {test} wykonuje pomiar.",
152
+ declinedDocs: "Przewodnik: {url}",
153
+ declinedLater: "Konfigurację z przewodnikiem uruchomisz w każdej chwili poleceniem {init}.",
154
+ noTerminal: "brak terminala: kreator przyjmuje odpowiedzi domyślne i niczego nie zapisuje (jak --dry-run). Użyj --yes, aby zapisać zmiany.",
155
+ dryRun: "tryb --dry-run: kreator pokazuje planowane zmiany i niczego nie zapisuje.",
156
+ interrupted: "przerwano.",
157
+ answerAgain: "Odpowiedz jeszcze raz: ta wartość nie jest tu poprawna.",
158
+ pressEnter: "Naciśnij Enter, aby kontynuować.",
159
+ yes: "tak",
160
+ no: "nie",
161
+ yesShort: "t",
162
+ noShort: "n",
163
+ stepProject: "Projekt",
164
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
165
+ versionUnknown: "wersja nieznana",
166
+ testDirLine: 'Katalog testów "{dir}" · pliki z importem @playwright/test: {imports} · pliki z wywołaniem .extend(): {extend}',
167
+ projectsPart: "projekty {names}",
168
+ ciLine: "CI: {platform}",
169
+ ciNone: "nie znaleziono",
170
+ alreadySetUp: "Już skonfigurowane: {items}",
171
+ measuredTestObject: "mierzony obiekt test",
172
+ stepHow: "Jak to działa",
173
+ how1: 'Pomiary to osobne przebiegi, niezależne od zwykłych testów: "{test}" uruchamia testy w trybie pomiarowym.',
174
+ how2: "Każdy test wykonuje się kilka razy w jednym workerze, więc każde żądanie do backendu ma dość próbek.",
175
+ how3: 'Żądania są grupowane w klucze endpointów, np. "GET api /users/:id".',
176
+ how4: '"{thresholds}" wyznacza progi dla każdego klucza i zapisuje je w plikach, które commitujesz do repozytorium.',
177
+ how5: "Kod wyjścia 0 oznacza sukces, 2 regresję wydajności, 3 błąd narzędzia albo konfiguracji.",
178
+ stepBackend: "Backend",
179
+ backendLesson: "Klucze endpointów zaczynają się od krótkiej etykiety originu backendu.",
180
+ noBaseUrl: "Brak baseURL w playwright.config: żądania będą oznaczone nazwą hosta.",
181
+ labelQuestion: "Etykieta dla {origin}?",
182
+ stepTests: "Które testy",
183
+ testsLesson: "Pomiar trwa mniej więcej tyle, co (testy × powtórzenia) uruchomień testów na 1 workerze, więc mierz testy, które wywołują ważne endpointy backendu.",
184
+ taggedFiles: "Pliki z testami oznaczonymi @perf: {count}.",
185
+ noTaggedMessage: "Żaden test nie ma tagu @perf, więc proponowane są wszystkie testy.",
186
+ noTaggedHint: "Oznacz testy do pomiaru: test('tytuł', { tag: '@perf' }, ...), a potem wybierz @perf.",
187
+ scopeQuestion: "Mierzyć wszystkie testy czy tylko oznaczone @perf? [{all}/@perf]",
188
+ scopeAll: "wszystkie",
189
+ stepRepeat: "Powtórzenia",
190
+ repeatLesson: "Każda reguła potrzebuje minimalnej liczby próbek na endpoint (minSamples), a próbek jest: wywołania w teście × testy × powtórzenia.",
191
+ repeatQuestion: "Ile powtórzeń każdego testu w pomiarze?",
192
+ stepTrial: "Okres próbny",
193
+ trialLesson: "W trybie warn-only regresje są zgłaszane, ale przebieg nie kończy się błędem, więc przez kilka tygodni możesz obserwować wyniki, zanim zaczną blokować buildy.",
194
+ warnOnlyQuestion: "Zacząć w trybie warn-only przez pierwsze tygodnie?",
195
+ stepEnvs: "Środowiska",
196
+ envsLesson: "Każde środowisko ma własne pliki progów (perf-thresholds.<kind>.<label>.json).",
197
+ envsQuestion: "Czy testujesz kilka środowisk?",
198
+ envLabelsQuestion: "Etykiety środowisk, oddzielone przecinkami?",
199
+ none: "brak",
200
+ stepCi: "CI",
201
+ ciLesson: "Job CI uruchamia pomiar w pull requestach i co noc oraz zachowuje raport.",
202
+ noCi: "Nie znaleziono konfiguracji CI. Przepisy dla GitHub Actions, GitLab CI, Jenkinsa i Azure Pipelines: {url}",
203
+ ciQuestion: "Dodać job CI z pomiarami ({platform})?",
204
+ stepChanges: "Zmiany",
205
+ nothingToChange: "Nic do zmiany: projekt jest już skonfigurowany dla tych odpowiedzi.",
206
+ changesLesson: "Każda zmiana jest najpierw pokazana jako diff, a dopiero potem zastosowana.",
207
+ newFile: "nowy plik",
208
+ modifiedFile: "zmiana",
209
+ overwriteQuestion: "{path} już istnieje. Nadpisać go?",
210
+ keptWithYes: "{path} już istnieje i zostaje bez zmian (--yes go nie nadpisuje).",
211
+ kept: "{path} już istnieje i zostaje bez zmian.",
212
+ applyQuestion: "Zastosować tę zmianę?",
213
+ fileWritten: "Zapisano: {path}",
214
+ stepFirstRun: "Pierwszy pomiar",
215
+ firstRunLesson: "Przebieg w trybie thresholds mierzy testy i zapisuje pliki progów oraz raport ({dir}/).",
216
+ firstRunLaptop: "Progi zmierzone na laptopie nie pasują do maszyn CI: te, które commitujesz, wyznacz w CI.",
217
+ firstRunQuestion: "Uruchomić teraz pierwszy przebieg thresholds?",
218
+ skipped: "Pominięto.",
219
+ stepSummary: "Podsumowanie",
220
+ changedFiles: "Zmienione pliki:",
221
+ noFilesChanged: "Żaden plik nie został zmieniony.",
222
+ plannedChanges: "Planowane zmiany (niezapisane):",
223
+ manualSteps: "Kroki ręczne: {count} (zobacz ostrzeżenia powyżej).",
224
+ nextSteps: "Następne kroki:",
225
+ nextThresholds: "{command}: wyznacz progi i zacommituj pliki perf-thresholds.*.json (wyznaczaj je na maszynach CI, żeby wartości były stabilne).",
226
+ nextTest: "{command}: pomiar, który kończy się błędem przy regresji.",
227
+ nextJenkins: "Utwórz w Jenkinsie job typu Pipeline ze ścieżką skryptu {path}.",
228
+ nextAzure: "Utwórz w Azure DevOps pipeline z pliku {path}.",
229
+ nextWarnOnly: "Po okresie próbnym usuń gate.warnOnly z pw-perf.config.ts.",
230
+ nextApply: "Zastosuj powyższe zmiany (uruchom init ponownie w terminalu albo z --yes).",
231
+ docs: "Dokumentacja: {links}",
232
+ finished: "Konfiguracja zakończona.",
233
+ noConfigMessage: "Brak playwright.config.* w {dir}.",
234
+ noConfigHint: 'Uruchom "{command} init" w katalogu z playwright.config (w monorepo: w pakiecie z testami Playwrighta).',
235
+ tooOldMessage: "@playwright/test {version} jest starszy niż {min}, najniższa wersja obsługiwana przez {pkg}.",
236
+ tooOldHint: 'Zaktualizuj @playwright/test do {min} lub nowszej, potem uruchom ponownie "{command} init".',
237
+ writeFailedMessage: "Nie udało się zapisać {detail}",
238
+ writeFailedHint: "Sprawdź uprawnienia pliku i jego katalogu, potem uruchom init ponownie.",
239
+ manualPerfConfigKept: "{file} już istnieje i nie został zmieniony.",
240
+ manualPerfConfigHint: "Ustaw w nim te opcje, jeśli ich potrzebujesz:",
241
+ manualConfigJson: "Nie zmieniono {config}: konfiguracja paczki jest w {file}.",
242
+ manualConfigPattern: "Nie zmieniono {config}: eksportuje coś innego niż zwykłe defineConfig({...}) albo obiekt (np. inny wrapper).",
243
+ configHintIntro: "Owiń eksportowaną konfigurację w withPerf() jako najbardziej zewnętrzne wywołanie (także wokół innych wrapperów):",
244
+ configHintCjs: "W {path} z module.exports: {call}.",
245
+ testHintIntro: "Owiń każdy obiekt test używany przez testy przeglądarkowe w withPerfFixtures() z '{entry}':",
246
+ testHintMerge: "Owiń wynik mergeTests() oraz test przekazywany do createBdd() (playwright-bdd).",
247
+ testHintImport: "Testy, które importują test z @playwright/test, mogą zamiast tego importować go z '{entry}'.",
248
+ manualNoTestObject: "Nie znaleziono obiektu test do pomiaru: żaden plik nie importuje test z @playwright/test.",
249
+ manualTestObjectOne: "Nie zmieniono {files}:",
250
+ manualTestObjectMany: "Nie zmieniono {files}:",
251
+ testObjectsReason: "obiekty test to nie jedno `export const test = base.extend(...)` (kilka obiektów test, mergeTests() albo inny układ).",
252
+ manualNoPackageJson: "Nie znaleziono package.json.",
253
+ addScripts: "Dodaj te skrypty:",
254
+ manualScriptExists: 'package.json: skrypt "{name}" już istnieje i nie został zmieniony.',
255
+ manualScriptHint: 'Kreator dodałby "{name}": "{command}". Zmień nazwę jednego z nich albo dodaj polecenie ręcznie.',
256
+ manualPackageJsonInvalid: 'Nie zmieniono package.json: to nie jest obiekt JSON z obiektem "scripts".',
257
+ manualCiKept: "{file} już istnieje i nie został zmieniony.",
258
+ manualCiHint: "Porównaj go z examples/ci/ w repozytorium {pkg}.",
259
+ manualGitlabInclude: "Nie zmieniono .gitlab-ci.yml: dołącz do niego nowy plik joba.",
260
+ manualNpmOne: "{files} instaluje zależności przez npm.",
261
+ manualNpmMany: "{files} instalują zależności przez npm.",
262
+ manualNpmHint: 'Ten projekt używa {manager}: zamień "npm ci" na "{install}", a "npx" na "{npx}".'
263
+ };
264
+ var es = {
265
+ declinedInstalled: "{pkg} está instalado; no se modificó ningún archivo.",
266
+ declinedSteps: "Para configurarlo a mano:",
267
+ declinedConfig: "Envuelve la configuración exportada en playwright.config con withPerf() de {config}.",
268
+ declinedTest: "Envuelve tu objeto test con withPerfFixtures() de {fixture}, o importa test de {test} en lugar de @playwright/test.",
269
+ declinedRun: "Ejecuta {thresholds} y sube los archivos perf-thresholds.*.json; después {test} ejecuta la medición.",
270
+ declinedDocs: "Guía: {url}",
271
+ declinedLater: "Ejecuta {init} cuando quieras para la configuración guiada.",
272
+ noTerminal: "sin terminal: se usan las respuestas por defecto y no se escribe nada (como --dry-run). Usa --yes para escribir los cambios.",
273
+ dryRun: "simulación: se muestran los cambios previstos y no se escribe nada.",
274
+ interrupted: "interrumpido.",
275
+ answerAgain: "Responde de nuevo: ese valor no es válido aquí.",
276
+ pressEnter: "Pulsa Enter para continuar.",
277
+ yes: "sí",
278
+ no: "no",
279
+ yesShort: "s",
280
+ noShort: "n",
281
+ stepProject: "Proyecto",
282
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
283
+ versionUnknown: "versión desconocida",
284
+ testDirLine: 'Directorio de tests "{dir}" · archivos que importan @playwright/test: {imports} · archivos que llaman a .extend(): {extend}',
285
+ projectsPart: "proyectos {names}",
286
+ ciLine: "CI: {platform}",
287
+ ciNone: "no encontrado",
288
+ alreadySetUp: "Ya configurado: {items}",
289
+ measuredTestObject: "objeto test medido",
290
+ stepHow: "Cómo funciona",
291
+ how1: 'Las mediciones son ejecuciones aparte de tus tests habituales: "{test}" ejecuta los tests en modo perf.',
292
+ how2: "Cada test se ejecuta varias veces en un worker, para que cada petición al backend tenga suficientes muestras.",
293
+ how3: 'Las peticiones se agrupan en claves de endpoint como "GET api /users/:id".',
294
+ how4: '"{thresholds}" calcula umbrales por clave en archivos que subes al repositorio.',
295
+ how5: "Código de salida 0: todo bien; 2: regresión de rendimiento; 3: error de la herramienta o de la configuración.",
296
+ stepBackend: "Backend",
297
+ backendLesson: "Las claves de endpoint empiezan con una etiqueta corta del origen del backend.",
298
+ noBaseUrl: "No hay baseURL en playwright.config: las peticiones se etiquetan con su host.",
299
+ labelQuestion: "¿Etiqueta para {origin}?",
300
+ stepTests: "Qué tests",
301
+ testsLesson: "Una medición dura unas (tests × repeticiones) ejecuciones de tests en 1 worker, así que mide los tests que llaman a los endpoints importantes del backend.",
302
+ taggedFiles: "Archivos con tests etiquetados @perf: {count}.",
303
+ noTaggedMessage: "Ningún test tiene la etiqueta @perf, así que se proponen todos los tests.",
304
+ noTaggedHint: "Etiqueta los tests a medir con test('título', { tag: '@perf' }, ...) y luego elige @perf.",
305
+ scopeQuestion: "¿Medir todos los tests o solo los etiquetados @perf? [{all}/@perf]",
306
+ scopeAll: "todos",
307
+ stepRepeat: "Repeticiones",
308
+ repeatLesson: "Cada regla necesita un mínimo de muestras por endpoint (minSamples), y las muestras son llamadas por test × tests × repeticiones.",
309
+ repeatQuestion: "¿Repeticiones por test en las mediciones?",
310
+ stepTrial: "Periodo de prueba",
311
+ trialLesson: "En modo warn-only las regresiones se notifican pero no hacen fallar la ejecución, así puedes observar los resultados unas semanas antes de que bloqueen los builds.",
312
+ warnOnlyQuestion: "¿Empezar en modo warn-only las primeras semanas?",
313
+ stepEnvs: "Entornos",
314
+ envsLesson: "Cada entorno tiene sus propios archivos de umbrales (perf-thresholds.<kind>.<label>.json).",
315
+ envsQuestion: "¿Ejecutas contra varios entornos?",
316
+ envLabelsQuestion: "¿Etiquetas de los entornos, separadas por comas?",
317
+ none: "ninguno",
318
+ stepCi: "CI",
319
+ ciLesson: "Un job de CI ejecuta la medición en los pull requests y cada noche, y guarda el informe.",
320
+ noCi: "No se encontró configuración de CI. Recetas para GitHub Actions, GitLab CI, Jenkins y Azure Pipelines: {url}",
321
+ ciQuestion: "¿Añadir un job de CI para las mediciones ({platform})?",
322
+ stepChanges: "Cambios",
323
+ nothingToChange: "Nada que cambiar: el proyecto ya está configurado para estas respuestas.",
324
+ changesLesson: "Cada cambio se muestra como diff antes de aplicarlo.",
325
+ newFile: "archivo nuevo",
326
+ modifiedFile: "cambio",
327
+ overwriteQuestion: "{path} ya existe. ¿Sobrescribirlo?",
328
+ keptWithYes: "{path} ya existe y se conserva (--yes no lo sobrescribe).",
329
+ kept: "{path} ya existe y se conserva.",
330
+ applyQuestion: "¿Aplicar este cambio?",
331
+ fileWritten: "Escrito: {path}",
332
+ stepFirstRun: "Primera medición",
333
+ firstRunLesson: "Una ejecución thresholds mide los tests y escribe los archivos de umbrales y el informe ({dir}/).",
334
+ firstRunLaptop: "Los umbrales medidos en un portátil no sirven para las máquinas de CI: calcula en CI los que subes al repositorio.",
335
+ firstRunQuestion: "¿Lanzar ahora una primera ejecución thresholds?",
336
+ skipped: "Omitido.",
337
+ stepSummary: "Resumen",
338
+ changedFiles: "Archivos modificados:",
339
+ noFilesChanged: "No se modificó ningún archivo.",
340
+ plannedChanges: "Cambios previstos (no escritos):",
341
+ manualSteps: "Pasos manuales: {count} (ver las advertencias de arriba).",
342
+ nextSteps: "Siguientes pasos:",
343
+ nextThresholds: "{command}: calcula los umbrales y sube los archivos perf-thresholds.*.json (calcúlalos en las máquinas de CI para tener valores estables).",
344
+ nextTest: "{command}: una medición que falla ante una regresión.",
345
+ nextJenkins: "Crea un job Pipeline en Jenkins con la ruta de script {path}.",
346
+ nextAzure: "Crea un pipeline en Azure DevOps a partir de {path}.",
347
+ nextWarnOnly: "Tras el periodo de prueba, quita gate.warnOnly de pw-perf.config.ts.",
348
+ nextApply: "Aplica los cambios de arriba (ejecuta init de nuevo en un terminal o con --yes).",
349
+ docs: "Documentación: {links}",
350
+ finished: "Configuración terminada.",
351
+ noConfigMessage: "No hay playwright.config.* en {dir}.",
352
+ noConfigHint: 'Ejecuta "{command} init" en el directorio de playwright.config (en un monorepo: el paquete con los tests de Playwright).',
353
+ tooOldMessage: "@playwright/test {version} es anterior a {min}, la versión mínima que admite {pkg}.",
354
+ tooOldHint: 'Actualiza @playwright/test a {min} o posterior y ejecuta "{command} init" de nuevo.',
355
+ writeFailedMessage: "No se pudo escribir {detail}",
356
+ writeFailedHint: "Revisa los permisos del archivo y de su directorio y ejecuta init de nuevo.",
357
+ manualPerfConfigKept: "{file} ya existe y no se modificó.",
358
+ manualPerfConfigHint: "Define en él estas opciones si las quieres:",
359
+ manualConfigJson: "{config} no se modificó: la configuración del paquete es {file}.",
360
+ manualConfigPattern: "{config} no se modificó: su export no es un defineConfig({...}) simple ni un objeto (por ejemplo, hay otro wrapper).",
361
+ configHintIntro: "Envuelve la configuración exportada en withPerf() como llamada más externa (también alrededor de otros wrappers):",
362
+ configHintCjs: "En {path} con module.exports: {call}.",
363
+ testHintIntro: "Envuelve cada objeto test usado por los tests de navegador en withPerfFixtures() de '{entry}':",
364
+ testHintMerge: "Envuelve el resultado de mergeTests() y el test que se pasa a createBdd() (playwright-bdd).",
365
+ testHintImport: "Los tests que importan test de @playwright/test pueden importarlo de '{entry}' en su lugar.",
366
+ manualNoTestObject: "No se encontró ningún objeto test que medir: ningún archivo importa test de @playwright/test.",
367
+ manualTestObjectOne: "{files} no se modificó:",
368
+ manualTestObjectMany: "{files} no se modificaron:",
369
+ testObjectsReason: "los objetos test no son un único `export const test = base.extend(...)` (varios objetos test, mergeTests() u otra estructura).",
370
+ manualNoPackageJson: "No se encontró package.json.",
371
+ addScripts: "Añade estos scripts:",
372
+ manualScriptExists: 'package.json: el script "{name}" ya existe y no se modificó.',
373
+ manualScriptHint: 'El asistente añadiría "{name}": "{command}". Renombra uno de los dos o añade el comando a mano.',
374
+ manualPackageJsonInvalid: 'package.json no se modificó: no es un objeto JSON con un objeto "scripts".',
375
+ manualCiKept: "{file} ya existe y no se modificó.",
376
+ manualCiHint: "Compáralo con examples/ci/ del repositorio de {pkg}.",
377
+ manualGitlabInclude: ".gitlab-ci.yml no se modificó: incluye en él el nuevo archivo del job.",
378
+ manualNpmOne: "{files} instala las dependencias con npm.",
379
+ manualNpmMany: "{files} instalan las dependencias con npm.",
380
+ manualNpmHint: 'Este proyecto usa {manager}: sustituye "npm ci" por "{install}" y "npx" por "{npx}".'
381
+ };
382
+ var fr = {
383
+ declinedInstalled: "{pkg} est installé ; aucun fichier n’a été modifié.",
384
+ declinedSteps: "Pour le configurer à la main :",
385
+ declinedConfig: "Enveloppez la configuration exportée de playwright.config dans withPerf() de {config}.",
386
+ declinedTest: "Enveloppez votre objet test dans withPerfFixtures() de {fixture}, ou importez test depuis {test} au lieu de @playwright/test.",
387
+ declinedRun: "Lancez {thresholds} et committez les fichiers perf-thresholds.*.json, puis {test} lance la mesure.",
388
+ declinedDocs: "Guide : {url}",
389
+ declinedLater: "Lancez {init} à tout moment pour la configuration guidée.",
390
+ noTerminal: "pas de terminal : les réponses par défaut sont utilisées et rien n'est écrit (comme --dry-run). Utilisez --yes pour écrire les modifications.",
391
+ dryRun: "simulation : les modifications prévues sont affichées et rien n'est écrit.",
392
+ interrupted: "interrompu.",
393
+ answerAgain: "Répondez à nouveau : cette valeur n'est pas valide ici.",
394
+ pressEnter: "Appuyez sur Entrée pour continuer.",
395
+ yes: "oui",
396
+ no: "non",
397
+ yesShort: "o",
398
+ noShort: "n",
399
+ stepProject: "Projet",
400
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
401
+ versionUnknown: "version inconnue",
402
+ testDirLine: 'Répertoire des tests "{dir}" · fichiers qui importent @playwright/test : {imports} · fichiers qui appellent .extend() : {extend}',
403
+ projectsPart: "projets {names}",
404
+ ciLine: "CI : {platform}",
405
+ ciNone: "aucune trouvée",
406
+ alreadySetUp: "Déjà configuré : {items}",
407
+ measuredTestObject: "objet test mesuré",
408
+ stepHow: "Fonctionnement",
409
+ how1: 'Les mesures sont des exécutions séparées de vos tests habituels : "{test}" lance les tests en mode perf.',
410
+ how2: "Chaque test tourne plusieurs fois dans un seul worker, pour que chaque requête au backend ait assez d’échantillons.",
411
+ how3: 'Les requêtes sont regroupées en clés d’endpoint comme "GET api /users/:id".',
412
+ how4: '"{thresholds}" calcule des seuils par clé dans des fichiers que vous committez dans le dépôt.',
413
+ how5: "Code de sortie 0 : tout va bien, 2 : régression de performance, 3 : erreur de l’outil ou de la configuration.",
414
+ stepBackend: "Backend",
415
+ backendLesson: "Les clés d’endpoint commencent par un court libellé de l’origine du backend.",
416
+ noBaseUrl: "Aucun baseURL dans playwright.config : les requêtes sont libellées avec leur hôte.",
417
+ labelQuestion: "Libellé pour {origin} ?",
418
+ stepTests: "Quels tests",
419
+ testsLesson: "Une mesure prend environ (tests × répétitions) exécutions de tests sur 1 worker : mesurez donc les tests qui appellent les endpoints importants du backend.",
420
+ taggedFiles: "Fichiers avec des tests marqués @perf : {count}.",
421
+ noTaggedMessage: "Aucun test n'est marqué @perf, tous les tests sont donc proposés.",
422
+ noTaggedHint: "Marquez les tests à mesurer avec test('titre', { tag: '@perf' }, ...), puis choisissez @perf.",
423
+ scopeQuestion: "Mesurer tous les tests ou seulement ceux marqués @perf ? [{all}/@perf]",
424
+ scopeAll: "tous",
425
+ stepRepeat: "Répétitions",
426
+ repeatLesson: "Chaque règle demande un nombre minimal d’échantillons par endpoint (minSamples), et les échantillons valent appels par test × tests × répétitions.",
427
+ repeatQuestion: "Répétitions par test dans les mesures ?",
428
+ stepTrial: "Période d’essai",
429
+ trialLesson: "En mode warn-only, les régressions sont signalées sans faire échouer l’exécution : vous pouvez suivre les résultats quelques semaines avant qu’ils ne bloquent les builds.",
430
+ warnOnlyQuestion: "Commencer en mode warn-only les premières semaines ?",
431
+ stepEnvs: "Environnements",
432
+ envsLesson: "Chaque environnement a ses propres fichiers de seuils (perf-thresholds.<kind>.<label>.json).",
433
+ envsQuestion: "Testez-vous plusieurs environnements ?",
434
+ envLabelsQuestion: "Libellés des environnements, séparés par des virgules ?",
435
+ none: "aucun",
436
+ stepCi: "CI",
437
+ ciLesson: "Un job CI lance la mesure sur les pull requests et chaque nuit, et conserve le rapport.",
438
+ noCi: "Aucune configuration CI trouvée. Recettes pour GitHub Actions, GitLab CI, Jenkins et Azure Pipelines : {url}",
439
+ ciQuestion: "Ajouter un job CI pour les mesures ({platform}) ?",
440
+ stepChanges: "Modifications",
441
+ nothingToChange: "Rien à modifier : le projet est déjà configuré pour ces réponses.",
442
+ changesLesson: "Chaque modification est affichée sous forme de diff avant d’être appliquée.",
443
+ newFile: "nouveau fichier",
444
+ modifiedFile: "modification",
445
+ overwriteQuestion: "{path} existe déjà. L’écraser ?",
446
+ keptWithYes: "{path} existe déjà et est conservé (--yes ne l’écrase pas).",
447
+ kept: "{path} existe déjà et est conservé.",
448
+ applyQuestion: "Appliquer cette modification ?",
449
+ fileWritten: "Écrit : {path}",
450
+ stepFirstRun: "Première mesure",
451
+ firstRunLesson: "Une exécution thresholds mesure les tests et écrit les fichiers de seuils et le rapport ({dir}/).",
452
+ firstRunLaptop: "Des seuils mesurés sur un portable ne conviennent pas aux machines CI : calculez ceux que vous committez dans la CI.",
453
+ firstRunQuestion: "Lancer maintenant une première exécution thresholds ?",
454
+ skipped: "Ignoré.",
455
+ stepSummary: "Résumé",
456
+ changedFiles: "Fichiers modifiés :",
457
+ noFilesChanged: "Aucun fichier n’a été modifié.",
458
+ plannedChanges: "Modifications prévues (non écrites) :",
459
+ manualSteps: "Étapes manuelles : {count} (voir les avertissements ci-dessus).",
460
+ nextSteps: "Étapes suivantes :",
461
+ nextThresholds: "{command} : calculez les seuils et committez les fichiers perf-thresholds.*.json (calculez-les sur les machines CI pour des valeurs stables).",
462
+ nextTest: "{command} : une mesure qui échoue en cas de régression.",
463
+ nextJenkins: "Créez dans Jenkins un job Pipeline avec le chemin de script {path}.",
464
+ nextAzure: "Créez un pipeline dans Azure DevOps à partir de {path}.",
465
+ nextWarnOnly: "Après la période d’essai, retirez gate.warnOnly de pw-perf.config.ts.",
466
+ nextApply: "Appliquez les modifications ci-dessus (relancez init dans un terminal ou avec --yes).",
467
+ docs: "Documentation : {links}",
468
+ finished: "Configuration terminée.",
469
+ noConfigMessage: "Aucun playwright.config.* dans {dir}.",
470
+ noConfigHint: 'Lancez "{command} init" dans le répertoire de playwright.config (dans un monorepo : le paquet qui contient les tests Playwright).',
471
+ tooOldMessage: "@playwright/test {version} est antérieur à {min}, la version minimale prise en charge par {pkg}.",
472
+ tooOldHint: 'Mettez à jour @playwright/test en {min} ou plus, puis relancez "{command} init".',
473
+ writeFailedMessage: "Impossible d’écrire {detail}",
474
+ writeFailedHint: "Vérifiez les droits du fichier et de son répertoire, puis relancez init.",
475
+ manualPerfConfigKept: "{file} existe déjà et n'a pas été modifié.",
476
+ manualPerfConfigHint: "Définissez-y ces options si vous les voulez :",
477
+ manualConfigJson: "{config} n'a pas été modifié : la configuration du paquet est {file}.",
478
+ manualConfigPattern: "{config} n'a pas été modifié : son export n'est pas un simple defineConfig({...}) ni un objet (par exemple un autre wrapper).",
479
+ configHintIntro: "Enveloppez la configuration exportée dans withPerf() comme appel le plus externe (aussi autour des autres wrappers) :",
480
+ configHintCjs: "Dans {path} avec module.exports : {call}.",
481
+ testHintIntro: "Enveloppez chaque objet test utilisé par les tests navigateur dans withPerfFixtures() de '{entry}' :",
482
+ testHintMerge: "Enveloppez le résultat de mergeTests() et le test passé à createBdd() (playwright-bdd).",
483
+ testHintImport: "Les tests qui importent test depuis @playwright/test peuvent l’importer depuis '{entry}' à la place.",
484
+ manualNoTestObject: "Aucun objet test à mesurer : aucun fichier n'importe test depuis @playwright/test.",
485
+ manualTestObjectOne: "{files} n'a pas été modifié :",
486
+ manualTestObjectMany: "{files} n'ont pas été modifiés :",
487
+ testObjectsReason: "les objets test ne sont pas un seul `export const test = base.extend(...)` (plusieurs objets test, mergeTests() ou une autre structure).",
488
+ manualNoPackageJson: "package.json est introuvable.",
489
+ addScripts: "Ajoutez ces scripts :",
490
+ manualScriptExists: 'package.json : le script "{name}" existe déjà et n’a pas été modifié.',
491
+ manualScriptHint: 'L’assistant ajouterait "{name}": "{command}". Renommez l’un des deux ou ajoutez la commande à la main.',
492
+ manualPackageJsonInvalid: `package.json n'a pas été modifié : ce n'est pas un objet JSON avec un objet "scripts".`,
493
+ manualCiKept: "{file} existe déjà et n'a pas été modifié.",
494
+ manualCiHint: "Comparez-le avec examples/ci/ dans le dépôt de {pkg}.",
495
+ manualGitlabInclude: ".gitlab-ci.yml n'a pas été modifié : incluez-y le nouveau fichier de job.",
496
+ manualNpmOne: "{files} installe les dépendances avec npm.",
497
+ manualNpmMany: "{files} installent les dépendances avec npm.",
498
+ manualNpmHint: 'Ce projet utilise {manager} : remplacez "npm ci" par "{install}" et "npx" par "{npx}".'
499
+ };
500
+ var it = {
501
+ declinedInstalled: "{pkg} è installato; nessun file è stato modificato.",
502
+ declinedSteps: "Per configurarlo a mano:",
503
+ declinedConfig: "Avvolgi la configurazione esportata in playwright.config con withPerf() da {config}.",
504
+ declinedTest: "Avvolgi il tuo oggetto test con withPerfFixtures() da {fixture}, oppure importa test da {test} invece che da @playwright/test.",
505
+ declinedRun: "Esegui {thresholds} e fai commit dei file perf-thresholds.*.json, poi {test} esegue la misurazione.",
506
+ declinedDocs: "Guida: {url}",
507
+ declinedLater: "Esegui {init} in qualsiasi momento per la configurazione guidata.",
508
+ noTerminal: "nessun terminale: vengono usate le risposte predefinite e non viene scritto nulla (come --dry-run). Usa --yes per scrivere le modifiche.",
509
+ dryRun: "simulazione: vengono mostrate le modifiche previste e non viene scritto nulla.",
510
+ interrupted: "interrotto.",
511
+ answerAgain: "Rispondi di nuovo: quel valore non è valido qui.",
512
+ pressEnter: "Premi Invio per continuare.",
513
+ yes: "sì",
514
+ no: "no",
515
+ yesShort: "s",
516
+ noShort: "n",
517
+ stepProject: "Progetto",
518
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
519
+ versionUnknown: "versione sconosciuta",
520
+ testDirLine: 'Cartella dei test "{dir}" · file che importano @playwright/test: {imports} · file che chiamano .extend(): {extend}',
521
+ projectsPart: "progetti {names}",
522
+ ciLine: "CI: {platform}",
523
+ ciNone: "non trovata",
524
+ alreadySetUp: "Già configurato: {items}",
525
+ measuredTestObject: "oggetto test misurato",
526
+ stepHow: "Come funziona",
527
+ how1: 'Le misurazioni sono esecuzioni separate dai tuoi test abituali: "{test}" esegue i test in modalità perf.',
528
+ how2: "Ogni test viene eseguito più volte in un solo worker, così ogni richiesta al backend ha abbastanza campioni.",
529
+ how3: 'Le richieste sono raggruppate in chiavi di endpoint come "GET api /users/:id".',
530
+ how4: '"{thresholds}" calcola le soglie per chiave in file che fai commit nel repository.',
531
+ how5: "Codice di uscita 0: tutto ok, 2: regressione delle prestazioni, 3: errore dello strumento o della configurazione.",
532
+ stepBackend: "Backend",
533
+ backendLesson: "Le chiavi di endpoint iniziano con un’etichetta breve dell’origine del backend.",
534
+ noBaseUrl: "Nessun baseURL in playwright.config: le richieste vengono etichettate con il loro host.",
535
+ labelQuestion: "Etichetta per {origin}?",
536
+ stepTests: "Quali test",
537
+ testsLesson: "Una misurazione richiede circa (test × ripetizioni) esecuzioni di test su 1 worker, quindi misura i test che chiamano gli endpoint importanti del backend.",
538
+ taggedFiles: "File con test contrassegnati @perf: {count}.",
539
+ noTaggedMessage: "Nessun test ha il tag @perf, quindi vengono proposti tutti i test.",
540
+ noTaggedHint: "Contrassegna i test da misurare con test('titolo', { tag: '@perf' }, ...), poi scegli @perf.",
541
+ scopeQuestion: "Misurare tutti i test o solo quelli contrassegnati @perf? [{all}/@perf]",
542
+ scopeAll: "tutti",
543
+ stepRepeat: "Ripetizioni",
544
+ repeatLesson: "Ogni regola richiede un numero minimo di campioni per endpoint (minSamples), e i campioni sono chiamate per test × test × ripetizioni.",
545
+ repeatQuestion: "Ripetizioni per test nelle misurazioni?",
546
+ stepTrial: "Periodo di prova",
547
+ trialLesson: "In modalità warn-only le regressioni vengono segnalate ma non fanno fallire l’esecuzione, così puoi osservare i risultati per qualche settimana prima che blocchino le build.",
548
+ warnOnlyQuestion: "Iniziare in modalità warn-only per le prime settimane?",
549
+ stepEnvs: "Ambienti",
550
+ envsLesson: "Ogni ambiente ha i propri file di soglie (perf-thresholds.<kind>.<label>.json).",
551
+ envsQuestion: "Esegui i test su più ambienti?",
552
+ envLabelsQuestion: "Etichette degli ambienti, separate da virgole?",
553
+ none: "nessuno",
554
+ stepCi: "CI",
555
+ ciLesson: "Un job CI esegue la misurazione sulle pull request e ogni notte, e conserva il report.",
556
+ noCi: "Nessuna configurazione CI trovata. Ricette per GitHub Actions, GitLab CI, Jenkins e Azure Pipelines: {url}",
557
+ ciQuestion: "Aggiungere un job CI per le misurazioni ({platform})?",
558
+ stepChanges: "Modifiche",
559
+ nothingToChange: "Niente da modificare: il progetto è già configurato per queste risposte.",
560
+ changesLesson: "Ogni modifica viene mostrata come diff prima di essere applicata.",
561
+ newFile: "nuovo file",
562
+ modifiedFile: "modifica",
563
+ overwriteQuestion: "{path} esiste già. Sovrascriverlo?",
564
+ keptWithYes: "{path} esiste già e viene mantenuto (--yes non lo sovrascrive).",
565
+ kept: "{path} esiste già e viene mantenuto.",
566
+ applyQuestion: "Applicare questa modifica?",
567
+ fileWritten: "Scritto: {path}",
568
+ stepFirstRun: "Prima misurazione",
569
+ firstRunLesson: "Un’esecuzione thresholds misura i test e scrive i file di soglie e il report ({dir}/).",
570
+ firstRunLaptop: "Le soglie misurate su un portatile non vanno bene per le macchine CI: calcola in CI quelle da fare commit.",
571
+ firstRunQuestion: "Avviare ora una prima esecuzione thresholds?",
572
+ skipped: "Saltato.",
573
+ stepSummary: "Riepilogo",
574
+ changedFiles: "File modificati:",
575
+ noFilesChanged: "Nessun file è stato modificato.",
576
+ plannedChanges: "Modifiche previste (non scritte):",
577
+ manualSteps: "Passi manuali: {count} (vedi gli avvisi sopra).",
578
+ nextSteps: "Prossimi passi:",
579
+ nextThresholds: "{command}: calcola le soglie e fai commit dei file perf-thresholds.*.json (calcolale sulle macchine CI per valori stabili).",
580
+ nextTest: "{command}: una misurazione che fallisce in caso di regressione.",
581
+ nextJenkins: "Crea in Jenkins un job Pipeline con il percorso dello script {path}.",
582
+ nextAzure: "Crea una pipeline in Azure DevOps da {path}.",
583
+ nextWarnOnly: "Dopo il periodo di prova rimuovi gate.warnOnly da pw-perf.config.ts.",
584
+ nextApply: "Applica le modifiche sopra (esegui di nuovo init in un terminale o con --yes).",
585
+ docs: "Documentazione: {links}",
586
+ finished: "Configurazione completata.",
587
+ noConfigMessage: "Nessun playwright.config.* in {dir}.",
588
+ noConfigHint: 'Esegui "{command} init" nella cartella di playwright.config (in un monorepo: il pacchetto con i test Playwright).',
589
+ tooOldMessage: "@playwright/test {version} è precedente a {min}, la versione minima supportata da {pkg}.",
590
+ tooOldHint: 'Aggiorna @playwright/test a {min} o successiva, poi esegui di nuovo "{command} init".',
591
+ writeFailedMessage: "Impossibile scrivere {detail}",
592
+ writeFailedHint: "Controlla i permessi del file e della sua cartella, poi esegui di nuovo init.",
593
+ manualPerfConfigKept: "{file} esiste già e non è stato modificato.",
594
+ manualPerfConfigHint: "Imposta lì queste opzioni, se ti servono:",
595
+ manualConfigJson: "{config} non è stato modificato: la configurazione del pacchetto è {file}.",
596
+ manualConfigPattern: "{config} non è stato modificato: il suo export non è un semplice defineConfig({...}) né un oggetto (per esempio un altro wrapper).",
597
+ configHintIntro: "Avvolgi la configurazione esportata in withPerf() come chiamata più esterna (anche attorno ad altri wrapper):",
598
+ configHintCjs: "In {path} con module.exports: {call}.",
599
+ testHintIntro: "Avvolgi ogni oggetto test usato dai test del browser in withPerfFixtures() da '{entry}':",
600
+ testHintMerge: "Avvolgi il risultato di mergeTests() e il test passato a createBdd() (playwright-bdd).",
601
+ testHintImport: "I test che importano test da @playwright/test possono importarlo invece da '{entry}'.",
602
+ manualNoTestObject: "Nessun oggetto test da misurare: nessun file importa test da @playwright/test.",
603
+ manualTestObjectOne: "{files} non è stato modificato:",
604
+ manualTestObjectMany: "{files} non sono stati modificati:",
605
+ testObjectsReason: "gli oggetti test non sono un unico `export const test = base.extend(...)` (più oggetti test, mergeTests() o un’altra struttura).",
606
+ manualNoPackageJson: "package.json non trovato.",
607
+ addScripts: "Aggiungi questi script:",
608
+ manualScriptExists: 'package.json: lo script "{name}" esiste già e non è stato modificato.',
609
+ manualScriptHint: 'La procedura guidata aggiungerebbe "{name}": "{command}". Rinomina uno dei due o aggiungi il comando a mano.',
610
+ manualPackageJsonInvalid: 'package.json non è stato modificato: non è un oggetto JSON con un oggetto "scripts".',
611
+ manualCiKept: "{file} esiste già e non è stato modificato.",
612
+ manualCiHint: "Confrontalo con examples/ci/ nel repository di {pkg}.",
613
+ manualGitlabInclude: ".gitlab-ci.yml non è stato modificato: includi il nuovo file del job.",
614
+ manualNpmOne: "{files} installa le dipendenze con npm.",
615
+ manualNpmMany: "{files} installano le dipendenze con npm.",
616
+ manualNpmHint: 'Questo progetto usa {manager}: sostituisci "npm ci" con "{install}" e "npx" con "{npx}".'
617
+ };
618
+ var uk = {
619
+ declinedInstalled: "{pkg} встановлено; жоден файл не змінено.",
620
+ declinedSteps: "Щоб налаштувати вручну:",
621
+ declinedConfig: "Обгорніть експортовану конфігурацію в playwright.config у withPerf() з {config}.",
622
+ declinedTest: "Обгорніть свій об’єкт test у withPerfFixtures() з {fixture} або імпортуйте test з {test} замість @playwright/test.",
623
+ declinedRun: "Запустіть {thresholds} і закомітьте файли perf-thresholds.*.json, після цього {test} виконує вимірювання.",
624
+ declinedDocs: "Посібник: {url}",
625
+ declinedLater: "Запустіть {init} будь-коли для налаштування з підказками.",
626
+ noTerminal: "немає термінала: використовуються типові відповіді, нічого не записується (як --dry-run). Додайте --yes, щоб записати зміни.",
627
+ dryRun: "пробний запуск: показано заплановані зміни, нічого не записується.",
628
+ interrupted: "перервано.",
629
+ answerAgain: "Відповідайте ще раз: це значення тут не підходить.",
630
+ pressEnter: "Натисніть Enter, щоб продовжити.",
631
+ yes: "так",
632
+ no: "ні",
633
+ yesShort: "т",
634
+ noShort: "н",
635
+ stepProject: "Проєкт",
636
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
637
+ versionUnknown: "версія невідома",
638
+ testDirLine: 'Каталог тестів "{dir}" · файли, що імпортують @playwright/test: {imports} · файли, що викликають .extend(): {extend}',
639
+ projectsPart: "проєкти {names}",
640
+ ciLine: "CI: {platform}",
641
+ ciNone: "не знайдено",
642
+ alreadySetUp: "Уже налаштовано: {items}",
643
+ measuredTestObject: "вимірюваний об’єкт test",
644
+ stepHow: "Як це працює",
645
+ how1: 'Вимірювання — це окремі запуски, не ваші звичайні тести: "{test}" запускає тести в режимі perf.',
646
+ how2: "Кожен тест виконується кілька разів в одному worker, тож кожен запит до бекенду має достатньо вимірів.",
647
+ how3: 'Запити групуються в ключі ендпоінтів, наприклад "GET api /users/:id".',
648
+ how4: '"{thresholds}" обчислює пороги для кожного ключа у файли, які ви комітите в репозиторій.',
649
+ how5: "Код виходу 0 — усе гаразд, 2 — регресія продуктивності, 3 — помилка інструмента або конфігурації.",
650
+ stepBackend: "Бекенд",
651
+ backendLesson: "Ключі ендпоінтів починаються з короткої мітки origin бекенду.",
652
+ noBaseUrl: "У playwright.config немає baseURL: запити позначаються своїм хостом.",
653
+ labelQuestion: "Мітка для {origin}?",
654
+ stepTests: "Які тести",
655
+ testsLesson: "Вимірювання триває приблизно (тести × повторення) запусків тестів на 1 worker, тож вимірюйте тести, що викликають важливі ендпоінти бекенду.",
656
+ taggedFiles: "Файли з тестами з тегом @perf: {count}.",
657
+ noTaggedMessage: "Жоден тест не має тегу @perf, тому пропонуються всі тести.",
658
+ noTaggedHint: "Позначте тести для вимірювання: test('назва', { tag: '@perf' }, ...), а потім виберіть @perf.",
659
+ scopeQuestion: "Вимірювати всі тести чи лише з тегом @perf? [{all}/@perf]",
660
+ scopeAll: "усі",
661
+ stepRepeat: "Повторення",
662
+ repeatLesson: "Кожне правило потребує мінімальної кількості вимірів на ендпоінт (minSamples), а вимірів буде: виклики в тесті × тести × повторення.",
663
+ repeatQuestion: "Скільки повторень кожного тесту під час вимірювання?",
664
+ stepTrial: "Пробний період",
665
+ trialLesson: "У режимі warn-only регресії показуються, але запуск не завершується помилкою, тож кілька тижнів можна спостерігати за результатами, перш ніж вони почнуть блокувати збірки.",
666
+ warnOnlyQuestion: "Почати в режимі warn-only на перші тижні?",
667
+ stepEnvs: "Середовища",
668
+ envsLesson: "Кожне середовище має власні файли порогів (perf-thresholds.<kind>.<label>.json).",
669
+ envsQuestion: "Ви тестуєте кілька середовищ?",
670
+ envLabelsQuestion: "Мітки середовищ через кому?",
671
+ none: "немає",
672
+ stepCi: "CI",
673
+ ciLesson: "Job у CI запускає вимірювання для pull request і щоночі та зберігає звіт.",
674
+ noCi: "Конфігурацію CI не знайдено. Рецепти для GitHub Actions, GitLab CI, Jenkins та Azure Pipelines: {url}",
675
+ ciQuestion: "Додати job у CI для вимірювань ({platform})?",
676
+ stepChanges: "Зміни",
677
+ nothingToChange: "Нічого змінювати: проєкт уже налаштовано для цих відповідей.",
678
+ changesLesson: "Кожну зміну показано як diff, перш ніж її застосувати.",
679
+ newFile: "новий файл",
680
+ modifiedFile: "зміна",
681
+ overwriteQuestion: "{path} уже існує. Перезаписати?",
682
+ keptWithYes: "{path} уже існує і залишається без змін (--yes його не перезаписує).",
683
+ kept: "{path} уже існує і залишається без змін.",
684
+ applyQuestion: "Застосувати цю зміну?",
685
+ fileWritten: "Записано: {path}",
686
+ stepFirstRun: "Перше вимірювання",
687
+ firstRunLesson: "Запуск thresholds вимірює тести та записує файли порогів і звіт ({dir}/).",
688
+ firstRunLaptop: "Пороги, виміряні на ноутбуці, не підходять для машин CI: ті, що комітите, обчислюйте в CI.",
689
+ firstRunQuestion: "Запустити зараз перший запуск thresholds?",
690
+ skipped: "Пропущено.",
691
+ stepSummary: "Підсумок",
692
+ changedFiles: "Змінені файли:",
693
+ noFilesChanged: "Жоден файл не змінено.",
694
+ plannedChanges: "Заплановані зміни (не записані):",
695
+ manualSteps: "Ручні кроки: {count} (див. попередження вище).",
696
+ nextSteps: "Наступні кроки:",
697
+ nextThresholds: "{command}: обчисліть пороги й закомітьте файли perf-thresholds.*.json (для стабільних значень обчислюйте їх на машинах CI).",
698
+ nextTest: "{command}: вимірювання, яке завершується помилкою при регресії.",
699
+ nextJenkins: "Створіть у Jenkins job типу Pipeline зі шляхом до скрипта {path}.",
700
+ nextAzure: "Створіть pipeline в Azure DevOps з {path}.",
701
+ nextWarnOnly: "Після пробного періоду видаліть gate.warnOnly з pw-perf.config.ts.",
702
+ nextApply: "Застосуйте зміни вище (запустіть init ще раз у терміналі або з --yes).",
703
+ docs: "Документація: {links}",
704
+ finished: "Налаштування завершено.",
705
+ noConfigMessage: "У {dir} немає playwright.config.*.",
706
+ noConfigHint: 'Запустіть "{command} init" у каталозі з playwright.config (у монорепозиторії: у пакеті з тестами Playwright).',
707
+ tooOldMessage: "@playwright/test {version} старіший за {min}, найнижчу версію, яку підтримує {pkg}.",
708
+ tooOldHint: 'Оновіть @playwright/test до {min} або новішої, потім знову запустіть "{command} init".',
709
+ writeFailedMessage: "Не вдалося записати {detail}",
710
+ writeFailedHint: "Перевірте права доступу до файлу та його каталогу, потім знову запустіть init.",
711
+ manualPerfConfigKept: "{file} уже існує і не змінювався.",
712
+ manualPerfConfigHint: "Задайте в ньому ці параметри, якщо вони потрібні:",
713
+ manualConfigJson: "{config} не змінено: конфігурація пакета — {file}.",
714
+ manualConfigPattern: "{config} не змінено: його export — не простий defineConfig({...}) і не об’єкт (наприклад, інша обгортка).",
715
+ configHintIntro: "Обгорніть експортовану конфігурацію у withPerf() як найзовнішній виклик (також навколо інших обгорток):",
716
+ configHintCjs: "У {path} з module.exports: {call}.",
717
+ testHintIntro: "Обгорніть кожен об’єкт test, який використовують браузерні тести, у withPerfFixtures() з '{entry}':",
718
+ testHintMerge: "Обгорніть результат mergeTests() і test, що передається в createBdd() (playwright-bdd).",
719
+ testHintImport: "Тести, які імпортують test з @playwright/test, можуть натомість імпортувати його з '{entry}'.",
720
+ manualNoTestObject: "Не знайдено об’єкта test для вимірювання: жоден файл не імпортує test з @playwright/test.",
721
+ manualTestObjectOne: "{files} не змінено:",
722
+ manualTestObjectMany: "{files} не змінено:",
723
+ testObjectsReason: "об’єкти test — це не один `export const test = base.extend(...)` (кілька об’єктів test, mergeTests() або інша структура).",
724
+ manualNoPackageJson: "package.json не знайдено.",
725
+ addScripts: "Додайте ці скрипти:",
726
+ manualScriptExists: 'package.json: скрипт "{name}" уже існує і не змінювався.',
727
+ manualScriptHint: 'Майстер додав би "{name}": "{command}". Перейменуйте один із них або додайте команду вручну.',
728
+ manualPackageJsonInvalid: 'package.json не змінено: це не JSON-об’єкт з об’єктом "scripts".',
729
+ manualCiKept: "{file} уже існує і не змінювався.",
730
+ manualCiHint: "Порівняйте його з examples/ci/ у репозиторії {pkg}.",
731
+ manualGitlabInclude: ".gitlab-ci.yml не змінено: підключіть у ньому новий файл job.",
732
+ manualNpmOne: "{files} встановлює залежності через npm.",
733
+ manualNpmMany: "{files} встановлюють залежності через npm.",
734
+ manualNpmHint: 'Цей проєкт використовує {manager}: замініть "npm ci" на "{install}", а "npx" на "{npx}".'
735
+ };
736
+ var ru = {
737
+ declinedInstalled: "{pkg} установлен; ни один файл не изменён.",
738
+ declinedSteps: "Чтобы настроить вручную:",
739
+ declinedConfig: "Оберните экспортируемую конфигурацию в playwright.config в withPerf() из {config}.",
740
+ declinedTest: "Оберните свой объект test в withPerfFixtures() из {fixture} или импортируйте test из {test} вместо @playwright/test.",
741
+ declinedRun: "Запустите {thresholds} и закоммитьте файлы perf-thresholds.*.json, после этого {test} выполняет измерение.",
742
+ declinedDocs: "Руководство: {url}",
743
+ declinedLater: "Запустите {init} в любой момент для настройки с подсказками.",
744
+ noTerminal: "нет терминала: используются ответы по умолчанию, ничего не записывается (как --dry-run). Добавьте --yes, чтобы записать изменения.",
745
+ dryRun: "пробный запуск: показаны запланированные изменения, ничего не записывается.",
746
+ interrupted: "прервано.",
747
+ answerAgain: "Ответьте ещё раз: это значение здесь не подходит.",
748
+ pressEnter: "Нажмите Enter, чтобы продолжить.",
749
+ yes: "да",
750
+ no: "нет",
751
+ yesShort: "д",
752
+ noShort: "н",
753
+ stepProject: "Проект",
754
+ projectLine: "{config} · Playwright {version} · {manager} · {modules}",
755
+ versionUnknown: "версия неизвестна",
756
+ testDirLine: 'Каталог тестов "{dir}" · файлы, импортирующие @playwright/test: {imports} · файлы, вызывающие .extend(): {extend}',
757
+ projectsPart: "проекты {names}",
758
+ ciLine: "CI: {platform}",
759
+ ciNone: "не найдено",
760
+ alreadySetUp: "Уже настроено: {items}",
761
+ measuredTestObject: "измеряемый объект test",
762
+ stepHow: "Как это работает",
763
+ how1: 'Измерения — это отдельные запуски, а не ваши обычные тесты: "{test}" запускает тесты в режиме perf.',
764
+ how2: "Каждый тест выполняется несколько раз в одном worker, поэтому у каждого запроса к бэкенду достаточно замеров.",
765
+ how3: 'Запросы группируются в ключи эндпоинтов, например "GET api /users/:id".',
766
+ how4: '"{thresholds}" вычисляет пороги по каждому ключу в файлы, которые вы коммитите в репозиторий.',
767
+ how5: "Код выхода 0 — всё в порядке, 2 — регрессия производительности, 3 — ошибка инструмента или конфигурации.",
768
+ stepBackend: "Бэкенд",
769
+ backendLesson: "Ключи эндпоинтов начинаются с короткой метки origin бэкенда.",
770
+ noBaseUrl: "В playwright.config нет baseURL: запросы помечаются своим хостом.",
771
+ labelQuestion: "Метка для {origin}?",
772
+ stepTests: "Какие тесты",
773
+ testsLesson: "Измерение занимает примерно (тесты × повторения) запусков тестов на 1 worker, поэтому измеряйте тесты, которые вызывают важные эндпоинты бэкенда.",
774
+ taggedFiles: "Файлы с тестами с тегом @perf: {count}.",
775
+ noTaggedMessage: "Ни у одного теста нет тега @perf, поэтому предлагаются все тесты.",
776
+ noTaggedHint: "Отметьте тесты для измерения: test('название', { tag: '@perf' }, ...), затем выберите @perf.",
777
+ scopeQuestion: "Измерять все тесты или только с тегом @perf? [{all}/@perf]",
778
+ scopeAll: "все",
779
+ stepRepeat: "Повторения",
780
+ repeatLesson: "Каждому правилу нужно минимальное число замеров на эндпоинт (minSamples), а замеров будет: вызовы в тесте × тесты × повторения.",
781
+ repeatQuestion: "Сколько повторений каждого теста при измерении?",
782
+ stepTrial: "Пробный период",
783
+ trialLesson: "В режиме warn-only регрессии показываются, но запуск не завершается ошибкой, так что несколько недель можно наблюдать за результатами, прежде чем они начнут блокировать сборки.",
784
+ warnOnlyQuestion: "Начать в режиме warn-only на первые недели?",
785
+ stepEnvs: "Окружения",
786
+ envsLesson: "У каждого окружения свои файлы порогов (perf-thresholds.<kind>.<label>.json).",
787
+ envsQuestion: "Вы тестируете несколько окружений?",
788
+ envLabelsQuestion: "Метки окружений через запятую?",
789
+ none: "нет",
790
+ stepCi: "CI",
791
+ ciLesson: "Job в CI запускает измерение для pull request и каждую ночь и сохраняет отчёт.",
792
+ noCi: "Конфигурация CI не найдена. Рецепты для GitHub Actions, GitLab CI, Jenkins и Azure Pipelines: {url}",
793
+ ciQuestion: "Добавить job в CI для измерений ({platform})?",
794
+ stepChanges: "Изменения",
795
+ nothingToChange: "Менять нечего: проект уже настроен для этих ответов.",
796
+ changesLesson: "Каждое изменение показывается как diff, прежде чем его применить.",
797
+ newFile: "новый файл",
798
+ modifiedFile: "изменение",
799
+ overwriteQuestion: "{path} уже существует. Перезаписать?",
800
+ keptWithYes: "{path} уже существует и остаётся без изменений (--yes его не перезаписывает).",
801
+ kept: "{path} уже существует и остаётся без изменений.",
802
+ applyQuestion: "Применить это изменение?",
803
+ fileWritten: "Записано: {path}",
804
+ stepFirstRun: "Первое измерение",
805
+ firstRunLesson: "Запуск thresholds измеряет тесты и записывает файлы порогов и отчёт ({dir}/).",
806
+ firstRunLaptop: "Пороги, измеренные на ноутбуке, не подходят для машин CI: те, что вы коммитите, вычисляйте в CI.",
807
+ firstRunQuestion: "Выполнить сейчас первый запуск thresholds?",
808
+ skipped: "Пропущено.",
809
+ stepSummary: "Итог",
810
+ changedFiles: "Изменённые файлы:",
811
+ noFilesChanged: "Ни один файл не изменён.",
812
+ plannedChanges: "Запланированные изменения (не записаны):",
813
+ manualSteps: "Ручные шаги: {count} (см. предупреждения выше).",
814
+ nextSteps: "Дальнейшие шаги:",
815
+ nextThresholds: "{command}: вычислите пороги и закоммитьте файлы perf-thresholds.*.json (для стабильных значений вычисляйте их на машинах CI).",
816
+ nextTest: "{command}: измерение, которое завершается ошибкой при регрессии.",
817
+ nextJenkins: "Создайте в Jenkins job типа Pipeline с путём к скрипту {path}.",
818
+ nextAzure: "Создайте pipeline в Azure DevOps из {path}.",
819
+ nextWarnOnly: "После пробного периода удалите gate.warnOnly из pw-perf.config.ts.",
820
+ nextApply: "Примените изменения выше (запустите init ещё раз в терминале или с --yes).",
821
+ docs: "Документация: {links}",
822
+ finished: "Настройка завершена.",
823
+ noConfigMessage: "В {dir} нет playwright.config.*.",
824
+ noConfigHint: 'Запустите "{command} init" в каталоге с playwright.config (в монорепозитории: в пакете с тестами Playwright).',
825
+ tooOldMessage: "@playwright/test {version} старше {min}, минимальной версии, которую поддерживает {pkg}.",
826
+ tooOldHint: 'Обновите @playwright/test до {min} или новее, затем снова запустите "{command} init".',
827
+ writeFailedMessage: "Не удалось записать {detail}",
828
+ writeFailedHint: "Проверьте права доступа к файлу и его каталогу, затем снова запустите init.",
829
+ manualPerfConfigKept: "{file} уже существует и не изменялся.",
830
+ manualPerfConfigHint: "Задайте в нём эти параметры, если они нужны:",
831
+ manualConfigJson: "{config} не изменён: конфигурация пакета — {file}.",
832
+ manualConfigPattern: "{config} не изменён: его export — не простой defineConfig({...}) и не объект (например, другая обёртка).",
833
+ configHintIntro: "Оберните экспортируемую конфигурацию в withPerf() как самый внешний вызов (в том числе вокруг других обёрток):",
834
+ configHintCjs: "В {path} с module.exports: {call}.",
835
+ testHintIntro: "Оберните каждый объект test, который используют браузерные тесты, в withPerfFixtures() из '{entry}':",
836
+ testHintMerge: "Оберните результат mergeTests() и test, передаваемый в createBdd() (playwright-bdd).",
837
+ testHintImport: "Тесты, которые импортируют test из @playwright/test, могут вместо этого импортировать его из '{entry}'.",
838
+ manualNoTestObject: "Не найден объект test для измерения: ни один файл не импортирует test из @playwright/test.",
839
+ manualTestObjectOne: "{files} не изменён:",
840
+ manualTestObjectMany: "{files} не изменены:",
841
+ testObjectsReason: "объекты test — это не один `export const test = base.extend(...)` (несколько объектов test, mergeTests() или другая структура).",
842
+ manualNoPackageJson: "package.json не найден.",
843
+ addScripts: "Добавьте эти скрипты:",
844
+ manualScriptExists: 'package.json: скрипт "{name}" уже существует и не изменялся.',
845
+ manualScriptHint: 'Мастер добавил бы "{name}": "{command}". Переименуйте один из них или добавьте команду вручную.',
846
+ manualPackageJsonInvalid: 'package.json не изменён: это не JSON-объект с объектом "scripts".',
847
+ manualCiKept: "{file} уже существует и не изменялся.",
848
+ manualCiHint: "Сравните его с examples/ci/ в репозитории {pkg}.",
849
+ manualGitlabInclude: ".gitlab-ci.yml не изменён: подключите в нём новый файл job.",
850
+ manualNpmOne: "{files} устанавливает зависимости через npm.",
851
+ manualNpmMany: "{files} устанавливают зависимости через npm.",
852
+ manualNpmHint: 'Этот проект использует {manager}: замените "npm ci" на "{install}", а "npx" на "{npx}".'
853
+ };
854
+ var MESSAGES = { en, es, fr, pl, it, uk, ru };
855
+ var PLACEHOLDER = /\{(\w+)\}/gu;
856
+ function format(text, values = {}) {
857
+ return text.replace(
858
+ PLACEHOLDER,
859
+ (whole, name) => values[name] === void 0 ? whole : String(values[name])
860
+ );
861
+ }
862
+ function translator(lang) {
863
+ return (key, values) => format(MESSAGES[lang][key], values);
864
+ }
865
+
866
+ // src/cli/help.ts
867
+ var REPEAT_NOTE = [
868
+ "Note: every test runs several times in one worker. Tests that create data with unique",
869
+ "constraints may conflict between repetitions: make the data unique per repetition, or",
870
+ "leave such tests out with --grep-invert."
871
+ ];
872
+ var EXIT_CODES = [
873
+ "Exit codes: 0 ok (failed tests are reported as a warning) · 2 performance regression ·",
874
+ "3 tool or config error, or an untrustworthy result (too many failed tests, incomplete run)",
875
+ "· 130/143 interrupted (SIGINT/SIGTERM)"
876
+ ];
877
+ var PASS_THROUGH = [
878
+ 'All other arguments go to "playwright test" unchanged; arguments after "--" are never read',
879
+ `as ${CLI_COMMAND} options. --ui, --debug and --shard are not supported. By default only`,
880
+ "Chromium projects are measured; other projects are left out of the run (option",
881
+ '"run.projects").'
882
+ ];
883
+ var GENERAL = [
884
+ `Usage: ${CLI_COMMAND} <command> [options] [playwright test arguments]`,
885
+ "",
886
+ "Commands:",
887
+ " test Measurement run: measure, evaluate against the thresholds, fail on regression",
888
+ " thresholds Thresholds run: measure without the gate, then write the thresholds files",
889
+ " thresholds --from <file> Derive the thresholds from an existing report.json (no tests)",
890
+ " report Render the HTML report again from report.json",
891
+ " init Guided setup in this project",
892
+ "",
893
+ "Options (test, thresholds):",
894
+ " --env <label> Environment label; selects perf-thresholds.<kind>.<label>.json",
895
+ " --repeat <n> Repetitions per test for this run",
896
+ " --prune (thresholds) Remove unlocked entries of keys not seen in this run",
897
+ "",
898
+ ...PASS_THROUGH,
899
+ "",
900
+ `Run "${CLI_COMMAND} <command> --help" for the options of a command, "${CLI_COMMAND} --version"`,
901
+ "for the version.",
902
+ "",
903
+ ...REPEAT_NOTE,
904
+ "",
905
+ ...EXIT_CODES
906
+ ];
907
+ var TEST = [
908
+ `Usage: ${CLI_COMMAND} test [--env <label>] [--repeat <n>] [playwright test arguments]`,
909
+ "",
910
+ "Runs the tests in perf mode, measures the backend requests and custom measurements, evaluates",
911
+ "them against the thresholds files and fails on a regression.",
912
+ "",
913
+ "Options:",
914
+ " --env <label> Environment label; selects perf-thresholds.<kind>.<label>.json (overrides run.env)",
915
+ " --repeat <n> Repetitions per test for this run (overrides run.repeat.test)",
916
+ " -h, --help Show this help",
917
+ "",
918
+ ...PASS_THROUGH,
919
+ "",
920
+ `Example: ${CLI_COMMAND} test --grep @perf`,
921
+ "",
922
+ ...REPEAT_NOTE,
923
+ "",
924
+ ...EXIT_CODES
925
+ ];
926
+ var THRESHOLDS = [
927
+ `Usage: ${CLI_COMMAND} thresholds [--env <label>] [--repeat <n>] [--prune] [playwright test arguments]`,
928
+ ` ${CLI_COMMAND} thresholds --from <report.json> [--env <label>] [--prune] [--config <file>]`,
929
+ "",
930
+ "Runs the tests in perf mode without the gate and writes the thresholds files, or derives them",
931
+ "from an existing run report without running tests (--from).",
932
+ "",
933
+ "Options:",
934
+ " --env <label> Environment label; the files perf-thresholds.<kind>.<label>.json are written",
935
+ " (with --from: default is the label of the report)",
936
+ " --repeat <n> Repetitions per test for this run (overrides run.repeat.thresholds)",
937
+ " --prune Remove unlocked entries of keys not seen in the run; not with a test filter",
938
+ " --from <file> Derive the thresholds from this report.json; no Playwright arguments",
939
+ " --config <file> (with --from) Package config file; default: pw-perf.config.* in the current",
940
+ " directory or the config directory of the report, else the report snapshot",
941
+ " -h, --help Show this help",
942
+ "",
943
+ ...PASS_THROUGH,
944
+ "",
945
+ ...REPEAT_NOTE,
946
+ "",
947
+ "Exit codes: 0 ok · 3 tool or config error, or an untrustworthy run (nothing is written)",
948
+ "· 130/143 interrupted (SIGINT/SIGTERM)"
949
+ ];
950
+ var REPORT = [
951
+ `Usage: ${CLI_COMMAND} report [--input <report.json>] [--output <report.html>] [--config <file>]`,
952
+ "",
953
+ "Renders the HTML report again from a run report, without running tests.",
954
+ "",
955
+ "Options:",
956
+ " --input <file> Run report; default: report.json in report.dir",
957
+ " --output <file> HTML file; default: report.html next to the input",
958
+ " --config <file> Package config file; default: pw-perf.config.* in the current directory",
959
+ " -h, --help Show this help",
960
+ "",
961
+ "Exit codes: 0 ok · 3 error"
962
+ ];
963
+ var INIT = [
964
+ `Usage: ${CLI_COMMAND} init [--yes] [--dry-run] [--lang <code>] [--no-tutorial]`,
965
+ "",
966
+ "Guided setup of the package in this project: asks a few questions, shows a diff of every",
967
+ "change and applies it after confirmation. Files it does not recognize are left unchanged",
968
+ "with instructions. Without a terminal and without --yes it only shows the planned changes.",
969
+ "",
970
+ "Options:",
971
+ " -y, --yes Accept the default answers and write the changes",
972
+ " --dry-run Show the planned changes only",
973
+ ` --lang <code> Language of the wizard: ${LANGUAGES.join(", ")} (default: en, or asked)`,
974
+ " --no-tutorial Print the manual setup steps and change nothing",
975
+ " -h, --help Show this help",
976
+ "",
977
+ "Exit codes: 0 done (also with manual steps left) · 3 error · 130 interrupted"
978
+ ];
979
+ var TOPICS = {
980
+ test: TEST,
981
+ thresholds: THRESHOLDS,
982
+ report: REPORT,
983
+ init: INIT
984
+ };
985
+ function helpText(command) {
986
+ return `${(command === void 0 ? GENERAL : TOPICS[command]).join("\n")}
987
+ `;
988
+ }
989
+
990
+ // src/cli/init/detect.ts
991
+ var PLAYWRIGHT_CONFIG_NAMES = [
992
+ "ts",
993
+ "mts",
994
+ "cts",
995
+ "js",
996
+ "mjs",
997
+ "cjs"
998
+ ].map((ext) => `playwright.config.${ext}`);
999
+ var PERF_CONFIG_NAMES = CONFIG_FILE_EXTENSIONS.map(
1000
+ (ext) => `${CONFIG_FILE_BASENAME}${ext}`
1001
+ );
1002
+ var INSTALLED_PLAYWRIGHT = "node_modules/@playwright/test/package.json";
1003
+ var LOCKFILES = {
1004
+ "pnpm-lock.yaml": "pnpm",
1005
+ "yarn.lock": "yarn",
1006
+ "package-lock.json": "npm"
1007
+ };
1008
+ var CI_MARKERS = [
1009
+ ["github", (p) => p.startsWith(".github/")],
1010
+ ["gitlab", (p) => p === ".gitlab-ci.yml"],
1011
+ ["jenkins", (p) => p === "Jenkinsfile"],
1012
+ ["azure", (p) => p === "azure-pipelines.yml"]
1013
+ ];
1014
+ var SOURCE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/u;
1015
+ var IMPORTS_PLAYWRIGHT_TEST = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*|^\s*import\s*)(['"])@playwright\/test\1/mu;
1016
+ var EXTEND_CALL = /(?<!\bexpect)\.extend\s*[<(]/gu;
1017
+ var PERF_TAG = /@perf\b/u;
1018
+ var WRAPPED_TEST = new RegExp(
1019
+ String.raw`\bwithPerfFixtures\s*\(|(['"])${PACKAGE_NAME}/test\1`,
1020
+ "u"
1021
+ );
1022
+ function testDirsOf(configText) {
1023
+ const dirs = [...configText.matchAll(/\btestDir\s*:\s*(['"`])([^'"`\n]+)\1/gu)].map(
1024
+ (m) => normalizeDir(m[2])
1025
+ );
1026
+ return dirs.length === 0 ? ["."] : [...new Set(dirs)];
1027
+ }
1028
+ function normalizeDir(dir) {
1029
+ const clean = dir.replaceAll("\\", "/").replace(/^\.\/+/u, "").replace(/\/+$/u, "");
1030
+ return clean === "" ? "." : clean;
1031
+ }
1032
+ function parseJson(text) {
1033
+ if (text === void 0) return null;
1034
+ try {
1035
+ const value = JSON.parse(text);
1036
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1037
+ } catch {
1038
+ return null;
1039
+ }
1040
+ }
1041
+ function stringField(obj, ...keys) {
1042
+ let value = obj;
1043
+ for (const key of keys) {
1044
+ if (typeof value !== "object" || value === null) return null;
1045
+ value = value[key];
1046
+ }
1047
+ return typeof value === "string" ? value : null;
1048
+ }
1049
+ function playwrightVersion(files, pkg) {
1050
+ const installed = stringField(parseJson(files.get(INSTALLED_PLAYWRIGHT)), "version");
1051
+ if (installed !== null) return installed;
1052
+ const range = stringField(pkg, "devDependencies", "@playwright/test") ?? stringField(pkg, "dependencies", "@playwright/test");
1053
+ return range === null ? null : /\d+\.\d+\.\d+/u.exec(range)?.[0] ?? null;
1054
+ }
1055
+ function packageManagerOf(files, pkg) {
1056
+ for (const [file, manager] of Object.entries(LOCKFILES)) {
1057
+ if (files.has(file)) return manager;
1058
+ }
1059
+ const declared = /^(npm|pnpm|yarn)@/u.exec(stringField(pkg, "packageManager") ?? "");
1060
+ return declared?.[1] ?? "npm";
1061
+ }
1062
+ function sourceFiles(files, configPath) {
1063
+ return [...files.keys()].filter(
1064
+ (path) => SOURCE_FILE.test(path) && path !== configPath && !path.startsWith("node_modules/") && !path.includes("/node_modules/") && !PERF_CONFIG_NAMES.includes(path)
1065
+ ).sort();
1066
+ }
1067
+ function detectProject(files) {
1068
+ const configPath = PLAYWRIGHT_CONFIG_NAMES.find((name) => files.has(name)) ?? null;
1069
+ const configText = configPath === null ? "" : files.get(configPath);
1070
+ const pkg = parseJson(files.get("package.json"));
1071
+ const sources = sourceFiles(files, configPath);
1072
+ const text = (path) => files.get(path) ?? "";
1073
+ const moduleType = configPath?.endsWith(".mts") || configPath?.endsWith(".mjs") ? "esm" : configPath?.endsWith(".cts") || configPath?.endsWith(".cjs") ? "cjs" : pkg?.["type"] === "module" ? "esm" : "cjs";
1074
+ const baseUrls = [
1075
+ ...new Set(
1076
+ [...configText.matchAll(/\bbaseURL\s*:[^\n]*?(['"`])(https?:\/\/[^'"`\s]+)\1/gu)].flatMap(
1077
+ (m) => {
1078
+ try {
1079
+ return [new URL(m[2]).origin];
1080
+ } catch {
1081
+ return [];
1082
+ }
1083
+ }
1084
+ )
1085
+ )
1086
+ ];
1087
+ const projectNames = [
1088
+ ...new Set(
1089
+ [...configText.matchAll(/\bname\s*:\s*(['"`])([^'"`\n]+)\1/gu)].map((m) => m[2])
1090
+ )
1091
+ ];
1092
+ const scripts = pkg?.["scripts"];
1093
+ const paths = [...files.keys()];
1094
+ return {
1095
+ playwrightConfig: configPath === null ? null : { path: configPath, text: configText },
1096
+ playwrightVersion: playwrightVersion(files, pkg),
1097
+ packageManager: packageManagerOf(files, pkg),
1098
+ moduleType,
1099
+ testDir: testDirsOf(configText)[0],
1100
+ filesImportingPlaywrightTest: sources.filter((p) => IMPORTS_PLAYWRIGHT_TEST.test(text(p))),
1101
+ filesWithExtend: sources.filter((p) => text(p).search(EXTEND_CALL) !== -1),
1102
+ taggedPerfTestFiles: sources.filter((p) => PERF_TAG.test(text(p))).length,
1103
+ baseUrls,
1104
+ projectNames,
1105
+ ciPlatform: CI_MARKERS.find(([, test]) => paths.some(test))?.[0] ?? null,
1106
+ existing: {
1107
+ perfConfig: PERF_CONFIG_NAMES.find((name) => files.has(name)) ?? null,
1108
+ wrappedConfig: /\bwithPerf\s*\(/u.test(configText),
1109
+ wrappedTest: sources.some((p) => WRAPPED_TEST.test(text(p))),
1110
+ scripts: typeof scripts === "object" && scripts !== null ? Object.keys(scripts).sort() : []
1111
+ },
1112
+ files
1113
+ };
1114
+ }
1115
+
1116
+ // src/cli/init/defaults.ts
1117
+ var DEFAULT_ANSWERS_REPEAT = DEFAULT_CONFIG.run.repeat.test;
1118
+ function defaultLabel(origin, used) {
1119
+ const host = new URL(origin).hostname;
1120
+ const first = host.split(".")[0] ?? "";
1121
+ const base = /^[a-z][a-z0-9-]{0,63}$/u.test(first) && first !== "www" && first !== "localhost" && host.includes(".") ? first : "app";
1122
+ let label = base;
1123
+ for (let n = 2; used.has(label); n += 1) label = `${base}${n}`;
1124
+ return label;
1125
+ }
1126
+
1127
+ // src/cli/init/diff.ts
1128
+ var CONTEXT = 3;
1129
+ function lines(text) {
1130
+ if (text === "") return [];
1131
+ const parts = text.split("\n");
1132
+ if (parts[parts.length - 1] === "") parts.pop();
1133
+ return parts;
1134
+ }
1135
+ function operations(a, b) {
1136
+ let start = 0;
1137
+ while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
1138
+ let endA = a.length;
1139
+ let endB = b.length;
1140
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
1141
+ endA -= 1;
1142
+ endB -= 1;
1143
+ }
1144
+ const midA = a.slice(start, endA);
1145
+ const midB = b.slice(start, endB);
1146
+ const n = midA.length;
1147
+ const m = midB.length;
1148
+ const lcs = new Uint32Array((n + 1) * (m + 1));
1149
+ const at = (i2, j2) => lcs[i2 * (m + 1) + j2];
1150
+ for (let i2 = n - 1; i2 >= 0; i2 -= 1) {
1151
+ for (let j2 = m - 1; j2 >= 0; j2 -= 1) {
1152
+ 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));
1153
+ }
1154
+ }
1155
+ const ops = a.slice(0, start).map((line) => ({ kind: " ", line }));
1156
+ let i = 0;
1157
+ let j = 0;
1158
+ while (i < n || j < m) {
1159
+ if (i < n && j < m && midA[i] === midB[j]) {
1160
+ ops.push({ kind: " ", line: midA[i] });
1161
+ i += 1;
1162
+ j += 1;
1163
+ } else if (i < n && (j === m || at(i + 1, j) >= at(i, j + 1))) {
1164
+ ops.push({ kind: "-", line: midA[i] });
1165
+ i += 1;
1166
+ } else {
1167
+ ops.push({ kind: "+", line: midB[j] });
1168
+ j += 1;
1169
+ }
1170
+ }
1171
+ for (const line of a.slice(endA)) ops.push({ kind: " ", line });
1172
+ return ops;
1173
+ }
1174
+ function unifiedDiff(change2) {
1175
+ const before = change2.before ?? "";
1176
+ if (before === change2.after) return "";
1177
+ const ops = operations(lines(before), lines(change2.after));
1178
+ const out = [
1179
+ change2.before === null ? "--- /dev/null" : `--- a/${change2.path}`,
1180
+ `+++ b/${change2.path}`
1181
+ ];
1182
+ const changed = ops.flatMap((op, index) => op.kind === " " ? [] : [index]);
1183
+ let h = 0;
1184
+ while (h < changed.length) {
1185
+ const first = Math.max(0, changed[h] - CONTEXT);
1186
+ let last = Math.min(ops.length - 1, changed[h] + CONTEXT);
1187
+ h += 1;
1188
+ while (h < changed.length && changed[h] - CONTEXT <= last + 1) {
1189
+ last = Math.min(ops.length - 1, changed[h] + CONTEXT);
1190
+ h += 1;
1191
+ }
1192
+ let oldStart = 1;
1193
+ let newStart = 1;
1194
+ for (const op of ops.slice(0, first)) {
1195
+ if (op.kind !== "+") oldStart += 1;
1196
+ if (op.kind !== "-") newStart += 1;
1197
+ }
1198
+ const hunk = ops.slice(first, last + 1);
1199
+ const oldCount = hunk.filter((op) => op.kind !== "+").length;
1200
+ const newCount = hunk.filter((op) => op.kind !== "-").length;
1201
+ out.push(
1202
+ `@@ -${oldCount === 0 ? oldStart - 1 : oldStart},${oldCount} +${newCount === 0 ? newStart - 1 : newStart},${newCount} @@`
1203
+ );
1204
+ for (const op of hunk) out.push(`${op.kind}${op.line}`);
1205
+ }
1206
+ return `${out.join("\n")}
1207
+ `;
1208
+ }
1209
+
1210
+ // src/cli/init/files.ts
1211
+ var ROOT_FILES = /* @__PURE__ */ new Set([
1212
+ "package.json",
1213
+ ".gitignore",
1214
+ ".gitlab-ci.yml",
1215
+ "Jenkinsfile",
1216
+ "azure-pipelines.yml",
1217
+ ...PLAYWRIGHT_CONFIG_NAMES,
1218
+ ...PERF_CONFIG_NAMES
1219
+ ]);
1220
+ var ROOT_CI_FILE = /^(?:Jenkinsfile\.perf(?:-[a-z0-9-]+)?|azure-pipelines\.perf(?:-[a-z0-9-]+)?\.yml)$/u;
1221
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
1222
+ "node_modules",
1223
+ ".git",
1224
+ "dist",
1225
+ "build",
1226
+ "coverage",
1227
+ "test-results",
1228
+ "playwright-report",
1229
+ "blob-report",
1230
+ DEFAULT_CONFIG.report.dir
1231
+ ]);
1232
+ var MAX_DEPTH = 8;
1233
+ var MAX_FILES = 3e3;
1234
+ async function readProjectFiles(host, root) {
1235
+ const files = /* @__PURE__ */ new Map();
1236
+ const join3 = (rel) => host.paths.join(root, rel);
1237
+ const read = async (rel) => {
1238
+ const text = await host.readText(join3(rel));
1239
+ if (text !== null) files.set(rel, text);
1240
+ };
1241
+ for (const entry of await host.listDir(root)) {
1242
+ if (entry.directory) continue;
1243
+ if (Object.hasOwn(LOCKFILES, entry.name)) files.set(entry.name, "");
1244
+ else if (ROOT_FILES.has(entry.name) || ROOT_CI_FILE.test(entry.name)) await read(entry.name);
1245
+ }
1246
+ for (const dir of [".github", ".github/workflows", ".gitlab"]) {
1247
+ for (const entry of await host.listDir(join3(dir))) {
1248
+ if (!entry.directory && /\.ya?ml$/u.test(entry.name)) await read(`${dir}/${entry.name}`);
1249
+ }
1250
+ }
1251
+ const playwright = host.resolvePlaywright(root);
1252
+ if (playwright !== null)
1253
+ files.set(INSTALLED_PLAYWRIGHT, JSON.stringify({ version: playwright.version }));
1254
+ const config = PLAYWRIGHT_CONFIG_NAMES.find((name) => files.has(name));
1255
+ if (config === void 0) return files;
1256
+ let count = 0;
1257
+ const walk = async (rel, depth) => {
1258
+ if (depth > MAX_DEPTH || rel.split("/").includes("..")) return;
1259
+ for (const entry of await host.listDir(rel === "." ? root : join3(rel))) {
1260
+ if (count >= MAX_FILES) return;
1261
+ const path = rel === "." ? entry.name : `${rel}/${entry.name}`;
1262
+ if (entry.directory) {
1263
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) await walk(path, depth + 1);
1264
+ } else if (SOURCE_FILE.test(entry.name) && !files.has(path)) {
1265
+ count += 1;
1266
+ await read(path);
1267
+ }
1268
+ }
1269
+ };
1270
+ for (const dir of testDirsOf(files.get(config))) await walk(dir, 0);
1271
+ return files;
1272
+ }
1273
+
1274
+ // src/cli/init/generated/ci-templates.ts
1275
+ var CI_TEMPLATES = {
1276
+ /** examples/ci/github-actions.yml */
1277
+ 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",
1278
+ /** examples/ci/gitlab-ci.yml */
1279
+ 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',
1280
+ /** examples/ci/Jenkinsfile */
1281
+ jenkins: `// Performance measurement run with playwright-performance-regression (pw-perf).
1282
+ // Use as the script of a pipeline job, e.g. "Jenkinsfile.perf". Exit code 2 (performance
1283
+ // regression) marks the build UNSTABLE, 3 (tool or config error) fails it. The report in
1284
+ // perf-results/ is archived also when the run fails.
1285
+ pipeline {
1286
+ agent any
1287
+ options {
1288
+ timeout(time: 60, unit: 'MINUTES')
1289
+ }
1290
+ triggers {
1291
+ cron('H 3 * * *')
1292
+ }
1293
+ stages {
1294
+ stage('Performance') {
1295
+ steps {
1296
+ sh 'npm ci'
1297
+ sh 'npx playwright install --with-deps chromium'
1298
+ script {
1299
+ def code = sh(script: 'npx pw-perf test', returnStatus: true)
1300
+ if (code == 2) {
1301
+ unstable('Performance regression (exit code 2)')
1302
+ } else if (code != 0) {
1303
+ error("Measurement run failed with exit code \${code}")
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ post {
1310
+ always {
1311
+ archiveArtifacts artifacts: 'perf-results/**', allowEmptyArchive: true
1312
+ }
1313
+ }
1314
+ }
1315
+ `,
1316
+ /** examples/ci/azure-pipelines.yml */
1317
+ azure: `# Performance measurement run with playwright-performance-regression (pw-perf).
1318
+ # Register as its own pipeline, e.g. azure-pipelines.perf.yml. Runs on pull requests and every
1319
+ # night. Exit code 2 (performance regression) ends the job as "succeeded with issues", 3 (tool or
1320
+ # config error) fails it. The report in perf-results/ is published also when the run fails.
1321
+ trigger: none
1322
+
1323
+ pr:
1324
+ branches:
1325
+ include:
1326
+ - '*'
1327
+
1328
+ schedules:
1329
+ - cron: '0 3 * * *'
1330
+ displayName: Nightly measurement run
1331
+ branches:
1332
+ include:
1333
+ - main
1334
+ always: true
1335
+
1336
+ pool:
1337
+ vmImage: ubuntu-latest
1338
+
1339
+ jobs:
1340
+ - job: perf
1341
+ timeoutInMinutes: 60
1342
+ steps:
1343
+ - task: NodeTool@0
1344
+ inputs:
1345
+ versionSpec: '22.x'
1346
+ - script: npm ci
1347
+ displayName: Install dependencies
1348
+ - script: npx playwright install --with-deps chromium
1349
+ displayName: Install Chromium
1350
+ - bash: |
1351
+ code=0
1352
+ npx pw-perf test || code=$?
1353
+ if [ "$code" -eq 2 ]; then
1354
+ echo "##vso[task.complete result=SucceededWithIssues;]Performance regression (exit code 2)"
1355
+ exit 0
1356
+ fi
1357
+ exit $code
1358
+ displayName: Measurement run
1359
+ - publish: perf-results
1360
+ artifact: perf-results
1361
+ condition: always()
1362
+ displayName: Publish the performance report
1363
+ `
1364
+ };
1365
+
1366
+ // src/cli/init/ci.ts
1367
+ var CI_COMMAND = "npx pw-perf test";
1368
+ var suffix = (label) => label === null ? "" : `-${label}`;
1369
+ var CI_TARGETS = {
1370
+ github: {
1371
+ path: (label) => `.github/workflows/perf${suffix(label)}.yml`,
1372
+ rename: (text, label) => text.replace(/^name: Performance$/mu, `name: Performance (${label})`)
1373
+ },
1374
+ gitlab: {
1375
+ path: (label) => `.gitlab/perf${suffix(label)}.gitlab-ci.yml`,
1376
+ rename: (text, label) => text.replace(/^perf:$/mu, `perf-${label}:`)
1377
+ },
1378
+ jenkins: { path: (label) => `Jenkinsfile.perf${suffix(label)}`, rename: (text) => text },
1379
+ azure: { path: (label) => `azure-pipelines.perf${suffix(label)}.yml`, rename: (text) => text }
1380
+ };
1381
+ function commandFlags(scope, label) {
1382
+ return `${scope === "tagged" ? " --grep @perf" : ""}${label === null ? "" : ` --env ${label}`}`;
1383
+ }
1384
+ function ciFiles(platform, scope, envLabels) {
1385
+ const target = CI_TARGETS[platform];
1386
+ const template = CI_TEMPLATES[platform];
1387
+ const labels = envLabels.length === 0 ? [null] : [...envLabels];
1388
+ return labels.map((label) => {
1389
+ let text = template.replace(CI_COMMAND, `${CI_COMMAND}${commandFlags(scope, label)}`);
1390
+ if (label !== null) text = target.rename(text, label);
1391
+ return { path: target.path(label), text };
1392
+ });
1393
+ }
1394
+
1395
+ // src/cli/init/perf-config.ts
1396
+ function ts(value) {
1397
+ if (typeof value === "string")
1398
+ return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
1399
+ if (Array.isArray(value)) return `[${value.map(ts).join(", ")}]`;
1400
+ if (typeof value === "object" && value !== null) {
1401
+ const entries = Object.entries(value).map(
1402
+ ([k, v]) => `${/^[A-Za-z_$][\w$]*$/u.test(k) ? k : ts(k)}: ${ts(v)}`
1403
+ );
1404
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
1405
+ }
1406
+ return String(value);
1407
+ }
1408
+ function renderPerfConfig(answers) {
1409
+ const d = DEFAULT_CONFIG;
1410
+ const body = [];
1411
+ const origins = Object.entries(answers.originLabels);
1412
+ if (origins.length > 0) {
1413
+ body.push(
1414
+ " keys: {",
1415
+ " // Labels of the backend origins in the endpoint keys.",
1416
+ " origins: {"
1417
+ );
1418
+ for (const [origin, label] of origins) body.push(` ${ts(origin)}: ${ts(label)},`);
1419
+ body.push(" },", " },");
1420
+ }
1421
+ if (answers.repeatTest !== d.run.repeat.test) {
1422
+ body.push(
1423
+ " run: {",
1424
+ ` // Repetitions per test in measurement runs (default ${d.run.repeat.test}).`,
1425
+ ` repeat: { test: ${answers.repeatTest} },`,
1426
+ " },"
1427
+ );
1428
+ }
1429
+ if (answers.warnOnly !== d.gate.warnOnly) {
1430
+ body.push(
1431
+ " gate: {",
1432
+ answers.warnOnly ? " // Report regressions without failing the run; remove after the first weeks." : " // Fail the run on a regression.",
1433
+ ` warnOnly: ${answers.warnOnly},`,
1434
+ " },"
1435
+ );
1436
+ }
1437
+ if (body.length > 0) body.push("");
1438
+ body.push(
1439
+ " // Options changed most often, with their default values:",
1440
+ ` // run: ${ts({ repeat: d.run.repeat, projects: d.run.projects, keepReporters: d.run.keepReporters })},`,
1441
+ ` // measure: ${ts({ exclude: d.measure.exclude })},`,
1442
+ ` // gate: ${ts({ warnOnly: d.gate.warnOnly, tolerance: d.gate.tolerance, maxFailedTestShare: d.gate.maxFailedTestShare })},`,
1443
+ ` // thresholds: ${ts({ dir: d.thresholds.dir })},`,
1444
+ ` // report: ${ts({ dir: d.report.dir })},`
1445
+ );
1446
+ return [
1447
+ `// Configuration of ${PACKAGE_NAME}, written by "npx pw-perf init".`,
1448
+ "// Only the values that differ from the defaults are set. All options:",
1449
+ `// ${DOCS_CONFIG_URL}`,
1450
+ `import { definePerfConfig } from '${PACKAGE_NAME}';`,
1451
+ "",
1452
+ "export default definePerfConfig({",
1453
+ ...body,
1454
+ "});",
1455
+ ""
1456
+ ].join("\n");
1457
+ }
1458
+
1459
+ // src/cli/init/scan.ts
1460
+ var OPEN = { "(": ")", "[": "]", "{": "}" };
1461
+ var CLOSE = /* @__PURE__ */ new Set([")", "]", "}"]);
1462
+ var REGEX_BEFORE = /* @__PURE__ */ new Set([
1463
+ "",
1464
+ "(",
1465
+ ",",
1466
+ "=",
1467
+ ":",
1468
+ "[",
1469
+ "!",
1470
+ "&",
1471
+ "|",
1472
+ "?",
1473
+ "{",
1474
+ "}",
1475
+ ";",
1476
+ "+",
1477
+ "-",
1478
+ "*",
1479
+ "%",
1480
+ "<",
1481
+ ">",
1482
+ "~",
1483
+ "^"
1484
+ ]);
1485
+ function skipString(text, i) {
1486
+ const quote = text[i];
1487
+ let j = i + 1;
1488
+ while (j < text.length) {
1489
+ const c = text[j];
1490
+ if (c === "\\") {
1491
+ j += 2;
1492
+ continue;
1493
+ }
1494
+ if (c === quote) return j + 1;
1495
+ if (quote === "`" && c === "$" && text[j + 1] === "{") {
1496
+ const end = matchBracket(text, j + 1);
1497
+ if (end === -1) return text.length;
1498
+ j = end;
1499
+ continue;
1500
+ }
1501
+ if (quote !== "`" && c === "\n") return j;
1502
+ j += 1;
1503
+ }
1504
+ return text.length;
1505
+ }
1506
+ function skipRegex(text, i) {
1507
+ let j = i + 1;
1508
+ let inClass = false;
1509
+ while (j < text.length) {
1510
+ const c = text[j];
1511
+ if (c === "\\") {
1512
+ j += 2;
1513
+ continue;
1514
+ }
1515
+ if (c === "\n") return j;
1516
+ if (inClass) {
1517
+ if (c === "]") inClass = false;
1518
+ } else if (c === "[") {
1519
+ inClass = true;
1520
+ } else if (c === "/") {
1521
+ j += 1;
1522
+ while (j < text.length && /[a-z]/u.test(text[j])) j += 1;
1523
+ return j;
1524
+ }
1525
+ j += 1;
1526
+ }
1527
+ return text.length;
1528
+ }
1529
+ function skipNonCode(text, i, previous) {
1530
+ const c = text[i];
1531
+ const next = text[i + 1];
1532
+ if (c === "/" && next === "/") {
1533
+ const end = text.indexOf("\n", i);
1534
+ return end === -1 ? text.length : end;
1535
+ }
1536
+ if (c === "/" && next === "*") {
1537
+ const end = text.indexOf("*/", i + 2);
1538
+ return end === -1 ? text.length : end + 2;
1539
+ }
1540
+ if (c === '"' || c === "'" || c === "`") return skipString(text, i);
1541
+ if (c === "/" && REGEX_BEFORE.has(previous)) return skipRegex(text, i);
1542
+ return i;
1543
+ }
1544
+ function matchBracket(text, open) {
1545
+ const stack = [];
1546
+ let previous = "";
1547
+ let i = open;
1548
+ while (i < text.length) {
1549
+ const skipped = skipNonCode(text, i, previous);
1550
+ if (skipped !== i) {
1551
+ i = skipped;
1552
+ previous = "x";
1553
+ continue;
1554
+ }
1555
+ const c = text[i];
1556
+ if (OPEN[c] !== void 0) {
1557
+ stack.push(OPEN[c]);
1558
+ } else if (CLOSE.has(c)) {
1559
+ if (stack.pop() !== c) return -1;
1560
+ if (stack.length === 0) return i + 1;
1561
+ }
1562
+ if (!/\s/u.test(c)) previous = /[\w$]/u.test(c) ? "x" : c;
1563
+ i += 1;
1564
+ }
1565
+ return -1;
1566
+ }
1567
+ function callParen(text, from) {
1568
+ let i = from;
1569
+ while (/\s/u.test(text[i] ?? "")) i += 1;
1570
+ if (text[i] === "<") {
1571
+ let depth = 0;
1572
+ for (; i < text.length; i += 1) {
1573
+ const c = text[i];
1574
+ if (c === "<" || c === "{" || c === "(" || c === "[") depth += 1;
1575
+ else if (c === "}" || c === ")" || c === "]") depth -= 1;
1576
+ else if (c === ">" && text[i - 1] !== "=") {
1577
+ depth -= 1;
1578
+ if (depth === 0) break;
1579
+ }
1580
+ }
1581
+ i += 1;
1582
+ while (/\s/u.test(text[i] ?? "")) i += 1;
1583
+ }
1584
+ return text[i] === "(" ? i : -1;
1585
+ }
1586
+ function onlyTrailing(text, i) {
1587
+ let semicolon = false;
1588
+ let j = i;
1589
+ while (j < text.length) {
1590
+ const c = text[j];
1591
+ if (/\s/u.test(c)) {
1592
+ j += 1;
1593
+ } else if (c === ";" && !semicolon) {
1594
+ semicolon = true;
1595
+ j += 1;
1596
+ } else if (c === "/" && (text[j + 1] === "/" || text[j + 1] === "*")) {
1597
+ j = skipNonCode(text, j, "");
1598
+ } else {
1599
+ return false;
1600
+ }
1601
+ }
1602
+ return true;
1603
+ }
1604
+ function statementEnds(text, i) {
1605
+ return /^[ \t]*(?:;|\r?\n|$|\/\/)/u.test(text.slice(i, i + 200));
1606
+ }
1607
+ var IMPORT_DONE = /(?:\bfrom\s*(['"])[^'"\n]+\1|^\s*import\s*(['"])[^'"\n]+\2)\s*;?\s*$/u;
1608
+ var REQUIRE_DONE = /\brequire\(\s*(['"])[^'"\n]+\1\s*\)(?:\.[\w$]+)*\s*;?\s*$/u;
1609
+ function importInsertOffset(text) {
1610
+ let offset = 0;
1611
+ let lastImportEnd = -1;
1612
+ let leadingEnd = 0;
1613
+ let seenCode = false;
1614
+ let inComment = false;
1615
+ let pending = null;
1616
+ for (const line of text.split("\n")) {
1617
+ const start = offset;
1618
+ const end = Math.min(offset + line.length + 1, text.length);
1619
+ offset += line.length + 1;
1620
+ const trimmed = line.trim();
1621
+ if (pending !== null) {
1622
+ pending.text += `
1623
+ ${line}`;
1624
+ if (pending.done.test(pending.text)) {
1625
+ pending = null;
1626
+ lastImportEnd = end;
1627
+ }
1628
+ continue;
1629
+ }
1630
+ const header = !seenCode;
1631
+ if (inComment || trimmed.startsWith("//") || trimmed.startsWith("/*")) {
1632
+ if (inComment) inComment = !trimmed.includes("*/");
1633
+ else if (trimmed.startsWith("/*")) inComment = !trimmed.includes("*/");
1634
+ if (header) leadingEnd = end;
1635
+ continue;
1636
+ }
1637
+ if (trimmed === "") continue;
1638
+ if (/^['"]use strict['"];?$/u.test(trimmed)) {
1639
+ leadingEnd = end;
1640
+ continue;
1641
+ }
1642
+ let done = null;
1643
+ if (/^import[\s{'"*]/u.test(trimmed)) done = IMPORT_DONE;
1644
+ else if (/^(?:const|let|var)\b/u.test(trimmed) && /\brequire\(\s*['"]/u.test(text.slice(start, end + 300).split(";")[0] ?? "")) {
1645
+ done = REQUIRE_DONE;
1646
+ }
1647
+ if (done === null) break;
1648
+ seenCode = true;
1649
+ if (done.test(line)) lastImportEnd = end;
1650
+ else pending = { done, text: line };
1651
+ }
1652
+ return lastImportEnd >= 0 ? lastImportEnd : leadingEnd;
1653
+ }
1654
+ function addImports(text, lines2) {
1655
+ if (lines2.length === 0) return text;
1656
+ const at = importInsertOffset(text);
1657
+ const before = text.slice(0, at);
1658
+ const block = `${lines2.join("\n")}
1659
+ `;
1660
+ const sep = before === "" || before.endsWith("\n") ? "" : "\n";
1661
+ return `${before}${sep}${block}${text.slice(at)}`;
1662
+ }
1663
+
1664
+ // src/cli/init/patterns.ts
1665
+ function wrapPlaywrightConfig(text, perfImport) {
1666
+ const esm = [...text.matchAll(/^export\s+default\s+/gmu)];
1667
+ const cjs = [...text.matchAll(/^module\.exports\s*=\s*/gmu)];
1668
+ if (esm.length + cjs.length !== 1) return null;
1669
+ const isEsm = esm.length === 1;
1670
+ const match = isEsm ? esm[0] : cjs[0];
1671
+ const start = match.index + match[0].length;
1672
+ const rest = text.slice(start);
1673
+ let open;
1674
+ if (rest.startsWith("{")) open = start;
1675
+ else {
1676
+ const call = /^defineConfig\s*/u.exec(rest);
1677
+ if (call === null) return null;
1678
+ open = callParen(text, start + "defineConfig".length);
1679
+ }
1680
+ if (open === -1) return null;
1681
+ const end = matchBracket(text, open);
1682
+ if (end === -1 || !onlyTrailing(text, end)) return null;
1683
+ const value = text.slice(start, end);
1684
+ const perfConfig = isEsm ? "perfConfig" : `require('${perfImport}').default`;
1685
+ const wrapped = `${text.slice(0, start)}withPerf(${value}, ${perfConfig})${text.slice(end)}`;
1686
+ return addImports(
1687
+ wrapped,
1688
+ isEsm ? [
1689
+ `import { withPerf } from '${PACKAGE_NAME}/config';`,
1690
+ `import perfConfig from '${perfImport}';`
1691
+ ] : [`const { withPerf } = require('${PACKAGE_NAME}/config');`]
1692
+ );
1693
+ }
1694
+ function wrapTestObject(text) {
1695
+ const esm = /^export\s+const\s+test\s*=\s*([\w$.]+)\.extend\b/mu.exec(text);
1696
+ const cjs = /^(?:module\.)?exports\.test\s*=\s*([\w$.]+)\.extend\b/mu.exec(text);
1697
+ const match = esm ?? cjs;
1698
+ if (match === null || esm !== null && cjs !== null) return null;
1699
+ const exprStart = match.index + match[0].length - match[1].length - ".extend".length;
1700
+ const open = callParen(text, match.index + match[0].length);
1701
+ if (open === -1) return null;
1702
+ const end = matchBracket(text, open);
1703
+ if (end === -1 || !statementEnds(text, end)) return null;
1704
+ const wrapped = `${text.slice(0, exprStart)}withPerfFixtures(${text.slice(exprStart, end)})${text.slice(end)}`;
1705
+ return addImports(wrapped, [
1706
+ esm !== null ? `import { withPerfFixtures } from '${PACKAGE_NAME}/fixture';` : `const { withPerfFixtures } = require('${PACKAGE_NAME}/fixture');`
1707
+ ]);
1708
+ }
1709
+ function specifiers(list, separator) {
1710
+ const result = [];
1711
+ for (const raw of list.split(",")) {
1712
+ const text = raw.trim();
1713
+ if (text === "") continue;
1714
+ const pattern = separator === "as" ? /^(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?$/u : /^()([\w$]+)(?:\s*:\s*([\w$]+))?$/u;
1715
+ const m = pattern.exec(text);
1716
+ if (m === null) return null;
1717
+ result.push({
1718
+ text,
1719
+ name: m[2],
1720
+ alias: m[3] ?? null,
1721
+ type: m[1] !== void 0 && m[1] !== ""
1722
+ });
1723
+ }
1724
+ return result;
1725
+ }
1726
+ var SWAPPED = /* @__PURE__ */ new Set(["test", "expect"]);
1727
+ function swapTestImport(text) {
1728
+ let changed = false;
1729
+ const esm = text.replace(
1730
+ /^import\s*\{([^}]*)\}\s*from\s*(['"])@playwright\/test\2(\s*;)?/gmu,
1731
+ (whole, list, quote, semi) => {
1732
+ const specs = specifiers(list, "as");
1733
+ if (specs === null || !specs.some((s) => s.name === "test" && s.alias === null && !s.type)) {
1734
+ return whole;
1735
+ }
1736
+ const swap = specs.filter((s) => SWAPPED.has(s.name) && s.alias === null && !s.type);
1737
+ const keep = specs.filter((s) => !swap.includes(s));
1738
+ changed = true;
1739
+ const end = semi === void 0 ? "" : ";";
1740
+ const lines2 = [
1741
+ `import { ${swap.map((s) => s.text).join(", ")} } from ${quote}${PACKAGE_NAME}/test${quote}${end}`
1742
+ ];
1743
+ if (keep.length > 0) {
1744
+ lines2.push(
1745
+ `import { ${keep.map((s) => s.text).join(", ")} } from ${quote}@playwright/test${quote}${end}`
1746
+ );
1747
+ }
1748
+ return lines2.join("\n");
1749
+ }
1750
+ );
1751
+ const cjs = esm.replace(
1752
+ /^(const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*(['"])@playwright\/test\3\s*\)(\s*;)?/gmu,
1753
+ (whole, kind, list, quote, semi) => {
1754
+ const specs = specifiers(list, ":");
1755
+ if (specs === null || !specs.some((s) => s.name === "test" && s.alias === null)) return whole;
1756
+ const swap = specs.filter((s) => SWAPPED.has(s.name) && s.alias === null);
1757
+ const keep = specs.filter((s) => !swap.includes(s));
1758
+ changed = true;
1759
+ const end = semi === void 0 ? "" : ";";
1760
+ const lines2 = [
1761
+ `${kind} { ${swap.map((s) => s.text).join(", ")} } = require(${quote}${PACKAGE_NAME}/test${quote})${end}`
1762
+ ];
1763
+ if (keep.length > 0) {
1764
+ lines2.push(
1765
+ `${kind} { ${keep.map((s) => s.text).join(", ")} } = require(${quote}@playwright/test${quote})${end}`
1766
+ );
1767
+ }
1768
+ return lines2.join("\n");
1769
+ }
1770
+ );
1771
+ return changed ? cjs : null;
1772
+ }
1773
+ function ignores(gitignore, dir) {
1774
+ return gitignore.split(/\r?\n/u).some((line) => line.trim().replace(/^\//u, "").replace(/\/$/u, "") === dir);
1775
+ }
1776
+ function addIgnore(gitignore, dir) {
1777
+ if (gitignore === null || gitignore === "") return `${dir}/
1778
+ `;
1779
+ const nl = gitignore.includes("\r\n") ? "\r\n" : "\n";
1780
+ return `${gitignore}${gitignore.endsWith("\n") ? "" : nl}${dir}/${nl}`;
1781
+ }
1782
+ function addScripts(text, scripts) {
1783
+ let pkg;
1784
+ try {
1785
+ pkg = JSON.parse(text);
1786
+ } catch {
1787
+ return null;
1788
+ }
1789
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) return null;
1790
+ const obj = pkg;
1791
+ const current = obj["scripts"];
1792
+ if (current !== void 0 && (typeof current !== "object" || current === null || Array.isArray(current))) {
1793
+ return null;
1794
+ }
1795
+ obj["scripts"] = { ...current, ...scripts };
1796
+ const indent = /^[ \t]+(?=")/mu.exec(text)?.[0] ?? " ";
1797
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
1798
+ const json = JSON.stringify(obj, null, indent).replaceAll("\n", nl);
1799
+ return /\r?\n$/u.test(text) ? `${json}${nl}` : json;
1800
+ }
1801
+
1802
+ // src/cli/init/plan.ts
1803
+ var PERF_CONFIG_FILE = "pw-perf.config.ts";
1804
+ function plannedScripts(answers) {
1805
+ const labels = answers.envLabels.length === 0 ? [null] : answers.envLabels;
1806
+ const scripts = {};
1807
+ for (const label of labels) {
1808
+ const name = label === null ? "" : `:${label}`;
1809
+ const flags = commandFlags(answers.scope, label);
1810
+ scripts[`perf:test${name}`] = `pw-perf test${flags}`;
1811
+ scripts[`perf:thresholds${name}`] = `pw-perf thresholds${flags}`;
1812
+ }
1813
+ return scripts;
1814
+ }
1815
+ function manual(message2, hint) {
1816
+ return { code: "INIT_MANUAL_STEP", message: message2, hint };
1817
+ }
1818
+ function change(info, path, after) {
1819
+ const before = info.files.get(path) ?? null;
1820
+ if (before === after) return null;
1821
+ return { path, kind: before === null ? "create" : "modify", before, after };
1822
+ }
1823
+ var CONFIG_HINT = (t, path) => [
1824
+ t("configHintIntro"),
1825
+ ` import { withPerf } from '${PACKAGE_NAME}/config';`,
1826
+ ` import perfConfig from './pw-perf.config';`,
1827
+ ` export default withPerf(otherWrapper(defineConfig({ ... })), perfConfig);`,
1828
+ t("configHintCjs", { path, call: "withPerf(config, require('./pw-perf.config').default)" })
1829
+ ].join("\n");
1830
+ var TEST_HINT = (t) => [
1831
+ t("testHintIntro", { entry: `${PACKAGE_NAME}/fixture` }),
1832
+ " export const test = withPerfFixtures(base.extend({ ... }));",
1833
+ " export const adminTest = withPerfFixtures(test.extend({ ... }));",
1834
+ " export const merged = withPerfFixtures(mergeTests(a, b));",
1835
+ t("testHintMerge"),
1836
+ t("testHintImport", { entry: `${PACKAGE_NAME}/test` })
1837
+ ].join("\n");
1838
+ function planPerfConfig(info, answers, plan, t) {
1839
+ const existing = info.existing.perfConfig;
1840
+ if (existing === null || existing === PERF_CONFIG_FILE) {
1841
+ const c = change(info, PERF_CONFIG_FILE, renderPerfConfig(answers));
1842
+ if (c !== null) plan.changes.push(c);
1843
+ return;
1844
+ }
1845
+ const values = [
1846
+ ...Object.entries(answers.originLabels).map(([o, l]) => `keys.origins["${o}"] = "${l}"`),
1847
+ ...answers.repeatTest === DEFAULT_CONFIG.run.repeat.test ? [] : [`run.repeat.test = ${answers.repeatTest}`],
1848
+ ...answers.warnOnly === DEFAULT_CONFIG.gate.warnOnly ? [] : [`gate.warnOnly = ${answers.warnOnly}`]
1849
+ ];
1850
+ if (values.length > 0) {
1851
+ plan.manualSteps.push(
1852
+ manual(
1853
+ t("manualPerfConfigKept", { file: existing }),
1854
+ `${t("manualPerfConfigHint")}
1855
+ ${values.map((v) => ` ${v}`).join("\n")}`
1856
+ )
1857
+ );
1858
+ }
1859
+ }
1860
+ function planPlaywrightConfig(info, plan, t) {
1861
+ const config = info.playwrightConfig;
1862
+ if (config === null || info.existing.wrappedConfig) return;
1863
+ const existing = info.existing.perfConfig;
1864
+ if (existing !== null && existing.endsWith(".json")) {
1865
+ plan.manualSteps.push(
1866
+ manual(
1867
+ t("manualConfigJson", { config: config.path, file: existing }),
1868
+ CONFIG_HINT(t, config.path).replaceAll("'./pw-perf.config'", `'./${existing}'`)
1869
+ )
1870
+ );
1871
+ return;
1872
+ }
1873
+ const after = wrapPlaywrightConfig(config.text, "./pw-perf.config");
1874
+ if (after === null) {
1875
+ plan.manualSteps.push(
1876
+ manual(t("manualConfigPattern", { config: config.path }), CONFIG_HINT(t, config.path))
1877
+ );
1878
+ return;
1879
+ }
1880
+ plan.changes.push({ path: config.path, kind: "modify", before: config.text, after });
1881
+ }
1882
+ function planTestObject(info, plan, t) {
1883
+ if (info.existing.wrappedTest) return;
1884
+ const text = (path) => info.files.get(path) ?? "";
1885
+ const extendFiles = info.filesWithExtend;
1886
+ const merges = [...info.files.keys()].filter(
1887
+ (p) => info.filesImportingPlaywrightTest.includes(p) && /\bmergeTests\s*\(/u.test(text(p))
1888
+ );
1889
+ if (extendFiles.length === 0 && merges.length === 0) {
1890
+ const swaps = info.filesImportingPlaywrightTest.flatMap((path) => {
1891
+ const after2 = swapTestImport(text(path));
1892
+ return after2 === null ? [] : [{ path, kind: "modify", before: text(path), after: after2 }];
1893
+ });
1894
+ if (swaps.length === 0) {
1895
+ plan.manualSteps.push(manual(t("manualNoTestObject"), TEST_HINT(t)));
1896
+ }
1897
+ plan.changes.push(...swaps);
1898
+ return;
1899
+ }
1900
+ const only = extendFiles.length === 1 && merges.length === 0 ? extendFiles[0] : null;
1901
+ const after = only !== null && [...text(only).matchAll(EXTEND_CALL)].length === 1 ? wrapTestObject(text(only)) : null;
1902
+ if (only === null || after === null) {
1903
+ const files = [.../* @__PURE__ */ new Set([...extendFiles, ...merges])].sort();
1904
+ plan.manualSteps.push(
1905
+ manual(
1906
+ `${t(files.length === 1 ? "manualTestObjectOne" : "manualTestObjectMany", {
1907
+ files: files.join(", ")
1908
+ })} ${t("testObjectsReason")}`,
1909
+ TEST_HINT(t)
1910
+ )
1911
+ );
1912
+ return;
1913
+ }
1914
+ plan.changes.push({ path: only, kind: "modify", before: text(only), after });
1915
+ }
1916
+ function planGitignore(info, plan) {
1917
+ const dir = DEFAULT_CONFIG.report.dir;
1918
+ const current = info.files.get(".gitignore") ?? null;
1919
+ if (current !== null && ignores(current, dir)) return;
1920
+ const c = change(info, ".gitignore", addIgnore(current, dir));
1921
+ if (c !== null) plan.changes.push(c);
1922
+ }
1923
+ function planScripts(info, answers, plan, t) {
1924
+ const text = info.files.get("package.json");
1925
+ const wanted = plannedScripts(answers);
1926
+ if (text === void 0) {
1927
+ plan.manualSteps.push(
1928
+ manual(
1929
+ t("manualNoPackageJson"),
1930
+ `${t("addScripts")}
1931
+ ${Object.entries(wanted).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1932
+ )
1933
+ );
1934
+ return;
1935
+ }
1936
+ let current = {};
1937
+ try {
1938
+ const scripts = JSON.parse(text).scripts;
1939
+ if (typeof scripts === "object" && scripts !== null)
1940
+ current = scripts;
1941
+ } catch {
1942
+ }
1943
+ const added = {};
1944
+ for (const [name, command] of Object.entries(wanted)) {
1945
+ if (current[name] === void 0) added[name] = command;
1946
+ else if (current[name] !== command) {
1947
+ plan.manualSteps.push(
1948
+ manual(t("manualScriptExists", { name }), t("manualScriptHint", { name, command }))
1949
+ );
1950
+ }
1951
+ }
1952
+ if (Object.keys(added).length === 0) return;
1953
+ const after = addScripts(text, added);
1954
+ if (after === null) {
1955
+ plan.manualSteps.push(
1956
+ manual(
1957
+ t("manualPackageJsonInvalid"),
1958
+ `${t("addScripts")}
1959
+ ${Object.entries(added).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1960
+ )
1961
+ );
1962
+ return;
1963
+ }
1964
+ plan.changes.push({ path: "package.json", kind: "modify", before: text, after });
1965
+ }
1966
+ var INSTALL = {
1967
+ npm: "npm ci",
1968
+ pnpm: "pnpm install --frozen-lockfile",
1969
+ yarn: "yarn install --immutable"
1970
+ };
1971
+ function planCi(info, answers, plan, t) {
1972
+ const platform = info.ciPlatform;
1973
+ if (!answers.addCi || platform === null) return;
1974
+ const created = [];
1975
+ for (const file of ciFiles(platform, answers.scope, answers.envLabels)) {
1976
+ const before = info.files.get(file.path) ?? null;
1977
+ if (before === file.text) continue;
1978
+ if (before !== null) {
1979
+ plan.manualSteps.push(
1980
+ manual(t("manualCiKept", { file: file.path }), t("manualCiHint", { pkg: PACKAGE_NAME }))
1981
+ );
1982
+ continue;
1983
+ }
1984
+ plan.changes.push({ path: file.path, kind: "create", before: null, after: file.text });
1985
+ created.push(file.path);
1986
+ }
1987
+ if (platform === "gitlab") {
1988
+ const main2 = info.files.get(".gitlab-ci.yml") ?? "";
1989
+ const missing = ciFiles(platform, answers.scope, answers.envLabels).map((f) => f.path).filter((p) => !main2.includes(p));
1990
+ if (missing.length > 0) {
1991
+ plan.manualSteps.push(
1992
+ manual(
1993
+ t("manualGitlabInclude"),
1994
+ ["include:", ...missing.map((p) => ` - local: ${p}`)].join("\n")
1995
+ )
1996
+ );
1997
+ }
1998
+ }
1999
+ if (created.length > 0 && info.packageManager !== "npm") {
2000
+ plan.manualSteps.push(
2001
+ manual(
2002
+ t(created.length === 1 ? "manualNpmOne" : "manualNpmMany", { files: created.join(", ") }),
2003
+ t("manualNpmHint", {
2004
+ manager: info.packageManager,
2005
+ install: INSTALL[info.packageManager],
2006
+ npx: info.packageManager === "pnpm" ? "pnpm exec" : "yarn"
2007
+ })
2008
+ )
2009
+ );
2010
+ }
2011
+ }
2012
+ function planInitChanges(info, answers, lang = "en") {
2013
+ const t = translator(lang);
2014
+ const plan = { changes: [], manualSteps: [] };
2015
+ planPerfConfig(info, answers, plan, t);
2016
+ planPlaywrightConfig(info, plan, t);
2017
+ planTestObject(info, plan, t);
2018
+ planGitignore(info, plan);
2019
+ planScripts(info, answers, plan, t);
2020
+ planCi(info, answers, plan, t);
2021
+ return plan;
2022
+ }
2023
+ function isProtected(info, path) {
2024
+ return PERF_CONFIG_NAMES.includes(path) && info.existing.perfConfig === path;
2025
+ }
2026
+ var PromptAborted = class extends Error {
2027
+ constructor() {
2028
+ super("interrupted");
2029
+ this.name = "PromptAborted";
2030
+ }
2031
+ };
2032
+ function readlinePrompt(input, output, terminal) {
2033
+ const rl = createInterface({ input, output, ...{} });
2034
+ const controller = new AbortController();
2035
+ let closed = false;
2036
+ rl.on("SIGINT", () => controller.abort());
2037
+ rl.on("close", () => {
2038
+ closed = true;
2039
+ controller.abort();
2040
+ });
2041
+ return {
2042
+ async ask(question) {
2043
+ if (controller.signal.aborted) throw new PromptAborted();
2044
+ try {
2045
+ return await rl.question(question, { signal: controller.signal });
2046
+ } catch (error) {
2047
+ if (controller.signal.aborted) {
2048
+ output.write("\n");
2049
+ throw new PromptAborted();
2050
+ }
2051
+ throw error;
2052
+ }
2053
+ },
2054
+ close() {
2055
+ if (!closed) rl.close();
2056
+ }
2057
+ };
2058
+ }
2059
+
2060
+ // src/cli/output.ts
2061
+ var PREFIX = `${PACKAGE_NAME}: `;
2062
+ function outputStyle(stream, env) {
2063
+ return { color: colorEnabled(stream, env) };
2064
+ }
2065
+ function paint2(text, style2, opts) {
2066
+ return paint(text, style2, opts.color);
2067
+ }
2068
+ function infoLine(text) {
2069
+ return `${PREFIX}${text}
2070
+ `;
2071
+ }
2072
+ function formatIssue(issue, level, opts) {
2073
+ const label = paint2(`${level} ${issue.code}`, level === "error" ? "red" : "yellow", opts);
2074
+ const lines2 = [`${PREFIX}${label}: ${issue.message}`];
2075
+ if (issue.hint !== void 0) {
2076
+ for (const line of issue.hint.split("\n")) lines2.push(` ${line}`);
2077
+ }
2078
+ return `${lines2.join("\n")}
2079
+ `;
2080
+ }
2081
+ function formatIssues(issues, level, opts) {
2082
+ return issues.map((issue) => formatIssue(issue, level, opts)).join("");
2083
+ }
2084
+ var TESTS_TEXT = {
2085
+ passed: "tests passed",
2086
+ failed: "tests failed",
2087
+ timedout: "tests timed out",
2088
+ interrupted: "tests interrupted"
2089
+ };
2090
+ var EVALUATION_TEXT = {
2091
+ passed: "performance passed",
2092
+ warned: "performance passed with warnings",
2093
+ failed: "performance failed",
2094
+ error: "performance not evaluated"
2095
+ };
2096
+ function resultLines(outcome, exitCode, opts) {
2097
+ const parts = [];
2098
+ if (outcome !== null) {
2099
+ parts.push(TESTS_TEXT[outcome.tests.status]);
2100
+ parts.push(
2101
+ outcome.mode === "thresholds" ? outcome.exitCode === 0 ? "thresholds derived" : "thresholds not written" : EVALUATION_TEXT[outcome.evaluation.status]
2102
+ );
2103
+ }
2104
+ const code = paint2(`exit code ${exitCode}`, exitCode === 0 ? "green" : "red", opts);
2105
+ parts.push(code);
2106
+ let text = infoLine(parts.join(" · "));
2107
+ const report = outcome?.paths.reportHtml ?? outcome?.paths.reportJson ?? null;
2108
+ if (report !== null) text += infoLine(`report: ${report}`);
2109
+ const diff = outcome?.paths.thresholdsDiff ?? null;
2110
+ if (diff !== null) text += infoLine(`thresholds diff: ${diff}`);
2111
+ return text;
2112
+ }
2113
+
2114
+ // src/cli/exit.ts
2115
+ var SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
2116
+ function resolveExitCode(input) {
2117
+ if (input.receivedSignal !== void 0) {
2118
+ return { code: SIGNAL_EXIT_CODES[input.receivedSignal], issues: [] };
2119
+ }
2120
+ if (input.listOnly) return { code: input.childExitCode ?? 1, issues: [] };
2121
+ if (input.outcome.ok) return { code: input.outcome.value.exitCode, issues: [] };
2122
+ const playwright = input.childExitCode === null ? "Playwright ended without an exit code (killed by a signal)" : `Playwright exited with code ${input.childExitCode}`;
2123
+ if (input.outcome.reason === "invalid") {
2124
+ return {
2125
+ code: 3,
2126
+ issues: [
2127
+ {
2128
+ code: "CLI_OUTCOME_INVALID",
2129
+ message: `The outcome file of the run is not valid${input.outcome.detail === void 0 ? "" : `: ${input.outcome.detail}`}. ${playwright}.`,
2130
+ hint: "Check that the project uses one version of playwright-performance-regression, then run again."
2131
+ }
2132
+ ]
2133
+ };
2134
+ }
2135
+ return {
2136
+ code: 3,
2137
+ issues: [
2138
+ {
2139
+ code: "CLI_OUTCOME_MISSING",
2140
+ message: `The run wrote no outcome file, so its result is unknown. ${playwright}.`,
2141
+ hint: [
2142
+ "Common causes:",
2143
+ `- playwright.config does not use withPerf() (set it up with "${CLI_COMMAND} init");`,
2144
+ "- a configuration error (see the message above);",
2145
+ "- no test matched the filters (Playwright then reports no tests);",
2146
+ "- Playwright stopped before the reporters finished (onEnd)."
2147
+ ].join("\n")
2148
+ }
2149
+ ]
2150
+ };
2151
+ }
2152
+
2153
+ // src/cli/playwright-args.ts
2154
+ var WITH_VALUE = /* @__PURE__ */ new Set([
2155
+ "--browser",
2156
+ "--config",
2157
+ "--global-timeout",
2158
+ "--grep",
2159
+ "--grep-invert",
2160
+ "--max-failures",
2161
+ "--output",
2162
+ "--repeat-each",
2163
+ "--reporter",
2164
+ "--retries",
2165
+ "--shard",
2166
+ "--test-list",
2167
+ "--test-list-invert",
2168
+ "--timeout",
2169
+ "--trace",
2170
+ "--tsconfig",
2171
+ "--ui-host",
2172
+ "--ui-port",
2173
+ "--update-source-method",
2174
+ "--workers"
2175
+ ]);
2176
+ var OPTIONAL_VALUE = /* @__PURE__ */ new Set(["--only-changed", "--update-snapshots"]);
2177
+ var VARIADIC = /* @__PURE__ */ new Set(["--project"]);
2178
+ var SHORT = {
2179
+ c: "--config",
2180
+ g: "--grep",
2181
+ j: "--workers",
2182
+ u: "--update-snapshots",
2183
+ x: "-x",
2184
+ h: "--help"
2185
+ };
2186
+ function isOptionLike(arg) {
2187
+ return arg.startsWith("-") && arg !== "-";
2188
+ }
2189
+ function scanPlaywrightArgs(args) {
2190
+ const options = [];
2191
+ const positionals = [];
2192
+ let i = 0;
2193
+ while (i < args.length) {
2194
+ const arg = args[i];
2195
+ if (!isOptionLike(arg)) {
2196
+ positionals.push(arg);
2197
+ i += 1;
2198
+ continue;
2199
+ }
2200
+ let name;
2201
+ let inlineValue;
2202
+ if (arg.startsWith("--")) {
2203
+ const eq = arg.indexOf("=");
2204
+ name = eq === -1 ? arg : arg.slice(0, eq);
2205
+ if (eq !== -1) inlineValue = arg.slice(eq + 1);
2206
+ } else {
2207
+ const long = SHORT[arg.charAt(1)];
2208
+ name = long ?? arg;
2209
+ if (long !== void 0 && arg.length > 2) {
2210
+ const rest = arg.slice(2);
2211
+ inlineValue = rest.startsWith("=") ? rest.slice(1) : rest;
2212
+ }
2213
+ }
2214
+ const option = { name, values: [], index: i, inline: false };
2215
+ options.push(option);
2216
+ i += 1;
2217
+ if (inlineValue !== void 0) {
2218
+ option.values.push(inlineValue);
2219
+ option.inline = true;
2220
+ continue;
2221
+ }
2222
+ if (WITH_VALUE.has(name)) {
2223
+ if (i < args.length) {
2224
+ option.values.push(args[i]);
2225
+ i += 1;
2226
+ }
2227
+ } else if (OPTIONAL_VALUE.has(name)) {
2228
+ if (i < args.length && !isOptionLike(args[i])) {
2229
+ option.values.push(args[i]);
2230
+ i += 1;
2231
+ }
2232
+ } else if (VARIADIC.has(name)) {
2233
+ while (i < args.length && !isOptionLike(args[i])) {
2234
+ option.values.push(args[i]);
2235
+ i += 1;
2236
+ }
2237
+ }
2238
+ }
2239
+ return { options, positionals };
2240
+ }
2241
+ var FILTERS = /* @__PURE__ */ new Set([
2242
+ "--grep",
2243
+ "--grep-invert",
2244
+ "--project",
2245
+ "--last-failed",
2246
+ "--only-changed",
2247
+ "--test-list",
2248
+ "--test-list-invert"
2249
+ ]);
2250
+ function testFilters(args) {
2251
+ const scanned = scanPlaywrightArgs(args);
2252
+ return [
2253
+ ...scanned.options.filter((o) => FILTERS.has(o.name)).map((o) => args.slice(o.index, o.index + 1 + (o.inline ? 0 : o.values.length)).join(" ")),
2254
+ ...scanned.positionals
2255
+ ];
2256
+ }
2257
+ var UNSUPPORTED = /* @__PURE__ */ new Set([
2258
+ "--ui",
2259
+ "--ui-host",
2260
+ "--ui-port",
2261
+ "--debug",
2262
+ "--shard"
2263
+ ]);
2264
+ function unsupportedOptions(args) {
2265
+ return scanPlaywrightArgs(args).options.filter((o) => UNSUPPORTED.has(o.name)).map((o) => o.name);
2266
+ }
2267
+ function isListOnly(args) {
2268
+ return scanPlaywrightArgs(args).options.some((o) => o.name === "--list");
2269
+ }
2270
+ function playwrightConfigArg(args) {
2271
+ const configs = scanPlaywrightArgs(args).options.filter(
2272
+ (o) => o.name === "--config" && o.values.length > 0
2273
+ );
2274
+ return configs.length === 0 ? null : configs[configs.length - 1]?.values[0] ?? null;
2275
+ }
2276
+
2277
+ // src/cli/reporter-arg.ts
2278
+ function withPerfReporterArg(args, reporterPath) {
2279
+ const reporters = scanPlaywrightArgs(args).options.filter(
2280
+ (o) => o.name === "--reporter" && o.values.length > 0
2281
+ );
2282
+ const last = reporters[reporters.length - 1];
2283
+ if (last === void 0) return { ok: true, value: [...args] };
2284
+ if (reporterPath.includes(",")) {
2285
+ return {
2286
+ ok: false,
2287
+ issues: [
2288
+ {
2289
+ code: "CLI_REPORTER_PATH_UNSUPPORTED",
2290
+ message: `The package reporter cannot be added to --reporter: its path contains a comma, and Playwright splits the --reporter value at commas (${reporterPath}).`,
2291
+ hint: "Remove --reporter from the arguments (withPerf() then adds the reporter itself), or move the project to a path without a comma."
2292
+ }
2293
+ ]
2294
+ };
2295
+ }
2296
+ const value = `${last.values[0]},${reporterPath}`;
2297
+ const result = [...args];
2298
+ if (last.inline) result[last.index] = `--reporter=${value}`;
2299
+ else result[last.index + 1] = value;
2300
+ return { ok: true, value: result };
2301
+ }
2302
+
2303
+ // src/cli/run.ts
2304
+ var FORCE_KILL_WINDOW_MS = 5 * 1e3;
2305
+ function outcomeFilePath(tmpdir2, runId, join3) {
2306
+ return join3(tmpdir2, `${PACKAGE_NAME}-${runId}.outcome.json`);
2307
+ }
2308
+ function planRun(cmd, input) {
2309
+ const args = withPerfReporterArg(cmd.playwrightArgs, input.reporterPath);
2310
+ if (!args.ok) return args;
2311
+ const warnings = [];
2312
+ const preset = MODE_ENV_NAMES.filter((name) => (input.env[name] ?? "") !== "");
2313
+ if (preset.length > 0) {
2314
+ warnings.push({
2315
+ code: "CLI_MODE_ALREADY_SET",
2316
+ message: `${preset.join(", ")} ${preset.length === 1 ? "is" : "are"} already set in the environment; the CLI replaces ${preset.length === 1 ? "it" : "them"} for this run.`,
2317
+ hint: 'Use the CLI options (--env, --repeat, --prune) instead of the variables, or run "npx playwright test" for the manual mode.'
2318
+ });
2319
+ }
2320
+ const env = {};
2321
+ for (const [name, value] of Object.entries(input.env)) {
2322
+ if (value !== void 0 && !MODE_ENV_NAMES.includes(name)) env[name] = value;
2323
+ }
2324
+ Object.assign(
2325
+ env,
2326
+ writeModeState({
2327
+ mode: cmd.mode,
2328
+ ...cmd.repeat === void 0 ? {} : { repeat: cmd.repeat },
2329
+ ...cmd.env === void 0 ? {} : { env: cmd.env },
2330
+ runId: input.runId,
2331
+ outcomeFile: input.outcomeFile,
2332
+ prune: cmd.prune
2333
+ })
2334
+ );
2335
+ const repeats = cmd.repeat === void 0 ? `repeats per test from run.repeat.${cmd.mode}` : `${cmd.repeat} ${cmd.repeat === 1 ? "repeat" : "repeats"} per test`;
2336
+ const lines2 = [`perf mode "${cmd.mode}", ${repeats}, 1 worker.`];
2337
+ if (!cmd.listOnly && testFilters(cmd.playwrightArgs).length === 0) {
2338
+ lines2.push("tip: measure a subset, e.g. --grep @perf or --project chromium.");
2339
+ }
2340
+ return { ok: true, value: { args: args.value, env, lines: lines2, warnings } };
2341
+ }
2342
+ function versionAtLeast(version2, minimum) {
2343
+ const parts = (v) => v.split(/[.+-]/u).slice(0, 3).map((p) => Number.parseInt(p, 10) || 0);
2344
+ const a = parts(version2);
2345
+ const b = parts(minimum);
2346
+ for (let i = 0; i < 3; i += 1) {
2347
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
2348
+ }
2349
+ return true;
2350
+ }
2351
+ function style(host) {
2352
+ return outputStyle(host.stderr, host.env);
2353
+ }
2354
+ async function playwrightDir(cmd, host) {
2355
+ const config = playwrightConfigArg(cmd.playwrightArgs);
2356
+ if (config === null) return host.cwd;
2357
+ const path = host.paths.resolve(host.cwd, config);
2358
+ return await host.isDirectory(path) ? path : host.paths.dirname(path);
2359
+ }
2360
+ async function readOutcome(host, file, runId) {
2361
+ let text;
2362
+ try {
2363
+ text = await host.readText(file);
2364
+ } catch (error) {
2365
+ return {
2366
+ ok: false,
2367
+ reason: "invalid",
2368
+ detail: error instanceof Error ? error.message : String(error)
2369
+ };
2370
+ }
2371
+ if (text === null) return { ok: false, reason: "missing" };
2372
+ const parsed = parseOutcome(text, file);
2373
+ if (!parsed.ok) {
2374
+ return { ok: false, reason: "invalid", detail: parsed.issues.map((i) => i.message).join("; ") };
2375
+ }
2376
+ if (parsed.value.runId !== runId) {
2377
+ return {
2378
+ ok: false,
2379
+ reason: "invalid",
2380
+ detail: `it belongs to run ${parsed.value.runId}, not to this run (${runId})`
2381
+ };
2382
+ }
2383
+ return { ok: true, value: parsed.value };
2384
+ }
2385
+ function waitForChild(child, host, received) {
2386
+ return new Promise((resolve2) => {
2387
+ let lastSigint = null;
2388
+ const forward = (signal) => {
2389
+ received.signal ??= signal;
2390
+ if (signal === "SIGINT") {
2391
+ const now = host.now().getTime();
2392
+ if (lastSigint !== null && now - lastSigint <= FORCE_KILL_WINDOW_MS) {
2393
+ child.kill("SIGKILL");
2394
+ return;
2395
+ }
2396
+ lastSigint = now;
2397
+ }
2398
+ if (host.platform === "win32") child.kill();
2399
+ else child.kill(signal);
2400
+ };
2401
+ const off = [
2402
+ host.onSignal("SIGINT", () => forward("SIGINT")),
2403
+ host.onSignal("SIGTERM", () => forward("SIGTERM"))
2404
+ ];
2405
+ let finished = false;
2406
+ const done = (result) => {
2407
+ if (finished) return;
2408
+ finished = true;
2409
+ for (const remove of off) remove();
2410
+ resolve2(result);
2411
+ };
2412
+ child.once("error", (error) => done({ code: null, error }));
2413
+ child.once("exit", (code) => done({ code }));
2414
+ });
2415
+ }
2416
+ async function runTests(cmd, host) {
2417
+ const out = style(host);
2418
+ const fail2 = (issues) => {
2419
+ host.stderr.write(formatIssues(issues, "error", out));
2420
+ return 3;
2421
+ };
2422
+ const install = host.resolvePlaywright(await playwrightDir(cmd, host));
2423
+ if (install === null) {
2424
+ return fail2([
2425
+ {
2426
+ code: "CLI_PLAYWRIGHT_NOT_FOUND",
2427
+ message: "@playwright/test is not installed in this project.",
2428
+ hint: 'Install it with "npm i -D @playwright/test", or run the command from the project directory (or pass -c <playwright.config>).'
2429
+ }
2430
+ ]);
2431
+ }
2432
+ const warnings = [];
2433
+ if (!versionAtLeast(install.version, host.minPlaywrightVersion)) {
2434
+ warnings.push({
2435
+ code: "CLI_PLAYWRIGHT_UNSUPPORTED_VERSION",
2436
+ message: `@playwright/test ${install.version} is older than ${host.minPlaywrightVersion}, the lowest supported version; the run continues.`,
2437
+ hint: `Update @playwright/test to ${host.minPlaywrightVersion} or newer.`
2438
+ });
2439
+ }
2440
+ const runId = generateRunId(host.now(), () => host.random());
2441
+ const outcomeFile = outcomeFilePath(host.tmpdir, runId, host.paths.join);
2442
+ const plan = planRun(cmd, { env: host.env, runId, outcomeFile, reporterPath: host.reporterPath });
2443
+ if (!plan.ok) return fail2(plan.issues);
2444
+ warnings.push(...plan.value.warnings);
2445
+ host.stderr.write(formatIssues(warnings, "warning", out));
2446
+ for (const line of plan.value.lines) host.stderr.write(infoLine(line));
2447
+ const received = {};
2448
+ let child;
2449
+ try {
2450
+ child = host.spawnNode([install.cliPath, "test", ...plan.value.args], {
2451
+ cwd: host.cwd,
2452
+ env: plan.value.env,
2453
+ stdio: "inherit",
2454
+ shell: false
2455
+ });
2456
+ } catch (error) {
2457
+ return fail2([spawnFailed(error)]);
2458
+ }
2459
+ const exit = await waitForChild(child, host, received);
2460
+ const outcome = await readOutcome(host, outcomeFile, runId);
2461
+ await host.removeFile(outcomeFile).catch(() => void 0);
2462
+ if (exit.error !== void 0) return fail2([spawnFailed(exit.error)]);
2463
+ const resolved = resolveExitCode({
2464
+ outcome,
2465
+ childExitCode: exit.code,
2466
+ ...received.signal === void 0 ? {} : { receivedSignal: received.signal },
2467
+ listOnly: cmd.listOnly
2468
+ });
2469
+ host.stderr.write(formatIssues(resolved.issues, "error", out));
2470
+ if (!cmd.listOnly) {
2471
+ const value = outcome.ok ? outcome.value : null;
2472
+ host.stderr.write(resultLines(value, resolved.code, out));
2473
+ }
2474
+ return resolved.code;
2475
+ }
2476
+ function spawnFailed(error) {
2477
+ return {
2478
+ code: "CLI_SPAWN_FAILED",
2479
+ message: `The Playwright process could not be started: ${error instanceof Error ? error.message : String(error)}`,
2480
+ hint: "Check that Node can run the Playwright CLI of the project (reinstall the dependencies)."
2481
+ };
2482
+ }
2483
+
2484
+ // src/cli/init/wizard.ts
2485
+ var STEPS = 11;
2486
+ var PLATFORM_NAMES = {
2487
+ github: "GitHub Actions",
2488
+ gitlab: "GitLab CI",
2489
+ jenkins: "Jenkins",
2490
+ azure: "Azure Pipelines"
2491
+ };
2492
+ var DOCS = `${REPOSITORY_URL}/blob/main/docs`;
2493
+ var TUTORIAL_QUESTION = `Set up ${PACKAGE_NAME} with a guided tutorial?`;
2494
+ var LANGUAGE_QUESTION = `Language / Język? [${LANGUAGES.join("/")}]`;
2495
+ var WriteFailed = class extends Error {
2496
+ };
2497
+ var Dialog = class {
2498
+ #host;
2499
+ #prompt;
2500
+ #style;
2501
+ /** Colors of stdout (04-REQ-44). */
2502
+ paint;
2503
+ t = translator("en");
2504
+ constructor(host, prompt, style2) {
2505
+ this.#host = host;
2506
+ this.#prompt = prompt;
2507
+ this.#style = style2;
2508
+ this.paint = painter(colorEnabled(host.stdout, host.env));
2509
+ }
2510
+ get interactive() {
2511
+ return this.#prompt !== null;
2512
+ }
2513
+ say(...lines2) {
2514
+ this.#host.stdout.write(lines2.map((l) => `${l}
2515
+ `).join(""));
2516
+ }
2517
+ /** An indented line in one color. */
2518
+ line(text, style2, indent = " ") {
2519
+ this.say(`${indent}${this.paint(text, style2)}`);
2520
+ }
2521
+ /** Step header in cyan ("[3/11] Backend") and the lesson dimmed. */
2522
+ step(n, title, ...lesson) {
2523
+ this.say("", this.paint(`[${n}/${STEPS}] ${title}`, "cyan"));
2524
+ for (const l of lesson) this.line(l, "dim");
2525
+ }
2526
+ stepOf(n, title, ...lesson) {
2527
+ this.step(n, this.t(title), ...lesson.map((k) => this.t(k)));
2528
+ }
2529
+ warn(issues) {
2530
+ if (issues.length > 0) this.#host.stderr.write(formatIssues(issues, "warning", this.#style));
2531
+ }
2532
+ error(code, message2, hint, values) {
2533
+ this.#host.stderr.write(
2534
+ formatIssues(
2535
+ [{ code, message: this.t(message2, values), hint: this.t(hint, values) }],
2536
+ "error",
2537
+ this.#style
2538
+ )
2539
+ );
2540
+ return 3;
2541
+ }
2542
+ /** A question with a default; `parse` returns the value or null to ask again. */
2543
+ async ask(question, shownDefault, fallback, parse, fallbackText = shownDefault) {
2544
+ const text = ` ${this.paint(question, "bold")} ${this.paint(`(${shownDefault})`, "dim")} `;
2545
+ if (this.#prompt === null) {
2546
+ this.say(`${text}→ ${this.paint(fallbackText, "bold")}`);
2547
+ return fallback;
2548
+ }
2549
+ for (; ; ) {
2550
+ const answer = (await this.#prompt.ask(text)).trim();
2551
+ if (answer === "") return fallback;
2552
+ const value = parse(answer);
2553
+ if (value !== null) return value;
2554
+ this.line(`⚠ ${this.t("answerAgain")}`, "yellow");
2555
+ }
2556
+ }
2557
+ confirm(question, fallback) {
2558
+ const t = this.t;
2559
+ const y = t("yesShort");
2560
+ const n = t("noShort");
2561
+ const yes = /* @__PURE__ */ new Set(["y", "yes", y, t("yes")]);
2562
+ const no = /* @__PURE__ */ new Set(["n", "no", n, t("no")]);
2563
+ return this.ask(
2564
+ question,
2565
+ fallback ? `${y.toUpperCase()}/${n}` : `${y}/${n.toUpperCase()}`,
2566
+ fallback,
2567
+ (a) => {
2568
+ const answer = a.toLowerCase();
2569
+ return yes.has(answer) ? true : no.has(answer) ? false : null;
2570
+ },
2571
+ fallback ? t("yes") : t("no")
2572
+ );
2573
+ }
2574
+ async pause() {
2575
+ if (this.#prompt !== null)
2576
+ await this.#prompt.ask(` ${this.paint(this.t("pressEnter"), "dim")} `);
2577
+ }
2578
+ };
2579
+ function runCommand(manager, script) {
2580
+ return manager === "npm" ? `npm run ${script}` : `${manager} ${script}`;
2581
+ }
2582
+ function describeProject(info, t) {
2583
+ const config = info.playwrightConfig;
2584
+ const lines2 = [
2585
+ t("projectLine", {
2586
+ config: config?.path ?? "-",
2587
+ version: info.playwrightVersion ?? t("versionUnknown"),
2588
+ manager: info.packageManager,
2589
+ modules: info.moduleType === "esm" ? "ES modules" : "CommonJS"
2590
+ }),
2591
+ t("testDirLine", {
2592
+ dir: info.testDir,
2593
+ imports: info.filesImportingPlaywrightTest.length,
2594
+ extend: info.filesWithExtend.length
2595
+ })
2596
+ ];
2597
+ if (info.baseUrls.length > 0 || info.projectNames.length > 0) {
2598
+ lines2.push(
2599
+ [
2600
+ info.baseUrls.length > 0 ? `baseURL ${info.baseUrls.join(", ")}` : null,
2601
+ info.projectNames.length > 0 ? t("projectsPart", { names: info.projectNames.join(", ") }) : null
2602
+ ].filter((part) => part !== null).join(" · ")
2603
+ );
2604
+ }
2605
+ lines2.push(
2606
+ t("ciLine", {
2607
+ platform: info.ciPlatform === null ? t("ciNone") : PLATFORM_NAMES[info.ciPlatform]
2608
+ })
2609
+ );
2610
+ if (info.existing.wrappedConfig || info.existing.wrappedTest || info.existing.perfConfig !== null) {
2611
+ lines2.push(
2612
+ t("alreadySetUp", {
2613
+ items: [
2614
+ info.existing.wrappedConfig ? "withPerf()" : null,
2615
+ info.existing.wrappedTest ? t("measuredTestObject") : null,
2616
+ info.existing.perfConfig
2617
+ ].filter((part) => part !== null).join(", ")
2618
+ })
2619
+ );
2620
+ }
2621
+ return lines2;
2622
+ }
2623
+ function printManualSetup(dialog) {
2624
+ const { t, paint: paint3 } = dialog;
2625
+ const cmd = (text) => paint3(text, "cyan");
2626
+ dialog.say("");
2627
+ dialog.line(`✔ ${t("declinedInstalled", { pkg: PACKAGE_NAME })}`, "green");
2628
+ dialog.say(
2629
+ ` ${paint3(t("declinedSteps"), "bold")}`,
2630
+ ` 1. ${t("declinedConfig", { config: `${PACKAGE_NAME}/config` })}`,
2631
+ ` 2. ${t("declinedTest", { fixture: `${PACKAGE_NAME}/fixture`, test: `${PACKAGE_NAME}/test` })}`,
2632
+ ` 3. ${t("declinedRun", { thresholds: cmd(`${CLI_COMMAND} thresholds`), test: cmd(`${CLI_COMMAND} test`) })}`
2633
+ );
2634
+ dialog.line(t("declinedDocs", { url: `${DOCS}/adoption.md` }), "dim");
2635
+ dialog.say(` ${t("declinedLater", { init: cmd(`${CLI_COMMAND} init`) })}`);
2636
+ }
2637
+ async function askLanguage(dialog, given) {
2638
+ dialog.step(0, "Language");
2639
+ dialog.line(LANGUAGES.map((l) => `${l} ${LANGUAGE_NAMES[l]}`).join(" · "), "dim");
2640
+ if (given !== void 0) {
2641
+ dialog.say(
2642
+ ` ${dialog.paint(LANGUAGE_QUESTION, "bold")} ${dialog.paint("(en)", "dim")} → ${dialog.paint(given, "bold")}`
2643
+ );
2644
+ return given;
2645
+ }
2646
+ return dialog.ask(LANGUAGE_QUESTION, "en", "en", (a) => {
2647
+ const code = a.toLowerCase();
2648
+ if (isWizardLanguage(code)) return code;
2649
+ return LANGUAGES.find((l) => LANGUAGE_NAMES[l].toLowerCase() === code) ?? null;
2650
+ });
2651
+ }
2652
+ async function askAnswers(dialog, info) {
2653
+ const { t } = dialog;
2654
+ dialog.step(
2655
+ 2,
2656
+ t("stepHow"),
2657
+ `1. ${t("how1", { test: `${CLI_COMMAND} test` })}`,
2658
+ `2. ${t("how2")}`,
2659
+ `3. ${t("how3")}`,
2660
+ `4. ${t("how4", { thresholds: `${CLI_COMMAND} thresholds` })}`,
2661
+ `5. ${t("how5")}`
2662
+ );
2663
+ await dialog.pause();
2664
+ dialog.stepOf(3, "stepBackend", "backendLesson");
2665
+ const originLabels = {};
2666
+ if (info.baseUrls.length === 0) dialog.say(` ${t("noBaseUrl")}`);
2667
+ const used = /* @__PURE__ */ new Set();
2668
+ for (const origin of info.baseUrls) {
2669
+ const fallback = defaultLabel(origin, used);
2670
+ const label = await dialog.ask(
2671
+ t("labelQuestion", { origin }),
2672
+ fallback,
2673
+ fallback,
2674
+ (a) => /^[a-z0-9.-]{1,64}$/u.test(a) ? a : null
2675
+ );
2676
+ used.add(label);
2677
+ originLabels[origin] = label;
2678
+ }
2679
+ const tagged = info.taggedPerfTestFiles > 0;
2680
+ dialog.step(
2681
+ 4,
2682
+ t("stepTests"),
2683
+ t("testsLesson"),
2684
+ t("taggedFiles", { count: info.taggedPerfTestFiles })
2685
+ );
2686
+ if (!tagged) {
2687
+ dialog.warn([
2688
+ {
2689
+ code: "INIT_NO_TAGGED_TESTS",
2690
+ message: t("noTaggedMessage"),
2691
+ hint: t("noTaggedHint")
2692
+ }
2693
+ ]);
2694
+ }
2695
+ const all = t("scopeAll");
2696
+ const scope = await dialog.ask(
2697
+ t("scopeQuestion", { all }),
2698
+ tagged ? "@perf" : all,
2699
+ tagged ? "tagged" : "all",
2700
+ (a) => {
2701
+ const answer = a.toLowerCase();
2702
+ if (answer === "all" || answer === all) return "all";
2703
+ return answer === "@perf" || answer === "perf" ? "tagged" : null;
2704
+ }
2705
+ );
2706
+ dialog.stepOf(5, "stepRepeat", "repeatLesson");
2707
+ const repeatTest = await dialog.ask(
2708
+ t("repeatQuestion"),
2709
+ String(DEFAULT_ANSWERS_REPEAT),
2710
+ DEFAULT_ANSWERS_REPEAT,
2711
+ (a) => {
2712
+ const n = parseRepeat(a);
2713
+ return n !== null && resolveConfig({ run: { repeat: { test: n } } }, {}).ok ? n : null;
2714
+ }
2715
+ );
2716
+ dialog.stepOf(6, "stepTrial", "trialLesson");
2717
+ const warnOnly = await dialog.confirm(t("warnOnlyQuestion"), true);
2718
+ dialog.stepOf(7, "stepEnvs", "envsLesson");
2719
+ let envLabels = [];
2720
+ if (await dialog.confirm(t("envsQuestion"), false)) {
2721
+ envLabels = await dialog.ask(t("envLabelsQuestion"), t("none"), [], (a) => {
2722
+ const labels = [
2723
+ ...new Set(
2724
+ a.split(",").map((l) => l.trim()).filter((l) => l !== "")
2725
+ )
2726
+ ];
2727
+ return labels.length > 0 && labels.every(isEnvLabel) ? labels : null;
2728
+ });
2729
+ }
2730
+ dialog.stepOf(8, "stepCi", "ciLesson");
2731
+ let addCi = false;
2732
+ if (info.ciPlatform === null) {
2733
+ dialog.say(` ${t("noCi", { url: `${DOCS}/ci.md` })}`);
2734
+ } else {
2735
+ addCi = await dialog.confirm(
2736
+ t("ciQuestion", { platform: PLATFORM_NAMES[info.ciPlatform] }),
2737
+ true
2738
+ );
2739
+ }
2740
+ return { originLabels, scope, repeatTest, warnOnly, envLabels, addCi };
2741
+ }
2742
+ function changeKind(change2, t) {
2743
+ return change2.kind === "create" ? t("newFile") : t("modifiedFile");
2744
+ }
2745
+ function diffStyle(line) {
2746
+ if (line.startsWith("+++") || line.startsWith("---")) return "bold";
2747
+ if (line.startsWith("+")) return "green";
2748
+ if (line.startsWith("-")) return "red";
2749
+ if (line.startsWith("@@")) return "cyan";
2750
+ return null;
2751
+ }
2752
+ async function applyChanges(dialog, host, info, changes, write, yes) {
2753
+ const { t, paint: paint3 } = dialog;
2754
+ const written = [];
2755
+ for (const change2 of changes) {
2756
+ dialog.say(
2757
+ "",
2758
+ ` ${paint3(change2.path, "bold")} ${paint3(`(${changeKind(change2, t)})`, "dim")}`,
2759
+ ...unifiedDiff(change2).trimEnd().split("\n").map((l) => {
2760
+ const style2 = diffStyle(l);
2761
+ return ` ${style2 === null ? l : paint3(l, style2)}`;
2762
+ })
2763
+ );
2764
+ let apply;
2765
+ if (isProtected(info, change2.path)) {
2766
+ if (dialog.interactive)
2767
+ apply = await dialog.confirm(t("overwriteQuestion", { path: change2.path }), false);
2768
+ else {
2769
+ dialog.say(` ${t(yes ? "keptWithYes" : "kept", { path: change2.path })}`);
2770
+ apply = false;
2771
+ }
2772
+ } else {
2773
+ apply = await dialog.confirm(t("applyQuestion"), true);
2774
+ }
2775
+ if (!apply || !write) continue;
2776
+ try {
2777
+ await host.writeText(host.paths.join(host.cwd, change2.path), change2.after);
2778
+ } catch (error) {
2779
+ throw new WriteFailed(
2780
+ `${change2.path}: ${error instanceof Error ? error.message : String(error)}`
2781
+ );
2782
+ }
2783
+ dialog.line(`✔ ${t("fileWritten", { path: change2.path })}`, "green");
2784
+ written.push(change2.path);
2785
+ }
2786
+ return written;
2787
+ }
2788
+ function nextSteps(dialog, info, answers, written) {
2789
+ const { t, paint: paint3 } = dialog;
2790
+ const scripts = Object.keys(plannedScripts(answers));
2791
+ const thresholds = scripts.find((s) => s.startsWith("perf:thresholds"));
2792
+ const test = scripts.find((s) => s.startsWith("perf:test"));
2793
+ const command = (script) => paint3(runCommand(info.packageManager, script), "cyan");
2794
+ const steps = [
2795
+ t("nextThresholds", { command: command(thresholds) }),
2796
+ t("nextTest", { command: command(test) })
2797
+ ];
2798
+ const platform = info.ciPlatform;
2799
+ if (answers.addCi && platform !== null) {
2800
+ const ci = CI_TARGETS[platform].path(answers.envLabels[0] ?? null);
2801
+ if (platform === "jenkins") steps.push(t("nextJenkins", { path: ci }));
2802
+ if (platform === "azure") steps.push(t("nextAzure", { path: ci }));
2803
+ }
2804
+ if (answers.warnOnly) steps.push(t("nextWarnOnly"));
2805
+ if (written.length === 0 && scripts.length > 0) steps.unshift(t("nextApply"));
2806
+ return steps;
2807
+ }
2808
+ async function runInit(cmd, host, style2) {
2809
+ const interactive = !cmd.yes && !cmd.dryRun && host.stdin.isTTY === true && host.stdout.isTTY === true;
2810
+ const write = !cmd.dryRun && (cmd.yes || interactive);
2811
+ const prompt = interactive && cmd.noTutorial !== true ? host.createPrompt() : null;
2812
+ const dialog = new Dialog(host, prompt, style2);
2813
+ try {
2814
+ if (cmd.noTutorial === true) {
2815
+ dialog.t = translator(cmd.lang ?? "en");
2816
+ printManualSetup(dialog);
2817
+ return 0;
2818
+ }
2819
+ if (interactive && !await dialog.confirm(TUTORIAL_QUESTION, true)) {
2820
+ dialog.t = translator(cmd.lang ?? "en");
2821
+ printManualSetup(dialog);
2822
+ return 0;
2823
+ }
2824
+ const lang = await askLanguage(dialog, cmd.lang);
2825
+ dialog.t = translator(lang);
2826
+ const { t, paint: paint3 } = dialog;
2827
+ if (!write) host.stderr.write(infoLine(t(cmd.dryRun ? "dryRun" : "noTerminal")));
2828
+ const info = detectProject(await readProjectFiles(host, host.cwd));
2829
+ dialog.step(1, t("stepProject"), ...describeProject(info, t));
2830
+ if (info.playwrightConfig === null) {
2831
+ return dialog.error("INIT_NO_PLAYWRIGHT_CONFIG", "noConfigMessage", "noConfigHint", {
2832
+ dir: host.cwd,
2833
+ command: CLI_COMMAND
2834
+ });
2835
+ }
2836
+ if (info.playwrightVersion !== null && !versionAtLeast(info.playwrightVersion, host.minPlaywrightVersion)) {
2837
+ return dialog.error("INIT_PLAYWRIGHT_TOO_OLD", "tooOldMessage", "tooOldHint", {
2838
+ version: info.playwrightVersion,
2839
+ min: host.minPlaywrightVersion,
2840
+ pkg: PACKAGE_NAME,
2841
+ command: CLI_COMMAND
2842
+ });
2843
+ }
2844
+ const answers = await askAnswers(dialog, info);
2845
+ const plan = planInitChanges(info, answers, lang);
2846
+ dialog.stepOf(
2847
+ 9,
2848
+ "stepChanges",
2849
+ plan.changes.length === 0 ? "nothingToChange" : "changesLesson"
2850
+ );
2851
+ let written;
2852
+ try {
2853
+ written = await applyChanges(dialog, host, info, plan.changes, write, cmd.yes);
2854
+ } catch (error) {
2855
+ if (!(error instanceof WriteFailed)) throw error;
2856
+ return dialog.error("INIT_WRITE_FAILED", "writeFailedMessage", "writeFailedHint", {
2857
+ detail: error.message
2858
+ });
2859
+ }
2860
+ dialog.warn(plan.manualSteps);
2861
+ dialog.step(
2862
+ 10,
2863
+ t("stepFirstRun"),
2864
+ t("firstRunLesson", { dir: DEFAULT_CONFIG.report.dir }),
2865
+ t("firstRunLaptop")
2866
+ );
2867
+ let firstRun = false;
2868
+ if (dialog.interactive && written.length > 0) {
2869
+ firstRun = await dialog.confirm(t("firstRunQuestion"), false);
2870
+ } else {
2871
+ dialog.line(t("skipped"), "dim");
2872
+ }
2873
+ dialog.step(11, t("stepSummary"));
2874
+ if (written.length > 0)
2875
+ dialog.say(
2876
+ ` ${t("changedFiles")}`,
2877
+ ...written.map((p) => ` ${paint3("✔", "green")} ${p}`)
2878
+ );
2879
+ else if (write) dialog.say(` ${t("noFilesChanged")}`);
2880
+ else
2881
+ dialog.say(
2882
+ ` ${t("plannedChanges")}`,
2883
+ ...plan.changes.map((c) => ` · ${c.path} (${changeKind(c, t)})`)
2884
+ );
2885
+ if (plan.manualSteps.length > 0)
2886
+ dialog.line(`⚠ ${t("manualSteps", { count: plan.manualSteps.length })}`, "yellow");
2887
+ dialog.say(
2888
+ ` ${paint3(t("nextSteps"), "bold")}`,
2889
+ ...nextSteps(dialog, info, answers, written).map((s, i) => ` ${i + 1}. ${s}`)
2890
+ );
2891
+ dialog.line(
2892
+ t("docs", { links: `${DOCS}/adoption.md · ${DOCS}/ci.md · ${DOCS}/configuration.md` }),
2893
+ "dim"
2894
+ );
2895
+ if (write) dialog.line(`✔ ${t("finished")}`, "green");
2896
+ prompt?.close();
2897
+ if (firstRun) {
2898
+ const args = answers.scope === "tagged" ? ["--grep", "@perf"] : [];
2899
+ return await runTests(
2900
+ { kind: "run", mode: "thresholds", prune: false, playwrightArgs: args, listOnly: false },
2901
+ host
2902
+ );
2903
+ }
2904
+ return 0;
2905
+ } catch (error) {
2906
+ if (error instanceof PromptAborted) {
2907
+ host.stderr.write(infoLine(dialog.t("interrupted")));
2908
+ return 130;
2909
+ }
2910
+ throw error;
2911
+ } finally {
2912
+ prompt?.close();
2913
+ }
2914
+ }
2915
+
2916
+ // src/cli/base-dir.ts
2917
+ function parentOf(path) {
2918
+ const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
2919
+ return cut <= 0 ? path.slice(0, cut + 1) || "." : path.slice(0, cut);
2920
+ }
2921
+ function resolveBaseDir(input) {
2922
+ if (input.loadedConfigFile !== void 0) {
2923
+ return { dir: (input.dirname ?? parentOf)(input.loadedConfigFile), issues: [] };
2924
+ }
2925
+ if (input.reportConfigDir !== void 0 && input.exists(input.reportConfigDir)) {
2926
+ return { dir: input.reportConfigDir, issues: [] };
2927
+ }
2928
+ return {
2929
+ dir: input.cwd,
2930
+ issues: [
2931
+ {
2932
+ code: "CLI_CONFIG_DIR_MISSING",
2933
+ 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}.`,
2934
+ hint: "Run the command from the directory of playwright.config, or pass the package config with --config."
2935
+ }
2936
+ ]
2937
+ };
2938
+ }
2939
+ function errorText(error) {
2940
+ const message2 = error instanceof Error ? error.message : String(error);
2941
+ return message2.split("\n")[0] ?? message2;
2942
+ }
2943
+ function loadFailureHint(error) {
2944
+ const e = typeof error === "object" && error !== null ? error : {};
2945
+ const message2 = typeof e.message === "string" ? e.message : "";
2946
+ if (e.code === "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
2947
+ return "Node loads the file by stripping the types: replace enums, namespaces with code and constructor parameter properties with erasable syntax.";
2948
+ }
2949
+ if (e.code === "ERR_MODULE_NOT_FOUND" && message2.startsWith("Cannot find module")) {
2950
+ return 'Add the extension to relative imports, e.g. "./helpers.ts" instead of "./helpers".';
2951
+ }
2952
+ if (e.code === "ERR_MODULE_NOT_FOUND" && message2.startsWith("Cannot find package")) {
2953
+ return "Path aliases from tsconfig do not work when Node loads the file: use a relative import.";
2954
+ }
2955
+ return "Fix the error in the file, or pass another package config with --config.";
2956
+ }
2957
+ function loadFailed(path, reason, hint) {
2958
+ return {
2959
+ code: "CONFIG_FILE_LOAD_FAILED",
2960
+ message: `The package config ${path} cannot be loaded: ${reason}`,
2961
+ hint
2962
+ };
2963
+ }
2964
+ function isLoadingWarning(warning) {
2965
+ return warning.name === "ExperimentalWarning" && /type stripping/iu.test(warning.message) || warning.code === "MODULE_TYPELESS_PACKAGE_JSON";
2966
+ }
2967
+ async function importCapturingWarnings(path, importModule, notes) {
2968
+ const listeners = process.listeners("warning");
2969
+ const captured = [];
2970
+ const capture = (warning) => {
2971
+ captured.push(warning);
2972
+ };
2973
+ process.removeAllListeners("warning");
2974
+ process.on("warning", capture);
2975
+ try {
2976
+ return await importModule(pathToFileURL(path).href);
2977
+ } finally {
2978
+ await new Promise((resolve2) => setImmediate(resolve2));
2979
+ process.off("warning", capture);
2980
+ for (const listener of listeners) process.on("warning", listener);
2981
+ const loading = captured.filter(isLoadingWarning);
2982
+ if (loading.length > 0) {
2983
+ notes.push(
2984
+ `note: Node printed ${loading.length === 1 ? "a warning" : `${loading.length} warnings`} while loading ${basename(path)}: ${loading.map((w) => w.message.split("\n")[0]).join("; ")}`
2985
+ );
2986
+ }
2987
+ for (const warning of captured.filter((w) => !isLoadingWarning(w))) {
2988
+ for (const listener of listeners) listener(warning);
2989
+ }
2990
+ }
2991
+ }
2992
+ function defaultExport(module) {
2993
+ if (typeof module !== "object" || module === null || !("default" in module)) return void 0;
2994
+ const value = module.default;
2995
+ if (typeof value === "object" && value !== null && "default" in value) {
2996
+ const keys = Object.keys(value).filter((k) => k !== "__esModule");
2997
+ if (keys.length === 1) return value.default;
2998
+ }
2999
+ return value;
3000
+ }
3001
+ async function loadFile(path, host, notes) {
3002
+ const json = extname(path) === ".json";
3003
+ try {
3004
+ if (json) {
3005
+ return { ok: true, value: { value: JSON.parse(await readFile(path, "utf8")), json } };
3006
+ }
3007
+ const module = await importCapturingWarnings(
3008
+ path,
3009
+ host.importModule ?? ((url) => import(url)),
3010
+ notes
3011
+ );
3012
+ const value = defaultExport(module);
3013
+ if (value === void 0) {
3014
+ return {
3015
+ ok: false,
3016
+ issues: [
3017
+ loadFailed(
3018
+ path,
3019
+ "the file has no default export.",
3020
+ "Export the config as default: export default definePerfConfig({ ... })."
3021
+ )
3022
+ ]
3023
+ };
3024
+ }
3025
+ return { ok: true, value: { value, json } };
3026
+ } catch (error) {
3027
+ return {
3028
+ ok: false,
3029
+ issues: [
3030
+ loadFailed(
3031
+ path,
3032
+ errorText(error),
3033
+ json ? "Fix the JSON syntax of the file." : loadFailureHint(error)
3034
+ )
3035
+ ]
3036
+ };
3037
+ }
3038
+ }
3039
+ async function findConfigFile(dirs, exists) {
3040
+ for (const dir of dirs) {
3041
+ for (const ext of CONFIG_FILE_EXTENSIONS) {
3042
+ const path = join(dir, `${CONFIG_FILE_BASENAME}${ext}`);
3043
+ if (await exists(path)) return path;
3044
+ }
3045
+ }
3046
+ return null;
3047
+ }
3048
+ var IGNORED_OPTIONS = /* @__PURE__ */ new Set([
3049
+ "$schema",
3050
+ "run",
3051
+ "report",
3052
+ "thresholds.dir",
3053
+ "thresholds.filePrefix"
3054
+ ]);
3055
+ function snapshotDifferences(a, b, path = []) {
3056
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3057
+ if (isObject(a) && isObject(b)) {
3058
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort();
3059
+ return keys.filter((k) => !IGNORED_OPTIONS.has([...path, k].join("."))).flatMap((k) => snapshotDifferences(a[k], b[k], [...path, k]));
3060
+ }
3061
+ return JSON.stringify(a) === JSON.stringify(b) ? [] : [path.join(".")];
3062
+ }
3063
+ var MAX_LISTED_DIFFERENCES = 10;
3064
+ function differsWarning(paths) {
3065
+ const listed = paths.slice(0, MAX_LISTED_DIFFERENCES).join(", ");
3066
+ const more = paths.length > MAX_LISTED_DIFFERENCES ? ` and ${paths.length - MAX_LISTED_DIFFERENCES} more` : "";
3067
+ return {
3068
+ code: "CONFIG_SNAPSHOT_DIFFERS",
3069
+ message: `The package config file differs from the config the report was recorded with: ${listed}${more}.`,
3070
+ 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."
3071
+ };
3072
+ }
3073
+ function configErrors(issues, where) {
3074
+ return issues.map((issue) => ({
3075
+ ...issue,
3076
+ message: `${where}: ${issue.message}`,
3077
+ hint: issue.hint ?? `See ${DOCS_CONFIG_URL} for all options.`
3078
+ }));
3079
+ }
3080
+ async function resolveCliConfig(input, host) {
3081
+ const warnings = [];
3082
+ const notes = [];
3083
+ const overrides = {
3084
+ mode: input.mode,
3085
+ ...input.env === void 0 ? {} : { env: input.env }
3086
+ };
3087
+ let file = null;
3088
+ if (input.explicit !== void 0) {
3089
+ if (!await host.exists(input.explicit)) {
3090
+ return {
3091
+ ok: false,
3092
+ issues: [
3093
+ {
3094
+ code: "CONFIG_FILE_NOT_FOUND",
3095
+ message: `The package config file given with --config does not exist: ${input.explicit}`,
3096
+ hint: "Check the path; it is resolved against the current directory."
3097
+ }
3098
+ ]
3099
+ };
3100
+ }
3101
+ file = { path: input.explicit, explicit: true };
3102
+ } else {
3103
+ const found = await findConfigFile(input.searchDirs, host.exists);
3104
+ if (found !== null) file = { path: found, explicit: false };
3105
+ }
3106
+ if (file !== null) {
3107
+ const loaded = await loadFile(file.path, host, notes);
3108
+ if (loaded.ok) {
3109
+ const resolved2 = resolveConfig(loaded.value.value, {
3110
+ ...overrides,
3111
+ source: loaded.value.json ? "json" : "code"
3112
+ });
3113
+ if (!resolved2.ok) return { ok: false, issues: configErrors(resolved2.issues, file.path) };
3114
+ warnings.push(...resolved2.value.warnings);
3115
+ if (input.report !== void 0) {
3116
+ const differences = snapshotDifferences(resolved2.value.snapshot, input.report.config);
3117
+ if (differences.length > 0) warnings.push(differsWarning(differences));
3118
+ }
3119
+ return {
3120
+ ok: true,
3121
+ value: {
3122
+ config: resolved2.value.config,
3123
+ snapshot: resolved2.value.snapshot,
3124
+ source: { kind: "file", ...file },
3125
+ warnings,
3126
+ notes
3127
+ }
3128
+ };
3129
+ }
3130
+ if (file.explicit) return { ok: false, issues: loaded.issues };
3131
+ warnings.push(
3132
+ ...loaded.issues.map((issue) => ({
3133
+ ...issue,
3134
+ message: `${issue.message} The ${input.report === void 0 ? "default config" : "config snapshot of the report"} is used instead.`
3135
+ }))
3136
+ );
3137
+ }
3138
+ const fromSnapshot = input.report !== void 0;
3139
+ const resolved = resolveConfig(fromSnapshot ? input.report?.config : void 0, {
3140
+ ...overrides,
3141
+ source: fromSnapshot ? "snapshot" : "code"
3142
+ });
3143
+ if (!resolved.ok) {
3144
+ return {
3145
+ ok: false,
3146
+ issues: configErrors(
3147
+ resolved.issues,
3148
+ fromSnapshot ? "config snapshot of the report" : "default config"
3149
+ )
3150
+ };
3151
+ }
3152
+ warnings.push(...resolved.value.warnings);
3153
+ return {
3154
+ ok: true,
3155
+ value: {
3156
+ config: resolved.value.config,
3157
+ snapshot: resolved.value.snapshot,
3158
+ source: fromSnapshot ? { kind: "snapshot" } : { kind: "defaults" },
3159
+ warnings,
3160
+ notes
3161
+ }
3162
+ };
3163
+ }
3164
+ function configSourceLine(source) {
3165
+ switch (source.kind) {
3166
+ case "file":
3167
+ return `config: ${source.path}${source.explicit ? " (--config)" : ""}`;
3168
+ case "snapshot":
3169
+ return "config: the config snapshot in the report";
3170
+ case "defaults":
3171
+ return "config: the defaults";
3172
+ }
3173
+ }
3174
+
3175
+ // src/cli/offline.ts
3176
+ var DEFAULT_WIDTH = 120;
3177
+ function message(error) {
3178
+ return error instanceof Error ? error.message : String(error);
3179
+ }
3180
+ var Printer = class {
3181
+ host;
3182
+ constructor(host) {
3183
+ this.host = host;
3184
+ }
3185
+ get color() {
3186
+ return outputStyle(this.host.stderr, this.host.env).color;
3187
+ }
3188
+ errors(issues) {
3189
+ this.host.stderr.write(formatIssues(issues, "error", this));
3190
+ return 3;
3191
+ }
3192
+ warnings(issues) {
3193
+ this.host.stderr.write(formatIssues(issues, "warning", this));
3194
+ }
3195
+ info(line) {
3196
+ this.host.stderr.write(infoLine(line));
3197
+ }
3198
+ };
3199
+ function reportNotFound(path, how) {
3200
+ return {
3201
+ code: "CLI_REPORT_NOT_FOUND",
3202
+ message: `The run report ${path} does not exist (${how}).`,
3203
+ hint: `Pass the report explicitly, e.g. --input apps/web/${DEFAULT_CONFIG.report.dir}/report.json, or run "${CLI_COMMAND} test" first.`
3204
+ };
3205
+ }
3206
+ async function readReport(path) {
3207
+ let text;
3208
+ try {
3209
+ text = await readTextFile(path);
3210
+ } catch (error) {
3211
+ return {
3212
+ ok: false,
3213
+ missing: false,
3214
+ issues: [
3215
+ {
3216
+ code: "SCHEMA_INVALID_JSON",
3217
+ message: `${path}: the file cannot be read (${message(error)})`,
3218
+ hint: "Check the path and the file permissions."
3219
+ }
3220
+ ]
3221
+ };
3222
+ }
3223
+ if (text === null) return { ok: false, missing: true, issues: [] };
3224
+ const parsed = parseRunReport(text, path);
3225
+ if (!parsed.ok)
3226
+ return { ok: false, missing: false, issues: parsed.issues.map(schemaIssueToIssue) };
3227
+ return { ok: true, report: parsed.value };
3228
+ }
3229
+ async function configFor(host, out, options) {
3230
+ const reportDir = options.report?.configDir;
3231
+ const reportDirExists = reportDir !== void 0 && await host.exists(reportDir);
3232
+ const searchDirs = [host.cwd];
3233
+ if (reportDirExists && reportDir !== host.cwd) searchDirs.push(reportDir);
3234
+ const resolved = await resolveCliConfig(
3235
+ {
3236
+ ...options.explicit === void 0 ? {} : { explicit: host.paths.resolve(host.cwd, options.explicit) },
3237
+ searchDirs,
3238
+ ...options.report === void 0 ? {} : { report: options.report },
3239
+ mode: options.mode,
3240
+ ...options.env === void 0 ? {} : { env: options.env }
3241
+ },
3242
+ { exists: (p) => host.exists(p), importModule: (url) => host.importModule(url) }
3243
+ );
3244
+ if (!resolved.ok) {
3245
+ out.errors(resolved.issues);
3246
+ return null;
3247
+ }
3248
+ const cfg = resolved.value;
3249
+ for (const note of cfg.notes) out.info(note);
3250
+ out.info(configSourceLine(cfg.source));
3251
+ out.warnings(cfg.warnings);
3252
+ const base = resolveBaseDir({
3253
+ ...cfg.source.kind === "file" ? { loadedConfigFile: cfg.source.path } : {},
3254
+ ...reportDir === void 0 ? {} : { reportConfigDir: reportDir },
3255
+ cwd: host.cwd,
3256
+ exists: (dir) => dir === reportDir && reportDirExists,
3257
+ dirname: host.paths.dirname
3258
+ });
3259
+ out.warnings(base.issues);
3260
+ out.info(`base directory: ${base.dir}`);
3261
+ return { cfg, baseDir: base.dir };
3262
+ }
3263
+ async function thresholdsFrom(cmd, host) {
3264
+ const out = new Printer(host);
3265
+ const reportPath = host.paths.resolve(host.cwd, cmd.from);
3266
+ const read = await readReport(reportPath);
3267
+ if (!read.ok) {
3268
+ return out.errors(
3269
+ read.missing ? [reportNotFound(reportPath, "given with --from")] : read.issues
3270
+ );
3271
+ }
3272
+ const report = read.report;
3273
+ const resolved = await configFor(host, out, {
3274
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
3275
+ report,
3276
+ env: cmd.env ?? report.env,
3277
+ mode: "thresholds"
3278
+ });
3279
+ if (resolved === null) return 3;
3280
+ const { cfg, baseDir } = resolved;
3281
+ const config = cfg.config;
3282
+ if (report.tests.status !== "passed") {
3283
+ out.warnings([
3284
+ {
3285
+ code: "CLI_REPORT_TESTS_FAILED",
3286
+ message: `The tests of the source run did not pass (status "${report.tests.status}"); the thresholds are derived anyway.`,
3287
+ hint: "Review the diff before committing the thresholds files."
3288
+ }
3289
+ ]);
3290
+ }
3291
+ const location = {
3292
+ configDir: baseDir,
3293
+ dir: config.thresholds.dir,
3294
+ filePrefix: config.thresholds.filePrefix,
3295
+ env: config.run.env
3296
+ };
3297
+ const loaded = await loadThresholds(location);
3298
+ const derived = deriveThresholds(report, config, loaded, {
3299
+ env: config.run.env,
3300
+ prune: cmd.prune,
3301
+ toolVersion: host.packageVersion
3302
+ });
3303
+ if (!derived.ok) return out.errors(derived.issues);
3304
+ out.warnings(derived.value.warnings);
3305
+ const absolute = thresholdsFilePaths(location);
3306
+ const writeErrors = [];
3307
+ const written = [];
3308
+ for (const file of derived.value.files) {
3309
+ if (file.content === null || !file.changed) continue;
3310
+ try {
3311
+ await writeJsonStable(absolute[file.kind], file.content);
3312
+ written.push(absolute[file.kind]);
3313
+ } catch (error) {
3314
+ writeErrors.push({
3315
+ code: "CLI_WRITE_FAILED",
3316
+ message: `The thresholds file ${absolute[file.kind]} could not be written: ${message(error)}`,
3317
+ hint: "Check that thresholds.dir is writable, then run the command again."
3318
+ });
3319
+ }
3320
+ }
3321
+ const diffs = derived.value.files.map(
3322
+ (file) => diffThresholds(loaded[file.kind], file, report, config)
3323
+ );
3324
+ const diffPath = resolvePath(resolvePath(baseDir, config.report.dir), "thresholds-diff.md");
3325
+ let diffWritten = false;
3326
+ try {
3327
+ await writeTextAtomic(
3328
+ diffPath,
3329
+ formatThresholdsDiffMarkdown(
3330
+ diffs,
3331
+ derived.value.files.map((file) => loaded[file.kind].path)
3332
+ )
3333
+ );
3334
+ diffWritten = true;
3335
+ } catch (error) {
3336
+ out.warnings([
3337
+ {
3338
+ code: "THRESHOLDS_DIFF_WRITE_FAILED",
3339
+ message: `The thresholds diff could not be written to ${diffPath}: ${message(error)}`,
3340
+ hint: "The thresholds files are written; check that report.dir is writable."
3341
+ }
3342
+ ]);
3343
+ }
3344
+ const stdout = host.stdout;
3345
+ const width = stdout.isTTY === true && stdout.columns !== void 0 && stdout.columns > 0 ? stdout.columns : DEFAULT_WIDTH;
3346
+ stdout.write(
3347
+ formatThresholdsDiff(diffs, {
3348
+ paths: derived.value.files.map((file) => relativeSlashPath(host.cwd, absolute[file.kind])),
3349
+ width,
3350
+ color: outputStyle(stdout, host.env).color,
3351
+ prune: cmd.prune,
3352
+ diffPath: diffWritten ? relativeSlashPath(host.cwd, diffPath) : null
3353
+ })
3354
+ );
3355
+ if (writeErrors.length > 0) return out.errors(writeErrors);
3356
+ out.info(
3357
+ written.length === 0 ? "thresholds files unchanged · exit code 0" : `${written.length === 1 ? "1 thresholds file" : `${written.length} thresholds files`} written · exit code 0`
3358
+ );
3359
+ return 0;
3360
+ }
3361
+ async function renderReport(cmd, host, renderHtml) {
3362
+ const out = new Printer(host);
3363
+ let report;
3364
+ let inputPath;
3365
+ if (cmd.input !== void 0) {
3366
+ inputPath = host.paths.resolve(host.cwd, cmd.input);
3367
+ const read = await readReport(inputPath);
3368
+ if (!read.ok)
3369
+ return out.errors(
3370
+ read.missing ? [reportNotFound(inputPath, "given with --input")] : read.issues
3371
+ );
3372
+ report = read.report;
3373
+ if (await configFor(host, out, {
3374
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
3375
+ report,
3376
+ mode: report.mode
3377
+ }) === null) {
3378
+ return 3;
3379
+ }
3380
+ } else {
3381
+ const resolved = await configFor(host, out, {
3382
+ ...cmd.config === void 0 ? {} : { explicit: cmd.config },
3383
+ mode: "test"
3384
+ });
3385
+ if (resolved === null) return 3;
3386
+ inputPath = resolvePath(
3387
+ resolvePath(resolved.baseDir, resolved.cfg.config.report.dir),
3388
+ "report.json"
3389
+ );
3390
+ const read = await readReport(inputPath);
3391
+ if (!read.ok)
3392
+ return out.errors(
3393
+ read.missing ? [reportNotFound(inputPath, "report.dir of the config")] : read.issues
3394
+ );
3395
+ report = read.report;
3396
+ }
3397
+ const outputPath = cmd.output === void 0 ? resolvePath(host.paths.dirname(inputPath), "report.html") : host.paths.resolve(host.cwd, cmd.output);
3398
+ let page;
3399
+ try {
3400
+ page = renderHtml(report);
3401
+ } catch (error) {
3402
+ return out.errors([
3403
+ {
3404
+ code: "HTML_RENDER_FAILED",
3405
+ message: `The HTML report could not be rendered from ${inputPath}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
3406
+ hint: "This is a bug in the package; please report it with the message above."
3407
+ }
3408
+ ]);
3409
+ }
3410
+ try {
3411
+ await writeTextAtomic(outputPath, page);
3412
+ } catch (error) {
3413
+ return out.errors([
3414
+ {
3415
+ code: "CLI_WRITE_FAILED",
3416
+ message: `The HTML report could not be written to ${outputPath}: ${message(error)}`,
3417
+ hint: "Check that the directory is writable, or pass another --output."
3418
+ }
3419
+ ]);
3420
+ }
3421
+ out.info(`report: ${outputPath}`);
3422
+ return 0;
3423
+ }
3424
+
3425
+ // src/cli/parse.ts
3426
+ var COMMANDS = ["test", "thresholds", "report", "init"];
3427
+ var HELP = /* @__PURE__ */ new Set(["--help", "-h"]);
3428
+ var VERSION = /* @__PURE__ */ new Set(["--version", "-v"]);
3429
+ var USAGE_HINT = `Commands: ${COMMANDS.join(", ")}. Run "${CLI_COMMAND} --help" for the usage.`;
3430
+ var RUN_OPTIONS = ["--env", "--repeat", "--prune", "--from"];
3431
+ var FROM_OPTIONS = ["--env", "--prune", "--from", "--config"];
3432
+ var REPORT_OPTIONS = ["--input", "--output", "--config"];
3433
+ var INIT_OPTIONS = ["--yes", "-y", "--dry-run", "--lang", "--no-tutorial"];
3434
+ var VALUED = /* @__PURE__ */ new Set([
3435
+ "--env",
3436
+ "--repeat",
3437
+ "--from",
3438
+ "--config",
3439
+ "--input",
3440
+ "--output",
3441
+ "--lang"
3442
+ ]);
3443
+ function ownOption(args, i, names, issues) {
3444
+ const arg = args[i];
3445
+ const eq = arg.indexOf("=");
3446
+ const name = eq === -1 ? arg : arg.slice(0, eq);
3447
+ if (!names.includes(name)) return null;
3448
+ if (!VALUED.has(name)) {
3449
+ if (eq !== -1) {
3450
+ issues.push({
3451
+ code: "CLI_INVALID_OPTION",
3452
+ message: `${name} takes no value, got "${arg}".`,
3453
+ hint: `Write ${name} on its own.`
3454
+ });
3455
+ }
3456
+ return { option: { name }, used: 1 };
3457
+ }
3458
+ const next = args[i + 1];
3459
+ const value = eq !== -1 ? arg.slice(eq + 1) : next;
3460
+ if (value === void 0 || value === "" || eq === -1 && value.startsWith("-")) {
3461
+ issues.push({
3462
+ code: "CLI_MISSING_ARGUMENT",
3463
+ message: `${name} needs a value.`,
3464
+ hint: `Write ${name} <value> or ${name}=<value>.`
3465
+ });
3466
+ return { option: { name }, used: eq === -1 && value === "" ? 2 : 1 };
3467
+ }
3468
+ return { option: { name, value }, used: eq !== -1 ? 1 : 2 };
3469
+ }
3470
+ function invalidValue(name, expected, value) {
3471
+ return {
3472
+ code: "CLI_INVALID_OPTION",
3473
+ message: `${name}: expected ${expected}, got ${JSON.stringify(value)}.`,
3474
+ hint: `Fix the value of ${name}.`
3475
+ };
3476
+ }
3477
+ function checkEnv(value, issues) {
3478
+ if (isEnvLabel(value)) return value;
3479
+ issues.push(invalidValue("--env", ENV_LABEL_FORMAT, value));
3480
+ return void 0;
3481
+ }
3482
+ function checkRepeat(value, mode, issues) {
3483
+ const repeat = parseRepeat(value);
3484
+ if (repeat === null) {
3485
+ issues.push(invalidValue("--repeat", REPEAT_FORMAT, value));
3486
+ return void 0;
3487
+ }
3488
+ const resolved = resolveConfig(void 0, { mode, repeat });
3489
+ if (!resolved.ok) {
3490
+ const reason = resolved.issues[0]?.message ?? "out of range";
3491
+ issues.push({
3492
+ code: "CLI_INVALID_OPTION",
3493
+ message: `--repeat: ${reason}.`,
3494
+ hint: "Fix the value of --repeat."
3495
+ });
3496
+ return void 0;
3497
+ }
3498
+ return repeat;
3499
+ }
3500
+ function fail(issues) {
3501
+ return { ok: false, issues };
3502
+ }
3503
+ function parseRun(mode, args) {
3504
+ const sep = args.indexOf("--");
3505
+ const before = sep === -1 ? args : args.slice(0, sep);
3506
+ const after = sep === -1 ? [] : args.slice(sep + 1);
3507
+ if (before.some((a) => HELP.has(a))) return { ok: true, value: { kind: "help", command: mode } };
3508
+ if (mode === "thresholds" && before.some((a) => a === "--from" || a.startsWith("--from="))) {
3509
+ return parseFrom(before, after);
3510
+ }
3511
+ const issues = [];
3512
+ const playwrightArgs = [];
3513
+ let env;
3514
+ let repeat;
3515
+ let prune = false;
3516
+ for (let i = 0; i < before.length; ) {
3517
+ const own = ownOption(before, i, RUN_OPTIONS, issues);
3518
+ if (own === null) {
3519
+ playwrightArgs.push(before[i]);
3520
+ i += 1;
3521
+ continue;
3522
+ }
3523
+ i += own.used;
3524
+ const { name, value } = own.option;
3525
+ if (mode === "test" && (name === "--prune" || name === "--from")) {
3526
+ issues.push({
3527
+ code: "CLI_INVALID_OPTION",
3528
+ message: `${name} is an option of the thresholds command, not of test.`,
3529
+ hint: name === "--from" ? `Derive thresholds from a report with "${CLI_COMMAND} thresholds --from <report.json>".` : `Remove ${name}, or run "${CLI_COMMAND} thresholds --prune".`
3530
+ });
3531
+ continue;
3532
+ }
3533
+ if (name === "--prune") prune = true;
3534
+ else if (value === void 0) continue;
3535
+ else if (name === "--env") env = checkEnv(value, issues);
3536
+ else if (name === "--repeat") repeat = checkRepeat(value, mode, issues);
3537
+ }
3538
+ playwrightArgs.push(...after);
3539
+ const unsupported = unsupportedOptions(playwrightArgs);
3540
+ if (unsupported.length > 0) {
3541
+ issues.push({
3542
+ code: "CLI_UNSUPPORTED_PLAYWRIGHT_OPTION",
3543
+ 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"}.`,
3544
+ hint: 'Remove the option; use "npx playwright test" for UI mode, debugging and sharding.'
3545
+ });
3546
+ }
3547
+ if (prune) {
3548
+ const filters = testFilters(playwrightArgs);
3549
+ if (filters.length > 0) {
3550
+ issues.push({
3551
+ code: "CLI_PRUNE_WITH_FILTER",
3552
+ message: `--prune cannot be used with a test filter (${filters.join(" ")}): entries of the tests left out would be removed from the thresholds files.`,
3553
+ hint: "Run --prune without --grep, --project or file paths, or leave --prune out."
3554
+ });
3555
+ }
3556
+ }
3557
+ if (issues.length > 0) return fail(issues);
3558
+ return {
3559
+ ok: true,
3560
+ value: {
3561
+ kind: "run",
3562
+ mode,
3563
+ ...env === void 0 ? {} : { env },
3564
+ ...repeat === void 0 ? {} : { repeat },
3565
+ prune,
3566
+ playwrightArgs,
3567
+ listOnly: isListOnly(playwrightArgs)
3568
+ }
3569
+ };
3570
+ }
3571
+ function parseFrom(before, after) {
3572
+ const issues = [];
3573
+ const rejected = [];
3574
+ let from;
3575
+ let env;
3576
+ let config;
3577
+ let prune = false;
3578
+ for (let i = 0; i < before.length; ) {
3579
+ const own = ownOption(before, i, FROM_OPTIONS, issues);
3580
+ if (own === null) {
3581
+ const arg = before[i];
3582
+ const name2 = arg.split("=")[0];
3583
+ if (REPORT_OPTIONS.includes(name2)) {
3584
+ issues.push({
3585
+ code: "CLI_INVALID_OPTION",
3586
+ message: `${name2} is an option of the report command, not of thresholds --from.`,
3587
+ hint: `Remove ${name2}.`
3588
+ });
3589
+ if (!arg.includes("=") && before[i + 1] !== void 0) i += 1;
3590
+ } else {
3591
+ rejected.push(arg);
3592
+ }
3593
+ i += 1;
3594
+ continue;
3595
+ }
3596
+ i += own.used;
3597
+ const { name, value } = own.option;
3598
+ if (name === "--prune") prune = true;
3599
+ else if (value === void 0) continue;
3600
+ else if (name === "--from") from = value;
3601
+ else if (name === "--env") env = checkEnv(value, issues);
3602
+ else if (name === "--config") config = value;
3603
+ }
3604
+ rejected.push(...after);
3605
+ if (rejected.length > 0) {
3606
+ issues.push({
3607
+ code: "CLI_FROM_WITH_PLAYWRIGHT_ARGS",
3608
+ message: `thresholds --from runs no tests, so it takes no Playwright arguments and no --repeat; got: ${rejected.join(" ")}.`,
3609
+ hint: `Use only --from, --env, --prune and --config, or run "${CLI_COMMAND} thresholds" without --from to run the tests.`
3610
+ });
3611
+ }
3612
+ if (issues.length > 0 || from === void 0) return fail(issues);
3613
+ return {
3614
+ ok: true,
3615
+ value: {
3616
+ kind: "thresholds-from",
3617
+ from,
3618
+ ...env === void 0 ? {} : { env },
3619
+ prune,
3620
+ ...config === void 0 ? {} : { config }
3621
+ }
3622
+ };
3623
+ }
3624
+ function unexpected(command, arg) {
3625
+ return {
3626
+ code: "CLI_INVALID_OPTION",
3627
+ message: `${command} does not take "${arg}".`,
3628
+ hint: `Run "${CLI_COMMAND} ${command} --help" for its options.`
3629
+ };
3630
+ }
3631
+ function parseReport(args) {
3632
+ if (args.some((a) => HELP.has(a)))
3633
+ return { ok: true, value: { kind: "help", command: "report" } };
3634
+ const issues = [];
3635
+ const found = {};
3636
+ for (let i = 0; i < args.length; ) {
3637
+ const own = ownOption(args, i, REPORT_OPTIONS, issues);
3638
+ if (own === null) {
3639
+ issues.push(unexpected("report", args[i]));
3640
+ i += 1;
3641
+ continue;
3642
+ }
3643
+ i += own.used;
3644
+ if (own.option.value !== void 0) found[own.option.name] = own.option.value;
3645
+ }
3646
+ if (issues.length > 0) return fail(issues);
3647
+ const { "--input": input, "--output": output, "--config": config } = found;
3648
+ return {
3649
+ ok: true,
3650
+ value: {
3651
+ kind: "report",
3652
+ ...input === void 0 ? {} : { input },
3653
+ ...output === void 0 ? {} : { output },
3654
+ ...config === void 0 ? {} : { config }
3655
+ }
3656
+ };
3657
+ }
3658
+ function parseInit(args) {
3659
+ if (args.some((a) => HELP.has(a))) return { ok: true, value: { kind: "help", command: "init" } };
3660
+ const issues = [];
3661
+ let yes = false;
3662
+ let dryRun = false;
3663
+ let noTutorial = false;
3664
+ let lang;
3665
+ for (let i = 0; i < args.length; ) {
3666
+ const own = ownOption(args, i, INIT_OPTIONS, issues);
3667
+ if (own === null) {
3668
+ issues.push(unexpected("init", args[i]));
3669
+ i += 1;
3670
+ continue;
3671
+ }
3672
+ i += own.used;
3673
+ const { name, value } = own.option;
3674
+ if (name === "--yes" || name === "-y") yes = true;
3675
+ else if (name === "--dry-run") dryRun = true;
3676
+ else if (name === "--no-tutorial") noTutorial = true;
3677
+ else if (value !== void 0) {
3678
+ const code = value.toLowerCase();
3679
+ if (isWizardLanguage(code)) lang = code;
3680
+ else issues.push(invalidValue("--lang", `one of ${LANGUAGES.join(", ")}`, value));
3681
+ }
3682
+ }
3683
+ if (issues.length > 0) return fail(issues);
3684
+ return {
3685
+ ok: true,
3686
+ value: {
3687
+ kind: "init",
3688
+ yes,
3689
+ dryRun,
3690
+ ...lang === void 0 ? {} : { lang },
3691
+ ...noTutorial ? { noTutorial: true } : {}
3692
+ }
3693
+ };
3694
+ }
3695
+ function parseArgs(argv) {
3696
+ const first = argv[0];
3697
+ if (first === void 0) {
3698
+ return fail([{ code: "CLI_UNKNOWN_COMMAND", message: "No command given.", hint: USAGE_HINT }]);
3699
+ }
3700
+ if (HELP.has(first)) return { ok: true, value: { kind: "help" } };
3701
+ if (VERSION.has(first)) return { ok: true, value: { kind: "version" } };
3702
+ const rest = argv.slice(1);
3703
+ switch (first) {
3704
+ case "test":
3705
+ case "thresholds":
3706
+ return parseRun(first, rest);
3707
+ case "report":
3708
+ return parseReport(rest);
3709
+ case "init":
3710
+ return parseInit(rest);
3711
+ default:
3712
+ return fail([
3713
+ { code: "CLI_UNKNOWN_COMMAND", message: `Unknown command "${first}".`, hint: USAGE_HINT }
3714
+ ]);
3715
+ }
3716
+ }
3717
+
3718
+ // src/cli/main.ts
3719
+ function color(host) {
3720
+ return outputStyle(host.stderr, host.env);
3721
+ }
3722
+ function internalError(error) {
3723
+ const text = error instanceof Error ? error.stack ?? error.message : String(error);
3724
+ return {
3725
+ code: "CLI_INTERNAL_ERROR",
3726
+ message: `Unexpected error in the CLI: ${text}`,
3727
+ hint: "This is a bug in the package; please report it with the message above."
3728
+ };
3729
+ }
3730
+ async function main(argv, host, options = {}) {
3731
+ try {
3732
+ const parsed = parseArgs(argv);
3733
+ if (!parsed.ok) {
3734
+ host.stderr.write(formatIssues(parsed.issues, "error", color(host)));
3735
+ return 3;
3736
+ }
3737
+ const cmd = parsed.value;
3738
+ switch (cmd.kind) {
3739
+ case "help":
3740
+ host.stdout.write(helpText(cmd.command));
3741
+ return 0;
3742
+ case "version":
3743
+ host.stdout.write(`${host.packageVersion}
3744
+ `);
3745
+ return 0;
3746
+ case "run":
3747
+ return await runTests(cmd, host);
3748
+ case "thresholds-from":
3749
+ return await thresholdsFrom(cmd, host);
3750
+ case "report":
3751
+ return await renderReport(cmd, host, options.renderHtml ?? renderHtmlReport);
3752
+ case "init":
3753
+ return await runInit(cmd, host, color(host));
3754
+ }
3755
+ } catch (error) {
3756
+ host.stderr.write(formatIssues([internalError(error)], "error", color(host)));
3757
+ return 3;
3758
+ }
3759
+ }
3760
+ function isModuleNotFound(error) {
3761
+ return typeof error === "object" && error !== null && "code" in error && error.code === "MODULE_NOT_FOUND";
3762
+ }
3763
+ function resolvePlaywright(dir) {
3764
+ const require2 = createRequire(join(dir, "noop.js"));
3765
+ let manifest;
3766
+ try {
3767
+ manifest = require2.resolve("@playwright/test/package.json");
3768
+ } catch (error) {
3769
+ if (isModuleNotFound(error)) return null;
3770
+ throw error;
3771
+ }
3772
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
3773
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.playwright;
3774
+ if (bin === void 0) throw new Error(`${manifest} has no "bin.playwright" entry`);
3775
+ return { cliPath: resolve(dirname(manifest), bin), version: pkg.version ?? "0.0.0" };
3776
+ }
3777
+ function minimumPlaywright() {
3778
+ const range = peerDependencies["@playwright/test"];
3779
+ return /\d+\.\d+\.\d+/u.exec(range)?.[0] ?? "0.0.0";
3780
+ }
3781
+ function nodeHost() {
3782
+ return {
3783
+ cwd: process.cwd(),
3784
+ paths: { join: join, resolve, dirname },
3785
+ env: process.env,
3786
+ platform: process.platform,
3787
+ tmpdir: tmpdir(),
3788
+ stdin: process.stdin,
3789
+ stdout: process.stdout,
3790
+ stderr: process.stderr,
3791
+ now: () => /* @__PURE__ */ new Date(),
3792
+ random: Math.random,
3793
+ packageVersion: version,
3794
+ minPlaywrightVersion: minimumPlaywright(),
3795
+ // dist/cli.js and dist/reporter.js are siblings (ESM build).
3796
+ reporterPath: fileURLToPath(new URL("./reporter.js", import.meta.url)),
3797
+ resolvePlaywright,
3798
+ spawnNode: (args, options) => spawn(process.execPath, args, options),
3799
+ onSignal: (signal, handler) => {
3800
+ process.on(signal, handler);
3801
+ return () => {
3802
+ process.off(signal, handler);
3803
+ };
3804
+ },
3805
+ readText: readTextFile,
3806
+ removeFile: (path) => rm(path, { force: true }),
3807
+ exists: fileExists,
3808
+ isDirectory: async (path) => {
3809
+ try {
3810
+ return (await stat(path)).isDirectory();
3811
+ } catch {
3812
+ return false;
3813
+ }
3814
+ },
3815
+ importModule: (url) => import(url),
3816
+ listDir: async (path) => {
3817
+ try {
3818
+ const entries = await readdir(path, { withFileTypes: true });
3819
+ return entries.map((e) => ({ name: e.name, directory: e.isDirectory() })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3820
+ } catch {
3821
+ return [];
3822
+ }
3823
+ },
3824
+ writeText: async (path, text) => {
3825
+ await mkdir(dirname(path), { recursive: true });
3826
+ await writeFile(path, text, "utf8");
3827
+ },
3828
+ createPrompt: () => readlinePrompt(process.stdin, process.stdout)
3829
+ };
3830
+ }
3831
+
3832
+ // src/entries/cli.ts
3833
+ process.exitCode = await main(process.argv.slice(2), nodeHost());