@dvl-software/eip-cypress 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 — unreleased
4
+
5
+ - Parallel runs: `eip-cypress run --parallel` lets the containers of one CI build share the specs and report into
6
+ one run (`EIP_CI_BUILD_ID`, automatic on GitHub Actions; `EIP_GROUP`, `EIP_PARALLEL_TOTAL`, `EIP_PARALLEL_BATCH`).
7
+ EIP hands out the longest specs first and gives a lost container's spec to another one. See docs/PARALLEL.md.
8
+ - New dependency: `tinyglobby`, to list the specs of Cypress' `specPattern`.
9
+ - A key EIP refuses (401, 403, 404) stops the parallel CLI at once instead of being retried as a lost connection.
10
+ - Tests of a crashed browser get the spec's error ("… Renderer process just crashed") instead of failing without one.
11
+
3
12
  ## 0.1.0 — unreleased
4
13
 
5
14
  - First version: run numbers, spec results with attempts and hook timings, steps, app requests,
package/README.md CHANGED
@@ -93,6 +93,52 @@ A re-run finds tests by their title path. Spec files that no longer exist are le
93
93
  runs), and the plugin prints how many tests of the earlier run it could not find — e.g. renamed tests or titles that
94
94
  change between runs (`it(\`… ${Date.now()}\`)`).
95
95
 
96
+ ## Parallel runs
97
+
98
+ Several CI containers can run one suite together and report into **one** EIP run. EIP hands out the specs one at a
99
+ time, longest first, so a fast container takes more of them; a spec whose container died goes to another one.
100
+
101
+ ```yaml
102
+ jobs:
103
+ e2e:
104
+ runs-on: ubuntu-latest
105
+ strategy:
106
+ fail-fast: false
107
+ matrix:
108
+ machine: [1, 2, 3, 4]
109
+ steps:
110
+ - uses: actions/checkout@v4
111
+ - run: npm ci
112
+ - run: npx eip-cypress run --parallel --browser chrome
113
+ env:
114
+ EIP_API_KEY: ${{ secrets.EIP_API_KEY }}
115
+ EIP_API_URL: https://api.example.eip
116
+ EIP_PROJECT_ID: <your project id>
117
+ EIP_PARALLEL_TOTAL: 4
118
+ ```
119
+
120
+ | Variable | |
121
+ |---|---|
122
+ | `EIP_CI_BUILD_ID` | Containers with the same build id share one run. On GitHub Actions it is set for you (workflow run + attempt); other CI systems must set it, e.g. to their pipeline id. |
123
+ | `EIP_GROUP` | Several runs in one build, e.g. one per browser: `chrome`, `firefox`. |
124
+ | `EIP_PARALLEL_TOTAL` | Optional: how many containers the build starts. The run then completes as soon as all of them have finished (otherwise one minute after the last one). |
125
+ | `EIP_PARALLEL_BATCH` | Specs per Cypress start, default 1. Cypress needs a few seconds to start; raise it when your specs are very short. |
126
+
127
+ `--parallel` needs `eip-cypress run`: Cypress fixes its spec list when it starts, so the command starts `cypress run`
128
+ again for every batch. Your `--spec` still works and limits the specs that are shared out.
129
+
130
+ - The command fails when any of its Cypress starts failed.
131
+ - If EIP can't be reached mid-run, it keeps trying for about two minutes. After that it stops and fails: the specs it
132
+ didn't run go to the other containers, and the job shouldn't look green for specs that may not have run.
133
+ - When it can't join the run at all, it runs every spec on its own.
134
+ - A spec that was handed out twice and never reported (e.g. the browser crashed) is given up; the run page lists it
135
+ under the machines.
136
+ - Re-running a finished CI job with the same build id starts a new run.
137
+ - Spec files with `" % ^ & | < > ,` in their path can't be shared and don't run with `--parallel`; the command names them.
138
+ - Your `afterRun` hook runs after each Cypress start, before the machine is reported as finished: don't revoke the
139
+ API key there.
140
+ - The host name is shown in EIP only for CI machines.
141
+
96
142
  ## What is recorded
97
143
 
98
144
  Per test attempt: before all / before each / test body / after each / after all timings, the commands
package/dist/cli.js CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawn } from "child_process";
5
- import { readFileSync } from "fs";
5
+ import { randomUUID } from "crypto";
6
+ import { mkdtempSync, readFileSync, rmSync } from "fs";
6
7
  import { createRequire } from "module";
7
- import { dirname, join } from "path";
8
+ import { tmpdir } from "os";
9
+ import { dirname, join, resolve as resolve2 } from "path";
8
10
 
9
11
  // src/api.ts
10
12
  var StorageFullError = class extends Error {
@@ -53,6 +55,17 @@ var EipApi = class {
53
55
  finish(runId, endedAt) {
54
56
  return this.json("POST", `/api/v1/auto-test-results/runs/${runId}/finish`, { ended_at: endedAt });
55
57
  }
58
+ /** Parallel runs: the machine's next specs; with `specs` it sends the run's spec list. */
59
+ next(runId, body) {
60
+ return this.json("POST", `/api/v1/auto-test-results/runs/${runId}/next`, body);
61
+ }
62
+ finishMachine(runId, machineId) {
63
+ return this.json("POST", `/api/v1/auto-test-results/runs/${runId}/machines/${machineId}/finish`);
64
+ }
65
+ /** Calls EIP again after it was unreachable (the parallel CLI keeps trying for a while before it gives up). */
66
+ resetReachability() {
67
+ this.networkFailures = 0;
68
+ }
56
69
  rerunList(runNumber, projectId) {
57
70
  const query = new URLSearchParams({ run_number: String(runNumber) });
58
71
  if (projectId) query.set("project_id", projectId);
@@ -132,10 +145,258 @@ function messageOf(text) {
132
145
 
133
146
  // src/context.ts
134
147
  import { execFileSync } from "child_process";
148
+
149
+ // src/redact.ts
150
+ var REDACTED = "[redacted]";
151
+ var EMAIL = "[email]";
152
+ var PHONE = "[phone]";
153
+ var SECRET_FIELDS = /* @__PURE__ */ new Set([
154
+ "password",
155
+ "passwd",
156
+ "pwd",
157
+ "secret",
158
+ "token",
159
+ "accesstoken",
160
+ "refreshtoken",
161
+ "idtoken",
162
+ "apikey",
163
+ "clientsecret",
164
+ "authorization",
165
+ "otp",
166
+ "pin",
167
+ "iban",
168
+ "cardnumber",
169
+ "creditcard",
170
+ "cvv",
171
+ "cvc",
172
+ "ssn",
173
+ "taxid",
174
+ "privatekey",
175
+ "sessionid",
176
+ "cookie",
177
+ "setcookie"
178
+ ]);
179
+ var SECRET_FIELD_SUFFIXES = ["password", "secret", "token"];
180
+ var SECRET_HEADER_PARTS = ["auth", "cookie", "token", "secret", "key", "session", "password"];
181
+ var BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi;
182
+ var JWT = /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
183
+ var EMAIL_PATTERN = /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,256}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,}/g;
184
+ var IBAN = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,7}(?:\s?[A-Z0-9]{1,3})?\b/g;
185
+ var CARD = /(?<!\d)\d(?:[ -]?\d){12,18}(?!\d)/g;
186
+ var PHONE_PATTERN = /\+\d{1,3}(?:[\s.-]?\(\d{1,4}\))?(?:[\s.-]?\d{2,8}){1,4}(?!\d)/g;
187
+ var FORM = /^[^=&\s]+=[^&]*(?:&[^=&\s]+=[^&]*)*$/;
188
+ var URL_IN_TEXT = /https?:\/\/[^\s"'<>]*[^\s"'<>.,;:!?)]|(?<![^\s"'`<>(\[{=,])\/[^\s"'`<>(\[{=,?#]{0,2048}[?#][^\s"'<>]*[^\s"'<>.,;:!?)]/g;
189
+ var JSON_PAIR = /"([^"\\]{1,100})"(\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/g;
190
+ var USER_INFO = /^(https?:\/\/)[^/@\s]+@/;
191
+ var STARTS_WITH_URL = /^https?:\/\//;
192
+ var MAX_EXTRA_PATTERNS = 20;
193
+ var MAX_EXTRA_PATTERN_LENGTH = 200;
194
+ function normalize(name) {
195
+ return name.toLowerCase().replace(/[^a-z0-9]/g, "");
196
+ }
197
+ function validIban(candidate) {
198
+ const iban = candidate.replace(/ /g, "");
199
+ if (iban.length < 15 || iban.length > 34) return false;
200
+ const rearranged = iban.slice(4) + iban.slice(0, 4);
201
+ let remainder = 0;
202
+ for (const c of rearranged) {
203
+ const digits = /[A-Z]/.test(c) ? String(c.charCodeAt(0) - 55) : c;
204
+ for (const d of digits) {
205
+ remainder = (remainder * 10 + Number(d)) % 97;
206
+ }
207
+ }
208
+ return remainder === 1;
209
+ }
210
+ function luhn(candidate) {
211
+ const digits = candidate.replace(/[ -]/g, "");
212
+ if (digits.length < 13 || digits.length > 19) return false;
213
+ let sum = 0;
214
+ let dbl = false;
215
+ for (let i = digits.length - 1; i >= 0; i--) {
216
+ let d = digits.charCodeAt(i) - 48;
217
+ if (dbl) {
218
+ d *= 2;
219
+ if (d > 9) d -= 9;
220
+ }
221
+ sum += d;
222
+ dbl = !dbl;
223
+ }
224
+ return sum % 10 === 0;
225
+ }
226
+ function phoneLength(candidate) {
227
+ const n = candidate.replace(/\D/g, "").length;
228
+ return n >= 8 && n <= 15;
229
+ }
230
+ function compile(patterns) {
231
+ const out = [];
232
+ for (const raw of patterns ?? []) {
233
+ if (!raw || raw.length > MAX_EXTRA_PATTERN_LENGTH || out.length >= MAX_EXTRA_PATTERNS) continue;
234
+ try {
235
+ out.push(new RegExp(raw, "g"));
236
+ } catch {
237
+ }
238
+ }
239
+ return out;
240
+ }
241
+ var Redaction = class {
242
+ count = 0;
243
+ extraFields;
244
+ extraPatterns;
245
+ constructor(extraFields = [], extraPatterns = []) {
246
+ this.extraFields = new Set(extraFields.filter((f) => f && f.trim()).map(normalize));
247
+ this.extraPatterns = compile(extraPatterns);
248
+ }
249
+ isSecretField(name) {
250
+ const n = normalize(name);
251
+ return SECRET_FIELDS.has(n) || this.extraFields.has(n) || SECRET_FIELD_SUFFIXES.some((s) => n.endsWith(s));
252
+ }
253
+ headers(headers) {
254
+ if (!isObject(headers)) return headers;
255
+ const out = {};
256
+ for (const [key, value] of Object.entries(headers)) {
257
+ const n = normalize(key);
258
+ const secret = SECRET_HEADER_PARTS.some((p) => n.includes(p)) || this.isSecretField(key);
259
+ if (secret && value !== null && value !== void 0) {
260
+ out[key] = REDACTED;
261
+ this.count++;
262
+ } else if (Array.isArray(value)) {
263
+ out[key] = value.map((item) => typeof item === "string" ? this.text(item) : item);
264
+ } else if (typeof value === "string") {
265
+ out[key] = STARTS_WITH_URL.test(value) ? this.url(value) : this.text(value);
266
+ } else {
267
+ out[key] = value;
268
+ }
269
+ }
270
+ return out;
271
+ }
272
+ body(body) {
273
+ if (Array.isArray(body)) return body.map((item) => this.body(item));
274
+ if (isObject(body)) {
275
+ const out = {};
276
+ for (const [key, value] of Object.entries(body)) {
277
+ if (this.isSecretField(key) && value !== null && value !== void 0) {
278
+ out[key] = REDACTED;
279
+ this.count++;
280
+ } else {
281
+ out[key] = this.body(value);
282
+ }
283
+ }
284
+ return out;
285
+ }
286
+ if (typeof body === "string") return this.stringBody(body);
287
+ return body;
288
+ }
289
+ stringBody(s) {
290
+ const trimmed = s.trim();
291
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
292
+ try {
293
+ return JSON.stringify(this.body(JSON.parse(trimmed)));
294
+ } catch {
295
+ return this.text(s);
296
+ }
297
+ }
298
+ if (FORM.test(trimmed)) return this.pairs(trimmed);
299
+ return this.text(s);
300
+ }
301
+ pairs(query) {
302
+ return query.split("&").map((pair) => {
303
+ const eq = pair.indexOf("=");
304
+ if (eq < 0) return this.text(pair);
305
+ const key = pair.slice(0, eq);
306
+ const value = pair.slice(eq + 1);
307
+ if (this.isSecretField(decode(key)) && value !== "") {
308
+ this.count++;
309
+ return `${key}=${REDACTED}`;
310
+ }
311
+ const decoded = decode(value);
312
+ const cleaned = this.text(decoded);
313
+ return `${key}=${cleaned === decoded ? value : cleaned}`;
314
+ }).join("&");
315
+ }
316
+ /** User info, base through the value patterns, query and a `k=v` fragment through the pair rules. */
317
+ url(url) {
318
+ let u = url;
319
+ if (USER_INFO.test(u)) {
320
+ u = u.replace(USER_INFO, `$1${REDACTED}@`);
321
+ this.count++;
322
+ }
323
+ const hash = u.indexOf("#");
324
+ const beforeHash = hash < 0 ? u : u.slice(0, hash);
325
+ const fragment = hash < 0 ? void 0 : u.slice(hash + 1);
326
+ const q = beforeHash.indexOf("?");
327
+ let out = this.plain(q < 0 ? beforeHash : beforeHash.slice(0, q));
328
+ if (q >= 0) out += `?${this.pairs(beforeHash.slice(q + 1))}`;
329
+ if (fragment !== void 0) out += `#${fragment.includes("=") ? this.pairs(fragment) : this.plain(fragment)}`;
330
+ return out;
331
+ }
332
+ /** URLs in the text (through {@link url}), then `"secret": "…"` pairs, then the value patterns. */
333
+ text(text) {
334
+ if (!text) return text;
335
+ let out = text.replace(URL_IN_TEXT, (match) => this.url(match));
336
+ out = out.replace(JSON_PAIR, (match, key, sep) => {
337
+ if (!this.isSecretField(key)) return match;
338
+ this.count++;
339
+ return `"${key}"${sep}"${REDACTED}"`;
340
+ });
341
+ return this.plain(out);
342
+ }
343
+ /** The value patterns only: bearer, JWT, email, IBAN, card, phone, own patterns. */
344
+ plain(text) {
345
+ if (!text) return text;
346
+ let out = this.replace(text, BEARER, () => `Bearer ${REDACTED}`);
347
+ out = this.replace(out, JWT, () => REDACTED);
348
+ out = this.replace(out, EMAIL_PATTERN, () => EMAIL);
349
+ out = this.replace(out, IBAN, () => REDACTED, validIban);
350
+ out = this.replace(out, CARD, () => REDACTED, luhn);
351
+ out = this.replace(out, PHONE_PATTERN, () => PHONE, phoneLength);
352
+ for (const extra of this.extraPatterns) {
353
+ out = this.replace(out, extra, () => REDACTED);
354
+ }
355
+ return out;
356
+ }
357
+ replace(text, pattern, by, check) {
358
+ pattern.lastIndex = 0;
359
+ return text.replace(pattern, (match) => {
360
+ if (!match || check && !check(match)) return match;
361
+ this.count++;
362
+ return by();
363
+ });
364
+ }
365
+ };
366
+ function decode(value) {
367
+ try {
368
+ return decodeURIComponent(value.replace(/\+/g, " "));
369
+ } catch {
370
+ return value;
371
+ }
372
+ }
373
+ function isObject(v) {
374
+ return typeof v === "object" && v !== null && !Array.isArray(v);
375
+ }
376
+
377
+ // src/context.ts
135
378
  var TRUE = ["1", "true", "yes"];
379
+ function buildIdFrom(env) {
380
+ const own = env.EIP_CI_BUILD_ID?.trim();
381
+ if (own) return own;
382
+ if (env.GITHUB_ACTIONS === "true" && env.GITHUB_RUN_ID) return `github-${env.GITHUB_RUN_ID}-${env.GITHUB_RUN_ATTEMPT || "1"}`;
383
+ return void 0;
384
+ }
385
+ function positiveInt(value, max) {
386
+ const n = Number(value?.trim());
387
+ return Number.isInteger(n) && n >= 1 ? Math.min(n, max) : void 0;
388
+ }
136
389
  function readOptions(env = process.env) {
137
390
  const rerun = env.EIP_RERUN_OF?.trim().replace(/^#/, "");
138
391
  return {
392
+ buildId: buildIdFrom(env)?.slice(0, 200),
393
+ group: env.EIP_GROUP?.trim().slice(0, 100) || void 0,
394
+ totalMachines: positiveInt(env.EIP_PARALLEL_TOTAL, 1e3),
395
+ batch: positiveInt(env.EIP_PARALLEL_BATCH, 100) ?? 1,
396
+ machineId: env.EIP_MACHINE_ID?.trim() || void 0,
397
+ parallelSeed: TRUE.includes((env.EIP_PARALLEL_SEED ?? "").toLowerCase()),
398
+ parallelStateFile: env.EIP_PARALLEL_STATE?.trim() || void 0,
399
+ parallelSpec: env.EIP_PARALLEL_SPEC?.trim() || void 0,
139
400
  apiKey: env.EIP_API_KEY?.trim() || void 0,
140
401
  apiUrl: env.EIP_API_URL?.trim().replace(/\/+$/, "") || void 0,
141
402
  projectId: env.EIP_PROJECT_ID?.trim() || void 0,
@@ -156,8 +417,74 @@ function insecureApiUrl(apiUrl) {
156
417
  return true;
157
418
  }
158
419
  }
420
+ function ciContext(env = process.env) {
421
+ if (env.GITHUB_ACTIONS !== "true") return void 0;
422
+ const attempt = Number(env.GITHUB_RUN_ATTEMPT);
423
+ return {
424
+ provider: "github",
425
+ run_id: env.GITHUB_RUN_ID,
426
+ run_attempt: Number.isFinite(attempt) && attempt > 0 ? attempt : void 0,
427
+ workflow_ref: env.GITHUB_WORKFLOW_REF,
428
+ repository: env.GITHUB_REPOSITORY,
429
+ server_url: env.GITHUB_SERVER_URL
430
+ };
431
+ }
432
+ function gitContext(env = process.env, git = runGit) {
433
+ const branch = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME || git(["rev-parse", "--abbrev-ref", "HEAD"]);
434
+ const sha = env.GITHUB_SHA || git(["rev-parse", "HEAD"]);
435
+ const message = git(["log", "-1", "--pretty=%s"]);
436
+ const author = git(["log", "-1", "--pretty=%an"]);
437
+ return {
438
+ branch: branch && branch !== "HEAD" ? branch : void 0,
439
+ sha: sha || void 0,
440
+ message: message ? new Redaction().text(message) : void 0,
441
+ author: author || void 0
442
+ };
443
+ }
444
+ function runGit(args) {
445
+ try {
446
+ return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3e3 }).trim();
447
+ } catch {
448
+ return void 0;
449
+ }
450
+ }
451
+
452
+ // src/parallel.ts
453
+ import { realpathSync, writeFileSync } from "fs";
454
+ import { hostname } from "os";
455
+ import { isAbsolute, relative, resolve } from "path";
456
+ import { glob } from "tinyglobby";
457
+
458
+ // src/collect.ts
459
+ function posixPath(path) {
460
+ return path.replace(/\\/g, "/");
461
+ }
462
+
463
+ // src/parallel.ts
464
+ var UNSAFE_SPEC = /(^|\/)\.\.(\/|$)|^\/|^[A-Za-z]:|["%^&|<>,\p{Cc}]/u;
465
+ function isShareableSpec(path) {
466
+ return path.length > 0 && !UNSAFE_SPEC.test(posixPath(path));
467
+ }
468
+ function literal(root, spec) {
469
+ return escapeGlob(posixPath(resolve(root, spec)));
470
+ }
471
+ function specArgFor(projectDir, specs) {
472
+ return specs.filter(isShareableSpec).map((s) => literal(projectDir, s)).join(",");
473
+ }
474
+ function escapeGlob(path) {
475
+ return path.replace(/[*?[\]{}()!+@]/g, "\\$&");
476
+ }
477
+ var CI_MARKERS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TF_BUILD", "CIRCLECI", "TEAMCITY_VERSION"];
478
+ function shareableHostName(env = process.env) {
479
+ const ci = CI_MARKERS.some((name) => {
480
+ const value = env[name]?.trim().toLowerCase();
481
+ return !!value && value !== "false" && value !== "0";
482
+ });
483
+ return ci ? hostname().slice(0, 255) : void 0;
484
+ }
159
485
 
160
486
  // src/cli.ts
487
+ var LOG = "[EIP]";
161
488
  function cypressCommand(cwd, platform = process.platform) {
162
489
  try {
163
490
  const require2 = createRequire(join(cwd, "package.json"));
@@ -172,34 +499,16 @@ function cypressCommand(cwd, platform = process.platform) {
172
499
  function shellQuote(arg) {
173
500
  return /^[\w./:=@,+-]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '\\"')}"`;
174
501
  }
175
- async function main(argv) {
176
- const [command, ...rest] = argv;
177
- if (command !== "run") {
178
- console.log("Usage: eip-cypress run [cypress run options]\n\nEnvironment: EIP_API_KEY, EIP_API_URL, EIP_PROJECT_ID, EIP_RERUN_OF (run number to re-run), EIP_ENVIRONMENT, EIP_RUN_NAME, EIP_APP_URL, EIP_CAPTURE_EXCLUDE, EIP_ALLOW_HTTP, EIP_DISABLED");
179
- return command === void 0 || command === "--help" || command === "-h" ? 0 : 1;
180
- }
181
- const opts = readOptions();
182
- const usable = opts.apiKey && opts.apiUrl && !opts.disabled && (opts.allowHttp || !insecureApiUrl(opts.apiUrl));
183
- if (opts.rerunOf !== void 0 && usable) {
184
- try {
185
- const list = await new EipApi(opts.apiUrl, opts.apiKey).rerunList(opts.rerunOf, opts.projectId);
186
- if (list.specs.length === 0) {
187
- console.log(`[EIP] Run #${opts.rerunOf} has no failed or skipped tests. Nothing to re-run.`);
188
- return 0;
189
- }
190
- } catch (e) {
191
- console.log(`[EIP] Could not load run #${opts.rerunOf}: ${e instanceof Error ? e.message : e}. Running everything.`);
192
- }
193
- }
502
+ var runCypress = (rest, env) => {
194
503
  const cy = cypressCommand(process.cwd());
195
504
  const args = [...cy.args, "run", ...rest];
196
- return new Promise((resolve) => {
505
+ return new Promise((resolve3) => {
197
506
  let child;
198
507
  try {
199
- child = spawn(cy.command, cy.shell ? args.map(shellQuote) : args, { stdio: "inherit", env: process.env, shell: cy.shell });
508
+ child = spawn(cy.command, cy.shell ? args.map(shellQuote) : args, { stdio: "inherit", env, shell: cy.shell });
200
509
  } catch (e) {
201
- console.error(`[EIP] Could not start Cypress: ${e instanceof Error ? e.message : e}`);
202
- resolve(1);
510
+ console.error(`${LOG} Could not start Cypress: ${e instanceof Error ? e.message : e}`);
511
+ resolve3(1);
203
512
  return;
204
513
  }
205
514
  const forward = (signal) => () => child.kill(signal);
@@ -210,17 +519,211 @@ async function main(argv) {
210
519
  child.on("exit", (code, signal) => {
211
520
  process.off("SIGINT", onInt);
212
521
  process.off("SIGTERM", onTerm);
213
- resolve(signal ? 1 : code ?? 1);
522
+ resolve3(signal ? 1 : code ?? 1);
214
523
  });
215
524
  child.on("error", (e) => {
216
- console.error(`[EIP] Could not start Cypress: ${e.message}`);
217
- resolve(1);
525
+ console.error(`${LOG} Could not start Cypress: ${e.message}`);
526
+ resolve3(1);
218
527
  });
219
528
  });
529
+ };
530
+ function takeOption(args, names) {
531
+ for (let i = 0; i < args.length; i++) {
532
+ const arg = args[i] ?? "";
533
+ const eq = names.find((n) => arg.startsWith(`${n}=`));
534
+ if (eq) {
535
+ args.splice(i, 1);
536
+ return arg.slice(eq.length + 1);
537
+ }
538
+ const value = args[i + 1];
539
+ if (names.includes(arg) && value !== void 0) {
540
+ args.splice(i, 2);
541
+ return value;
542
+ }
543
+ }
544
+ return void 0;
545
+ }
546
+ function peekOption(args, names) {
547
+ return takeOption([...args], names);
548
+ }
549
+ var MAX_SEED_FAILURES = 2;
550
+ var RECONNECT_TRIES = 8;
551
+ var RECONNECT_WAIT_MS = 15e3;
552
+ async function runParallel(args, opts, deps) {
553
+ const userSpec = takeOption(args, ["--spec", "-s"]);
554
+ const projectDir = resolve2(deps.cwd, peekOption(args, ["--project", "-P"]) ?? ".");
555
+ const env = {
556
+ ...deps.env,
557
+ EIP_MACHINE_ID: deps.machineId,
558
+ EIP_CI_BUILD_ID: opts.buildId,
559
+ EIP_PARALLEL_SEED: void 0,
560
+ EIP_PARALLEL_STATE: void 0,
561
+ EIP_PARALLEL_SPEC: userSpec
562
+ };
563
+ let runId;
564
+ let runNumber;
565
+ try {
566
+ const opened = await deps.api.openRun({
567
+ project_id: opts.projectId,
568
+ name: opts.runName,
569
+ framework: "cypress",
570
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
571
+ environment: opts.environment,
572
+ rerun_of: opts.rerunOf,
573
+ ci: ciContext(deps.env),
574
+ git: gitContext(deps.env),
575
+ parallel: {
576
+ build_id: opts.buildId,
577
+ group: opts.group,
578
+ machine_id: deps.machineId,
579
+ host_name: shareableHostName(deps.env),
580
+ total_machines: opts.totalMachines
581
+ }
582
+ });
583
+ runId = opened.run_id;
584
+ runNumber = opened.run_number;
585
+ } catch (e) {
586
+ console.log(`${LOG} Could not join the parallel run in EIP: ${errorText(e)}. Running every spec on this machine.`);
587
+ return deps.run(userSpec ? [...args, "--spec", userSpec] : args, deps.env);
588
+ }
589
+ let failed = false;
590
+ let seedFailures = 0;
591
+ let machineNo;
592
+ let batches = 0;
593
+ for (; ; ) {
594
+ const answer = await nextWithRetry(deps, runId, opts.batch);
595
+ if (!answer) return 1;
596
+ if (machineNo === void 0 && answer.machine_no !== void 0) {
597
+ machineNo = answer.machine_no;
598
+ console.log(`${LOG} Run #${runNumber}: this is machine ${machineNo}.`);
599
+ }
600
+ if (answer.action === "done") break;
601
+ if (answer.action === "wait") {
602
+ await deps.sleep(Math.max(1, answer.retry_after_seconds ?? 5) * 1e3);
603
+ continue;
604
+ }
605
+ if (answer.action === "seed") {
606
+ const dir = deps.tempDir();
607
+ const stateFile = join(dir, "seed.json");
608
+ const code = await deps.run(args, { ...env, EIP_PARALLEL_SEED: "1", EIP_PARALLEL_STATE: stateFile });
609
+ const state = readState(stateFile);
610
+ rmSync(dir, { recursive: true, force: true });
611
+ if (!state || state.error) {
612
+ seedFailures++;
613
+ console.log(`${LOG} Could not send the spec list to EIP${state?.error ? `: ${state.error}` : ` \u2014 Cypress ended with exit code ${code} before sending it. Did Cypress start, and is setupEip() called in setupNodeEvents?`}`);
614
+ if (seedFailures >= MAX_SEED_FAILURES) return 1;
615
+ continue;
616
+ }
617
+ seedFailures = 0;
618
+ if (state.specs.length) {
619
+ batches++;
620
+ if (code !== 0) failed = true;
621
+ }
622
+ continue;
623
+ }
624
+ const spec = specArgFor(projectDir, answer.specs);
625
+ if (!spec) {
626
+ console.log(`${LOG} Skipped spec path(s) that can't be passed to Cypress safely: ${answer.specs.join(" ")}`);
627
+ continue;
628
+ }
629
+ batches++;
630
+ if (await deps.run([...args, "--spec", spec], env) !== 0) failed = true;
631
+ }
632
+ try {
633
+ const totals = await deps.api.finishMachine(runId, deps.machineId);
634
+ console.log(summary(totals, machineNo, batches));
635
+ } catch (e) {
636
+ console.log(`${LOG} Could not report this machine as finished: ${errorText(e)}. EIP completes the run later.`);
637
+ }
638
+ return failed ? 1 : 0;
639
+ }
640
+ async function nextWithRetry(deps, runId, batch) {
641
+ for (let attempt = 0; ; attempt++) {
642
+ try {
643
+ return await deps.api.next(runId, { machine_id: deps.machineId, batch });
644
+ } catch (e) {
645
+ if (e instanceof ApiError && e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429) {
646
+ console.log(`${LOG} EIP refused to hand out specs (${e.status}: ${e.message}). Stopping: asking again won't help, and this job fails so no spec goes unnoticed.`);
647
+ return void 0;
648
+ }
649
+ if (attempt >= RECONNECT_TRIES) {
650
+ console.log(`${LOG} EIP stayed unreachable (${errorText(e)}). Stopping: the specs this machine didn't run go to the other machines, and this job fails so no spec goes unnoticed.`);
651
+ return void 0;
652
+ }
653
+ if (attempt === 0) console.log(`${LOG} Lost the connection to EIP (${errorText(e)}); trying again for about two minutes.`);
654
+ await deps.sleep(RECONNECT_WAIT_MS);
655
+ deps.api.resetReachability();
656
+ }
657
+ }
658
+ }
659
+ function summary(totals, machineNo, batches) {
660
+ const who = machineNo !== void 0 ? `Machine ${machineNo}` : "This machine";
661
+ if (totals.status && totals.status !== "COMPLETED") {
662
+ return `${LOG} ${who} finished after ${batches} Cypress start(s); run #${totals.run_number} goes on on other machines.`;
663
+ }
664
+ const skipped = totals.skipped + totals.pending;
665
+ return `${LOG} ${who} finished. Run #${totals.run_number}: ${totals.passed} passed, ${totals.failed} failed, ${skipped} skipped${totals.flaky ? `, ${totals.flaky} flaky` : ""}.`;
666
+ }
667
+ function readState(path) {
668
+ try {
669
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
670
+ return Array.isArray(parsed?.specs) ? parsed : void 0;
671
+ } catch {
672
+ return void 0;
673
+ }
674
+ }
675
+ function errorText(e) {
676
+ return e instanceof Error ? e.message : String(e);
677
+ }
678
+ var USAGE = "Usage: eip-cypress run [--parallel] [cypress run options]\n\nEnvironment: EIP_API_KEY, EIP_API_URL, EIP_PROJECT_ID, EIP_RERUN_OF (run number to re-run), EIP_ENVIRONMENT, EIP_RUN_NAME, EIP_APP_URL, EIP_CAPTURE_EXCLUDE, EIP_ALLOW_HTTP, EIP_DISABLED\nParallel: EIP_CI_BUILD_ID (GitHub: automatic), EIP_GROUP, EIP_PARALLEL_TOTAL, EIP_PARALLEL_BATCH";
679
+ async function main(argv, run = runCypress) {
680
+ const [command, ...rest] = argv;
681
+ if (command !== "run") {
682
+ console.log(USAGE);
683
+ return command === void 0 || command === "--help" || command === "-h" ? 0 : 1;
684
+ }
685
+ const parallelAt = rest.indexOf("--parallel");
686
+ const parallel = parallelAt >= 0;
687
+ if (parallel) rest.splice(parallelAt, 1);
688
+ const opts = readOptions();
689
+ const usable = !!(opts.apiKey && opts.apiUrl && !opts.disabled && (opts.allowHttp || !insecureApiUrl(opts.apiUrl)));
690
+ const api = usable ? new EipApi(opts.apiUrl, opts.apiKey) : void 0;
691
+ if (opts.rerunOf !== void 0 && api) {
692
+ try {
693
+ const list = await api.rerunList(opts.rerunOf, opts.projectId);
694
+ if (list.specs.length === 0) {
695
+ console.log(`${LOG} Run #${opts.rerunOf} has no failed or skipped tests. Nothing to re-run.`);
696
+ return 0;
697
+ }
698
+ } catch (e) {
699
+ console.log(`${LOG} Could not load run #${opts.rerunOf}: ${errorText(e)}. Running everything.`);
700
+ }
701
+ }
702
+ if (parallel) {
703
+ if (!api) {
704
+ console.log(`${LOG} --parallel needs EIP_API_KEY and EIP_API_URL. Running every spec on this machine.`);
705
+ } else if (!buildIdFrom(process.env)) {
706
+ console.log(`${LOG} --parallel needs EIP_CI_BUILD_ID (set automatically on GitHub Actions). Running every spec on this machine.`);
707
+ } else {
708
+ return runParallel(rest, opts, {
709
+ api,
710
+ run,
711
+ env: process.env,
712
+ cwd: process.cwd(),
713
+ machineId: randomUUID(),
714
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
715
+ tempDir: () => mkdtempSync(join(tmpdir(), "eip-parallel-"))
716
+ });
717
+ }
718
+ }
719
+ return run(rest, process.env);
220
720
  }
221
721
  if (!process.env.VITEST) {
222
722
  main(process.argv.slice(2)).then((code) => process.exit(code));
223
723
  }
224
724
  export {
225
- cypressCommand
725
+ cypressCommand,
726
+ main,
727
+ runParallel,
728
+ takeOption
226
729
  };