@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["sleep","sleep"],"sources":["../../cli/src/api.ts","../../cli/src/ci-env.ts","../../cli/src/errors.ts","../../cli/src/git.ts","../../cli/src/context.ts","../../cli/src/concurrency.ts","../../cli/src/files.ts","../../cli/src/upload.ts","../../cli/src/shard.ts","../../cli/src/captures.ts","../src/plugin.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { setTimeout as sleep } from 'node:timers/promises'\n\n/** Thin client for the CirCI `/v1` API, using the built-in fetch. */\n\nexport namespace ApiClient {\n export interface Options {\n baseUrl: string\n token: string\n fetch?: typeof fetch | undefined\n /** Per request, in milliseconds (default 30 s; file and site uploads get four times that). */\n timeoutMs?: number\n /** Tries per call for transient failures (default 4). */\n attempts?: number\n /** First backoff in milliseconds; each retry doubles it, with jitter (default 500). */\n retryDelayMs?: number | undefined\n }\n\n export interface Project {\n workspace: string\n slug: string\n name: string\n defaultBranch: string\n dashboardUrl: string\n }\n\n export interface Build {\n id: string\n number: number\n name: string\n status: string\n conclusion: string | null\n reviewStatus: string\n url: string\n }\n\n export interface UploadInstruction {\n sha256: string\n url: string\n method: 'PUT'\n headers: Record<string, string>\n /** `token`: send the project token too (uploads through the API, local-disk storage). */\n auth: 'token' | 'none'\n }\n\n export interface Status {\n build: ApiClient.Build\n counts: {\n added: number\n removed: number\n changed: number\n unchanged: number\n failed: number\n total: number\n }\n /** Screenshots the server couldn't read, with why. */\n unreadable: { name: string; reason: string }[]\n outcome: { state: 'pending' | 'pass' | 'fail'; summary: string; warning?: string }\n gate: 'exit-code' | 'status'\n errorMessage: string | null\n }\n\n export interface SiteUpload {\n site: { name: string; kind: string; slug: string }\n version: { commitSha: string; fileCount: number; totalBytes: number }\n addresses: { commit: string; branch?: string }\n branchMoved: boolean\n replaced: boolean\n }\n}\n\nexport class ApiError extends Error {\n readonly status: number\n readonly body: unknown\n constructor(status: number, message: string, body: unknown) {\n super(message)\n this.name = 'ApiError'\n this.status = status\n this.body = body\n }\n}\n\n/** The server (or the way to it) didn't answer: a refused connection, an unknown host, a timeout. */\nexport class NetworkError extends Error {\n readonly url: string\n /** The Node error code (`ECONNREFUSED`…), `TIMEOUT`, or undefined. */\n readonly code: string | undefined\n constructor(url: string, code: string | undefined, detail: string) {\n super(`Couldn't reach ${originOf(url)} (${detail})`)\n this.name = 'NetworkError'\n this.url = url\n this.code = code\n }\n}\n\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin\n } catch {\n // Not a URL at all (a typo in CIRCI_API_URL): show what was typed, without the API path.\n return url.split('/v1/')[0] ?? url\n }\n}\n\nconst CODE_TEXT: Record<string, string> = {\n ECONNREFUSED: 'connection refused',\n ENOTFOUND: 'host not found',\n EAI_AGAIN: 'host not found',\n ECONNRESET: 'connection reset',\n ETIMEDOUT: 'timed out',\n UND_ERR_CONNECT_TIMEOUT: 'timed out',\n CERT_HAS_EXPIRED: 'certificate expired',\n DEPTH_ZERO_SELF_SIGNED_CERT: 'self-signed certificate',\n ERR_INVALID_URL: 'not a valid URL',\n}\n\n/** Turns what `fetch` throws (`TypeError: fetch failed` with a cause) into a `NetworkError`. */\nfunction toNetworkError(url: string, err: unknown): NetworkError {\n if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {\n return new NetworkError(url, 'TIMEOUT', 'timed out')\n }\n const cause: unknown = err instanceof Error ? err.cause : undefined\n const code =\n cause instanceof Error && 'code' in cause && typeof cause.code === 'string'\n ? cause.code\n : err instanceof Error && 'code' in err && typeof err.code === 'string'\n ? err.code\n : undefined\n const detail =\n (code && CODE_TEXT[code]) ||\n code ||\n (cause instanceof Error ? cause.message : err instanceof Error ? err.message : String(err))\n return new NetworkError(url, code, detail)\n}\n\n/** Failures that mean the request never reached the application, so even a POST can be resent. */\nconst NEVER_ARRIVED = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN'])\n\n/**\n * Whether to resend after `err`. `safe` calls (reads, and writes that replace rather than add)\n * retry on any 5xx, 429 and network failure; others only when the request cannot have been\n * processed: the connection never opened, or a gateway (502/503/504) answered for the server.\n */\nexport function isRetryable(err: unknown, safe: boolean): boolean {\n if (err instanceof NetworkError) {\n if (err.code === 'ERR_INVALID_URL') return false\n return safe || (err.code !== undefined && NEVER_ARRIVED.has(err.code))\n }\n if (err instanceof ApiError) {\n if (safe) return err.status >= 500 || err.status === 429\n return err.status === 502 || err.status === 503 || err.status === 504\n }\n return false\n}\n\n/** Backoff for retry number `retry` (1, 2, …): `base * 2^(retry-1)`, scaled by 50-100% jitter. */\nexport function backoffDelay(retry: number, baseMs: number, random = Math.random): number {\n return Math.round(baseMs * 2 ** (retry - 1) * (0.5 + random() / 2))\n}\n\n/** Runs `fn`, resending after a transient failure (see `isRetryable`) with exponential backoff. */\nasync function withRetry<T>(\n fn: () => Promise<T>,\n options: { attempts: number; baseDelayMs: number; safe: boolean },\n): Promise<T> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n // oxlint-disable-next-line no-await-in-loop -- retries are sequential by nature\n return await fn()\n } catch (err) {\n if (attempt >= options.attempts || !isRetryable(err, options.safe)) throw err\n // oxlint-disable-next-line no-await-in-loop -- backoff between retries\n await sleep(backoffDelay(attempt, options.baseDelayMs))\n }\n }\n}\n\nexport class ApiClient {\n readonly baseUrl: string\n private readonly token: string\n private readonly fetchImpl: typeof fetch\n private readonly timeoutMs: number\n private readonly attempts: number\n private readonly retryDelayMs: number\n\n constructor(options: ApiClient.Options) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.token = options.token\n this.fetchImpl = options.fetch ?? fetch\n this.timeoutMs = options.timeoutMs ?? 30_000\n this.attempts = options.attempts ?? 4\n this.retryDelayMs = options.retryDelayMs ?? 500\n }\n\n project(): Promise<ApiClient.Project> {\n return this.json('GET', '/v1/project')\n }\n\n createBuild(\n body: Record<string, unknown>,\n ): Promise<{ build: ApiClient.Build; uploads: ApiClient.UploadInstruction[] }> {\n // One key per call, the same on every resend: when an answer is lost (a gateway timing out\n // after the server committed) the resend gets the build the first request made, not another.\n return this.json('POST', '/v1/builds', body, {\n safe: true,\n headers: { 'idempotency-key': randomUUID() },\n })\n }\n\n finalize(\n buildId: string,\n body: Record<string, unknown>,\n ): Promise<{\n build: ApiClient.Build\n complete: boolean\n shardsReceived: number\n shardsTotal: number\n }> {\n // Replaces the shard's screenshots in one transaction, and the server answers a repeat of one\n // it already finalized the same way: a resend lands on the same state.\n return this.json('POST', `/v1/builds/${buildId}/finalize`, body, { safe: true })\n }\n\n status(buildId: string, gate?: 'status' | 'exit-code'): Promise<ApiClient.Status> {\n return this.json('GET', `/v1/builds/${buildId}/status${gate ? `?gate=${gate}` : ''}`)\n }\n\n /** Uploads a site (a `.tar.gz`); the query says what and where it is. */\n uploadSite(query: Record<string, string>, archive: Uint8Array): Promise<ApiClient.SiteUpload> {\n // It replaces the version of that commit, so a resend is harmless.\n return withRetry(\n async () => {\n const res = await this.send(\n `${this.baseUrl}/v1/sites?${new URLSearchParams(query).toString()}`,\n {\n method: 'POST',\n headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/gzip' },\n body: archive,\n },\n this.timeoutMs * 4,\n )\n return this.parse<ApiClient.SiteUpload>(res)\n },\n { attempts: this.attempts, baseDelayMs: this.retryDelayMs, safe: true },\n )\n }\n\n /** The commit a branch's address serves now, or null when the server says it has none yet. */\n async servedCommit(name: string, branch: string): Promise<string | null> {\n const res = await this.json<{ commit: string | null }>(\n 'GET',\n `/v1/sites/served?${new URLSearchParams({ name, branch }).toString()}`,\n )\n return res.commit\n }\n\n /** Sends one file as instructed by the server, retrying transient failures. */\n async upload(instruction: ApiClient.UploadInstruction, bytes: Uint8Array): Promise<void> {\n // fetch sets content-length itself from the body; passing it explicitly is not allowed.\n const headers = Object.fromEntries(\n Object.entries(instruction.headers).filter(([k]) => k.toLowerCase() !== 'content-length'),\n )\n if (instruction.auth === 'token') headers.authorization = `Bearer ${this.token}`\n try {\n await withRetry(\n async () => {\n const res = await this.send(\n instruction.url,\n { method: instruction.method, headers, body: bytes },\n this.timeoutMs * 4,\n )\n if (!res.ok) throw new ApiError(res.status, await safeText(res), undefined)\n },\n { attempts: this.attempts, baseDelayMs: this.retryDelayMs, safe: true },\n )\n } catch (err) {\n const detail =\n err instanceof ApiError\n ? `${err.status} ${err.message}`.trim()\n : err instanceof Error\n ? err.message\n : String(err)\n throw new Error(`Upload of ${instruction.sha256.slice(0, 12)} failed: ${detail}`, {\n cause: err,\n })\n }\n }\n\n /** One request with a timeout; a failure to get an answer becomes a `NetworkError`. */\n private async send(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n try {\n return await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) })\n } catch (err) {\n throw toNetworkError(url, err)\n }\n }\n\n /** Reads the answer; a non-2xx one throws an `ApiError` carrying the server's `error` text. */\n private async parse<T>(res: Response): Promise<T> {\n let text: string\n try {\n text = await res.text()\n } catch (err) {\n throw toNetworkError(res.url, err)\n }\n let parsed: unknown = undefined\n try {\n parsed = text ? JSON.parse(text) : undefined\n } catch {\n parsed = text\n }\n if (!res.ok) {\n const message =\n typeof parsed === 'object' &&\n parsed !== null &&\n 'error' in parsed &&\n typeof parsed.error === 'string'\n ? parsed.error\n : `HTTP ${res.status}`\n throw new ApiError(res.status, message, parsed)\n }\n // The server's JSON is the contract here; shapes are covered by the API tests.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return parsed as T\n }\n\n private json<T>(\n method: string,\n path: string,\n body?: unknown,\n options: { safe?: boolean; headers?: Record<string, string> } = {},\n ): Promise<T> {\n // Reads are always safe to resend.\n const safe = options.safe ?? method === 'GET'\n return withRetry(\n async () => {\n const res = await this.send(\n `${this.baseUrl}${path}`,\n {\n method,\n headers: {\n authorization: `Bearer ${this.token}`,\n ...options.headers,\n ...(body === undefined ? {} : { 'content-type': 'application/json' }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n },\n this.timeoutMs,\n )\n return this.parse<T>(res)\n },\n { attempts: this.attempts, baseDelayMs: this.retryDelayMs, safe },\n )\n }\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 300)\n } catch {\n return ''\n }\n}\n","/**\n * Reads build context from CI environment variables (PLAN §7.1 step 2). Pure: takes the env and\n * a JSON reader, so every provider is covered by table-driven tests.\n */\n\n/**\n * An id shared by every job of one CI run, so the shards of a parallel build find each other.\n * `undefined` when the CI isn't recognised (pass `--nonce` or `CIRCI_PARALLEL_NONCE` then).\n */\nexport function ciRunId(env: Record<string, string | undefined>): string | undefined {\n const pick = (...names: string[]) => names.map((n) => env[n]).find((v) => v)\n const base = pick(\n 'CIRCI_PARALLEL_NONCE',\n 'GITHUB_RUN_ID',\n 'CI_PIPELINE_ID',\n 'BUILDKITE_BUILD_ID',\n 'CIRCLE_WORKFLOW_ID',\n 'BITBUCKET_BUILD_NUMBER',\n 'BUILD_TAG',\n 'BUILD_ID',\n 'BUILD_BUILDID',\n )\n // A re-run of a GitHub job is a new attempt and must not join the old build.\n return base && env.GITHUB_RUN_ATTEMPT && !env.CIRCI_PARALLEL_NONCE\n ? `${base}-${env.GITHUB_RUN_ATTEMPT}`\n : base\n}\n\nexport namespace detectCi {\n export interface Context {\n provider:\n | 'github'\n | 'gitea'\n | 'gitlab'\n | 'bitbucket'\n | 'circleci'\n | 'buildkite'\n | 'jenkins'\n | 'azure'\n | 'local'\n /** The commit that was built. For PRs this is the PR's head, never a synthetic merge commit. */\n commitSha?: string\n branch?: string\n prNumber?: number\n /** Branch the PR targets. */\n baseBranch?: string\n /** The PR comes from a fork (PLAN §7.6: forks never move branch links). */\n fromFork?: boolean\n /** Link to the CI job, for \"re-run to unblock\" messages. */\n jobUrl?: string\n /** Who triggered the run, as the CI names them. The server may replace it with the PR's author. */\n author?: detectCi.Author\n }\n\n export interface Author {\n login: string\n email?: string\n /** Sign-in provider the id belongs to, so the server can match a linked account. */\n provider?: string\n providerId?: string\n }\n}\n\ntype Env = Record<string, string | undefined>\ntype ReadJson = (path: string) => unknown\n\nexport function detectCi(env: Env, readJson: ReadJson): detectCi.Context {\n const ctx = detectProvider(env, readJson)\n const author = detectAuthor(ctx.provider, env)\n return applyOverrides(author ? { ...ctx, author } : ctx, env)\n}\n\nfunction detectProvider(env: Env, readJson: ReadJson): detectCi.Context {\n if (env.GITHUB_ACTIONS === 'true')\n return github(env, readJson, env.GITEA_ACTIONS === 'true' ? 'gitea' : 'github')\n if (env.GITLAB_CI === 'true') return gitlab(env)\n if (env.BITBUCKET_BUILD_NUMBER) return bitbucket(env)\n if (env.CIRCLECI === 'true') return circleci(env)\n if (env.BUILDKITE === 'true') return buildkite(env)\n if (env.JENKINS_URL) return jenkins(env)\n if (env.TF_BUILD === 'True' || env.TF_BUILD === 'true') return azure(env)\n return { provider: 'local' }\n}\n\nfunction github(env: Env, readJson: ReadJson, provider: 'github' | 'gitea'): detectCi.Context {\n const jobUrl =\n env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID\n ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}`\n : undefined\n const isPr =\n env.GITHUB_EVENT_NAME === 'pull_request' || env.GITHUB_EVENT_NAME === 'pull_request_target'\n if (isPr && env.GITHUB_EVENT_PATH) {\n const pr = field(readJson(env.GITHUB_EVENT_PATH), 'pull_request')\n const head = field(pr, 'head')\n const base = field(pr, 'base')\n const headRepo = str(field(field(head, 'repo'), 'full_name'))\n const baseRepo = str(field(field(base, 'repo'), 'full_name'))\n return {\n provider,\n // GITHUB_SHA is the synthetic merge commit on PR events; the head SHA is what was pushed.\n commitSha: str(field(head, 'sha')) ?? env.GITHUB_SHA,\n branch: str(field(head, 'ref')) ?? env.GITHUB_HEAD_REF,\n prNumber: num(field(pr, 'number')),\n baseBranch: str(field(base, 'ref')) ?? env.GITHUB_BASE_REF,\n fromFork: headRepo && baseRepo ? headRepo !== baseRepo : undefined,\n jobUrl,\n }\n }\n return {\n provider,\n commitSha: env.GITHUB_SHA,\n branch: env.GITHUB_REF_TYPE === 'branch' ? env.GITHUB_REF_NAME : undefined,\n jobUrl,\n }\n}\n\nfunction gitlab(env: Env): detectCi.Context {\n if (env.CI_MERGE_REQUEST_IID) {\n return {\n provider: 'gitlab',\n commitSha: nonEmpty(env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA) ?? env.CI_COMMIT_SHA,\n branch: env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,\n prNumber: num(env.CI_MERGE_REQUEST_IID),\n baseBranch: env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME,\n fromFork:\n env.CI_MERGE_REQUEST_SOURCE_PROJECT_ID && env.CI_MERGE_REQUEST_PROJECT_ID\n ? env.CI_MERGE_REQUEST_SOURCE_PROJECT_ID !== env.CI_MERGE_REQUEST_PROJECT_ID\n : undefined,\n jobUrl: env.CI_JOB_URL,\n }\n }\n return {\n provider: 'gitlab',\n commitSha: env.CI_COMMIT_SHA,\n branch: env.CI_COMMIT_BRANCH,\n jobUrl: env.CI_JOB_URL,\n }\n}\n\nfunction bitbucket(env: Env): detectCi.Context {\n return {\n provider: 'bitbucket',\n commitSha: env.BITBUCKET_COMMIT,\n branch: env.BITBUCKET_BRANCH,\n prNumber: num(env.BITBUCKET_PR_ID),\n baseBranch: env.BITBUCKET_PR_DESTINATION_BRANCH,\n jobUrl: env.BITBUCKET_GIT_HTTP_ORIGIN\n ? `${env.BITBUCKET_GIT_HTTP_ORIGIN}/addon/pipelines/home#!/results/${env.BITBUCKET_BUILD_NUMBER}`\n : undefined,\n }\n}\n\nfunction circleci(env: Env): detectCi.Context {\n return {\n provider: 'circleci',\n commitSha: env.CIRCLE_SHA1,\n branch: env.CIRCLE_BRANCH,\n prNumber: num(env.CIRCLE_PULL_REQUEST?.match(/\\/(\\d+)$/)?.[1]),\n jobUrl: env.CIRCLE_BUILD_URL,\n }\n}\n\nfunction buildkite(env: Env): detectCi.Context {\n const pr = env.BUILDKITE_PULL_REQUEST\n return {\n provider: 'buildkite',\n commitSha: env.BUILDKITE_COMMIT,\n branch: env.BUILDKITE_BRANCH,\n prNumber: pr && pr !== 'false' ? num(pr) : undefined,\n baseBranch: pr && pr !== 'false' ? nonEmpty(env.BUILDKITE_PULL_REQUEST_BASE_BRANCH) : undefined,\n jobUrl: env.BUILDKITE_BUILD_URL,\n }\n}\n\nfunction jenkins(env: Env): detectCi.Context {\n const isPr = Boolean(env.CHANGE_ID)\n return {\n provider: 'jenkins',\n commitSha: env.GIT_COMMIT,\n // Multibranch PR jobs set BRANCH_NAME to \"PR-12\"; the real branch is CHANGE_BRANCH.\n branch: isPr\n ? env.CHANGE_BRANCH\n : (env.BRANCH_NAME ?? env.GIT_BRANCH?.replace(/^origin\\//, '')),\n prNumber: num(env.CHANGE_ID),\n baseBranch: isPr ? env.CHANGE_TARGET : undefined,\n jobUrl: env.BUILD_URL,\n }\n}\n\nfunction azure(env: Env): detectCi.Context {\n const pr = num(env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER ?? env.SYSTEM_PULLREQUEST_PULLREQUESTID)\n const jobUrl =\n env.SYSTEM_COLLECTIONURI && env.SYSTEM_TEAMPROJECT && env.BUILD_BUILDID\n ? `${env.SYSTEM_COLLECTIONURI}${env.SYSTEM_TEAMPROJECT}/_build/results?buildId=${env.BUILD_BUILDID}`\n : undefined\n if (pr) {\n return {\n provider: 'azure',\n commitSha: env.SYSTEM_PULLREQUEST_SOURCECOMMITID ?? env.BUILD_SOURCEVERSION,\n branch: stripRef(env.SYSTEM_PULLREQUEST_SOURCEBRANCH),\n prNumber: pr,\n baseBranch: stripRef(env.SYSTEM_PULLREQUEST_TARGETBRANCH),\n fromFork: env.SYSTEM_PULLREQUEST_ISFORK\n ? env.SYSTEM_PULLREQUEST_ISFORK === 'True'\n : undefined,\n jobUrl,\n }\n }\n return {\n provider: 'azure',\n commitSha: env.BUILD_SOURCEVERSION,\n branch: stripRef(env.BUILD_SOURCEBRANCH),\n jobUrl,\n }\n}\n\nfunction makeAuthor(\n login: string | undefined,\n extra: { email?: string | undefined; provider?: string; providerId?: string | undefined } = {},\n): detectCi.Author | undefined {\n return login\n ? {\n login,\n ...(extra.email ? { email: extra.email } : {}),\n ...(extra.provider && extra.providerId\n ? { provider: extra.provider, providerId: extra.providerId }\n : {}),\n }\n : undefined\n}\n\n/** Each CI's own variable for who started the run; the first one that is set wins. */\nfunction detectAuthor(\n provider: detectCi.Context['provider'],\n env: Env,\n): detectCi.Author | undefined {\n const pick = (...names: string[]) => names.map((n) => nonEmpty(env[n])).find((v) => v)\n switch (provider) {\n case 'github':\n return makeAuthor(pick('GITHUB_ACTOR'), {\n provider: 'github',\n providerId: pick('GITHUB_ACTOR_ID'),\n })\n case 'gitea':\n return makeAuthor(pick('GITHUB_ACTOR', 'GITEA_ACTOR'))\n case 'gitlab':\n return makeAuthor(pick('GITLAB_USER_LOGIN'), {\n email: pick('GITLAB_USER_EMAIL'),\n provider: 'gitlab',\n providerId: pick('GITLAB_USER_ID'),\n })\n case 'bitbucket':\n return makeAuthor(pick('BITBUCKET_STEP_TRIGGERER_UUID'))\n case 'circleci':\n return makeAuthor(pick('CIRCLE_USERNAME'))\n case 'buildkite':\n return makeAuthor(pick('BUILDKITE_BUILD_AUTHOR', 'BUILDKITE_BUILD_CREATOR'), {\n email: pick('BUILDKITE_BUILD_AUTHOR_EMAIL', 'BUILDKITE_BUILD_CREATOR_EMAIL'),\n })\n case 'azure':\n return makeAuthor(pick('BUILD_REQUESTEDFOR'), { email: pick('BUILD_REQUESTEDFOREMAIL') })\n default:\n return undefined\n }\n}\n\n/** `CIRCI_*` variables win over anything detected, for CIs we don't know or odd setups. */\nfunction applyOverrides(ctx: detectCi.Context, env: Env): detectCi.Context {\n const author = nonEmpty(env.CIRCI_AUTHOR)\n return {\n ...ctx,\n commitSha: nonEmpty(env.CIRCI_COMMIT) ?? ctx.commitSha,\n branch: nonEmpty(env.CIRCI_BRANCH) ?? ctx.branch,\n prNumber: num(env.CIRCI_PR_NUMBER) ?? ctx.prNumber,\n baseBranch: nonEmpty(env.CIRCI_BASE_BRANCH) ?? ctx.baseBranch,\n ...(author ? { author: { login: author } } : {}),\n }\n}\n\nfunction field(obj: unknown, key: string): unknown {\n if (typeof obj !== 'object' || obj === null) return undefined\n const value: unknown = Reflect.get(obj, key)\n return value\n}\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v !== '' ? v : undefined\n}\nfunction num(v: unknown): number | undefined {\n const n = typeof v === 'number' ? v : typeof v === 'string' && /^\\d+$/.test(v) ? Number(v) : NaN\n return Number.isInteger(n) && n > 0 ? n : undefined\n}\nfunction nonEmpty(v: string | undefined): string | undefined {\n return v === undefined || v.trim() === '' ? undefined : v.trim()\n}\n\nfunction stripRef(ref: string | undefined): string | undefined {\n return ref?.replace(/^refs\\/heads\\//, '')\n}\n","import { ApiError, NetworkError } from './api.ts'\n\n/** A problem with how the CLI was called or configured (exit code 2, no stack trace). */\nexport class UsageError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'UsageError'\n }\n}\n\n/**\n * The one line to print for a failure, without the `error: ` prefix: what went wrong and, where\n * we can tell, what to do about it. Nothing here shows a stack; `reportError` adds that for\n * `--debug`.\n */\nexport function errorLine(err: unknown): string {\n if (err instanceof UsageError) return err.message\n if (err instanceof NetworkError) return `${err.message}. Check CIRCI_API_URL.`\n if (err instanceof ApiError) {\n if (err.status === 401 || err.status === 403) {\n return `The server refused the token (${err.message}). Check that CIRCI_TOKEN is this project's CI token.`\n }\n return err.status >= 500\n ? `The server failed: ${err.message} (HTTP ${err.status})`\n : err.message\n }\n if (err instanceof SyntaxError) return `Invalid JSON: ${err.message}`\n if (err instanceof Error) {\n const code = 'code' in err && typeof err.code === 'string' ? err.code : undefined\n const path = 'path' in err && typeof err.path === 'string' ? err.path : undefined\n if (code === 'ENOENT' && path === 'git') return \"Couldn't run git. Is it installed and on PATH?\"\n if (code === 'ENOENT' && path) return `No such file or directory: ${path}`\n if (code === 'ENOTDIR' && path) return `Not a directory: ${path}`\n if (code === 'EISDIR' && path) return `Is a directory, not a file: ${path}`\n if ((code === 'EACCES' || code === 'EPERM') && path) return `Permission denied: ${path}`\n if (code === 'EMFILE') return 'Too many open files. Raise the limit (ulimit -n) and retry.'\n return err.message.split('\\n')[0] || err.name\n }\n return String(err)\n}\n\n/** What to print for a failure: one line, plus the stack when `debug` is on. */\nexport function reportError(err: unknown, debug: boolean): string {\n const line = `error: ${errorLine(err)}`\n if (debug) return err instanceof Error && err.stack ? `${line}\\n${err.stack}` : line\n const expected =\n err instanceof UsageError || err instanceof ApiError || err instanceof NetworkError\n return expected ? line : `${line}\\n(Run again with --debug, or set DEBUG=1, for the stack trace.)`\n}\n\n/** `--debug` or a non-empty DEBUG other than `0`/`false`. */\nexport function debugOn(argv: string[], env: Record<string, string | undefined>): boolean {\n const value = env.DEBUG\n return argv.includes('--debug') || (!!value && value !== '0' && value !== 'false')\n}\n\n/**\n * If whoever reads our output goes away (`circi upload … | head -1`), keep going quietly instead\n * of dying halfway with EPIPE. Call once at the start of a command-line program.\n */\nexport function ignoreBrokenPipe(): void {\n for (const stream of [process.stdout, process.stderr]) {\n stream.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') throw err\n })\n }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst exec = promisify(execFile)\n\nexport namespace gitRunner {\n export interface Runner {\n /** Runs git and returns trimmed stdout; throws on a non-zero exit. */\n run(args: string[]): Promise<string>\n }\n}\n\nexport function gitRunner(cwd: string): gitRunner.Runner {\n return {\n async run(args) {\n const { stdout } = await exec('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 })\n return stdout.trim()\n },\n }\n}\n\nasync function tryRun(git: gitRunner.Runner, args: string[]): Promise<string | undefined> {\n try {\n return await git.run(args)\n } catch {\n return undefined\n }\n}\n\nexport namespace collectAncestry {\n export interface Options {\n /** The commit being uploaded: the PR head, never a synthetic merge commit (PLAN §7.1). */\n headSha: string\n /** Branch whose history holds the baselines: the PR's base, or the project's default branch. */\n baseBranch: string\n /** True for builds on the default branch itself: history starts at the head's parent. */\n isBaseBranchBuild: boolean\n remote?: string\n /** Fetch missing history from the remote (default true). */\n fetch?: boolean\n /** How many commits to send. */\n limit?: number\n /** Stop deepening a shallow clone after this many commits. */\n maxDepth?: number\n }\n\n export interface Result {\n status: 'ok' | 'missing' | 'truncated'\n mergeBaseSha?: string\n /** Nearest first. */\n ancestorShas: string[]\n /** Why history is missing or truncated, for the CLI to print. */\n warning?: string\n }\n}\n\nconst DEEPEN_STEP = 200\n\n/**\n * Collects the history the server uses to pick a baseline (PLAN §7.1 step 3, §7.2), so baseline\n * selection never depends on a git host's API.\n */\nexport async function collectAncestry(\n git: gitRunner.Runner,\n options: collectAncestry.Options,\n): Promise<collectAncestry.Result> {\n const remote = options.remote ?? 'origin'\n const limit = options.limit ?? 200\n const maxDepth = options.maxDepth ?? 2_000\n const doFetch = options.fetch ?? true\n if ((await tryRun(git, ['rev-parse', '--is-inside-work-tree'])) !== 'true') {\n return { status: 'missing', ancestorShas: [], warning: 'Not inside a git repository' }\n }\n const head = options.headSha\n\n let present = await hasCommit(git, head)\n if (!present && doFetch) {\n await tryRun(git, ['fetch', '--no-tags', ...(await depthArgs(git)), remote, head])\n present = await hasCommit(git, head)\n }\n if (!present) {\n return {\n status: 'missing',\n ancestorShas: [],\n warning: `Commit ${head} is not available locally`,\n }\n }\n\n if (options.isBaseBranchBuild) {\n // The merge-base of a default-branch build is the head itself; baselines are its ancestors.\n // In a shallow checkout (e.g. depth 1) the parent may not be there yet: deepen until it is.\n const parents = await withDeepening(git, {\n rounds: doFetch ? Math.floor(maxDepth / DEEPEN_STEP) : 0,\n attempt: () => listFirstParent(git, `${head}~1`, limit),\n deepen: () => tryRun(git, ['fetch', '--no-tags', `--deepen=${DEEPEN_STEP}`, remote, head]),\n })\n if (parents === undefined) {\n const root = (await tryRun(git, ['rev-list', '--max-parents=0', head]))?.split('\\n') ?? []\n if (root.includes(head)) return { status: 'ok', mergeBaseSha: head, ancestorShas: [] }\n return {\n status: 'missing',\n ancestorShas: [],\n warning: 'Could not read the commit history (shallow clone)',\n }\n }\n return {\n status: await statusFor(git, parents, limit),\n mergeBaseSha: head,\n ancestorShas: parents,\n }\n }\n\n // PR / feature branch: find where it forked from the base branch.\n const baseRef = `refs/remotes/${remote}/${options.baseBranch}`\n if (doFetch) {\n // CI checkouts often lack the base branch entirely (GitHub's default fetches only the PR).\n await tryRun(git, [\n 'fetch',\n '--no-tags',\n ...(await depthArgs(git)),\n remote,\n `+refs/heads/${options.baseBranch}:${baseRef}`,\n ])\n }\n if (!(await tryRun(git, ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]))) {\n return {\n status: 'missing',\n ancestorShas: [],\n warning: `Base branch \"${options.baseBranch}\" is not available from ${remote}`,\n }\n }\n\n const mergeBase = await withDeepening(git, {\n rounds: doFetch ? Math.floor(maxDepth / DEEPEN_STEP) : 0,\n attempt: async () => (await tryRun(git, ['merge-base', head, baseRef])) || undefined,\n deepen: () =>\n tryRun(git, [\n 'fetch',\n '--no-tags',\n `--deepen=${DEEPEN_STEP}`,\n remote,\n head,\n `+refs/heads/${options.baseBranch}:${baseRef}`,\n ]),\n })\n if (!mergeBase) {\n return {\n status: 'missing',\n ancestorShas: [],\n warning: `No common history with \"${options.baseBranch}\" within ${maxDepth} commits; use a deeper checkout (e.g. fetch-depth: 0)`,\n }\n }\n const ancestors = (await listFirstParent(git, mergeBase, limit)) ?? [mergeBase]\n return {\n status: await statusFor(git, ancestors, limit),\n mergeBaseSha: mergeBase,\n ancestorShas: ancestors,\n }\n}\n\n/** Branch tip on the remote (PLAN §7.6 branch links); undefined if it can't be read. */\nexport async function remoteBranchTip(\n git: gitRunner.Runner,\n branch: string,\n remote = 'origin',\n): Promise<string | undefined> {\n const out = await tryRun(git, ['ls-remote', remote, `refs/heads/${branch}`])\n return out?.split(/\\s+/)[0] || undefined\n}\n\n/** Whether `ancestor` is HEAD or one of its ancestors (false when it can't be told). */\nexport async function isAncestor(\n git: gitRunner.Runner,\n ancestor: string,\n head = 'HEAD',\n): Promise<boolean> {\n return (await tryRun(git, ['merge-base', '--is-ancestor', ancestor, head])) !== undefined\n}\n\nexport async function localHead(git: gitRunner.Runner): Promise<{ sha?: string; branch?: string }> {\n // One call for both: the commit, then the branch (`HEAD` when detached).\n const out = await tryRun(git, ['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD'])\n const [sha, branch] = out?.split('\\n') ?? []\n return {\n ...(sha ? { sha } : {}),\n ...(branch && branch !== 'HEAD' ? { branch } : {}),\n }\n}\n\nasync function hasCommit(git: gitRunner.Runner, sha: string): Promise<boolean> {\n return (await tryRun(git, ['cat-file', '-e', `${sha}^{commit}`])) !== undefined\n}\n\n/**\n * `--depth` writes `.git/shallow`: on a full clone it would cut the user's history for good, so\n * only a repository that is already shallow gets it. A full clone fetches what is missing whole.\n */\nasync function depthArgs(git: gitRunner.Runner): Promise<string[]> {\n return (await isShallow(git)) ? [`--depth=${DEEPEN_STEP}`] : []\n}\n\nasync function isShallow(git: gitRunner.Runner): Promise<boolean> {\n return (await tryRun(git, ['rev-parse', '--is-shallow-repository'])) === 'true'\n}\n\nasync function listFirstParent(\n git: gitRunner.Runner,\n rev: string,\n limit: number,\n): Promise<string[] | undefined> {\n const out = await tryRun(git, ['rev-list', '--first-parent', `--max-count=${limit}`, rev])\n return out === undefined ? undefined : out.split('\\n').filter(Boolean)\n}\n\n/** Fewer commits than asked for in a shallow clone means history was cut off, not exhausted. */\nasync function statusFor(\n git: gitRunner.Runner,\n shas: string[],\n limit: number,\n): Promise<'ok' | 'truncated'> {\n return shas.length < limit && (await isShallow(git)) ? 'truncated' : 'ok'\n}\n\n/**\n * Tries `attempt`; while it finds nothing and the clone is shallow, fetches more history and\n * tries again, at most `rounds` times. Each step depends on the previous fetch, so it's sequential.\n */\nasync function withDeepening<T>(\n git: gitRunner.Runner,\n steps: { rounds: number; attempt: () => Promise<T | undefined>; deepen: () => Promise<unknown> },\n): Promise<T | undefined> {\n for (let round = 0; ; round += 1) {\n // oxlint-disable-next-line no-await-in-loop -- depends on the previous round's fetch\n const found = await steps.attempt()\n // oxlint-disable-next-line no-await-in-loop -- see above\n if (found !== undefined || round >= steps.rounds || !(await isShallow(git))) return found\n // oxlint-disable-next-line no-await-in-loop -- see above\n await steps.deepen()\n }\n}\n","import { readFileSync } from 'node:fs'\n\nimport { detectCi } from './ci-env.ts'\nimport { UsageError } from './errors.ts'\nimport { type gitRunner, localHead } from './git.ts'\n\n/**\n * What the CI says about this build, with the commit and branch taken from the checkout when it\n * says nothing; fails when no commit can be found either way.\n */\nexport async function buildContext(\n env: Record<string, string | undefined>,\n git: gitRunner.Runner,\n): Promise<detectCi.Context & { commitSha: string }> {\n const ci = detectCi(env, (path) => JSON.parse(readFileSync(path, 'utf8')))\n if (!ci.commitSha || !ci.branch) {\n const local = await localHead(git)\n ci.commitSha ??= local.sha\n // A detached checkout reports no branch, so this only fills in a real one.\n if (!ci.branch && local.branch) ci.branch = local.branch\n }\n const { commitSha } = ci\n if (!commitSha) {\n throw new UsageError(\n 'Could not determine the commit. Run inside a git checkout or set CIRCI_COMMIT.',\n )\n }\n return { ...ci, commitSha }\n}\n","/** `fn` over `items`, at most `limit` at a time; results keep the order of `items`. */\nexport async function mapLimit<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = Array.from<R>({ length: items.length })\n // One iterator shared by the lanes: each pulls the next item when it is free.\n const pending = items.entries()\n const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (const [index, item] of pending) {\n // oxlint-disable-next-line no-await-in-loop -- each lane takes one item at a time\n results[index] = await fn(item)\n }\n })\n await Promise.all(lanes)\n return results\n}\n","import { createHash } from 'node:crypto'\nimport { createReadStream } from 'node:fs'\nimport { readdir, readFile, realpath, stat } from 'node:fs/promises'\nimport { join, relative, sep } from 'node:path'\n\nimport { mapLimit } from './concurrency.ts'\nimport { UsageError } from './errors.ts'\n\nexport namespace collectScreenshots {\n export interface Screenshot {\n /** Relative path without `.png`, using `/` on every OS: the name screenshots are paired by. */\n name: string\n path: string\n sha256: string\n size: number\n metadata?: Record<string, unknown>\n }\n}\n\nconst MAX_BYTES = 25 * 1024 * 1024\n/** Files read and hashed at once: enough to keep the disk busy, few enough to stay under the descriptor limit. */\nconst HASH_CONCURRENCY = 8\n\n/**\n * Finds every `*.png` under `dir` (skipping hidden folders and node_modules; symbolic links to\n * files and folders are followed, a link back up the tree is not), hashes it, and reads an\n * optional `<file>.png.json` sidecar with metadata (browser, viewport, test…).\n */\nexport async function collectScreenshots(dir: string): Promise<collectScreenshots.Screenshot[]> {\n const info = await stat(dir).catch(() => undefined)\n if (!info) throw new UsageError(`No such directory: ${dir}`)\n if (!info.isDirectory()) throw new UsageError(`${dir} is not a directory`)\n const paths = await walk(dir, [])\n const shots = await mapLimit(paths, HASH_CONCURRENCY, async (path) => {\n const { size } = await stat(path)\n if (size > MAX_BYTES) {\n throw new UsageError(\n `${path} is ${(size / 1024 / 1024).toFixed(1)} MB; the limit is ${MAX_BYTES / 1024 / 1024} MB per screenshot`,\n )\n }\n const metadata = await readSidecar(`${path}.json`)\n const shot: collectScreenshots.Screenshot = {\n name: relative(dir, path)\n .split(sep)\n .join('/')\n .replace(/\\.png$/i, ''),\n path,\n sha256: await hashFile(path),\n size,\n }\n if (metadata) shot.metadata = metadata\n return shot\n })\n return shots.toSorted((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n}\n\n/** `ancestors` are the real paths of the folders above, so a link that loops back is skipped. */\nasync function walk(dir: string, ancestors: string[]): Promise<string[]> {\n const real = await realpath(dir)\n if (ancestors.includes(real)) return []\n const chain = [...ancestors, real]\n const entries = await readdir(dir, { withFileTypes: true })\n const nested = await Promise.all(\n entries.map(async (e): Promise<string[]> => {\n if (e.name.startsWith('.') || e.name === 'node_modules') return []\n const full = join(dir, e.name)\n // A link is judged by what it points at; a dangling one is skipped.\n const target = e.isSymbolicLink() ? await stat(full).catch(() => undefined) : e\n if (!target) return []\n if (target.isDirectory()) return walk(full, chain)\n return target.isFile() && /\\.png$/i.test(e.name) ? [full] : []\n }),\n )\n return nested.flat()\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash('sha256')\n for await (const chunk of createReadStream(path)) hash.update(chunk)\n return hash.digest('hex')\n}\n\nasync function readSidecar(path: string): Promise<Record<string, unknown> | undefined> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch {\n return undefined\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (err) {\n throw new UsageError(\n `${path} isn't valid JSON (${err instanceof Error ? err.message : String(err)})`,\n )\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new UsageError(`${path} must contain a JSON object`)\n }\n return Object.fromEntries(Object.entries(parsed))\n}\n","import { readFile } from 'node:fs/promises'\nimport { setTimeout as sleep } from 'node:timers/promises'\n\nimport { ApiClient, ApiError, isRetryable } from './api.ts'\nimport { ciRunId, type detectCi } from './ci-env.ts'\nimport { mapLimit } from './concurrency.ts'\nimport { buildContext } from './context.ts'\nimport { errorLine, UsageError } from './errors.ts'\nimport { collectScreenshots } from './files.ts'\nimport { collectAncestry, gitRunner } from './git.ts'\n\nexport namespace upload {\n export interface Options {\n dir: string\n apiUrl: string\n token: string\n /** Build name, for several kinds of builds per commit (e.g. `chromium`, `mobile`). */\n name?: string\n wait?: boolean\n /**\n * This job uploads one shard of a parallel build: `index` is 0-based. Shards of one build\n * share a nonce (default: the CI run's id), and the build is processed once all `total` arrive.\n */\n shard?: { index: number; total: number; nonce?: string }\n /** Who blocks the merge: the git host's check (`status`) or this job (`exit-code`). Default: the server decides. */\n gate?: 'status' | 'exit-code'\n /** Who made the change (`--author`); replaces what the CI environment says. */\n author?: string\n waitTimeoutMs?: number\n pollIntervalMs?: number\n /** First backoff between retries of a failed API call, in milliseconds (default 500). */\n retryDelayMs?: number\n /** Allow `git fetch` to complete shallow history (default true). */\n fetch?: boolean\n cwd?: string\n env?: Record<string, string | undefined>\n fetchImpl?: typeof fetch\n log?: (line: string) => void\n }\n\n export interface Result {\n /**\n * 0 pass, 1 the result should block the merge, 2 something went wrong (including a build the\n * server couldn't process).\n */\n exitCode: 0 | 1 | 2\n build: ApiClient.Build\n ci: detectCi.Context\n ancestry: collectAncestry.Result\n uploaded: number\n deduplicated: number\n status?: ApiClient.Status\n }\n}\n\nconst UPLOAD_CONCURRENCY = 8\n\nexport async function upload(options: upload.Options): Promise<upload.Result> {\n const log = options.log ?? ((line: string) => console.log(line))\n const env = options.env ?? process.env\n const cwd = options.cwd ?? process.cwd()\n\n // Check the flags before touching the disk or the network.\n const parallel = parallelOf(options.shard, env)\n\n const client = new ApiClient({\n baseUrl: options.apiUrl,\n token: options.token,\n fetch: options.fetchImpl,\n retryDelayMs: options.retryDelayMs,\n })\n const git = gitRunner(cwd)\n\n // Hashing the files, asking the server about the project and reading the checkout don't\n // depend on each other.\n const [shots, context] = await Promise.all([\n collectScreenshots(options.dir),\n (async () => {\n const [project, ci] = await Promise.all([client.project(), buildContext(env, git)])\n if (options.author?.trim()) ci.author = { login: options.author.trim() }\n const isBaseBranchBuild = !ci.prNumber && ci.branch === project.defaultBranch\n const ancestry = await collectAncestry(git, {\n headSha: ci.commitSha,\n baseBranch: ci.baseBranch ?? project.defaultBranch,\n isBaseBranchBuild,\n fetch: options.fetch ?? true,\n })\n return { project, ci, commitSha: ci.commitSha, isBaseBranchBuild, ancestry }\n })(),\n ])\n // A shard with nothing to show (more shards than tests, or every test skipped) still reports in:\n // the build is processed once all its shards have arrived, so a missing one would stall it.\n if (shots.length === 0 && !options.shard) {\n throw new UsageError(`No .png files found in ${options.dir}`)\n }\n const { project, ci, commitSha, isBaseBranchBuild, ancestry } = context\n log(`Found ${plural(shots.length, 'screenshot')} in ${options.dir}`)\n if (shots.length === 0)\n log('This shard has no screenshots; reporting it so the build can complete')\n if (ancestry.warning) {\n log(\n `warning: ${ancestry.warning}. CirCI will compare against the latest ${project.defaultBranch} build instead.`,\n )\n }\n\n log(\n `Uploading for ${commitSha.slice(0, 12)}` +\n (ci.branch ? ` on ${ci.branch}` : '') +\n (ci.prNumber ? ` (PR #${ci.prNumber})` : ''),\n )\n const { build, uploads } = await client.createBuild({\n commitSha,\n ...(options.name ? { name: options.name } : {}),\n branch: ci.branch ?? null,\n prNumber: ci.prNumber ?? null,\n baseBranch: ci.baseBranch ?? (isBaseBranchBuild ? null : project.defaultBranch),\n mergeBaseSha: ancestry.mergeBaseSha ?? null,\n ancestorShas: ancestry.ancestorShas,\n ancestryStatus: ancestry.status,\n ...(parallel ? { parallel } : {}),\n ...(ci.author ? { author: ci.author } : {}),\n files: uniqueFiles(shots),\n })\n\n const byHash = new Map(shots.map((s) => [s.sha256, s]))\n const unique = byHash.size\n const deduplicated = unique - uploads.length\n log(\n `Build #${build.number}: sending ${uploads.length} of ${unique} files (${deduplicated} already on the server)`,\n )\n await sendAll(client, uploads, byHash, log)\n const finalizeBody = {\n ...(options.shard ? { shardIndex: String(options.shard.index) } : {}),\n screenshots: shots.map((s) => ({\n name: s.name,\n sha256: s.sha256,\n ...(s.metadata ? { metadata: s.metadata } : {}),\n })),\n }\n try {\n await client.finalize(build.id, finalizeBody)\n } catch (err) {\n // Something didn't land (e.g. a storage hiccup): resend those files once, then retry.\n const missing = missingFrom(err)\n if (!missing) throw err\n log(`${plural(missing.length, 'file')} didn't arrive; sending again`)\n await sendAll(\n client,\n uploads.filter((u) => missing.includes(u.sha256)),\n byHash,\n log,\n )\n await client.finalize(build.id, finalizeBody)\n }\n log(`Build #${build.number}: ${build.url}`)\n if (options.shard) {\n log(` shard ${options.shard.index + 1} of ${options.shard.total} uploaded`)\n }\n log(\n ` ${plural(shots.length, 'screenshot')}: ${uploads.length} uploaded, ${deduplicated} already on the server`,\n )\n\n const result: upload.Result = {\n exitCode: 0,\n build,\n ci,\n ancestry,\n uploaded: uploads.length,\n deduplicated,\n }\n if (!options.wait) return result\n\n log('Waiting for the result…')\n const status = await waitForResult(client, build.id, {\n timeoutMs: options.waitTimeoutMs ?? 10 * 60_000,\n ...(options.pollIntervalMs !== undefined ? { intervalMs: options.pollIntervalMs } : {}),\n ...(options.gate ? { gate: options.gate } : {}),\n onTransient: (err) => log(`warning: ${errorLine(err)}; still waiting`),\n })\n result.status = status\n if (!status) {\n log('error: timed out waiting for the build to be processed')\n result.exitCode = 2\n return result\n }\n if (status.build.status === 'error') {\n // The server couldn't process the build: nothing to review, so no review advice either.\n // (A project that doesn't block merges still gets a pass from the server, with its warning.)\n log(\n `error: Build #${status.build.number} failed to process: ${status.errorMessage ?? 'the server gave no reason'}`,\n )\n if (status.outcome.warning) log(`warning: ${status.outcome.warning}`)\n log(`Details: ${status.build.url}`)\n if (status.outcome.state === 'fail') result.exitCode = 2\n return result\n }\n const c = status.counts\n log(\n `${status.outcome.summary}: ${c.changed} changed, ${c.added} added, ${c.removed} removed, ${c.unchanged} unchanged${c.failed ? `, ${c.failed} couldn't be read` : ''}`,\n )\n if (status.outcome.warning) log(`warning: ${status.outcome.warning}`)\n if (c.failed > 0) {\n // An input problem, not a visual change: no review settles it. It follows the project's\n // blocking setting like a build that failed to process: when the outcome fails the job ends\n // with an error (2) rather than the \"needs review\" exit (1); otherwise it passes, warned.\n for (const shot of status.unreadable) log(`error: ${shot.name}: ${shot.reason}`)\n log(`Upload the build again with valid PNGs: ${status.build.url}`)\n if (status.outcome.state === 'fail') result.exitCode = 2\n return result\n }\n if (status.outcome.state === 'fail') {\n // With an integration the commit status is the gate and the job doesn't fail on changes (PLAN §7.4).\n if (status.gate === 'exit-code') {\n log(`Review the changes at ${status.build.url}`)\n if (ci.jobUrl) log(`After approving, re-run this job to unblock the merge: ${ci.jobUrl}`)\n result.exitCode = 1\n }\n }\n return result\n}\n\n/** Checks `--shard`/`--nonce` and returns what the server needs, or undefined for a whole build. */\nfunction parallelOf(\n shard: upload.Options['shard'],\n env: Record<string, string | undefined>,\n): { nonce: string; total: number } | undefined {\n if (!shard) return undefined\n const { index, total } = shard\n if (\n !Number.isInteger(index) ||\n !Number.isInteger(total) ||\n total < 1 ||\n index < 0 ||\n index >= total\n ) {\n throw new UsageError(\n \"--shard must look like 1/4: this job's number, then how many jobs there are\",\n )\n }\n const nonce = shard.nonce ?? ciRunId(env)\n if (!nonce) {\n throw new UsageError(\n 'Could not tell which CI run these shards belong to. Set CIRCI_PARALLEL_NONCE (or --nonce) to the same value in every shard.',\n )\n }\n return { nonce, total }\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n\nasync function waitForResult(\n client: ApiClient,\n buildId: string,\n opts: {\n timeoutMs: number\n intervalMs?: number\n gate?: 'status' | 'exit-code'\n onTransient: (err: unknown) => void\n },\n): Promise<ApiClient.Status | undefined> {\n const deadline = Date.now() + opts.timeoutMs\n let warned = false\n for (let attempt = 0; ; attempt += 1) {\n let status: ApiClient.Status | undefined\n try {\n // oxlint-disable-next-line no-await-in-loop -- polling\n status = await client.status(buildId, opts.gate)\n } catch (err) {\n // The client already retried; a server that is still down keeps us waiting until the deadline.\n if (!isRetryable(err, true)) throw err\n if (!warned) opts.onTransient(err)\n warned = true\n }\n if (status && status.outcome.state !== 'pending') return status\n const delay = opts.intervalMs ?? pollDelay(attempt)\n if (Date.now() + delay > deadline) return undefined\n // oxlint-disable-next-line no-await-in-loop -- polling interval\n await sleep(delay)\n }\n}\n\n/**\n * How long to wait before the next status poll: 500 ms at first, so a build that finishes in a\n * moment is seen at once, growing by half each time to a ceiling of 2 s, so a long build is not\n * hammered. `attempt` counts from 0.\n */\nexport function pollDelay(attempt: number): number {\n return Math.min(2_000, Math.round(500 * 1.5 ** attempt))\n}\n\nfunction uniqueFiles(shots: collectScreenshots.Screenshot[]) {\n const seen = new Map<string, { sha256: string; size: number; contentType: string }>()\n for (const s of shots)\n seen.set(s.sha256, { sha256: s.sha256, size: s.size, contentType: 'image/png' })\n return [...seen.values()]\n}\n\nasync function sendAll(\n client: ApiClient,\n instructions: ApiClient.UploadInstruction[],\n byHash: Map<string, collectScreenshots.Screenshot>,\n log: (line: string) => void,\n): Promise<void> {\n let done = 0\n // A line per quarter, so a long upload shows life in a CI log without a line per file.\n const step = Math.max(1, Math.ceil(instructions.length / 4))\n await mapLimit(instructions, UPLOAD_CONCURRENCY, async (instruction) => {\n const shot = byHash.get(instruction.sha256)\n if (!shot) throw new Error(`Server asked for unknown file ${instruction.sha256}`)\n await client.upload(instruction, await readFile(shot.path))\n done += 1\n if (instructions.length > 4 && (done % step === 0 || done === instructions.length)) {\n log(` uploaded ${done} of ${instructions.length}`)\n }\n })\n}\n\nfunction missingFrom(err: unknown): string[] | undefined {\n if (!(err instanceof ApiError) || err.status !== 409) return undefined\n const body = err.body\n if (\n typeof body !== 'object' ||\n body === null ||\n !('missing' in body) ||\n !Array.isArray(body.missing)\n ) {\n return undefined\n }\n return body.missing.filter((m): m is string => typeof m === 'string')\n}\n","import { UsageError } from './errors.ts'\nimport type { CirciOptions } from './options.ts'\n\n/**\n * `2/4` → the second of four jobs, 0-based (`{ index: 1, total: 4 }`); undefined unless it's a\n * job number from 1 to the total. Read the same way by `circi upload --shard` and Vitest's `--shard`.\n */\nexport function parseShard(text: string): { index: number; total: number } | undefined {\n const m = /^(\\d+)\\/(\\d+)$/.exec(text.trim())\n if (!m?.[1] || !m[2]) return undefined\n const index = Number(m[1]) - 1\n const total = Number(m[2])\n return total >= 1 && index >= 0 && index < total ? { index, total } : undefined\n}\n\n/** The value of a `--shard` flag (and `--nonce`), or a usage error saying how to write it. */\nexport function shardFlag(text: string, nonce?: string): CirciOptions.Shard {\n const shard = parseShard(text)\n if (!shard) {\n throw new UsageError(\n \"--shard must look like 1/4: this job's number, then how many jobs there are\",\n )\n }\n return { ...shard, ...(nonce ? { nonce } : {}) }\n}\n\n/** Vitest's `--shard=2/4` or `--shard 2/4` (1-based like CirCI's) from a command line. */\nexport function shardFromArgs(argv: readonly string[]): CirciOptions.Shard | undefined {\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i] ?? ''\n const value = arg.startsWith('--shard=')\n ? arg.slice('--shard='.length)\n : arg === '--shard'\n ? argv[i + 1]\n : undefined\n const shard = value ? parseShard(value) : undefined\n if (shard) return shard\n }\n return undefined\n}\n\n/** `CIRCI_SHARD=2/4` from the environment, for runners that have no `--shard` of their own. */\nexport function shardFromEnv(\n env: Record<string, string | undefined>,\n): CirciOptions.Shard | undefined {\n const value = env.CIRCI_SHARD\n return value ? parseShard(value) : undefined\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nimport { errorLine } from './errors.ts'\nimport type { CirciOptions } from './options.ts'\nimport { uploadSite } from './site.ts'\nimport { upload } from './upload.ts'\n\n/**\n * What a `<name>.png.json` beside a capture holds: free-form JSON that `collectScreenshots` reads\n * and the server keeps with the screenshot (the labels that come later are read from it). The\n * integrations agree on: `storyId` (Storybook), `browser` (a name) and `viewport` (a string: its\n * name, or `1280x720`).\n */\nexport type CaptureMetadata = Record<string, unknown>\n\n/** Writes a capture and, when there is metadata, its `.png.json` sidecar, creating the folder. */\nexport async function writeCapture(\n file: string,\n png: Uint8Array,\n metadata?: CaptureMetadata,\n): Promise<void> {\n await mkdir(dirname(file), { recursive: true })\n await Promise.all([\n writeFile(file, png),\n metadata ? writeFile(`${file}.json`, `${JSON.stringify(metadata, null, 2)}\\n`) : undefined,\n ])\n}\n\nexport namespace uploadCaptures {\n export interface Options extends Omit<CirciOptions.Common, 'dir' | 'root' | 'clean'> {\n /** The folder with the captures, absolute (or relative to the working directory). */\n dir: string\n /** The build's name when `name` isn't set: each integration has its own (`vitest`, `storybook`). */\n defaultName: string\n /**\n * The exit code for an upload that failed when `strict` is set. Default 2, the CLI's code for\n * an error (1 means \"changes need review\"); `@circi/vitest` keeps 1, which it has always used.\n */\n strictExitCode?: 1 | 2\n /** Looked at only once there are credentials: no captures means nothing to upload, quietly. */\n isEmpty?: () => Promise<boolean>\n /** How long `wait` waits for the build, in milliseconds. Default: the CLI's. */\n waitTimeoutMs?: number\n /** Allow `git fetch` to complete shallow history. Default true. */\n fetch?: boolean\n cwd?: string\n env?: Record<string, string | undefined>\n /** For tests. */\n uploadImpl?: (options: upload.Options) => Promise<Pick<upload.Result, 'exitCode'>>\n }\n\n export interface Result {\n /**\n * `skipped`: no `CIRCI_API_URL` or `CIRCI_TOKEN`. `empty`: no captures (and no shard to report). `uploaded`.\n * `failed`: the upload threw (reported, not thrown).\n */\n status: 'skipped' | 'empty' | 'uploaded' | 'failed'\n /**\n * What the run's exit code should become: the upload's own (1 changes need review, 2 an error)\n * when `wait` is set, `strictExitCode` for a failed upload when `strict` is set, else 0.\n */\n exitCode: 0 | 1 | 2\n }\n}\n\n/**\n * The end of every integration's run (Vitest, Storybook, Cypress): send the captures in `dir` to\n * CirCI as one build, unless there is nothing to send or nowhere to send it, and never throw. The\n * policy lives here once: credentials from the options, else `CIRCI_API_URL` and `CIRCI_TOKEN`;\n * without them a notice and no upload; a failed upload is reported and only `strict` turns it into\n * an exit code; only `wait` lets the build's result decide the exit code.\n */\nexport async function uploadCaptures(\n options: uploadCaptures.Options,\n): Promise<uploadCaptures.Result> {\n const log = options.log ?? ((line: string) => console.log(line))\n const env = options.env ?? process.env\n const apiUrl = options.apiUrl ?? env.CIRCI_API_URL\n const token = options.token ?? env.CIRCI_TOKEN\n if (!apiUrl || !token) {\n log('[circi] skipped: set CIRCI_API_URL and CIRCI_TOKEN to upload screenshots')\n return { status: 'skipped', exitCode: 0 }\n }\n if (await options.isEmpty?.()) {\n // One shard of a parallel build still reports in, empty: the build waits for every shard.\n if (!options.shard) {\n log('[circi] no screenshots found, nothing to upload')\n return { status: 'empty', exitCode: 0 }\n }\n log('[circi] no screenshots found in this shard; reporting it so the build can complete')\n }\n try {\n const result = await (options.uploadImpl ?? upload)({\n dir: options.dir,\n apiUrl,\n token,\n name: options.name ?? options.defaultName,\n wait: options.wait ?? false,\n ...(options.shard ? { shard: options.shard } : {}),\n ...(options.waitTimeoutMs ? { waitTimeoutMs: options.waitTimeoutMs } : {}),\n ...(options.fetch === false ? { fetch: false } : {}),\n ...(options.cwd ? { cwd: options.cwd } : {}),\n env,\n log,\n })\n return {\n status: 'uploaded',\n exitCode: options.wait && result.exitCode !== 0 ? result.exitCode : 0,\n }\n } catch (err) {\n log(`[circi] upload failed: ${errorLine(err)}`)\n return { status: 'failed', exitCode: options.strict ? (options.strictExitCode ?? 2) : 0 }\n }\n}\n\nexport namespace uploadSiteAfter {\n export interface Options extends Pick<\n CirciOptions.Common,\n 'apiUrl' | 'token' | 'strict' | 'shard' | 'log'\n > {\n /** The built site, such as Storybook's output or Vitest's HTML report. */\n dir: string\n /** The site's name in the project (`storybook`, `vitest-report`). */\n name: string\n /** The site's kind, so CirCI doesn't have to guess from the files. */\n kind: string\n /** Whether the captures were uploaded: the site goes up only after them, never alone. */\n capturesUploaded: boolean\n /** The exit code for a failed site upload when `strict` is set. Default 2, as `uploadCaptures`. */\n strictExitCode?: 1 | 2\n cwd?: string\n env?: Record<string, string | undefined>\n /** For tests. */\n uploadSiteImpl?: (options: uploadSite.Options) => Promise<unknown>\n }\n\n export interface Result {\n /** `skipped`: not this run's job (see the rules on `uploadSiteAfter`). */\n status: 'skipped' | 'uploaded' | 'failed'\n exitCode: 0 | 1 | 2\n }\n}\n\n/**\n * Hosts a built site next to the captures, after `uploadCaptures` uploaded them. It does so only\n * when the captures were uploaded, there is an address and a token (the options, else\n * `CIRCI_API_URL` and `CIRCI_TOKEN`), and this is the whole run or the first shard (one shard hosts\n * the site; the others send only their screenshots). A failed site upload is logged as\n * \"[circi] site upload failed: ...\" and never thrown; only `strict` turns it into an exit code.\n */\nexport async function uploadSiteAfter(\n options: uploadSiteAfter.Options,\n): Promise<uploadSiteAfter.Result> {\n const log = options.log ?? ((line: string) => console.log(line))\n const env = options.env ?? process.env\n const apiUrl = options.apiUrl ?? env.CIRCI_API_URL\n const token = options.token ?? env.CIRCI_TOKEN\n if (!options.capturesUploaded || !apiUrl || !token || (options.shard?.index ?? 0) !== 0) {\n return { status: 'skipped', exitCode: 0 }\n }\n try {\n await (options.uploadSiteImpl ?? uploadSite)({\n dir: options.dir,\n apiUrl,\n token,\n name: options.name,\n kind: options.kind,\n ...(options.cwd ? { cwd: options.cwd } : {}),\n env,\n log,\n })\n return { status: 'uploaded', exitCode: 0 }\n } catch (err) {\n log(`[circi] site upload failed: ${errorLine(err)}`)\n return { status: 'failed', exitCode: options.strict ? (options.strictExitCode ?? 2) : 0 }\n }\n}\n","import { readFile, rm } from 'node:fs/promises'\nimport { resolve } from 'node:path'\n\nimport {\n type CirciOptions,\n errorLine,\n shardFromEnv,\n type upload,\n uploadCaptures,\n writeCapture,\n} from '@circi/cli'\nimport { capturePath, DEFAULT_DIR, toolDir } from '@circi/cli/names'\n\nexport namespace circi {\n /** `name` defaults to `cypress`; give each browser project its own (`cypress-chrome`). */\n export interface Options extends CirciOptions.Common {\n /**\n * Empty this plugin's own folder, `<dir>/cypress`, when a run starts, so a build holds only\n * this run's screenshots. Other tools' folders under `dir` are never touched. Default true.\n */\n clean?: boolean\n /** For tests. */\n uploadImpl?: (options: upload.Options) => Promise<Pick<upload.Result, 'exitCode'>>\n env?: Record<string, string | undefined>\n }\n}\n\n/** The parts of Cypress's Node-side events and config this plugin reads (the real ones fit). */\nnamespace CypressNode {\n /** `after:screenshot`'s details. */\n export interface ScreenshotDetails {\n name?: string | null\n /** Only the spec's base name, and so not unique: the spec's path comes from `before:spec`. */\n specName?: string\n path: string\n testFailure?: boolean\n /** Not in Cypress's types; read when a version sends it. */\n viewport?: { width: number; height: number }\n }\n export interface RunDetails {\n browser?: { name?: string }\n }\n export interface RunResults {\n /** `failed` when Cypress could not run at all (a failed run result has no `runs`). */\n status?: string\n runs?: unknown\n }\n export interface Spec {\n /** The spec's path from the project root, as Cypress lists it. */\n relative?: string\n name?: string\n }\n /** Cypress's `on`, only the events used here (the real one accepts these handlers). */\n export interface Events {\n (event: 'before:run', handler: (details: RunDetails) => void | Promise<void>): void\n (event: 'before:spec', handler: (spec: Spec) => void | Promise<void>): void\n (\n event: 'after:screenshot',\n handler: (details: ScreenshotDetails) => Promise<{ path?: string }>,\n ): void\n (event: 'after:run', handler: (results: RunResults) => void | Promise<void>): void\n }\n export interface Config {\n projectRoot: string\n viewportWidth?: number\n viewportHeight?: number\n }\n}\n\n/** Where this plugin keeps its screenshots under the shared `dir`: one folder per tool. */\nconst TOOL = 'cypress'\n\n/**\n * The Cypress plugin: `setupNodeEvents: circi({ name: 'cypress-chrome' })` in `cypress.config.ts`.\n *\n * Tests keep `cy.screenshot('name')`. Every named screenshot a run takes (not the automatic\n * screenshot of a failing test) is copied to\n * `.circi/screenshots/cypress/<spec path>/<name>.png`, with a `.png.json` sidecar naming the spec,\n * browser and viewport, and `cypress run` uploads them to CirCI when it ends. To also do your own\n * setup, call it inside yours:\n * `setupNodeEvents(on, config) { circi(options)(on, config); return config }`.\n */\nexport function circi(options: circi.Options = {}) {\n return function setupNodeEvents<C extends CypressNode.Config>(\n on: CypressNode.Events,\n config: C,\n ): C {\n const log = options.log ?? ((line: string) => console.log(line))\n const env = options.env ?? process.env\n const root = resolve(options.root ?? config.projectRoot)\n const parent = options.dir ?? DEFAULT_DIR\n const dirOption = toolDir(parent, TOOL)\n const dir = resolve(root, dirOption)\n let browser: string | undefined\n let spec: string | undefined\n let taken = 0\n\n on('before:run', async (details) => {\n browser = details.browser?.name\n taken = 0\n // A run uploads only its own captures, and only this tool's folder is ever emptied.\n if (options.clean ?? true) await rm(dir, { recursive: true, force: true })\n })\n\n // `specName` is a base name: `admin/home.cy.ts` and `public/home.cy.ts` would share it.\n on('before:spec', (details) => {\n spec = details.relative\n })\n\n on('after:screenshot', async (details) => {\n // Cypress's automatic failure screenshot and any unnamed one are not part of the review.\n if (details.testFailure || !details.name) return {}\n let file: string\n const specPath = spec || details.specName || 'unknown-spec'\n try {\n file = resolve(root, capturePath(dirOption, specPath, details.name))\n } catch (err) {\n // A name with nothing usable in it (`'!!'`) skips this screenshot, not the test.\n log(`[circi] skipped screenshot \"${details.name}\": ${errorLine(err)}`)\n return {}\n }\n const viewport =\n details.viewport ??\n (config.viewportWidth && config.viewportHeight\n ? { width: config.viewportWidth, height: config.viewportHeight }\n : undefined)\n // The last one wins: a retried test takes the same screenshot again.\n await writeCapture(file, await readFile(details.path), {\n spec: specPath,\n ...(browser ? { browser } : {}),\n ...(viewport ? { viewport: `${viewport.width}x${viewport.height}` } : {}),\n })\n taken += 1\n // Nothing changes for Cypress: the screenshot stays where it was written.\n return {}\n })\n\n on('after:run', async (results) => {\n // The run itself failed to start: there is nothing to upload.\n if (results.status === 'failed') return\n const { exitCode } = await uploadCaptures({\n dir,\n defaultName: 'cypress',\n name: options.name,\n apiUrl: options.apiUrl,\n token: options.token,\n wait: options.wait,\n strict: options.strict,\n strictExitCode: 1,\n shard: options.shard ?? shardFromEnv(env),\n isEmpty: () => Promise.resolve(taken === 0),\n cwd: root,\n env,\n log,\n uploadImpl: options.uploadImpl,\n })\n // Cypress turns a throw in `after:run` into a non-zero exit code.\n if (exitCode !== 0) throw new Error(`[circi] exit code ${exitCode}`)\n })\n return config\n }\n}\n"],"mappings":";;;;;;;;;;AAuEA,IAAa,WAAb,cAA8B,MAAM;CACzB;CACA;CACT,YAAY,QAAgB,SAAiB,MAAe;EAC1D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,eAAb,cAAkC,MAAM;CAC7B;;CAEA;CACT,YAAY,KAAa,MAA0B,QAAgB;EACjE,MAAM,kBAAkB,SAAS,GAAG,EAAE,IAAI,OAAO,EAAE;EACnD,KAAK,OAAO;EACZ,KAAK,MAAM;EACX,KAAK,OAAO;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QAAQ,aACP,OAAO,iBAAiB,OAAO,iBAC5B;IAAE,OAAO,OAAO;IAAe,QAAQ,OAAO;GAAe,IAC7D,KAAA;GAEN,MAAM,aAAa,MAAM,MAAM,SAAS,QAAQ,IAAI,GAAG;IACrD,MAAM;IACN,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;IAC7B,GAAI,WAAW,EAAE,UAAU,GAAG,SAAS,MAAM,GAAG,SAAS,SAAS,IAAI,CAAC;GACzE,CAAC;GACD,SAAS;GAET,OAAO,CAAC;EACV,CAAC;EAED,GAAG,aAAa,OAAO,YAAY;GAEjC,IAAI,QAAQ,WAAW,UAAU;GACjC,MAAM,EAAE,aAAa,MAAM,eAAe;IACxC;IACA,aAAa;IACb,MAAM,QAAQ;IACd,QAAQ,QAAQ;IAChB,OAAO,QAAQ;IACf,MAAM,QAAQ;IACd,QAAQ,QAAQ;IAChB,gBAAgB;IAChB,OAAO,QAAQ,SAAS,aAAa,GAAG;IACxC,eAAe,QAAQ,QAAQ,UAAU,CAAC;IAC1C,KAAK;IACL;IACA;IACA,YAAY,QAAQ;GACtB,CAAC;GAED,IAAI,aAAa,GAAG,MAAM,IAAI,MAAM,qBAAqB,UAAU;EACrE,CAAC;EACD,OAAO;CACT;AACF"}
@@ -0,0 +1,51 @@
1
+ // ../cli/dist/names.mjs
2
+ /**
3
+ * Where a capture goes, and what CirCI calls it. Pure string work, shared by the browser-side
4
+ * matcher and the tests; it imports nothing, so a browser bundle can load it.
5
+ */
6
+ /** Vitest's own rule for a screenshot name: words kept, whitespace to dashes, the rest dropped. */
7
+ function sanitize(input) {
8
+ return input.replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/-{2,}/g, "-");
9
+ }
10
+ /**
11
+ * A screenshot's file name from the `name` given to `toMatchScreenshot`, or from the generated
12
+ * `<describe> > <test> <n>` when none was given. The same rule Vitest applies to its own
13
+ * references, so a name means the same file in both: `/` keeps folders, nothing escapes upward.
14
+ */
15
+ function captureName(name) {
16
+ const parts = (name.endsWith(".png") ? name.slice(0, -4) : name).split("/").filter((part) => part !== ".." && part !== ".").map(sanitize).filter((part) => part.length > 0);
17
+ if (parts.length === 0) throw new Error(`"${name}" is not a usable screenshot name`);
18
+ return parts.join("/");
19
+ }
20
+ /**
21
+ * The path of a capture relative to the project root: `<dir>/<test file>/<name>.png`, with the test
22
+ * file relative to the root too, so two tests with the same screenshot name never share a file.
23
+ */
24
+ function capturePath(dir, testFile, name) {
25
+ const file = testFile.split(/[\\/]/).filter((part) => part.length > 0 && part !== "." && part !== "..").join("/");
26
+ return `${dir.replace(/\/+$/, "")}/${file}/${captureName(name)}.png`;
27
+ }
28
+ /** Where captures go unless told otherwise, relative to the project root. */
29
+ const DEFAULT_DIR = ".circi/screenshots";
30
+ /**
31
+ * The folder a tool owns inside the captures' folder: `.circi/screenshots/vitest`,
32
+ * `.circi/screenshots/storybook`, `.circi/screenshots/cypress`. `dir` is the parent, the same for
33
+ * every tool (`options.dir ?? DEFAULT_DIR`); a tool writes, cleans and uploads only its own
34
+ * folder, so two tools in one project never upload or delete each other's captures. Names in CirCI
35
+ * are relative to the tool's folder, so they don't carry the tool's name.
36
+ */
37
+ function toolDir(dir, tool) {
38
+ return `${dir.replace(/\/+$/, "")}/${tool}`;
39
+ }
40
+ /** CSS that stops everything that moves or blinks, so a screenshot doesn't catch a frame halfway. */
41
+ const STABILIZE_CSS = `
42
+ *, *::before, *::after {
43
+ animation: none !important;
44
+ transition: none !important;
45
+ caret-color: transparent !important;
46
+ scroll-behavior: auto !important;
47
+ }
48
+ `;
49
+ export { toolDir as i, STABILIZE_CSS as n, capturePath as r, DEFAULT_DIR as t };
50
+
51
+ //# sourceMappingURL=names-D1laAiFj.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"names-D1laAiFj.mjs","names":[],"sources":["../../cli/src/names.ts"],"sourcesContent":["/**\n * Where a capture goes, and what CirCI calls it. Pure string work, shared by the browser-side\n * matcher and the tests; it imports nothing, so a browser bundle can load it.\n */\n\n/** Vitest's own rule for a screenshot name: words kept, whitespace to dashes, the rest dropped. */\nfunction sanitize(input: string): string {\n return input\n .replace(/\\s+/g, '-')\n .replace(/[^\\w-]+/g, '')\n .replace(/-{2,}/g, '-')\n}\n\n/**\n * A screenshot's file name from the `name` given to `toMatchScreenshot`, or from the generated\n * `<describe> > <test> <n>` when none was given. The same rule Vitest applies to its own\n * references, so a name means the same file in both: `/` keeps folders, nothing escapes upward.\n */\nexport function captureName(name: string): string {\n const withoutExtension = name.endsWith('.png') ? name.slice(0, -'.png'.length) : name\n const parts = withoutExtension\n .split('/')\n .filter((part) => part !== '..' && part !== '.')\n .map(sanitize)\n .filter((part) => part.length > 0)\n if (parts.length === 0) throw new Error(`\"${name}\" is not a usable screenshot name`)\n return parts.join('/')\n}\n\n/**\n * The path of a capture relative to the project root: `<dir>/<test file>/<name>.png`, with the test\n * file relative to the root too, so two tests with the same screenshot name never share a file.\n */\nexport function capturePath(dir: string, testFile: string, name: string): string {\n const file = testFile\n .split(/[\\\\/]/)\n .filter((part) => part.length > 0 && part !== '.' && part !== '..')\n .join('/')\n return `${dir.replace(/\\/+$/, '')}/${file}/${captureName(name)}.png`\n}\n\n/** Where captures go unless told otherwise, relative to the project root. */\nexport const DEFAULT_DIR = '.circi/screenshots'\n\n/**\n * The folder a tool owns inside the captures' folder: `.circi/screenshots/vitest`,\n * `.circi/screenshots/storybook`, `.circi/screenshots/cypress`. `dir` is the parent, the same for\n * every tool (`options.dir ?? DEFAULT_DIR`); a tool writes, cleans and uploads only its own\n * folder, so two tools in one project never upload or delete each other's captures. Names in CirCI\n * are relative to the tool's folder, so they don't carry the tool's name.\n */\nexport function toolDir(dir: string, tool: string): string {\n return `${dir.replace(/\\/+$/, '')}/${tool}`\n}\n\n/** CSS that stops everything that moves or blinks, so a screenshot doesn't catch a frame halfway. */\nexport const STABILIZE_CSS = `\n*, *::before, *::after {\n animation: none !important;\n transition: none !important;\n caret-color: transparent !important;\n scroll-behavior: auto !important;\n}\n`\n"],"mappings":";;;;;;AAMA,SAAS,SAAS,OAAuB;CACvC,OAAO,MACJ,QAAQ,QAAQ,GAAG,CAAC,CACpB,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ,UAAU,GAAG;AAC1B;;;;;;AAOA,SAAgB,YAAY,MAAsB;CAEhD,MAAM,SADmB,KAAK,SAAS,MAAM,IAAI,KAAK,MAAM,GAAG,EAAc,IAAI,KAAA,CAE9E,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS,SAAS,QAAQ,SAAS,GAAG,CAAC,CAC/C,IAAI,QAAQ,CAAC,CACb,QAAQ,SAAS,KAAK,SAAS,CAAC;CACnC,IAAI,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,IAAI,KAAK,kCAAkC;CACnF,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;AAMA,SAAgB,YAAY,KAAa,UAAkB,MAAsB;CAC/E,MAAM,OAAO,SACV,MAAM,OAAO,CAAC,CACd,QAAQ,SAAS,KAAK,SAAS,KAAK,SAAS,OAAO,SAAS,IAAI,CAAC,CAClE,KAAK,GAAG;CACX,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE,EAAE,GAAG,KAAK,GAAG,YAAY,IAAI,EAAE;AACjE;;AAGA,MAAa,cAAc;;;;;;;;AAS3B,SAAgB,QAAQ,KAAa,MAAsB;CACzD,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE,EAAE,GAAG;AACvC;;AAGA,MAAa,gBAAgB"}
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,161 @@
1
+ import { n as STABILIZE_CSS } from "./names-D1laAiFj.mjs";
2
+ // src/page.ts
3
+ /**
4
+ * Browser-side steps behind `cy.screenshot()`: make the page hold still, and decide what the
5
+ * picture is of so that it holds the thing and nothing around it. Runs inside the page, so it uses
6
+ * the DOM; Node never imports it.
7
+ */
8
+ const STABILIZE_ID = "circi-stabilize";
9
+ const frame = (win) => new Promise((r) => win.requestAnimationFrame(() => r()));
10
+ /** Add the stabilizing style, then wait for fonts and two painted frames. */
11
+ async function settle(win) {
12
+ const doc = win.document;
13
+ if (!doc.getElementById("circi-stabilize")) {
14
+ const style = doc.createElement("style");
15
+ style.id = STABILIZE_ID;
16
+ style.textContent = STABILIZE_CSS;
17
+ doc.head.append(style);
18
+ }
19
+ await frame(win);
20
+ await doc.fonts.ready;
21
+ await frame(win);
22
+ await frame(win);
23
+ }
24
+ function unsettle(win) {
25
+ win.document.getElementById(STABILIZE_ID)?.remove();
26
+ }
27
+ function describe(el) {
28
+ const id = el.id ? `#${el.id}` : "";
29
+ const cls = el.classList.length > 0 ? `.${[...el.classList].join(".")}` : "";
30
+ return `<${el.tagName.toLowerCase()}${id}${cls}>`;
31
+ }
32
+ /** Not `display: none` or `visibility: hidden` (browsers without `checkVisibility` say yes). */
33
+ function isShown(el) {
34
+ return typeof el.checkVisibility === "function" ? el.checkVisibility() : true;
35
+ }
36
+ /** An element with a box and not hidden: otherwise there is nothing to take a picture of. */
37
+ function assertCapturable(el, what = describe(el)) {
38
+ const box = el.getBoundingClientRect();
39
+ if (box.width <= 0 || box.height <= 0 || !isShown(el)) throw new Error(`cy.screenshot(): nothing to capture, ${what} has no size or isn't visible. Wait for it to render before taking the screenshot.`);
40
+ }
41
+ /** The bottom of everything on the page, in page coordinates: where its content ends. */
42
+ function contentBottom(win) {
43
+ const doc = win.document;
44
+ const body = doc.body;
45
+ let bottom = 0;
46
+ const range = doc.createRange();
47
+ range.selectNodeContents(body);
48
+ const own = range.getBoundingClientRect();
49
+ if (own.width > 0 || own.height > 0) bottom = own.bottom;
50
+ for (const el of body.querySelectorAll("*")) {
51
+ const box = el.getBoundingClientRect();
52
+ if (box.width > 0 && box.height > 0 && isShown(el)) bottom = Math.max(bottom, box.bottom);
53
+ }
54
+ return Math.ceil(bottom + win.scrollY);
55
+ }
56
+ /** The padding below the content that the caller asked for (the `bottom` of Cypress's `padding`). */
57
+ function bottomPadding(padding) {
58
+ if (typeof padding === "number") return padding;
59
+ if (Array.isArray(padding)) {
60
+ const bottom = padding.length === 2 ? padding[0] : padding[2];
61
+ return typeof bottom === "number" ? bottom : 0;
62
+ }
63
+ return 0;
64
+ }
65
+ /** Decide what a `cy.screenshot()` without a subject photographs. */
66
+ function pageTarget(win, testingType, padding) {
67
+ const doc = win.document;
68
+ if (testingType === "component") {
69
+ const root = doc.querySelector("[data-cy-root]");
70
+ if (!root) throw new Error("cy.screenshot(): nothing to capture, no component is mounted");
71
+ const target = root.children.length === 1 ? root.children[0] ?? root : root;
72
+ assertCapturable(target, root.children.length === 1 ? "the mounted component" : "the mount point");
73
+ return { element: target };
74
+ }
75
+ const content = contentBottom(win);
76
+ if (content <= 0) throw new Error("cy.screenshot(): nothing to capture, the page has no content");
77
+ return { clip: {
78
+ x: 0,
79
+ y: 0,
80
+ width: doc.documentElement.clientWidth,
81
+ height: Math.min(content + bottomPadding(padding), Math.max(doc.documentElement.scrollHeight, content))
82
+ } };
83
+ }
84
+ // src/support.ts
85
+ /**
86
+ * `import '@circi/cypress/support'` in the support file. `cy.screenshot()` keeps its signature and
87
+ * what it yields; before a capture it waits for fonts and stops animations and the caret, and
88
+ * what it photographs is exactly the thing and nothing around it:
89
+ *
90
+ * - on an element (`cy.get(sel).screenshot('x')`): the element's box;
91
+ * - on the page: its content, as tall as the content is (not padded to the viewport), without
92
+ * Cypress's own interface;
93
+ * - in component testing: the mounted component's box.
94
+ *
95
+ * An element with no size, or hidden, is an error rather than a blank image. `padding` adds space
96
+ * on purpose. An explicit `capture` or `clip` is left alone.
97
+ */
98
+ Cypress.Screenshot.defaults({
99
+ capture: "fullPage",
100
+ disableTimersAndAnimations: true
101
+ });
102
+ function isOptions(value) {
103
+ return typeof value === "object" && value !== null;
104
+ }
105
+ /** The element a command was chained off (`cy.get(...)` yields a jQuery collection), if any. */
106
+ function subjectElement(subject) {
107
+ if (!isOptions(subject) || !("length" in subject)) return void 0;
108
+ const first = Reflect.get(subject, "0");
109
+ return isElement(first) ? first : void 0;
110
+ }
111
+ /** Structural, not `instanceof`: the page under test is another window with its own `Element`. */
112
+ function isElement(value) {
113
+ return typeof value === "object" && value !== null && "getBoundingClientRect" in value && typeof value.getBoundingClientRect === "function";
114
+ }
115
+ function screenshot(original, subject, ...rest) {
116
+ const [first, second] = rest;
117
+ const name = typeof first === "string" ? first : void 0;
118
+ const given = (isOptions(first) ? first : isOptions(second) ? second : void 0) ?? {};
119
+ const chained = subjectElement(subject);
120
+ const own = Reflect.get(given, "timeout");
121
+ const timeout = typeof own === "number" ? own : Cypress.config("responseTimeout");
122
+ return cy.window({ log: false }).then(async (win) => {
123
+ await settle(win);
124
+ if (chained) {
125
+ assertCapturable(chained);
126
+ return {
127
+ win,
128
+ options: {},
129
+ target: void 0
130
+ };
131
+ }
132
+ if (given.capture !== void 0 || given.clip !== void 0) return {
133
+ win,
134
+ options: {},
135
+ target: void 0
136
+ };
137
+ const plan = pageTarget(win, Cypress.testingType, given.padding);
138
+ return {
139
+ win,
140
+ options: plan.clip ? {
141
+ capture: "fullPage",
142
+ clip: plan.clip
143
+ } : {},
144
+ target: plan.element ? Cypress.$(plan.element) : void 0
145
+ };
146
+ }).then({ timeout }, ({ win, options, target }) => {
147
+ const merged = {
148
+ ...given,
149
+ ...options,
150
+ onAfterScreenshot(...args) {
151
+ unsettle(win);
152
+ given.onAfterScreenshot?.(...args);
153
+ }
154
+ };
155
+ return original(target ?? subject, ...name === void 0 ? [merged] : [name, merged]);
156
+ });
157
+ }
158
+ Cypress.Commands.overwrite("screenshot", screenshot);
159
+ export {};
160
+
161
+ //# sourceMappingURL=support.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"support.mjs","names":[],"sources":["../src/page.ts","../src/support.ts"],"sourcesContent":["/**\n * Browser-side steps behind `cy.screenshot()`: make the page hold still, and decide what the\n * picture is of so that it holds the thing and nothing around it. Runs inside the page, so it uses\n * the DOM; Node never imports it.\n */\nimport { STABILIZE_CSS } from '@circi/cli/names'\n\nexport const STABILIZE_ID = 'circi-stabilize'\n\nconst frame = (win: Window): Promise<void> =>\n new Promise((r) => win.requestAnimationFrame(() => r()))\n\n/** Add the stabilizing style, then wait for fonts and two painted frames. */\nexport async function settle(win: Window): Promise<void> {\n const doc = win.document\n if (!doc.getElementById(STABILIZE_ID)) {\n const style = doc.createElement('style')\n style.id = STABILIZE_ID\n style.textContent = STABILIZE_CSS\n doc.head.append(style)\n }\n // A frame first: a font is only requested once text that uses it has been laid out, and\n // `fonts.ready` resolves at once while nothing has been requested yet.\n await frame(win)\n await doc.fonts.ready\n await frame(win)\n await frame(win)\n}\n\nexport function unsettle(win: Window): void {\n win.document.getElementById(STABILIZE_ID)?.remove()\n}\n\nfunction describe(el: Element): string {\n const id = el.id ? `#${el.id}` : ''\n const cls = el.classList.length > 0 ? `.${[...el.classList].join('.')}` : ''\n return `<${el.tagName.toLowerCase()}${id}${cls}>`\n}\n\n/** Not `display: none` or `visibility: hidden` (browsers without `checkVisibility` say yes). */\nfunction isShown(el: Element): boolean {\n return typeof el.checkVisibility === 'function' ? el.checkVisibility() : true\n}\n\n/** An element with a box and not hidden: otherwise there is nothing to take a picture of. */\nexport function assertCapturable(el: Element, what = describe(el)): void {\n const box = el.getBoundingClientRect()\n if (box.width <= 0 || box.height <= 0 || !isShown(el)) {\n throw new Error(\n `cy.screenshot(): nothing to capture, ${what} has no size or isn't visible. ` +\n 'Wait for it to render before taking the screenshot.',\n )\n }\n}\n\n/** What to photograph when `cy.screenshot()` is called on the page. */\nexport interface PageTarget {\n /** A page: capture it at this size, from the top. */\n clip?: { x: number; y: number; width: number; height: number }\n /** Component testing: the mounted component itself. */\n element?: Element\n}\n\n/** The bottom of everything on the page, in page coordinates: where its content ends. */\nexport function contentBottom(win: Window): number {\n const doc = win.document\n const body = doc.body\n let bottom = 0\n const range = doc.createRange()\n range.selectNodeContents(body)\n const own = range.getBoundingClientRect()\n if (own.width > 0 || own.height > 0) bottom = own.bottom\n for (const el of body.querySelectorAll('*')) {\n const box = el.getBoundingClientRect()\n if (box.width > 0 && box.height > 0 && isShown(el)) bottom = Math.max(bottom, box.bottom)\n }\n return Math.ceil(bottom + win.scrollY)\n}\n\n/** The padding below the content that the caller asked for (the `bottom` of Cypress's `padding`). */\nexport function bottomPadding(padding: unknown): number {\n if (typeof padding === 'number') return padding\n if (Array.isArray(padding)) {\n const bottom: unknown = padding.length === 2 ? padding[0] : padding[2]\n return typeof bottom === 'number' ? bottom : 0\n }\n return 0\n}\n\n/** Decide what a `cy.screenshot()` without a subject photographs. */\nexport function pageTarget(win: Window, testingType: string, padding: unknown): PageTarget {\n const doc = win.document\n if (testingType === 'component') {\n const root = doc.querySelector('[data-cy-root]')\n if (!root) throw new Error('cy.screenshot(): nothing to capture, no component is mounted')\n // The component's own box: the one element the root renders, or the root if there are several.\n const target = root.children.length === 1 ? (root.children[0] ?? root) : root\n assertCapturable(\n target,\n root.children.length === 1 ? 'the mounted component' : 'the mount point',\n )\n return { element: target }\n }\n const content = contentBottom(win)\n if (content <= 0) throw new Error('cy.screenshot(): nothing to capture, the page has no content')\n return {\n clip: {\n x: 0,\n y: 0,\n width: doc.documentElement.clientWidth,\n // Padding adds space below the content, but never past the end of the document: a capture\n // can't show more page than there is.\n height: Math.min(\n content + bottomPadding(padding),\n Math.max(doc.documentElement.scrollHeight, content),\n ),\n },\n }\n}\n","/// <reference types=\"cypress\" />\n/**\n * `import '@circi/cypress/support'` in the support file. `cy.screenshot()` keeps its signature and\n * what it yields; before a capture it waits for fonts and stops animations and the caret, and\n * what it photographs is exactly the thing and nothing around it:\n *\n * - on an element (`cy.get(sel).screenshot('x')`): the element's box;\n * - on the page: its content, as tall as the content is (not padded to the viewport), without\n * Cypress's own interface;\n * - in component testing: the mounted component's box.\n *\n * An element with no size, or hidden, is an error rather than a blank image. `padding` adds space\n * on purpose. An explicit `capture` or `clip` is left alone.\n */\nimport { assertCapturable, pageTarget, settle, unsettle } from './page.ts'\n\nCypress.Screenshot.defaults({ capture: 'fullPage', disableTimersAndAnimations: true })\n\ntype Options = Partial<Cypress.ScreenshotOptions>\n\nfunction isOptions(value: unknown): value is Options {\n return typeof value === 'object' && value !== null\n}\n\n/** The element a command was chained off (`cy.get(...)` yields a jQuery collection), if any. */\nfunction subjectElement(subject: unknown): Element | undefined {\n if (!isOptions(subject) || !('length' in subject)) return undefined\n const first: unknown = Reflect.get(subject, '0')\n return isElement(first) ? first : undefined\n}\n\n/** Structural, not `instanceof`: the page under test is another window with its own `Element`. */\nfunction isElement(value: unknown): value is Element {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'getBoundingClientRect' in value &&\n typeof value.getBoundingClientRect === 'function'\n )\n}\n\ninterface Plan {\n win: Window\n options: Options\n target: JQuery<Element> | undefined\n}\n\n// A dual command: the argument after the original is the subject (undefined on `cy`).\nfunction screenshot(\n original: (...args: unknown[]) => unknown,\n subject: unknown,\n ...rest: unknown[]\n) {\n const [first, second] = rest\n const name = typeof first === 'string' ? first : undefined\n const given: Options = (isOptions(first) ? first : isOptions(second) ? second : undefined) ?? {}\n const chained = subjectElement(subject)\n // The real `cy.screenshot` runs inside the last `.then()`, so that step gets the screenshot's own\n // limit (its `timeout`, else `responseTimeout`) rather than `.then()`'s 4 s: a full-page capture of\n // a tall page is several captures stitched together, which took longer than 4 s on CI.\n const own: unknown = Reflect.get(given, 'timeout')\n const timeout = typeof own === 'number' ? own : Cypress.config('responseTimeout')\n\n return cy\n .window({ log: false })\n .then(async (win): Promise<Plan> => {\n await settle(win)\n if (chained) {\n assertCapturable(chained)\n return { win, options: {}, target: undefined }\n }\n // An explicit `capture` or `clip` is the test's own choice.\n if (given.capture !== undefined || given.clip !== undefined) {\n return { win, options: {}, target: undefined }\n }\n const plan = pageTarget(win, Cypress.testingType, given.padding)\n return {\n win,\n options: plan.clip ? { capture: 'fullPage', clip: plan.clip } : {},\n target: plan.element ? Cypress.$(plan.element) : undefined,\n }\n })\n .then({ timeout }, ({ win, options, target }) => {\n const merged: Options = {\n ...given,\n ...options,\n onAfterScreenshot(...args) {\n unsettle(win)\n given.onAfterScreenshot?.(...args)\n },\n }\n return original(target ?? subject, ...(name === undefined ? [merged] : [name, merged]))\n })\n}\n\n// The command types describe `cy.screenshot(name?, options?)`; the subject-first form the\n// overwrite is called with isn't in them.\n// oxlint-disable-next-line typescript/no-unsafe-type-assertion\nCypress.Commands.overwrite('screenshot', screenshot as never)\n"],"mappings":";;;;;;;AAOA,MAAa,eAAe;AAE5B,MAAM,SAAS,QACb,IAAI,SAAS,MAAM,IAAI,4BAA4B,EAAE,CAAC,CAAC;;AAGzD,eAAsB,OAAO,KAA4B;CACvD,MAAM,MAAM,IAAI;CAChB,IAAI,CAAC,IAAI,eAAA,iBAA2B,GAAG;EACrC,MAAM,QAAQ,IAAI,cAAc,OAAO;EACvC,MAAM,KAAK;EACX,MAAM,cAAc;EACpB,IAAI,KAAK,OAAO,KAAK;CACvB;CAGA,MAAM,MAAM,GAAG;CACf,MAAM,IAAI,MAAM;CAChB,MAAM,MAAM,GAAG;CACf,MAAM,MAAM,GAAG;AACjB;AAEA,SAAgB,SAAS,KAAmB;CAC1C,IAAI,SAAS,eAAe,YAAY,CAAC,EAAE,OAAO;AACpD;AAEA,SAAS,SAAS,IAAqB;CACrC,MAAM,KAAK,GAAG,KAAK,IAAI,GAAG,OAAO;CACjC,MAAM,MAAM,GAAG,UAAU,SAAS,IAAI,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC,CAAC,KAAK,GAAG,MAAM;CAC1E,OAAO,IAAI,GAAG,QAAQ,YAAY,IAAI,KAAK,IAAI;AACjD;;AAGA,SAAS,QAAQ,IAAsB;CACrC,OAAO,OAAO,GAAG,oBAAoB,aAAa,GAAG,gBAAgB,IAAI;AAC3E;;AAGA,SAAgB,iBAAiB,IAAa,OAAO,SAAS,EAAE,GAAS;CACvE,MAAM,MAAM,GAAG,sBAAsB;CACrC,IAAI,IAAI,SAAS,KAAK,IAAI,UAAU,KAAK,CAAC,QAAQ,EAAE,GAClD,MAAM,IAAI,MACR,wCAAwC,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M,OAAO,WAAW,KAAK,QAAQ,aAAa,MAAM,OAAO;EAC/D,OAAO;GACL;GACA,SAAS,KAAK,OAAO;IAAE,SAAS;IAAY,MAAM,KAAK;GAAK,IAAI,CAAC;GACjE,QAAQ,KAAK,UAAU,QAAQ,EAAE,KAAK,OAAO,IAAI,KAAA;EACnD;CACF,CAAC,CAAC,CACD,KAAK,EAAE,QAAQ,IAAI,EAAE,KAAK,SAAS,aAAa;EAC/C,MAAM,SAAkB;GACtB,GAAG;GACH,GAAG;GACH,kBAAkB,GAAG,MAAM;IACzB,SAAS,GAAG;IACZ,MAAM,oBAAoB,GAAG,IAAI;GACnC;EACF;EACA,OAAO,SAAS,UAAU,SAAS,GAAI,SAAS,KAAA,IAAY,CAAC,MAAM,IAAI,CAAC,MAAM,MAAM,CAAE;CACxF,CAAC;AACL;AAKA,QAAQ,SAAS,UAAU,cAAc,UAAmB"}
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@circi/cypress",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Cypress integration: cy.circiScreenshot() and a plugin that uploads the screenshots to CirCI",
5
+ "keywords": [
6
+ "cypress",
7
+ "cypress-plugin",
8
+ "screenshots",
9
+ "visual-regression",
10
+ "visual-testing"
11
+ ],
12
+ "homepage": "https://circi.dev/ci/cypress/",
13
+ "bugs": {
14
+ "url": "https://github.com/cir-ci/repo/issues"
15
+ },
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/cir-ci/repo.git",
20
+ "directory": "packages/cypress"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md"
25
+ ],
26
+ "type": "module",
27
+ "imports": {
28
+ "#src/*": "./src/*"
29
+ },
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.mts",
33
+ "default": "./dist/index.mjs"
34
+ },
35
+ "./support": {
36
+ "types": "./dist/support.d.mts",
37
+ "default": "./dist/support.mjs"
38
+ }
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "provenance": true
43
+ },
44
+ "dependencies": {
45
+ "tar": "7.5.23"
46
+ },
47
+ "devDependencies": {
48
+ "@arethetypeswrong/core": "0.18.5",
49
+ "@circi/cli": "0.3.1",
50
+ "cypress": "16.3.0",
51
+ "publint": "0.3.25",
52
+ "tsdown": "0.23.7",
53
+ "vite": "8.3.8"
54
+ },
55
+ "peerDependencies": {
56
+ "cypress": ">=13"
57
+ },
58
+ "engines": {
59
+ "node": ">=22"
60
+ },
61
+ "scripts": {
62
+ "build": "tsdown"
63
+ }
6
64
  }