playwright-performance-regression 0.1.0-next.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { renderHtmlReport, fileExists, readTextFile, resolvePath, writeTextAtomic, loadThresholds, deriveThresholds, thresholdsFilePaths, writeJsonStable, diffThresholds, formatThresholdsDiffMarkdown, formatThresholdsDiff, relativeSlashPath, parseRunReport, schemaIssueToIssue, parseOutcome } from './chunk-JEHUFIY3.js';
3
- import { CONFIG_FILE_EXTENSIONS, CONFIG_FILE_BASENAME, version, CLI_COMMAND, PACKAGE_NAME, REPOSITORY_URL, generateRunId, peerDependencies, parseRepeat, isEnvLabel, MODE_ENV_NAMES, writeModeState, DOCS_CONFIG_URL, ENV_LABEL_FORMAT, REPEAT_FORMAT } from './chunk-6AB42SPF.js';
4
- import { DEFAULT_CONFIG, resolveConfig } from './chunk-HES6BVZT.js';
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
5
  import { createInterface } from 'readline/promises';
6
6
  import { mkdir, writeFile, readdir, stat, rm, readFile } from 'fs/promises';
7
7
  import { dirname, resolve, join, extname, basename } from 'path';
@@ -11,6 +11,858 @@ import { readFileSync } from 'fs';
11
11
  import { createRequire } from 'module';
12
12
  import { tmpdir } from 'os';
13
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
+
14
866
  // src/cli/help.ts
15
867
  var REPEAT_NOTE = [
16
868
  "Note: every test runs several times in one worker. Tests that create data with unique",
@@ -18,9 +870,9 @@ var REPEAT_NOTE = [
18
870
  "leave such tests out with --grep-invert."
19
871
  ];
20
872
  var EXIT_CODES = [
21
- "Exit codes: 0 ok (failed tests are reported as a warning) \xB7 2 performance regression \xB7",
873
+ "Exit codes: 0 ok (failed tests are reported as a warning) · 2 performance regression ·",
22
874
  "3 tool or config error, or an untrustworthy result (too many failed tests, incomplete run)",
23
- "\xB7 130/143 interrupted (SIGINT/SIGTERM)"
875
+ "· 130/143 interrupted (SIGINT/SIGTERM)"
24
876
  ];
25
877
  var PASS_THROUGH = [
26
878
  'All other arguments go to "playwright test" unchanged; arguments after "--" are never read',
@@ -92,8 +944,8 @@ var THRESHOLDS = [
92
944
  "",
93
945
  ...REPEAT_NOTE,
94
946
  "",
95
- "Exit codes: 0 ok \xB7 3 tool or config error, or an untrustworthy run (nothing is written)",
96
- "\xB7 130/143 interrupted (SIGINT/SIGTERM)"
947
+ "Exit codes: 0 ok · 3 tool or config error, or an untrustworthy run (nothing is written)",
948
+ "· 130/143 interrupted (SIGINT/SIGTERM)"
97
949
  ];
98
950
  var REPORT = [
99
951
  `Usage: ${CLI_COMMAND} report [--input <report.json>] [--output <report.html>] [--config <file>]`,
@@ -106,10 +958,10 @@ var REPORT = [
106
958
  " --config <file> Package config file; default: pw-perf.config.* in the current directory",
107
959
  " -h, --help Show this help",
108
960
  "",
109
- "Exit codes: 0 ok \xB7 3 error"
961
+ "Exit codes: 0 ok · 3 error"
110
962
  ];
111
963
  var INIT = [
112
- `Usage: ${CLI_COMMAND} init [--yes] [--dry-run]`,
964
+ `Usage: ${CLI_COMMAND} init [--yes] [--dry-run] [--lang <code>] [--no-tutorial]`,
113
965
  "",
114
966
  "Guided setup of the package in this project: asks a few questions, shows a diff of every",
115
967
  "change and applies it after confirmation. Files it does not recognize are left unchanged",
@@ -118,9 +970,11 @@ var INIT = [
118
970
  "Options:",
119
971
  " -y, --yes Accept the default answers and write the changes",
120
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",
121
975
  " -h, --help Show this help",
122
976
  "",
123
- "Exit codes: 0 done (also with manual steps left) \xB7 3 error \xB7 130 interrupted"
977
+ "Exit codes: 0 done (also with manual steps left) · 3 error · 130 interrupted"
124
978
  ];
125
979
  var TOPICS = {
126
980
  test: TEST,
@@ -399,16 +1253,16 @@ async function readProjectFiles(host, root) {
399
1253
  files.set(INSTALLED_PLAYWRIGHT, JSON.stringify({ version: playwright.version }));
400
1254
  const config = PLAYWRIGHT_CONFIG_NAMES.find((name) => files.has(name));
401
1255
  if (config === void 0) return files;
402
- let count2 = 0;
1256
+ let count = 0;
403
1257
  const walk = async (rel, depth) => {
404
1258
  if (depth > MAX_DEPTH || rel.split("/").includes("..")) return;
405
1259
  for (const entry of await host.listDir(rel === "." ? root : join3(rel))) {
406
- if (count2 >= MAX_FILES) return;
1260
+ if (count >= MAX_FILES) return;
407
1261
  const path = rel === "." ? entry.name : `${rel}/${entry.name}`;
408
1262
  if (entry.directory) {
409
1263
  if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) await walk(path, depth + 1);
410
1264
  } else if (SOURCE_FILE.test(entry.name) && !files.has(path)) {
411
- count2 += 1;
1265
+ count += 1;
412
1266
  await read(path);
413
1267
  }
414
1268
  }
@@ -966,22 +1820,22 @@ function change(info, path, after) {
966
1820
  if (before === after) return null;
967
1821
  return { path, kind: before === null ? "create" : "modify", before, after };
968
1822
  }
969
- var CONFIG_HINT = (path) => [
970
- `Wrap the exported config in withPerf() as the outermost call (also around other wrappers):`,
1823
+ var CONFIG_HINT = (t, path) => [
1824
+ t("configHintIntro"),
971
1825
  ` import { withPerf } from '${PACKAGE_NAME}/config';`,
972
1826
  ` import perfConfig from './pw-perf.config';`,
973
1827
  ` export default withPerf(otherWrapper(defineConfig({ ... })), perfConfig);`,
974
- `In ${path} with module.exports: withPerf(config, require('./pw-perf.config').default).`
1828
+ t("configHintCjs", { path, call: "withPerf(config, require('./pw-perf.config').default)" })
975
1829
  ].join("\n");
976
- var TEST_HINT = [
977
- `Wrap every test object used by browser tests in withPerfFixtures() from '${PACKAGE_NAME}/fixture':`,
1830
+ var TEST_HINT = (t) => [
1831
+ t("testHintIntro", { entry: `${PACKAGE_NAME}/fixture` }),
978
1832
  " export const test = withPerfFixtures(base.extend({ ... }));",
979
1833
  " export const adminTest = withPerfFixtures(test.extend({ ... }));",
980
1834
  " export const merged = withPerfFixtures(mergeTests(a, b));",
981
- "Wrap the result of mergeTests() and the test passed to createBdd() (playwright-bdd).",
982
- `Tests that import test from @playwright/test can import it from '${PACKAGE_NAME}/test' instead.`
1835
+ t("testHintMerge"),
1836
+ t("testHintImport", { entry: `${PACKAGE_NAME}/test` })
983
1837
  ].join("\n");
984
- function planPerfConfig(info, answers, plan) {
1838
+ function planPerfConfig(info, answers, plan, t) {
985
1839
  const existing = info.existing.perfConfig;
986
1840
  if (existing === null || existing === PERF_CONFIG_FILE) {
987
1841
  const c = change(info, PERF_CONFIG_FILE, renderPerfConfig(answers));
@@ -996,22 +1850,22 @@ function planPerfConfig(info, answers, plan) {
996
1850
  if (values.length > 0) {
997
1851
  plan.manualSteps.push(
998
1852
  manual(
999
- `${existing} exists and was not changed.`,
1000
- `Set these options in it if you want them:
1853
+ t("manualPerfConfigKept", { file: existing }),
1854
+ `${t("manualPerfConfigHint")}
1001
1855
  ${values.map((v) => ` ${v}`).join("\n")}`
1002
1856
  )
1003
1857
  );
1004
1858
  }
1005
1859
  }
1006
- function planPlaywrightConfig(info, plan) {
1860
+ function planPlaywrightConfig(info, plan, t) {
1007
1861
  const config = info.playwrightConfig;
1008
1862
  if (config === null || info.existing.wrappedConfig) return;
1009
1863
  const existing = info.existing.perfConfig;
1010
1864
  if (existing !== null && existing.endsWith(".json")) {
1011
1865
  plan.manualSteps.push(
1012
1866
  manual(
1013
- `${config.path} was not changed: the package config is ${existing}.`,
1014
- CONFIG_HINT(config.path).replaceAll("'./pw-perf.config'", `'./${existing}'`)
1867
+ t("manualConfigJson", { config: config.path, file: existing }),
1868
+ CONFIG_HINT(t, config.path).replaceAll("'./pw-perf.config'", `'./${existing}'`)
1015
1869
  )
1016
1870
  );
1017
1871
  return;
@@ -1019,16 +1873,13 @@ function planPlaywrightConfig(info, plan) {
1019
1873
  const after = wrapPlaywrightConfig(config.text, "./pw-perf.config");
1020
1874
  if (after === null) {
1021
1875
  plan.manualSteps.push(
1022
- manual(
1023
- `${config.path} was not changed: its export is not a plain defineConfig({...}) or object (for example another wrapper).`,
1024
- CONFIG_HINT(config.path)
1025
- )
1876
+ manual(t("manualConfigPattern", { config: config.path }), CONFIG_HINT(t, config.path))
1026
1877
  );
1027
1878
  return;
1028
1879
  }
1029
1880
  plan.changes.push({ path: config.path, kind: "modify", before: config.text, after });
1030
1881
  }
1031
- function planTestObject(info, plan) {
1882
+ function planTestObject(info, plan, t) {
1032
1883
  if (info.existing.wrappedTest) return;
1033
1884
  const text = (path) => info.files.get(path) ?? "";
1034
1885
  const extendFiles = info.filesWithExtend;
@@ -1041,12 +1892,7 @@ function planTestObject(info, plan) {
1041
1892
  return after2 === null ? [] : [{ path, kind: "modify", before: text(path), after: after2 }];
1042
1893
  });
1043
1894
  if (swaps.length === 0) {
1044
- plan.manualSteps.push(
1045
- manual(
1046
- "No test object was found to measure: no file imports test from @playwright/test.",
1047
- TEST_HINT
1048
- )
1049
- );
1895
+ plan.manualSteps.push(manual(t("manualNoTestObject"), TEST_HINT(t)));
1050
1896
  }
1051
1897
  plan.changes.push(...swaps);
1052
1898
  return;
@@ -1057,8 +1903,10 @@ function planTestObject(info, plan) {
1057
1903
  const files = [.../* @__PURE__ */ new Set([...extendFiles, ...merges])].sort();
1058
1904
  plan.manualSteps.push(
1059
1905
  manual(
1060
- `${files.join(", ")} ${files.length === 1 ? "was" : "were"} not changed: the test objects are not one \`export const test = base.extend(...)\` (several test objects, mergeTests() or another layout).`,
1061
- TEST_HINT
1906
+ `${t(files.length === 1 ? "manualTestObjectOne" : "manualTestObjectMany", {
1907
+ files: files.join(", ")
1908
+ })} ${t("testObjectsReason")}`,
1909
+ TEST_HINT(t)
1062
1910
  )
1063
1911
  );
1064
1912
  return;
@@ -1072,14 +1920,14 @@ function planGitignore(info, plan) {
1072
1920
  const c = change(info, ".gitignore", addIgnore(current, dir));
1073
1921
  if (c !== null) plan.changes.push(c);
1074
1922
  }
1075
- function planScripts(info, answers, plan) {
1923
+ function planScripts(info, answers, plan, t) {
1076
1924
  const text = info.files.get("package.json");
1077
1925
  const wanted = plannedScripts(answers);
1078
1926
  if (text === void 0) {
1079
1927
  plan.manualSteps.push(
1080
1928
  manual(
1081
- "package.json was not found.",
1082
- `Add these scripts:
1929
+ t("manualNoPackageJson"),
1930
+ `${t("addScripts")}
1083
1931
  ${Object.entries(wanted).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1084
1932
  )
1085
1933
  );
@@ -1097,10 +1945,7 @@ ${Object.entries(wanted).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1097
1945
  if (current[name] === void 0) added[name] = command;
1098
1946
  else if (current[name] !== command) {
1099
1947
  plan.manualSteps.push(
1100
- manual(
1101
- `package.json: the script "${name}" exists and was not changed.`,
1102
- `The wizard would add "${name}": "${command}". Rename one of them, or add the command by hand.`
1103
- )
1948
+ manual(t("manualScriptExists", { name }), t("manualScriptHint", { name, command }))
1104
1949
  );
1105
1950
  }
1106
1951
  }
@@ -1109,8 +1954,8 @@ ${Object.entries(wanted).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1109
1954
  if (after === null) {
1110
1955
  plan.manualSteps.push(
1111
1956
  manual(
1112
- 'package.json was not changed: it is not a JSON object with a "scripts" object.',
1113
- `Add these scripts:
1957
+ t("manualPackageJsonInvalid"),
1958
+ `${t("addScripts")}
1114
1959
  ${Object.entries(added).map(([k, v]) => ` "${k}": "${v}"`).join("\n")}`
1115
1960
  )
1116
1961
  );
@@ -1123,7 +1968,7 @@ var INSTALL = {
1123
1968
  pnpm: "pnpm install --frozen-lockfile",
1124
1969
  yarn: "yarn install --immutable"
1125
1970
  };
1126
- function planCi(info, answers, plan) {
1971
+ function planCi(info, answers, plan, t) {
1127
1972
  const platform = info.ciPlatform;
1128
1973
  if (!answers.addCi || platform === null) return;
1129
1974
  const created = [];
@@ -1132,10 +1977,7 @@ function planCi(info, answers, plan) {
1132
1977
  if (before === file.text) continue;
1133
1978
  if (before !== null) {
1134
1979
  plan.manualSteps.push(
1135
- manual(
1136
- `${file.path} exists and was not changed.`,
1137
- `Compare it with examples/ci/ in the ${PACKAGE_NAME} repository.`
1138
- )
1980
+ manual(t("manualCiKept", { file: file.path }), t("manualCiHint", { pkg: PACKAGE_NAME }))
1139
1981
  );
1140
1982
  continue;
1141
1983
  }
@@ -1148,7 +1990,7 @@ function planCi(info, answers, plan) {
1148
1990
  if (missing.length > 0) {
1149
1991
  plan.manualSteps.push(
1150
1992
  manual(
1151
- ".gitlab-ci.yml was not changed: include the new job file in it.",
1993
+ t("manualGitlabInclude"),
1152
1994
  ["include:", ...missing.map((p) => ` - local: ${p}`)].join("\n")
1153
1995
  )
1154
1996
  );
@@ -1157,20 +1999,25 @@ function planCi(info, answers, plan) {
1157
1999
  if (created.length > 0 && info.packageManager !== "npm") {
1158
2000
  plan.manualSteps.push(
1159
2001
  manual(
1160
- `${created.join(", ")} ${created.length === 1 ? "installs" : "install"} the dependencies with npm.`,
1161
- `This project uses ${info.packageManager}: replace "npm ci" with "${INSTALL[info.packageManager]}" and "npx" with "${info.packageManager === "pnpm" ? "pnpm exec" : "yarn"}".`
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
+ })
1162
2008
  )
1163
2009
  );
1164
2010
  }
1165
2011
  }
1166
- function planInitChanges(info, answers) {
2012
+ function planInitChanges(info, answers, lang = "en") {
2013
+ const t = translator(lang);
1167
2014
  const plan = { changes: [], manualSteps: [] };
1168
- planPerfConfig(info, answers, plan);
1169
- planPlaywrightConfig(info, plan);
1170
- planTestObject(info, plan);
2015
+ planPerfConfig(info, answers, plan, t);
2016
+ planPlaywrightConfig(info, plan, t);
2017
+ planTestObject(info, plan, t);
1171
2018
  planGitignore(info, plan);
1172
- planScripts(info, answers, plan);
1173
- planCi(info, answers, plan);
2019
+ planScripts(info, answers, plan, t);
2020
+ planCi(info, answers, plan, t);
1174
2021
  return plan;
1175
2022
  }
1176
2023
  function isProtected(info, path) {
@@ -1212,17 +2059,18 @@ function readlinePrompt(input, output, terminal) {
1212
2059
 
1213
2060
  // src/cli/output.ts
1214
2061
  var PREFIX = `${PACKAGE_NAME}: `;
1215
- var ANSI = { red: "\x1B[31m", yellow: "\x1B[33m", green: "\x1B[32m" };
1216
- var RESET = "\x1B[0m";
1217
- function paint(text, style2, opts) {
1218
- return opts.color ? `${ANSI[style2]}${text}${RESET}` : text;
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);
1219
2067
  }
1220
2068
  function infoLine(text) {
1221
2069
  return `${PREFIX}${text}
1222
2070
  `;
1223
2071
  }
1224
2072
  function formatIssue(issue, level, opts) {
1225
- const label = paint(`${level} ${issue.code}`, level === "error" ? "red" : "yellow", opts);
2073
+ const label = paint2(`${level} ${issue.code}`, level === "error" ? "red" : "yellow", opts);
1226
2074
  const lines2 = [`${PREFIX}${label}: ${issue.message}`];
1227
2075
  if (issue.hint !== void 0) {
1228
2076
  for (const line of issue.hint.split("\n")) lines2.push(` ${line}`);
@@ -1253,9 +2101,9 @@ function resultLines(outcome, exitCode, opts) {
1253
2101
  outcome.mode === "thresholds" ? outcome.exitCode === 0 ? "thresholds derived" : "thresholds not written" : EVALUATION_TEXT[outcome.evaluation.status]
1254
2102
  );
1255
2103
  }
1256
- const code = paint(`exit code ${exitCode}`, exitCode === 0 ? "green" : "red", opts);
2104
+ const code = paint2(`exit code ${exitCode}`, exitCode === 0 ? "green" : "red", opts);
1257
2105
  parts.push(code);
1258
- let text = infoLine(parts.join(" \xB7 "));
2106
+ let text = infoLine(parts.join(" · "));
1259
2107
  const report = outcome?.paths.reportHtml ?? outcome?.paths.reportJson ?? null;
1260
2108
  if (report !== null) text += infoLine(`report: ${report}`);
1261
2109
  const diff = outcome?.paths.thresholdsDiff ?? null;
@@ -1501,7 +2349,7 @@ function versionAtLeast(version2, minimum) {
1501
2349
  return true;
1502
2350
  }
1503
2351
  function style(host) {
1504
- return { color: host.stderr.isTTY === true && (host.env.NO_COLOR ?? "") === "" };
2352
+ return outputStyle(host.stderr, host.env);
1505
2353
  }
1506
2354
  async function playwrightDir(cmd, host) {
1507
2355
  const config = playwrightConfigArg(cmd.playwrightArgs);
@@ -1642,16 +2490,22 @@ var PLATFORM_NAMES = {
1642
2490
  azure: "Azure Pipelines"
1643
2491
  };
1644
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("/")}]`;
1645
2495
  var WriteFailed = class extends Error {
1646
2496
  };
1647
2497
  var Dialog = class {
1648
2498
  #host;
1649
2499
  #prompt;
1650
2500
  #style;
2501
+ /** Colors of stdout (04-REQ-44). */
2502
+ paint;
2503
+ t = translator("en");
1651
2504
  constructor(host, prompt, style2) {
1652
2505
  this.#host = host;
1653
2506
  this.#prompt = prompt;
1654
2507
  this.#style = style2;
2508
+ this.paint = painter(colorEnabled(host.stdout, host.env));
1655
2509
  }
1656
2510
  get interactive() {
1657
2511
  return this.#prompt !== null;
@@ -1660,17 +2514,36 @@ var Dialog = class {
1660
2514
  this.#host.stdout.write(lines2.map((l) => `${l}
1661
2515
  `).join(""));
1662
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. */
1663
2522
  step(n, title, ...lesson) {
1664
- this.say("", `Step ${n}/${STEPS} \xB7 ${title}`, ...lesson.map((l) => ` ${l}`));
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)));
1665
2528
  }
1666
2529
  warn(issues) {
1667
2530
  if (issues.length > 0) this.#host.stderr.write(formatIssues(issues, "warning", this.#style));
1668
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
+ }
1669
2542
  /** A question with a default; `parse` returns the value or null to ask again. */
1670
2543
  async ask(question, shownDefault, fallback, parse, fallbackText = shownDefault) {
1671
- const text = ` ${question} (${shownDefault}) `;
2544
+ const text = ` ${this.paint(question, "bold")} ${this.paint(`(${shownDefault})`, "dim")} `;
1672
2545
  if (this.#prompt === null) {
1673
- this.say(`${text}\u2192 ${fallbackText}`);
2546
+ this.say(`${text}→ ${this.paint(fallbackText, "bold")}`);
1674
2547
  return fallback;
1675
2548
  }
1676
2549
  for (; ; ) {
@@ -1678,75 +2551,124 @@ var Dialog = class {
1678
2551
  if (answer === "") return fallback;
1679
2552
  const value = parse(answer);
1680
2553
  if (value !== null) return value;
1681
- this.say(" Please answer again: that value is not valid here.");
2554
+ this.line(`⚠ ${this.t("answerAgain")}`, "yellow");
1682
2555
  }
1683
2556
  }
1684
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")]);
1685
2563
  return this.ask(
1686
2564
  question,
1687
- fallback ? "Y/n" : "y/N",
2565
+ fallback ? `${y.toUpperCase()}/${n}` : `${y}/${n.toUpperCase()}`,
1688
2566
  fallback,
1689
- (a) => /^(y|yes)$/iu.test(a) ? true : /^(n|no)$/iu.test(a) ? false : null,
1690
- fallback ? "yes" : "no"
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")
1691
2572
  );
1692
2573
  }
1693
2574
  async pause() {
1694
- if (this.#prompt !== null) await this.#prompt.ask(" Press Enter to continue. ");
2575
+ if (this.#prompt !== null)
2576
+ await this.#prompt.ask(` ${this.paint(this.t("pressEnter"), "dim")} `);
1695
2577
  }
1696
2578
  };
1697
- function count(n, one, many) {
1698
- return `${n} ${n === 1 ? one : many}`;
1699
- }
1700
2579
  function runCommand(manager, script) {
1701
2580
  return manager === "npm" ? `npm run ${script}` : `${manager} ${script}`;
1702
2581
  }
1703
- function describeProject(info) {
2582
+ function describeProject(info, t) {
1704
2583
  const config = info.playwrightConfig;
1705
2584
  const lines2 = [
1706
- `${config?.path ?? "-"} \xB7 Playwright ${info.playwrightVersion ?? "version unknown"} \xB7 ${info.packageManager} \xB7 ${info.moduleType === "esm" ? "ES modules" : "CommonJS"}`,
1707
- `Test directory "${info.testDir}": ${count(info.filesImportingPlaywrightTest.length, "file imports", "files import")} @playwright/test, ${count(info.filesWithExtend.length, "file calls", "files call")} .extend()`
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
+ })
1708
2596
  ];
1709
2597
  if (info.baseUrls.length > 0 || info.projectNames.length > 0) {
1710
2598
  lines2.push(
1711
2599
  [
1712
2600
  info.baseUrls.length > 0 ? `baseURL ${info.baseUrls.join(", ")}` : null,
1713
- info.projectNames.length > 0 ? `projects ${info.projectNames.join(", ")}` : null
1714
- ].filter((part) => part !== null).join(" \xB7 ")
2601
+ info.projectNames.length > 0 ? t("projectsPart", { names: info.projectNames.join(", ") }) : null
2602
+ ].filter((part) => part !== null).join(" · ")
1715
2603
  );
1716
2604
  }
1717
- lines2.push(`CI: ${info.ciPlatform === null ? "none found" : PLATFORM_NAMES[info.ciPlatform]}`);
2605
+ lines2.push(
2606
+ t("ciLine", {
2607
+ platform: info.ciPlatform === null ? t("ciNone") : PLATFORM_NAMES[info.ciPlatform]
2608
+ })
2609
+ );
1718
2610
  if (info.existing.wrappedConfig || info.existing.wrappedTest || info.existing.perfConfig !== null) {
1719
2611
  lines2.push(
1720
- `Already set up: ${[
1721
- info.existing.wrappedConfig ? "withPerf()" : null,
1722
- info.existing.wrappedTest ? "measured test object" : null,
1723
- info.existing.perfConfig
1724
- ].filter((part) => part !== null).join(", ")}`
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
+ })
1725
2619
  );
1726
2620
  }
1727
2621
  return lines2;
1728
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
+ }
1729
2652
  async function askAnswers(dialog, info) {
2653
+ const { t } = dialog;
1730
2654
  dialog.step(
1731
2655
  2,
1732
- "How it works",
1733
- `1. Measurement runs are separate from your usual test runs: "${CLI_COMMAND} test" runs the tests in perf mode.`,
1734
- "2. Every test runs several times in one worker, so each backend request gets enough samples.",
1735
- '3. Requests are grouped into endpoint keys such as "GET api /users/:id".',
1736
- `4. "${CLI_COMMAND} thresholds" derives thresholds per key into files you commit to the repository.`,
1737
- "5. Exit code 0 means ok, 2 a performance regression, 3 a tool or config error."
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")}`
1738
2662
  );
1739
2663
  await dialog.pause();
1740
- dialog.step(3, "Backend", "Endpoint keys start with a short label of the backend origin.");
2664
+ dialog.stepOf(3, "stepBackend", "backendLesson");
1741
2665
  const originLabels = {};
1742
- if (info.baseUrls.length === 0) {
1743
- dialog.say(" No baseURL found in playwright.config: requests are labeled with their host.");
1744
- }
2666
+ if (info.baseUrls.length === 0) dialog.say(` ${t("noBaseUrl")}`);
1745
2667
  const used = /* @__PURE__ */ new Set();
1746
2668
  for (const origin of info.baseUrls) {
1747
2669
  const fallback = defaultLabel(origin, used);
1748
2670
  const label = await dialog.ask(
1749
- `Label for ${origin}?`,
2671
+ t("labelQuestion", { origin }),
1750
2672
  fallback,
1751
2673
  fallback,
1752
2674
  (a) => /^[a-z0-9.-]{1,64}$/u.test(a) ? a : null
@@ -1757,33 +2679,33 @@ async function askAnswers(dialog, info) {
1757
2679
  const tagged = info.taggedPerfTestFiles > 0;
1758
2680
  dialog.step(
1759
2681
  4,
1760
- "Which tests",
1761
- "A measurement run takes about (tests \xD7 repetitions) test runs on 1 worker, so measure the tests",
1762
- `that call the important backend endpoints. Files with tests tagged @perf: ${info.taggedPerfTestFiles}.`
2682
+ t("stepTests"),
2683
+ t("testsLesson"),
2684
+ t("taggedFiles", { count: info.taggedPerfTestFiles })
1763
2685
  );
1764
2686
  if (!tagged) {
1765
2687
  dialog.warn([
1766
2688
  {
1767
2689
  code: "INIT_NO_TAGGED_TESTS",
1768
- message: "No test is tagged @perf, so all tests are proposed.",
1769
- hint: "Tag the tests to measure with test('title @perf', ...) or test('title', { tag: '@perf' }, ...), then choose @perf."
2690
+ message: t("noTaggedMessage"),
2691
+ hint: t("noTaggedHint")
1770
2692
  }
1771
2693
  ]);
1772
2694
  }
2695
+ const all = t("scopeAll");
1773
2696
  const scope = await dialog.ask(
1774
- "Measure all tests or only tests tagged @perf? [all/@perf]",
1775
- tagged ? "@perf" : "all",
2697
+ t("scopeQuestion", { all }),
2698
+ tagged ? "@perf" : all,
1776
2699
  tagged ? "tagged" : "all",
1777
- (a) => a === "all" ? "all" : a === "@perf" || a === "perf" ? "tagged" : null
1778
- );
1779
- dialog.step(
1780
- 5,
1781
- "Repetitions",
1782
- "Each rule needs a minimum number of samples per endpoint (minSamples), and samples are",
1783
- "calls per test \xD7 tests \xD7 repetitions."
2700
+ (a) => {
2701
+ const answer = a.toLowerCase();
2702
+ if (answer === "all" || answer === all) return "all";
2703
+ return answer === "@perf" || answer === "perf" ? "tagged" : null;
2704
+ }
1784
2705
  );
2706
+ dialog.stepOf(5, "stepRepeat", "repeatLesson");
1785
2707
  const repeatTest = await dialog.ask(
1786
- "Repetitions per test in measurement runs?",
2708
+ t("repeatQuestion"),
1787
2709
  String(DEFAULT_ANSWERS_REPEAT),
1788
2710
  DEFAULT_ANSWERS_REPEAT,
1789
2711
  (a) => {
@@ -1791,75 +2713,64 @@ async function askAnswers(dialog, info) {
1791
2713
  return n !== null && resolveConfig({ run: { repeat: { test: n } } }, {}).ok ? n : null;
1792
2714
  }
1793
2715
  );
1794
- dialog.step(
1795
- 6,
1796
- "Trial period",
1797
- "In warn-only mode regressions are reported but do not fail the run, so you can watch the",
1798
- "results for a few weeks before they block builds."
1799
- );
1800
- const warnOnly = await dialog.confirm("Start in warn-only mode for the first weeks?", true);
1801
- dialog.step(
1802
- 7,
1803
- "Environments",
1804
- "Each environment gets its own thresholds files (perf-thresholds.<kind>.<label>.json)."
1805
- );
2716
+ dialog.stepOf(6, "stepTrial", "trialLesson");
2717
+ const warnOnly = await dialog.confirm(t("warnOnlyQuestion"), true);
2718
+ dialog.stepOf(7, "stepEnvs", "envsLesson");
1806
2719
  let envLabels = [];
1807
- if (await dialog.confirm("Do you run against several environments?", false)) {
1808
- envLabels = await dialog.ask(
1809
- "Environment labels, separated by commas?",
1810
- "none",
1811
- [],
1812
- (a) => {
1813
- const labels = [
1814
- ...new Set(
1815
- a.split(",").map((l) => l.trim()).filter((l) => l !== "")
1816
- )
1817
- ];
1818
- return labels.length > 0 && labels.every(isEnvLabel) ? labels : null;
1819
- }
1820
- );
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
+ });
1821
2729
  }
1822
- dialog.step(
1823
- 8,
1824
- "CI",
1825
- "A CI job runs the measurement on pull requests and every night and keeps the report."
1826
- );
2730
+ dialog.stepOf(8, "stepCi", "ciLesson");
1827
2731
  let addCi = false;
1828
2732
  if (info.ciPlatform === null) {
1829
- dialog.say(
1830
- ` No CI configuration found. Recipes for GitHub Actions, GitLab CI, Jenkins and Azure Pipelines: ${DOCS}/ci.md`
1831
- );
2733
+ dialog.say(` ${t("noCi", { url: `${DOCS}/ci.md` })}`);
1832
2734
  } else {
1833
2735
  addCi = await dialog.confirm(
1834
- `Add a CI job for measurement runs (${PLATFORM_NAMES[info.ciPlatform]})?`,
2736
+ t("ciQuestion", { platform: PLATFORM_NAMES[info.ciPlatform] }),
1835
2737
  true
1836
2738
  );
1837
2739
  }
1838
2740
  return { originLabels, scope, repeatTest, warnOnly, envLabels, addCi };
1839
2741
  }
1840
- function changeTitle(change2) {
1841
- return `${change2.path} (${change2.kind === "create" ? "new file" : "change"})`;
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;
1842
2751
  }
1843
2752
  async function applyChanges(dialog, host, info, changes, write, yes) {
2753
+ const { t, paint: paint3 } = dialog;
1844
2754
  const written = [];
1845
2755
  for (const change2 of changes) {
1846
2756
  dialog.say(
1847
2757
  "",
1848
- ` ${changeTitle(change2)}`,
1849
- ...unifiedDiff(change2).trimEnd().split("\n").map((l) => ` ${l}`)
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
+ })
1850
2763
  );
1851
2764
  let apply;
1852
2765
  if (isProtected(info, change2.path)) {
1853
2766
  if (dialog.interactive)
1854
- apply = await dialog.confirm(`${change2.path} exists. Overwrite it?`, false);
2767
+ apply = await dialog.confirm(t("overwriteQuestion", { path: change2.path }), false);
1855
2768
  else {
1856
- dialog.say(
1857
- ` ${change2.path} exists and is kept${yes ? " (--yes does not overwrite it)" : ""}.`
1858
- );
2769
+ dialog.say(` ${t(yes ? "keptWithYes" : "kept", { path: change2.path })}`);
1859
2770
  apply = false;
1860
2771
  }
1861
2772
  } else {
1862
- apply = await dialog.confirm("Apply this change?", true);
2773
+ apply = await dialog.confirm(t("applyQuestion"), true);
1863
2774
  }
1864
2775
  if (!apply || !write) continue;
1865
2776
  try {
@@ -1869,133 +2780,119 @@ async function applyChanges(dialog, host, info, changes, write, yes) {
1869
2780
  `${change2.path}: ${error instanceof Error ? error.message : String(error)}`
1870
2781
  );
1871
2782
  }
2783
+ dialog.line(`✔ ${t("fileWritten", { path: change2.path })}`, "green");
1872
2784
  written.push(change2.path);
1873
2785
  }
1874
2786
  return written;
1875
2787
  }
1876
- function nextSteps(info, answers, written) {
2788
+ function nextSteps(dialog, info, answers, written) {
2789
+ const { t, paint: paint3 } = dialog;
1877
2790
  const scripts = Object.keys(plannedScripts(answers));
1878
2791
  const thresholds = scripts.find((s) => s.startsWith("perf:thresholds"));
1879
2792
  const test = scripts.find((s) => s.startsWith("perf:test"));
2793
+ const command = (script) => paint3(runCommand(info.packageManager, script), "cyan");
1880
2794
  const steps = [
1881
- `${runCommand(info.packageManager, thresholds)}: derive the thresholds and commit the perf-thresholds.*.json files (derive them on the CI machines for stable values).`,
1882
- `${runCommand(info.packageManager, test)}: a measurement run that fails on a regression.`
2795
+ t("nextThresholds", { command: command(thresholds) }),
2796
+ t("nextTest", { command: command(test) })
1883
2797
  ];
1884
2798
  const platform = info.ciPlatform;
1885
2799
  if (answers.addCi && platform !== null) {
1886
2800
  const ci = CI_TARGETS[platform].path(answers.envLabels[0] ?? null);
1887
- if (platform === "jenkins")
1888
- steps.push(`Create a Pipeline job in Jenkins with the script path ${ci}.`);
1889
- if (platform === "azure") steps.push(`Create a pipeline in Azure DevOps from ${ci}.`);
1890
- }
1891
- if (answers.warnOnly)
1892
- steps.push("After the trial period remove gate.warnOnly from pw-perf.config.ts.");
1893
- if (written.length === 0 && scripts.length > 0)
1894
- steps.unshift("Apply the changes above (run init again in a terminal or with --yes).");
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"));
1895
2806
  return steps;
1896
2807
  }
1897
2808
  async function runInit(cmd, host, style2) {
1898
2809
  const interactive = !cmd.yes && !cmd.dryRun && host.stdin.isTTY === true && host.stdout.isTTY === true;
1899
2810
  const write = !cmd.dryRun && (cmd.yes || interactive);
1900
- const prompt = interactive ? host.createPrompt() : null;
2811
+ const prompt = interactive && cmd.noTutorial !== true ? host.createPrompt() : null;
1901
2812
  const dialog = new Dialog(host, prompt, style2);
1902
2813
  try {
1903
- if (!write) {
1904
- host.stderr.write(
1905
- infoLine(
1906
- cmd.dryRun ? "dry run: the planned changes are shown and nothing is written." : "no terminal: the default answers are used and nothing is written (like --dry-run). Use --yes to write the changes."
1907
- )
1908
- );
1909
- }
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")));
1910
2828
  const info = detectProject(await readProjectFiles(host, host.cwd));
1911
- dialog.step(1, "Project", ...describeProject(info));
2829
+ dialog.step(1, t("stepProject"), ...describeProject(info, t));
1912
2830
  if (info.playwrightConfig === null) {
1913
- host.stderr.write(
1914
- formatIssues(
1915
- [
1916
- {
1917
- code: "INIT_NO_PLAYWRIGHT_CONFIG",
1918
- message: `No playwright.config.* in ${host.cwd}.`,
1919
- hint: `Run "${CLI_COMMAND} init" in the directory of playwright.config (in a monorepo: the package with the Playwright tests).`
1920
- }
1921
- ],
1922
- "error",
1923
- style2
1924
- )
1925
- );
1926
- return 3;
2831
+ return dialog.error("INIT_NO_PLAYWRIGHT_CONFIG", "noConfigMessage", "noConfigHint", {
2832
+ dir: host.cwd,
2833
+ command: CLI_COMMAND
2834
+ });
1927
2835
  }
1928
2836
  if (info.playwrightVersion !== null && !versionAtLeast(info.playwrightVersion, host.minPlaywrightVersion)) {
1929
- host.stderr.write(
1930
- formatIssues(
1931
- [
1932
- {
1933
- code: "INIT_PLAYWRIGHT_TOO_OLD",
1934
- message: `@playwright/test ${info.playwrightVersion} is older than ${host.minPlaywrightVersion}, the lowest version ${PACKAGE_NAME} supports.`,
1935
- hint: `Update @playwright/test to ${host.minPlaywrightVersion} or later, then run "${CLI_COMMAND} init" again.`
1936
- }
1937
- ],
1938
- "error",
1939
- style2
1940
- )
1941
- );
1942
- return 3;
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
+ });
1943
2843
  }
1944
2844
  const answers = await askAnswers(dialog, info);
1945
- const plan = planInitChanges(info, answers);
1946
- dialog.step(
2845
+ const plan = planInitChanges(info, answers, lang);
2846
+ dialog.stepOf(
1947
2847
  9,
1948
- "Changes",
1949
- plan.changes.length === 0 ? "Nothing to change: the project is already set up for these answers." : "Each change is shown as a diff before it is applied."
2848
+ "stepChanges",
2849
+ plan.changes.length === 0 ? "nothingToChange" : "changesLesson"
1950
2850
  );
1951
2851
  let written;
1952
2852
  try {
1953
2853
  written = await applyChanges(dialog, host, info, plan.changes, write, cmd.yes);
1954
2854
  } catch (error) {
1955
2855
  if (!(error instanceof WriteFailed)) throw error;
1956
- host.stderr.write(
1957
- formatIssues(
1958
- [
1959
- {
1960
- code: "INIT_WRITE_FAILED",
1961
- message: `Could not write ${error.message}`,
1962
- hint: "Check the permissions of the file and its directory, then run init again."
1963
- }
1964
- ],
1965
- "error",
1966
- style2
1967
- )
1968
- );
1969
- return 3;
2856
+ return dialog.error("INIT_WRITE_FAILED", "writeFailedMessage", "writeFailedHint", {
2857
+ detail: error.message
2858
+ });
1970
2859
  }
1971
2860
  dialog.warn(plan.manualSteps);
1972
2861
  dialog.step(
1973
2862
  10,
1974
- "First measurement",
1975
- `A thresholds run measures the tests and writes the thresholds files and the report (${DEFAULT_CONFIG.report.dir}/).`,
1976
- "Thresholds measured on a laptop do not fit CI machines: derive the committed ones in CI."
2863
+ t("stepFirstRun"),
2864
+ t("firstRunLesson", { dir: DEFAULT_CONFIG.report.dir }),
2865
+ t("firstRunLaptop")
1977
2866
  );
1978
2867
  let firstRun = false;
1979
2868
  if (dialog.interactive && written.length > 0) {
1980
- firstRun = await dialog.confirm("Run a first thresholds run now?", false);
2869
+ firstRun = await dialog.confirm(t("firstRunQuestion"), false);
1981
2870
  } else {
1982
- dialog.say(" Skipped.");
2871
+ dialog.line(t("skipped"), "dim");
1983
2872
  }
1984
- dialog.step(11, "Summary");
1985
- if (written.length > 0) dialog.say(" Changed files:", ...written.map((p) => ` ${p}`));
1986
- else if (write) dialog.say(" No files were changed.");
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")}`);
1987
2880
  else
1988
2881
  dialog.say(
1989
- " Planned changes (not written):",
1990
- ...plan.changes.map((c) => ` ${changeTitle(c)}`)
2882
+ ` ${t("plannedChanges")}`,
2883
+ ...plan.changes.map((c) => ` · ${c.path} (${changeKind(c, t)})`)
1991
2884
  );
1992
2885
  if (plan.manualSteps.length > 0)
1993
- dialog.say(` Manual steps: ${plan.manualSteps.length} (see the warnings above).`);
2886
+ dialog.line(`⚠ ${t("manualSteps", { count: plan.manualSteps.length })}`, "yellow");
1994
2887
  dialog.say(
1995
- " Next steps:",
1996
- ...nextSteps(info, answers, written).map((s, i) => ` ${i + 1}. ${s}`)
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"
1997
2894
  );
1998
- dialog.say(` Docs: ${DOCS}/adoption.md \xB7 ${DOCS}/ci.md \xB7 ${DOCS}/configuration.md`);
2895
+ if (write) dialog.line(`✔ ${t("finished")}`, "green");
1999
2896
  prompt?.close();
2000
2897
  if (firstRun) {
2001
2898
  const args = answers.scope === "tagged" ? ["--grep", "@perf"] : [];
@@ -2007,7 +2904,7 @@ async function runInit(cmd, host, style2) {
2007
2904
  return 0;
2008
2905
  } catch (error) {
2009
2906
  if (error instanceof PromptAborted) {
2010
- host.stderr.write(infoLine("interrupted."));
2907
+ host.stderr.write(infoLine(dialog.t("interrupted")));
2011
2908
  return 130;
2012
2909
  }
2013
2910
  throw error;
@@ -2286,7 +3183,7 @@ var Printer = class {
2286
3183
  this.host = host;
2287
3184
  }
2288
3185
  get color() {
2289
- return this.host.stderr.isTTY === true && (this.host.env.NO_COLOR ?? "") === "";
3186
+ return outputStyle(this.host.stderr, this.host.env).color;
2290
3187
  }
2291
3188
  errors(issues) {
2292
3189
  this.host.stderr.write(formatIssues(issues, "error", this));
@@ -2450,14 +3347,14 @@ async function thresholdsFrom(cmd, host) {
2450
3347
  formatThresholdsDiff(diffs, {
2451
3348
  paths: derived.value.files.map((file) => relativeSlashPath(host.cwd, absolute[file.kind])),
2452
3349
  width,
2453
- color: stdout.isTTY === true && (host.env.NO_COLOR ?? "") === "",
3350
+ color: outputStyle(stdout, host.env).color,
2454
3351
  prune: cmd.prune,
2455
3352
  diffPath: diffWritten ? relativeSlashPath(host.cwd, diffPath) : null
2456
3353
  })
2457
3354
  );
2458
3355
  if (writeErrors.length > 0) return out.errors(writeErrors);
2459
3356
  out.info(
2460
- written.length === 0 ? "thresholds files unchanged \xB7 exit code 0" : `${written.length === 1 ? "1 thresholds file" : `${written.length} thresholds files`} written \xB7 exit code 0`
3357
+ written.length === 0 ? "thresholds files unchanged · exit code 0" : `${written.length === 1 ? "1 thresholds file" : `${written.length} thresholds files`} written · exit code 0`
2461
3358
  );
2462
3359
  return 0;
2463
3360
  }
@@ -2533,13 +3430,15 @@ var USAGE_HINT = `Commands: ${COMMANDS.join(", ")}. Run "${CLI_COMMAND} --help"
2533
3430
  var RUN_OPTIONS = ["--env", "--repeat", "--prune", "--from"];
2534
3431
  var FROM_OPTIONS = ["--env", "--prune", "--from", "--config"];
2535
3432
  var REPORT_OPTIONS = ["--input", "--output", "--config"];
3433
+ var INIT_OPTIONS = ["--yes", "-y", "--dry-run", "--lang", "--no-tutorial"];
2536
3434
  var VALUED = /* @__PURE__ */ new Set([
2537
3435
  "--env",
2538
3436
  "--repeat",
2539
3437
  "--from",
2540
3438
  "--config",
2541
3439
  "--input",
2542
- "--output"
3440
+ "--output",
3441
+ "--lang"
2543
3442
  ]);
2544
3443
  function ownOption(args, i, names, issues) {
2545
3444
  const arg = args[i];
@@ -2761,12 +3660,37 @@ function parseInit(args) {
2761
3660
  const issues = [];
2762
3661
  let yes = false;
2763
3662
  let dryRun = false;
2764
- for (const arg of args) {
2765
- if (arg === "--yes" || arg === "-y") yes = true;
2766
- else if (arg === "--dry-run") dryRun = true;
2767
- else issues.push(unexpected("init", arg));
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
+ }
2768
3682
  }
2769
- return issues.length > 0 ? fail(issues) : { ok: true, value: { kind: "init", yes, dryRun } };
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
+ };
2770
3694
  }
2771
3695
  function parseArgs(argv) {
2772
3696
  const first = argv[0];
@@ -2793,7 +3717,7 @@ function parseArgs(argv) {
2793
3717
 
2794
3718
  // src/cli/main.ts
2795
3719
  function color(host) {
2796
- return { color: host.stderr.isTTY === true && (host.env.NO_COLOR ?? "") === "" };
3720
+ return outputStyle(host.stderr, host.env);
2797
3721
  }
2798
3722
  function internalError(error) {
2799
3723
  const text = error instanceof Error ? error.stack ?? error.message : String(error);