@circi/cypress 0.0.0-stage → 0.1.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/index.mjs ADDED
@@ -0,0 +1,1077 @@
1
+ import { mkdir, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
2
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { setTimeout } from "node:timers/promises";
5
+ import "tar";
6
+ import { createReadStream, readFileSync } from "node:fs";
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
9
+ import { i as toolDir, r as capturePath } from "./names-D1laAiFj.mjs";
10
+ // ../cli/dist/shard-BqmjvX9r.mjs
11
+ var ApiError = class extends Error {
12
+ status;
13
+ body;
14
+ constructor(status, message, body) {
15
+ super(message);
16
+ this.name = "ApiError";
17
+ this.status = status;
18
+ this.body = body;
19
+ }
20
+ };
21
+ /** The server (or the way to it) didn't answer: a refused connection, an unknown host, a timeout. */
22
+ var NetworkError = class extends Error {
23
+ url;
24
+ /** The Node error code (`ECONNREFUSED`…), `TIMEOUT`, or undefined. */
25
+ code;
26
+ constructor(url, code, detail) {
27
+ super(`Couldn't reach ${originOf(url)} (${detail})`);
28
+ this.name = "NetworkError";
29
+ this.url = url;
30
+ this.code = code;
31
+ }
32
+ };
33
+ function originOf(url) {
34
+ try {
35
+ return new URL(url).origin;
36
+ } catch {
37
+ return url.split("/v1/")[0] ?? url;
38
+ }
39
+ }
40
+ const CODE_TEXT = {
41
+ ECONNREFUSED: "connection refused",
42
+ ENOTFOUND: "host not found",
43
+ EAI_AGAIN: "host not found",
44
+ ECONNRESET: "connection reset",
45
+ ETIMEDOUT: "timed out",
46
+ UND_ERR_CONNECT_TIMEOUT: "timed out",
47
+ CERT_HAS_EXPIRED: "certificate expired",
48
+ DEPTH_ZERO_SELF_SIGNED_CERT: "self-signed certificate",
49
+ ERR_INVALID_URL: "not a valid URL"
50
+ };
51
+ /** Turns what `fetch` throws (`TypeError: fetch failed` with a cause) into a `NetworkError`. */
52
+ function toNetworkError(url, err) {
53
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) return new NetworkError(url, "TIMEOUT", "timed out");
54
+ const cause = err instanceof Error ? err.cause : void 0;
55
+ const code = cause instanceof Error && "code" in cause && typeof cause.code === "string" ? cause.code : err instanceof Error && "code" in err && typeof err.code === "string" ? err.code : void 0;
56
+ return new NetworkError(url, code, code && CODE_TEXT[code] || code || (cause instanceof Error ? cause.message : err instanceof Error ? err.message : String(err)));
57
+ }
58
+ /** Failures that mean the request never reached the application, so even a POST can be resent. */
59
+ const NEVER_ARRIVED = /* @__PURE__ */ new Set([
60
+ "ECONNREFUSED",
61
+ "ENOTFOUND",
62
+ "EAI_AGAIN"
63
+ ]);
64
+ /**
65
+ * Whether to resend after `err`. `safe` calls (reads, and writes that replace rather than add)
66
+ * retry on any 5xx, 429 and network failure; others only when the request cannot have been
67
+ * processed: the connection never opened, or a gateway (502/503/504) answered for the server.
68
+ */
69
+ function isRetryable(err, safe) {
70
+ if (err instanceof NetworkError) {
71
+ if (err.code === "ERR_INVALID_URL") return false;
72
+ return safe || err.code !== void 0 && NEVER_ARRIVED.has(err.code);
73
+ }
74
+ if (err instanceof ApiError) {
75
+ if (safe) return err.status >= 500 || err.status === 429;
76
+ return err.status === 502 || err.status === 503 || err.status === 504;
77
+ }
78
+ return false;
79
+ }
80
+ /** Backoff for retry number `retry` (1, 2, …): `base * 2^(retry-1)`, scaled by 50-100% jitter. */
81
+ function backoffDelay(retry, baseMs, random = Math.random) {
82
+ return Math.round(baseMs * 2 ** (retry - 1) * (.5 + random() / 2));
83
+ }
84
+ /** Runs `fn`, resending after a transient failure (see `isRetryable`) with exponential backoff. */
85
+ async function withRetry(fn, options) {
86
+ for (let attempt = 1;; attempt += 1) try {
87
+ return await fn();
88
+ } catch (err) {
89
+ if (attempt >= options.attempts || !isRetryable(err, options.safe)) throw err;
90
+ await setTimeout(backoffDelay(attempt, options.baseDelayMs));
91
+ }
92
+ }
93
+ var ApiClient = class {
94
+ baseUrl;
95
+ token;
96
+ fetchImpl;
97
+ timeoutMs;
98
+ attempts;
99
+ retryDelayMs;
100
+ constructor(options) {
101
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
102
+ this.token = options.token;
103
+ this.fetchImpl = options.fetch ?? fetch;
104
+ this.timeoutMs = options.timeoutMs ?? 3e4;
105
+ this.attempts = options.attempts ?? 4;
106
+ this.retryDelayMs = options.retryDelayMs ?? 500;
107
+ }
108
+ project() {
109
+ return this.json("GET", "/v1/project");
110
+ }
111
+ createBuild(body) {
112
+ return this.json("POST", "/v1/builds", body, {
113
+ safe: true,
114
+ headers: { "idempotency-key": randomUUID() }
115
+ });
116
+ }
117
+ finalize(buildId, body) {
118
+ return this.json("POST", `/v1/builds/${buildId}/finalize`, body, { safe: true });
119
+ }
120
+ status(buildId, gate) {
121
+ return this.json("GET", `/v1/builds/${buildId}/status${gate ? `?gate=${gate}` : ""}`);
122
+ }
123
+ /** Uploads a site (a `.tar.gz`); the query says what and where it is. */
124
+ uploadSite(query, archive) {
125
+ return withRetry(async () => {
126
+ const res = await this.send(`${this.baseUrl}/v1/sites?${new URLSearchParams(query).toString()}`, {
127
+ method: "POST",
128
+ headers: {
129
+ authorization: `Bearer ${this.token}`,
130
+ "content-type": "application/gzip"
131
+ },
132
+ body: archive
133
+ }, this.timeoutMs * 4);
134
+ return this.parse(res);
135
+ }, {
136
+ attempts: this.attempts,
137
+ baseDelayMs: this.retryDelayMs,
138
+ safe: true
139
+ });
140
+ }
141
+ /** The commit a branch's address serves now, or null when the server says it has none yet. */
142
+ async servedCommit(name, branch) {
143
+ return (await this.json("GET", `/v1/sites/served?${new URLSearchParams({
144
+ name,
145
+ branch
146
+ }).toString()}`)).commit;
147
+ }
148
+ /** Sends one file as instructed by the server, retrying transient failures. */
149
+ async upload(instruction, bytes) {
150
+ const headers = Object.fromEntries(Object.entries(instruction.headers).filter(([k]) => k.toLowerCase() !== "content-length"));
151
+ if (instruction.auth === "token") headers.authorization = `Bearer ${this.token}`;
152
+ try {
153
+ await withRetry(async () => {
154
+ const res = await this.send(instruction.url, {
155
+ method: instruction.method,
156
+ headers,
157
+ body: bytes
158
+ }, this.timeoutMs * 4);
159
+ if (!res.ok) throw new ApiError(res.status, await safeText(res), void 0);
160
+ }, {
161
+ attempts: this.attempts,
162
+ baseDelayMs: this.retryDelayMs,
163
+ safe: true
164
+ });
165
+ } catch (err) {
166
+ const detail = err instanceof ApiError ? `${err.status} ${err.message}`.trim() : err instanceof Error ? err.message : String(err);
167
+ throw new Error(`Upload of ${instruction.sha256.slice(0, 12)} failed: ${detail}`, { cause: err });
168
+ }
169
+ }
170
+ /** One request with a timeout; a failure to get an answer becomes a `NetworkError`. */
171
+ async send(url, init, timeoutMs) {
172
+ try {
173
+ return await this.fetchImpl(url, {
174
+ ...init,
175
+ signal: AbortSignal.timeout(timeoutMs)
176
+ });
177
+ } catch (err) {
178
+ throw toNetworkError(url, err);
179
+ }
180
+ }
181
+ /** Reads the answer; a non-2xx one throws an `ApiError` carrying the server's `error` text. */
182
+ async parse(res) {
183
+ let text;
184
+ try {
185
+ text = await res.text();
186
+ } catch (err) {
187
+ throw toNetworkError(res.url, err);
188
+ }
189
+ let parsed = void 0;
190
+ try {
191
+ parsed = text ? JSON.parse(text) : void 0;
192
+ } catch {
193
+ parsed = text;
194
+ }
195
+ if (!res.ok) {
196
+ const message = typeof parsed === "object" && parsed !== null && "error" in parsed && typeof parsed.error === "string" ? parsed.error : `HTTP ${res.status}`;
197
+ throw new ApiError(res.status, message, parsed);
198
+ }
199
+ return parsed;
200
+ }
201
+ json(method, path, body, options = {}) {
202
+ const safe = options.safe ?? method === "GET";
203
+ return withRetry(async () => {
204
+ const res = await this.send(`${this.baseUrl}${path}`, {
205
+ method,
206
+ headers: {
207
+ authorization: `Bearer ${this.token}`,
208
+ ...options.headers,
209
+ ...body === void 0 ? {} : { "content-type": "application/json" }
210
+ },
211
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
212
+ }, this.timeoutMs);
213
+ return this.parse(res);
214
+ }, {
215
+ attempts: this.attempts,
216
+ baseDelayMs: this.retryDelayMs,
217
+ safe
218
+ });
219
+ }
220
+ };
221
+ async function safeText(res) {
222
+ try {
223
+ return (await res.text()).slice(0, 300);
224
+ } catch {
225
+ return "";
226
+ }
227
+ }
228
+ /**
229
+ * Reads build context from CI environment variables (PLAN §7.1 step 2). Pure: takes the env and
230
+ * a JSON reader, so every provider is covered by table-driven tests.
231
+ */
232
+ /**
233
+ * An id shared by every job of one CI run, so the shards of a parallel build find each other.
234
+ * `undefined` when the CI isn't recognised (pass `--nonce` or `CIRCI_PARALLEL_NONCE` then).
235
+ */
236
+ function ciRunId(env) {
237
+ const pick = (...names) => names.map((n) => env[n]).find((v) => v);
238
+ const base = pick("CIRCI_PARALLEL_NONCE", "GITHUB_RUN_ID", "CI_PIPELINE_ID", "BUILDKITE_BUILD_ID", "CIRCLE_WORKFLOW_ID", "BITBUCKET_BUILD_NUMBER", "BUILD_TAG", "BUILD_ID", "BUILD_BUILDID");
239
+ return base && env.GITHUB_RUN_ATTEMPT && !env.CIRCI_PARALLEL_NONCE ? `${base}-${env.GITHUB_RUN_ATTEMPT}` : base;
240
+ }
241
+ function detectCi(env, readJson) {
242
+ const ctx = detectProvider(env, readJson);
243
+ const author = detectAuthor(ctx.provider, env);
244
+ return applyOverrides(author ? {
245
+ ...ctx,
246
+ author
247
+ } : ctx, env);
248
+ }
249
+ function detectProvider(env, readJson) {
250
+ if (env.GITHUB_ACTIONS === "true") return github(env, readJson, env.GITEA_ACTIONS === "true" ? "gitea" : "github");
251
+ if (env.GITLAB_CI === "true") return gitlab(env);
252
+ if (env.BITBUCKET_BUILD_NUMBER) return bitbucket(env);
253
+ if (env.CIRCLECI === "true") return circleci(env);
254
+ if (env.BUILDKITE === "true") return buildkite(env);
255
+ if (env.JENKINS_URL) return jenkins(env);
256
+ if (env.TF_BUILD === "True" || env.TF_BUILD === "true") return azure(env);
257
+ return { provider: "local" };
258
+ }
259
+ function github(env, readJson, provider) {
260
+ const jobUrl = env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : void 0;
261
+ if ((env.GITHUB_EVENT_NAME === "pull_request" || env.GITHUB_EVENT_NAME === "pull_request_target") && env.GITHUB_EVENT_PATH) {
262
+ const pr = field(readJson(env.GITHUB_EVENT_PATH), "pull_request");
263
+ const head = field(pr, "head");
264
+ const base = field(pr, "base");
265
+ const headRepo = str(field(field(head, "repo"), "full_name"));
266
+ const baseRepo = str(field(field(base, "repo"), "full_name"));
267
+ return {
268
+ provider,
269
+ commitSha: str(field(head, "sha")) ?? env.GITHUB_SHA,
270
+ branch: str(field(head, "ref")) ?? env.GITHUB_HEAD_REF,
271
+ prNumber: num(field(pr, "number")),
272
+ baseBranch: str(field(base, "ref")) ?? env.GITHUB_BASE_REF,
273
+ fromFork: headRepo && baseRepo ? headRepo !== baseRepo : void 0,
274
+ jobUrl
275
+ };
276
+ }
277
+ return {
278
+ provider,
279
+ commitSha: env.GITHUB_SHA,
280
+ branch: env.GITHUB_REF_TYPE === "branch" ? env.GITHUB_REF_NAME : void 0,
281
+ jobUrl
282
+ };
283
+ }
284
+ function gitlab(env) {
285
+ if (env.CI_MERGE_REQUEST_IID) return {
286
+ provider: "gitlab",
287
+ commitSha: nonEmpty(env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA) ?? env.CI_COMMIT_SHA,
288
+ branch: env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,
289
+ prNumber: num(env.CI_MERGE_REQUEST_IID),
290
+ baseBranch: env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME,
291
+ fromFork: env.CI_MERGE_REQUEST_SOURCE_PROJECT_ID && env.CI_MERGE_REQUEST_PROJECT_ID ? env.CI_MERGE_REQUEST_SOURCE_PROJECT_ID !== env.CI_MERGE_REQUEST_PROJECT_ID : void 0,
292
+ jobUrl: env.CI_JOB_URL
293
+ };
294
+ return {
295
+ provider: "gitlab",
296
+ commitSha: env.CI_COMMIT_SHA,
297
+ branch: env.CI_COMMIT_BRANCH,
298
+ jobUrl: env.CI_JOB_URL
299
+ };
300
+ }
301
+ function bitbucket(env) {
302
+ return {
303
+ provider: "bitbucket",
304
+ commitSha: env.BITBUCKET_COMMIT,
305
+ branch: env.BITBUCKET_BRANCH,
306
+ prNumber: num(env.BITBUCKET_PR_ID),
307
+ baseBranch: env.BITBUCKET_PR_DESTINATION_BRANCH,
308
+ jobUrl: env.BITBUCKET_GIT_HTTP_ORIGIN ? `${env.BITBUCKET_GIT_HTTP_ORIGIN}/addon/pipelines/home#!/results/${env.BITBUCKET_BUILD_NUMBER}` : void 0
309
+ };
310
+ }
311
+ function circleci(env) {
312
+ return {
313
+ provider: "circleci",
314
+ commitSha: env.CIRCLE_SHA1,
315
+ branch: env.CIRCLE_BRANCH,
316
+ prNumber: num(env.CIRCLE_PULL_REQUEST?.match(/\/(\d+)$/)?.[1]),
317
+ jobUrl: env.CIRCLE_BUILD_URL
318
+ };
319
+ }
320
+ function buildkite(env) {
321
+ const pr = env.BUILDKITE_PULL_REQUEST;
322
+ return {
323
+ provider: "buildkite",
324
+ commitSha: env.BUILDKITE_COMMIT,
325
+ branch: env.BUILDKITE_BRANCH,
326
+ prNumber: pr && pr !== "false" ? num(pr) : void 0,
327
+ baseBranch: pr && pr !== "false" ? nonEmpty(env.BUILDKITE_PULL_REQUEST_BASE_BRANCH) : void 0,
328
+ jobUrl: env.BUILDKITE_BUILD_URL
329
+ };
330
+ }
331
+ function jenkins(env) {
332
+ const isPr = Boolean(env.CHANGE_ID);
333
+ return {
334
+ provider: "jenkins",
335
+ commitSha: env.GIT_COMMIT,
336
+ branch: isPr ? env.CHANGE_BRANCH : env.BRANCH_NAME ?? env.GIT_BRANCH?.replace(/^origin\//, ""),
337
+ prNumber: num(env.CHANGE_ID),
338
+ baseBranch: isPr ? env.CHANGE_TARGET : void 0,
339
+ jobUrl: env.BUILD_URL
340
+ };
341
+ }
342
+ function azure(env) {
343
+ const pr = num(env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER ?? env.SYSTEM_PULLREQUEST_PULLREQUESTID);
344
+ const jobUrl = env.SYSTEM_COLLECTIONURI && env.SYSTEM_TEAMPROJECT && env.BUILD_BUILDID ? `${env.SYSTEM_COLLECTIONURI}${env.SYSTEM_TEAMPROJECT}/_build/results?buildId=${env.BUILD_BUILDID}` : void 0;
345
+ if (pr) return {
346
+ provider: "azure",
347
+ commitSha: env.SYSTEM_PULLREQUEST_SOURCECOMMITID ?? env.BUILD_SOURCEVERSION,
348
+ branch: stripRef(env.SYSTEM_PULLREQUEST_SOURCEBRANCH),
349
+ prNumber: pr,
350
+ baseBranch: stripRef(env.SYSTEM_PULLREQUEST_TARGETBRANCH),
351
+ fromFork: env.SYSTEM_PULLREQUEST_ISFORK ? env.SYSTEM_PULLREQUEST_ISFORK === "True" : void 0,
352
+ jobUrl
353
+ };
354
+ return {
355
+ provider: "azure",
356
+ commitSha: env.BUILD_SOURCEVERSION,
357
+ branch: stripRef(env.BUILD_SOURCEBRANCH),
358
+ jobUrl
359
+ };
360
+ }
361
+ function makeAuthor(login, extra = {}) {
362
+ return login ? {
363
+ login,
364
+ ...extra.email ? { email: extra.email } : {},
365
+ ...extra.provider && extra.providerId ? {
366
+ provider: extra.provider,
367
+ providerId: extra.providerId
368
+ } : {}
369
+ } : void 0;
370
+ }
371
+ /** Each CI's own variable for who started the run; the first one that is set wins. */
372
+ function detectAuthor(provider, env) {
373
+ const pick = (...names) => names.map((n) => nonEmpty(env[n])).find((v) => v);
374
+ switch (provider) {
375
+ case "github": return makeAuthor(pick("GITHUB_ACTOR"), {
376
+ provider: "github",
377
+ providerId: pick("GITHUB_ACTOR_ID")
378
+ });
379
+ case "gitea": return makeAuthor(pick("GITHUB_ACTOR", "GITEA_ACTOR"));
380
+ case "gitlab": return makeAuthor(pick("GITLAB_USER_LOGIN"), {
381
+ email: pick("GITLAB_USER_EMAIL"),
382
+ provider: "gitlab",
383
+ providerId: pick("GITLAB_USER_ID")
384
+ });
385
+ case "bitbucket": return makeAuthor(pick("BITBUCKET_STEP_TRIGGERER_UUID"));
386
+ case "circleci": return makeAuthor(pick("CIRCLE_USERNAME"));
387
+ case "buildkite": return makeAuthor(pick("BUILDKITE_BUILD_AUTHOR", "BUILDKITE_BUILD_CREATOR"), { email: pick("BUILDKITE_BUILD_AUTHOR_EMAIL", "BUILDKITE_BUILD_CREATOR_EMAIL") });
388
+ case "azure": return makeAuthor(pick("BUILD_REQUESTEDFOR"), { email: pick("BUILD_REQUESTEDFOREMAIL") });
389
+ default: return;
390
+ }
391
+ }
392
+ /** `CIRCI_*` variables win over anything detected, for CIs we don't know or odd setups. */
393
+ function applyOverrides(ctx, env) {
394
+ const author = nonEmpty(env.CIRCI_AUTHOR);
395
+ return {
396
+ ...ctx,
397
+ commitSha: nonEmpty(env.CIRCI_COMMIT) ?? ctx.commitSha,
398
+ branch: nonEmpty(env.CIRCI_BRANCH) ?? ctx.branch,
399
+ prNumber: num(env.CIRCI_PR_NUMBER) ?? ctx.prNumber,
400
+ baseBranch: nonEmpty(env.CIRCI_BASE_BRANCH) ?? ctx.baseBranch,
401
+ ...author ? { author: { login: author } } : {}
402
+ };
403
+ }
404
+ function field(obj, key) {
405
+ if (typeof obj !== "object" || obj === null) return void 0;
406
+ return Reflect.get(obj, key);
407
+ }
408
+ function str(v) {
409
+ return typeof v === "string" && v !== "" ? v : void 0;
410
+ }
411
+ function num(v) {
412
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : NaN;
413
+ return Number.isInteger(n) && n > 0 ? n : void 0;
414
+ }
415
+ function nonEmpty(v) {
416
+ return v === void 0 || v.trim() === "" ? void 0 : v.trim();
417
+ }
418
+ function stripRef(ref) {
419
+ return ref?.replace(/^refs\/heads\//, "");
420
+ }
421
+ /** A problem with how the CLI was called or configured (exit code 2, no stack trace). */
422
+ var UsageError = class extends Error {
423
+ constructor(message) {
424
+ super(message);
425
+ this.name = "UsageError";
426
+ }
427
+ };
428
+ /**
429
+ * The one line to print for a failure, without the `error: ` prefix: what went wrong and, where
430
+ * we can tell, what to do about it. Nothing here shows a stack; `reportError` adds that for
431
+ * `--debug`.
432
+ */
433
+ function errorLine(err) {
434
+ if (err instanceof UsageError) return err.message;
435
+ if (err instanceof NetworkError) return `${err.message}. Check CIRCI_API_URL.`;
436
+ if (err instanceof ApiError) {
437
+ if (err.status === 401 || err.status === 403) return `The server refused the token (${err.message}). Check that CIRCI_TOKEN is this project's CI token.`;
438
+ return err.status >= 500 ? `The server failed: ${err.message} (HTTP ${err.status})` : err.message;
439
+ }
440
+ if (err instanceof SyntaxError) return `Invalid JSON: ${err.message}`;
441
+ if (err instanceof Error) {
442
+ const code = "code" in err && typeof err.code === "string" ? err.code : void 0;
443
+ const path = "path" in err && typeof err.path === "string" ? err.path : void 0;
444
+ if (code === "ENOENT" && path === "git") return "Couldn't run git. Is it installed and on PATH?";
445
+ if (code === "ENOENT" && path) return `No such file or directory: ${path}`;
446
+ if (code === "ENOTDIR" && path) return `Not a directory: ${path}`;
447
+ if (code === "EISDIR" && path) return `Is a directory, not a file: ${path}`;
448
+ if ((code === "EACCES" || code === "EPERM") && path) return `Permission denied: ${path}`;
449
+ if (code === "EMFILE") return "Too many open files. Raise the limit (ulimit -n) and retry.";
450
+ return err.message.split("\n")[0] || err.name;
451
+ }
452
+ return String(err);
453
+ }
454
+ const exec = promisify(execFile);
455
+ function gitRunner(cwd) {
456
+ return { async run(args) {
457
+ const { stdout } = await exec("git", args, {
458
+ cwd,
459
+ maxBuffer: 16777216
460
+ });
461
+ return stdout.trim();
462
+ } };
463
+ }
464
+ async function tryRun(git, args) {
465
+ try {
466
+ return await git.run(args);
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ const DEEPEN_STEP = 200;
472
+ /**
473
+ * Collects the history the server uses to pick a baseline (PLAN §7.1 step 3, §7.2), so baseline
474
+ * selection never depends on a git host's API.
475
+ */
476
+ async function collectAncestry(git, options) {
477
+ const remote = options.remote ?? "origin";
478
+ const limit = options.limit ?? 200;
479
+ const maxDepth = options.maxDepth ?? 2e3;
480
+ const doFetch = options.fetch ?? true;
481
+ if (await tryRun(git, ["rev-parse", "--is-inside-work-tree"]) !== "true") return {
482
+ status: "missing",
483
+ ancestorShas: [],
484
+ warning: "Not inside a git repository"
485
+ };
486
+ const head = options.headSha;
487
+ let present = await hasCommit(git, head);
488
+ if (!present && doFetch) {
489
+ await tryRun(git, [
490
+ "fetch",
491
+ "--no-tags",
492
+ ...await depthArgs(git),
493
+ remote,
494
+ head
495
+ ]);
496
+ present = await hasCommit(git, head);
497
+ }
498
+ if (!present) return {
499
+ status: "missing",
500
+ ancestorShas: [],
501
+ warning: `Commit ${head} is not available locally`
502
+ };
503
+ if (options.isBaseBranchBuild) {
504
+ const parents = await withDeepening(git, {
505
+ rounds: doFetch ? Math.floor(maxDepth / DEEPEN_STEP) : 0,
506
+ attempt: () => listFirstParent(git, `${head}~1`, limit),
507
+ deepen: () => tryRun(git, [
508
+ "fetch",
509
+ "--no-tags",
510
+ `--deepen=${DEEPEN_STEP}`,
511
+ remote,
512
+ head
513
+ ])
514
+ });
515
+ if (parents === void 0) {
516
+ if (((await tryRun(git, [
517
+ "rev-list",
518
+ "--max-parents=0",
519
+ head
520
+ ]))?.split("\n") ?? []).includes(head)) return {
521
+ status: "ok",
522
+ mergeBaseSha: head,
523
+ ancestorShas: []
524
+ };
525
+ return {
526
+ status: "missing",
527
+ ancestorShas: [],
528
+ warning: "Could not read the commit history (shallow clone)"
529
+ };
530
+ }
531
+ return {
532
+ status: await statusFor(git, parents, limit),
533
+ mergeBaseSha: head,
534
+ ancestorShas: parents
535
+ };
536
+ }
537
+ const baseRef = `refs/remotes/${remote}/${options.baseBranch}`;
538
+ if (doFetch) await tryRun(git, [
539
+ "fetch",
540
+ "--no-tags",
541
+ ...await depthArgs(git),
542
+ remote,
543
+ `+refs/heads/${options.baseBranch}:${baseRef}`
544
+ ]);
545
+ if (!await tryRun(git, [
546
+ "rev-parse",
547
+ "--verify",
548
+ "--quiet",
549
+ `${baseRef}^{commit}`
550
+ ])) return {
551
+ status: "missing",
552
+ ancestorShas: [],
553
+ warning: `Base branch "${options.baseBranch}" is not available from ${remote}`
554
+ };
555
+ const mergeBase = await withDeepening(git, {
556
+ rounds: doFetch ? Math.floor(maxDepth / DEEPEN_STEP) : 0,
557
+ attempt: async () => await tryRun(git, [
558
+ "merge-base",
559
+ head,
560
+ baseRef
561
+ ]) || void 0,
562
+ deepen: () => tryRun(git, [
563
+ "fetch",
564
+ "--no-tags",
565
+ `--deepen=${DEEPEN_STEP}`,
566
+ remote,
567
+ head,
568
+ `+refs/heads/${options.baseBranch}:${baseRef}`
569
+ ])
570
+ });
571
+ if (!mergeBase) return {
572
+ status: "missing",
573
+ ancestorShas: [],
574
+ warning: `No common history with "${options.baseBranch}" within ${maxDepth} commits; use a deeper checkout (e.g. fetch-depth: 0)`
575
+ };
576
+ const ancestors = await listFirstParent(git, mergeBase, limit) ?? [mergeBase];
577
+ return {
578
+ status: await statusFor(git, ancestors, limit),
579
+ mergeBaseSha: mergeBase,
580
+ ancestorShas: ancestors
581
+ };
582
+ }
583
+ async function localHead(git) {
584
+ const [sha, branch] = (await tryRun(git, [
585
+ "rev-parse",
586
+ "HEAD",
587
+ "--abbrev-ref",
588
+ "HEAD"
589
+ ]))?.split("\n") ?? [];
590
+ return {
591
+ ...sha ? { sha } : {},
592
+ ...branch && branch !== "HEAD" ? { branch } : {}
593
+ };
594
+ }
595
+ async function hasCommit(git, sha) {
596
+ return await tryRun(git, [
597
+ "cat-file",
598
+ "-e",
599
+ `${sha}^{commit}`
600
+ ]) !== void 0;
601
+ }
602
+ /**
603
+ * `--depth` writes `.git/shallow`: on a full clone it would cut the user's history for good, so
604
+ * only a repository that is already shallow gets it. A full clone fetches what is missing whole.
605
+ */
606
+ async function depthArgs(git) {
607
+ return await isShallow(git) ? [`--depth=${DEEPEN_STEP}`] : [];
608
+ }
609
+ async function isShallow(git) {
610
+ return await tryRun(git, ["rev-parse", "--is-shallow-repository"]) === "true";
611
+ }
612
+ async function listFirstParent(git, rev, limit) {
613
+ const out = await tryRun(git, [
614
+ "rev-list",
615
+ "--first-parent",
616
+ `--max-count=${limit}`,
617
+ rev
618
+ ]);
619
+ return out === void 0 ? void 0 : out.split("\n").filter(Boolean);
620
+ }
621
+ /** Fewer commits than asked for in a shallow clone means history was cut off, not exhausted. */
622
+ async function statusFor(git, shas, limit) {
623
+ return shas.length < limit && await isShallow(git) ? "truncated" : "ok";
624
+ }
625
+ /**
626
+ * Tries `attempt`; while it finds nothing and the clone is shallow, fetches more history and
627
+ * tries again, at most `rounds` times. Each step depends on the previous fetch, so it's sequential.
628
+ */
629
+ async function withDeepening(git, steps) {
630
+ for (let round = 0;; round += 1) {
631
+ const found = await steps.attempt();
632
+ if (found !== void 0 || round >= steps.rounds || !await isShallow(git)) return found;
633
+ await steps.deepen();
634
+ }
635
+ }
636
+ /**
637
+ * What the CI says about this build, with the commit and branch taken from the checkout when it
638
+ * says nothing; fails when no commit can be found either way.
639
+ */
640
+ async function buildContext(env, git) {
641
+ const ci = detectCi(env, (path) => JSON.parse(readFileSync(path, "utf8")));
642
+ if (!ci.commitSha || !ci.branch) {
643
+ const local = await localHead(git);
644
+ ci.commitSha ??= local.sha;
645
+ if (!ci.branch && local.branch) ci.branch = local.branch;
646
+ }
647
+ const { commitSha } = ci;
648
+ if (!commitSha) throw new UsageError("Could not determine the commit. Run inside a git checkout or set CIRCI_COMMIT.");
649
+ return {
650
+ ...ci,
651
+ commitSha
652
+ };
653
+ }
654
+ /** `fn` over `items`, at most `limit` at a time; results keep the order of `items`. */
655
+ async function mapLimit(items, limit, fn) {
656
+ const results = Array.from({ length: items.length });
657
+ const pending = items.entries();
658
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
659
+ for (const [index, item] of pending) results[index] = await fn(item);
660
+ });
661
+ await Promise.all(lanes);
662
+ return results;
663
+ }
664
+ const MAX_BYTES = 26214400;
665
+ /** Files read and hashed at once: enough to keep the disk busy, few enough to stay under the descriptor limit. */
666
+ const HASH_CONCURRENCY = 8;
667
+ /**
668
+ * Finds every `*.png` under `dir` (skipping hidden folders and node_modules; symbolic links to
669
+ * files and folders are followed, a link back up the tree is not), hashes it, and reads an
670
+ * optional `<file>.png.json` sidecar with metadata (browser, viewport, test…).
671
+ */
672
+ async function collectScreenshots(dir) {
673
+ const info = await stat(dir).catch(() => void 0);
674
+ if (!info) throw new UsageError(`No such directory: ${dir}`);
675
+ if (!info.isDirectory()) throw new UsageError(`${dir} is not a directory`);
676
+ return (await mapLimit(await walk(dir, []), HASH_CONCURRENCY, async (path) => {
677
+ const { size } = await stat(path);
678
+ if (size > MAX_BYTES) throw new UsageError(`${path} is ${(size / 1024 / 1024).toFixed(1)} MB; the limit is ${MAX_BYTES / 1024 / 1024} MB per screenshot`);
679
+ const metadata = await readSidecar(`${path}.json`);
680
+ const shot = {
681
+ name: relative(dir, path).split(sep).join("/").replace(/\.png$/i, ""),
682
+ path,
683
+ sha256: await hashFile(path),
684
+ size
685
+ };
686
+ if (metadata) shot.metadata = metadata;
687
+ return shot;
688
+ })).toSorted((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
689
+ }
690
+ /** `ancestors` are the real paths of the folders above, so a link that loops back is skipped. */
691
+ async function walk(dir, ancestors) {
692
+ const real = await realpath(dir);
693
+ if (ancestors.includes(real)) return [];
694
+ const chain = [...ancestors, real];
695
+ const entries = await readdir(dir, { withFileTypes: true });
696
+ return (await Promise.all(entries.map(async (e) => {
697
+ if (e.name.startsWith(".") || e.name === "node_modules") return [];
698
+ const full = join(dir, e.name);
699
+ const target = e.isSymbolicLink() ? await stat(full).catch(() => void 0) : e;
700
+ if (!target) return [];
701
+ if (target.isDirectory()) return walk(full, chain);
702
+ return target.isFile() && /\.png$/i.test(e.name) ? [full] : [];
703
+ }))).flat();
704
+ }
705
+ async function hashFile(path) {
706
+ const hash = createHash("sha256");
707
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
708
+ return hash.digest("hex");
709
+ }
710
+ async function readSidecar(path) {
711
+ let text;
712
+ try {
713
+ text = await readFile(path, "utf8");
714
+ } catch {
715
+ return;
716
+ }
717
+ let parsed;
718
+ try {
719
+ parsed = JSON.parse(text);
720
+ } catch (err) {
721
+ throw new UsageError(`${path} isn't valid JSON (${err instanceof Error ? err.message : String(err)})`);
722
+ }
723
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new UsageError(`${path} must contain a JSON object`);
724
+ return Object.fromEntries(Object.entries(parsed));
725
+ }
726
+ const UPLOAD_CONCURRENCY = 8;
727
+ async function upload(options) {
728
+ const log = options.log ?? ((line) => console.log(line));
729
+ const env = options.env ?? process.env;
730
+ const cwd = options.cwd ?? process.cwd();
731
+ const parallel = parallelOf(options.shard, env);
732
+ const client = new ApiClient({
733
+ baseUrl: options.apiUrl,
734
+ token: options.token,
735
+ fetch: options.fetchImpl,
736
+ retryDelayMs: options.retryDelayMs
737
+ });
738
+ const git = gitRunner(cwd);
739
+ const [shots, context] = await Promise.all([collectScreenshots(options.dir), (async () => {
740
+ const [project, ci] = await Promise.all([client.project(), buildContext(env, git)]);
741
+ if (options.author?.trim()) ci.author = { login: options.author.trim() };
742
+ const isBaseBranchBuild = !ci.prNumber && ci.branch === project.defaultBranch;
743
+ const ancestry = await collectAncestry(git, {
744
+ headSha: ci.commitSha,
745
+ baseBranch: ci.baseBranch ?? project.defaultBranch,
746
+ isBaseBranchBuild,
747
+ fetch: options.fetch ?? true
748
+ });
749
+ return {
750
+ project,
751
+ ci,
752
+ commitSha: ci.commitSha,
753
+ isBaseBranchBuild,
754
+ ancestry
755
+ };
756
+ })()]);
757
+ if (shots.length === 0 && !options.shard) throw new UsageError(`No .png files found in ${options.dir}`);
758
+ const { project, ci, commitSha, isBaseBranchBuild, ancestry } = context;
759
+ log(`Found ${plural(shots.length, "screenshot")} in ${options.dir}`);
760
+ if (shots.length === 0) log("This shard has no screenshots; reporting it so the build can complete");
761
+ if (ancestry.warning) log(`warning: ${ancestry.warning}. CirCI will compare against the latest ${project.defaultBranch} build instead.`);
762
+ log(`Uploading for ${commitSha.slice(0, 12)}` + (ci.branch ? ` on ${ci.branch}` : "") + (ci.prNumber ? ` (PR #${ci.prNumber})` : ""));
763
+ const { build, uploads } = await client.createBuild({
764
+ commitSha,
765
+ ...options.name ? { name: options.name } : {},
766
+ branch: ci.branch ?? null,
767
+ prNumber: ci.prNumber ?? null,
768
+ baseBranch: ci.baseBranch ?? (isBaseBranchBuild ? null : project.defaultBranch),
769
+ mergeBaseSha: ancestry.mergeBaseSha ?? null,
770
+ ancestorShas: ancestry.ancestorShas,
771
+ ancestryStatus: ancestry.status,
772
+ ...parallel ? { parallel } : {},
773
+ ...ci.author ? { author: ci.author } : {},
774
+ files: uniqueFiles(shots)
775
+ });
776
+ const byHash = new Map(shots.map((s) => [s.sha256, s]));
777
+ const unique = byHash.size;
778
+ const deduplicated = unique - uploads.length;
779
+ log(`Build #${build.number}: sending ${uploads.length} of ${unique} files (${deduplicated} already on the server)`);
780
+ await sendAll(client, uploads, byHash, log);
781
+ const finalizeBody = {
782
+ ...options.shard ? { shardIndex: String(options.shard.index) } : {},
783
+ screenshots: shots.map((s) => ({
784
+ name: s.name,
785
+ sha256: s.sha256,
786
+ ...s.metadata ? { metadata: s.metadata } : {}
787
+ }))
788
+ };
789
+ try {
790
+ await client.finalize(build.id, finalizeBody);
791
+ } catch (err) {
792
+ const missing = missingFrom(err);
793
+ if (!missing) throw err;
794
+ log(`${plural(missing.length, "file")} didn't arrive; sending again`);
795
+ await sendAll(client, uploads.filter((u) => missing.includes(u.sha256)), byHash, log);
796
+ await client.finalize(build.id, finalizeBody);
797
+ }
798
+ log(`Build #${build.number}: ${build.url}`);
799
+ if (options.shard) log(` shard ${options.shard.index + 1} of ${options.shard.total} uploaded`);
800
+ log(` ${plural(shots.length, "screenshot")}: ${uploads.length} uploaded, ${deduplicated} already on the server`);
801
+ const result = {
802
+ exitCode: 0,
803
+ build,
804
+ ci,
805
+ ancestry,
806
+ uploaded: uploads.length,
807
+ deduplicated
808
+ };
809
+ if (!options.wait) return result;
810
+ log("Waiting for the result…");
811
+ const status = await waitForResult(client, build.id, {
812
+ timeoutMs: options.waitTimeoutMs ?? 6e5,
813
+ ...options.pollIntervalMs !== void 0 ? { intervalMs: options.pollIntervalMs } : {},
814
+ ...options.gate ? { gate: options.gate } : {},
815
+ onTransient: (err) => log(`warning: ${errorLine(err)}; still waiting`)
816
+ });
817
+ result.status = status;
818
+ if (!status) {
819
+ log("error: timed out waiting for the build to be processed");
820
+ result.exitCode = 2;
821
+ return result;
822
+ }
823
+ if (status.build.status === "error") {
824
+ log(`error: Build #${status.build.number} failed to process: ${status.errorMessage ?? "the server gave no reason"}`);
825
+ if (status.outcome.warning) log(`warning: ${status.outcome.warning}`);
826
+ log(`Details: ${status.build.url}`);
827
+ if (status.outcome.state === "fail") result.exitCode = 2;
828
+ return result;
829
+ }
830
+ const c = status.counts;
831
+ log(`${status.outcome.summary}: ${c.changed} changed, ${c.added} added, ${c.removed} removed, ${c.unchanged} unchanged${c.failed ? `, ${c.failed} couldn't be read` : ""}`);
832
+ if (status.outcome.warning) log(`warning: ${status.outcome.warning}`);
833
+ if (c.failed > 0) {
834
+ for (const shot of status.unreadable) log(`error: ${shot.name}: ${shot.reason}`);
835
+ log(`Upload the build again with valid PNGs: ${status.build.url}`);
836
+ if (status.outcome.state === "fail") result.exitCode = 2;
837
+ return result;
838
+ }
839
+ if (status.outcome.state === "fail") {
840
+ if (status.gate === "exit-code") {
841
+ log(`Review the changes at ${status.build.url}`);
842
+ if (ci.jobUrl) log(`After approving, re-run this job to unblock the merge: ${ci.jobUrl}`);
843
+ result.exitCode = 1;
844
+ }
845
+ }
846
+ return result;
847
+ }
848
+ /** Checks `--shard`/`--nonce` and returns what the server needs, or undefined for a whole build. */
849
+ function parallelOf(shard, env) {
850
+ if (!shard) return void 0;
851
+ const { index, total } = shard;
852
+ if (!Number.isInteger(index) || !Number.isInteger(total) || total < 1 || index < 0 || index >= total) throw new UsageError("--shard must look like 1/4: this job's number, then how many jobs there are");
853
+ const nonce = shard.nonce ?? ciRunId(env);
854
+ if (!nonce) throw new UsageError("Could not tell which CI run these shards belong to. Set CIRCI_PARALLEL_NONCE (or --nonce) to the same value in every shard.");
855
+ return {
856
+ nonce,
857
+ total
858
+ };
859
+ }
860
+ function plural(count, noun) {
861
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
862
+ }
863
+ async function waitForResult(client, buildId, opts) {
864
+ const deadline = Date.now() + opts.timeoutMs;
865
+ let warned = false;
866
+ for (let attempt = 0;; attempt += 1) {
867
+ let status;
868
+ try {
869
+ status = await client.status(buildId, opts.gate);
870
+ } catch (err) {
871
+ if (!isRetryable(err, true)) throw err;
872
+ if (!warned) opts.onTransient(err);
873
+ warned = true;
874
+ }
875
+ if (status && status.outcome.state !== "pending") return status;
876
+ const delay = opts.intervalMs ?? pollDelay(attempt);
877
+ if (Date.now() + delay > deadline) return void 0;
878
+ await setTimeout(delay);
879
+ }
880
+ }
881
+ /**
882
+ * How long to wait before the next status poll: 500 ms at first, so a build that finishes in a
883
+ * moment is seen at once, growing by half each time to a ceiling of 2 s, so a long build is not
884
+ * hammered. `attempt` counts from 0.
885
+ */
886
+ function pollDelay(attempt) {
887
+ return Math.min(2e3, Math.round(500 * 1.5 ** attempt));
888
+ }
889
+ function uniqueFiles(shots) {
890
+ const seen = /* @__PURE__ */ new Map();
891
+ for (const s of shots) seen.set(s.sha256, {
892
+ sha256: s.sha256,
893
+ size: s.size,
894
+ contentType: "image/png"
895
+ });
896
+ return [...seen.values()];
897
+ }
898
+ async function sendAll(client, instructions, byHash, log) {
899
+ let done = 0;
900
+ const step = Math.max(1, Math.ceil(instructions.length / 4));
901
+ await mapLimit(instructions, UPLOAD_CONCURRENCY, async (instruction) => {
902
+ const shot = byHash.get(instruction.sha256);
903
+ if (!shot) throw new Error(`Server asked for unknown file ${instruction.sha256}`);
904
+ await client.upload(instruction, await readFile(shot.path));
905
+ done += 1;
906
+ if (instructions.length > 4 && (done % step === 0 || done === instructions.length)) log(` uploaded ${done} of ${instructions.length}`);
907
+ });
908
+ }
909
+ function missingFrom(err) {
910
+ if (!(err instanceof ApiError) || err.status !== 409) return void 0;
911
+ const body = err.body;
912
+ if (typeof body !== "object" || body === null || !("missing" in body) || !Array.isArray(body.missing)) return;
913
+ return body.missing.filter((m) => typeof m === "string");
914
+ }
915
+ /**
916
+ * `2/4` → the second of four jobs, 0-based (`{ index: 1, total: 4 }`); undefined unless it's a
917
+ * job number from 1 to the total. Read the same way by `circi upload --shard` and Vitest's `--shard`.
918
+ */
919
+ function parseShard(text) {
920
+ const m = /^(\d+)\/(\d+)$/.exec(text.trim());
921
+ if (!m?.[1] || !m[2]) return void 0;
922
+ const index = Number(m[1]) - 1;
923
+ const total = Number(m[2]);
924
+ return total >= 1 && index >= 0 && index < total ? {
925
+ index,
926
+ total
927
+ } : void 0;
928
+ }
929
+ /** `CIRCI_SHARD=2/4` from the environment, for runners that have no `--shard` of their own. */
930
+ function shardFromEnv(env) {
931
+ const value = env.CIRCI_SHARD;
932
+ return value ? parseShard(value) : void 0;
933
+ }
934
+ // ../cli/dist/index.mjs
935
+ /** Writes a capture and, when there is metadata, its `.png.json` sidecar, creating the folder. */
936
+ async function writeCapture(file, png, metadata) {
937
+ await mkdir(dirname(file), { recursive: true });
938
+ await Promise.all([writeFile(file, png), metadata ? writeFile(`${file}.json`, `${JSON.stringify(metadata, null, 2)}\n`) : void 0]);
939
+ }
940
+ /**
941
+ * The end of every integration's run (Vitest, Storybook, Cypress): send the captures in `dir` to
942
+ * CirCI as one build, unless there is nothing to send or nowhere to send it, and never throw. The
943
+ * policy lives here once: credentials from the options, else `CIRCI_API_URL` and `CIRCI_TOKEN`;
944
+ * without them a notice and no upload; a failed upload is reported and only `strict` turns it into
945
+ * an exit code; only `wait` lets the build's result decide the exit code.
946
+ */
947
+ async function uploadCaptures(options) {
948
+ const log = options.log ?? ((line) => console.log(line));
949
+ const env = options.env ?? process.env;
950
+ const apiUrl = options.apiUrl ?? env.CIRCI_API_URL;
951
+ const token = options.token ?? env.CIRCI_TOKEN;
952
+ if (!apiUrl || !token) {
953
+ log("[circi] skipped: set CIRCI_API_URL and CIRCI_TOKEN to upload screenshots");
954
+ return {
955
+ status: "skipped",
956
+ exitCode: 0
957
+ };
958
+ }
959
+ if (await options.isEmpty?.()) {
960
+ if (!options.shard) {
961
+ log("[circi] no screenshots found, nothing to upload");
962
+ return {
963
+ status: "empty",
964
+ exitCode: 0
965
+ };
966
+ }
967
+ log("[circi] no screenshots found in this shard; reporting it so the build can complete");
968
+ }
969
+ try {
970
+ const result = await (options.uploadImpl ?? upload)({
971
+ dir: options.dir,
972
+ apiUrl,
973
+ token,
974
+ name: options.name ?? options.defaultName,
975
+ wait: options.wait ?? false,
976
+ ...options.shard ? { shard: options.shard } : {},
977
+ ...options.waitTimeoutMs ? { waitTimeoutMs: options.waitTimeoutMs } : {},
978
+ ...options.fetch === false ? { fetch: false } : {},
979
+ ...options.cwd ? { cwd: options.cwd } : {},
980
+ env,
981
+ log
982
+ });
983
+ return {
984
+ status: "uploaded",
985
+ exitCode: options.wait && result.exitCode !== 0 ? result.exitCode : 0
986
+ };
987
+ } catch (err) {
988
+ log(`[circi] upload failed: ${errorLine(err)}`);
989
+ return {
990
+ status: "failed",
991
+ exitCode: options.strict ? options.strictExitCode ?? 2 : 0
992
+ };
993
+ }
994
+ }
995
+ // src/plugin.ts
996
+ /** Where this plugin keeps its screenshots under the shared `dir`: one folder per tool. */
997
+ const TOOL = "cypress";
998
+ /**
999
+ * The Cypress plugin: `setupNodeEvents: circi({ name: 'cypress-chrome' })` in `cypress.config.ts`.
1000
+ *
1001
+ * Tests keep `cy.screenshot('name')`. Every named screenshot a run takes (not the automatic
1002
+ * screenshot of a failing test) is copied to
1003
+ * `.circi/screenshots/cypress/<spec path>/<name>.png`, with a `.png.json` sidecar naming the spec,
1004
+ * browser and viewport, and `cypress run` uploads them to CirCI when it ends. To also do your own
1005
+ * setup, call it inside yours:
1006
+ * `setupNodeEvents(on, config) { circi(options)(on, config); return config }`.
1007
+ */
1008
+ function circi(options = {}) {
1009
+ return function setupNodeEvents(on, config) {
1010
+ const log = options.log ?? ((line) => console.log(line));
1011
+ const env = options.env ?? process.env;
1012
+ const root = resolve(options.root ?? config.projectRoot);
1013
+ const parent = options.dir ?? ".circi/screenshots";
1014
+ const dirOption = toolDir(parent, TOOL);
1015
+ const dir = resolve(root, dirOption);
1016
+ let browser;
1017
+ let spec;
1018
+ let taken = 0;
1019
+ on("before:run", async (details) => {
1020
+ browser = details.browser?.name;
1021
+ taken = 0;
1022
+ if (options.clean ?? true) await rm(dir, {
1023
+ recursive: true,
1024
+ force: true
1025
+ });
1026
+ });
1027
+ on("before:spec", (details) => {
1028
+ spec = details.relative;
1029
+ });
1030
+ on("after:screenshot", async (details) => {
1031
+ if (details.testFailure || !details.name) return {};
1032
+ let file;
1033
+ const specPath = spec || details.specName || "unknown-spec";
1034
+ try {
1035
+ file = resolve(root, capturePath(dirOption, specPath, details.name));
1036
+ } catch (err) {
1037
+ log(`[circi] skipped screenshot "${details.name}": ${errorLine(err)}`);
1038
+ return {};
1039
+ }
1040
+ const viewport = details.viewport ?? (config.viewportWidth && config.viewportHeight ? {
1041
+ width: config.viewportWidth,
1042
+ height: config.viewportHeight
1043
+ } : void 0);
1044
+ await writeCapture(file, await readFile(details.path), {
1045
+ spec: specPath,
1046
+ ...browser ? { browser } : {},
1047
+ ...viewport ? { viewport: `${viewport.width}x${viewport.height}` } : {}
1048
+ });
1049
+ taken += 1;
1050
+ return {};
1051
+ });
1052
+ on("after:run", async (results) => {
1053
+ if (results.status === "failed") return;
1054
+ const { exitCode } = await uploadCaptures({
1055
+ dir,
1056
+ defaultName: "cypress",
1057
+ name: options.name,
1058
+ apiUrl: options.apiUrl,
1059
+ token: options.token,
1060
+ wait: options.wait,
1061
+ strict: options.strict,
1062
+ strictExitCode: 1,
1063
+ shard: options.shard ?? shardFromEnv(env),
1064
+ isEmpty: () => Promise.resolve(taken === 0),
1065
+ cwd: root,
1066
+ env,
1067
+ log,
1068
+ uploadImpl: options.uploadImpl
1069
+ });
1070
+ if (exitCode !== 0) throw new Error(`[circi] exit code ${exitCode}`);
1071
+ });
1072
+ return config;
1073
+ };
1074
+ }
1075
+ export { circi };
1076
+
1077
+ //# sourceMappingURL=index.mjs.map