@recursica/adapter-tester 5.1.0 → 5.1.2
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/README.md +6 -6
- package/dist/adapter-tester.schema.json.d.ts +2 -2
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/fileConfig.d.ts +1 -1
- package/dist/fileConfig.d.ts.map +1 -1
- package/dist/golden/resolveSourceOfTruthGolden.d.ts.map +1 -1
- package/dist/harness/mantineSourceOfTruth.d.ts +2 -2
- package/dist/harness/mantineSourceOfTruth.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/{mantineSourceOfTruth-DE7XOgea.js → mantineSourceOfTruth-BDJ5mfpd.js} +7 -7
- package/dist/mantineSourceOfTruth-BDJ5mfpd.js.map +1 -0
- package/dist/{mantineSourceOfTruth-Dpe4mlmF.cjs → mantineSourceOfTruth-CdRlVrRC.cjs} +5 -5
- package/dist/mantineSourceOfTruth-CdRlVrRC.cjs.map +1 -0
- package/dist/testing/runVisualRegression.d.ts.map +1 -1
- package/dist/testing.cjs +4 -4
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js +96 -83
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
- package/src/adapter-tester.schema.json +2 -2
- package/dist/mantineSourceOfTruth-DE7XOgea.js.map +0 -1
- package/dist/mantineSourceOfTruth-Dpe4mlmF.cjs.map +0 -1
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","sources":["../src/golden/diffPng.ts","../src/golden/validateManifest.ts","../src/golden/manifestStore.ts","../src/golden/resolveSourceOfTruthGolden.ts","../src/testing/runVisualRegression.ts"],"sourcesContent":["import pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\nexport interface PngDiffResult {\n /** Mismatched-pixel count, or `Infinity` if the two images aren't even the\n * same dimensions — pixelmatch itself throws on a size mismatch, and a size\n * mismatch is itself a real difference, not something to swallow. */\n diffPixels: number;\n /** Visual highlight of the mismatched pixels, encoded as a PNG buffer.\n * `null` when `diffPixels` is `Infinity` — there's no pixel-aligned diff to\n * render across two different-sized images. */\n diffImage: Buffer | null;\n}\n\n/** Pixel-diffs two PNG buffers. */\nexport function diffPngBuffers(a: Buffer, b: Buffer): PngDiffResult {\n const imgA = PNG.sync.read(a);\n const imgB = PNG.sync.read(b);\n if (imgA.width !== imgB.width || imgA.height !== imgB.height) {\n return { diffPixels: Infinity, diffImage: null };\n }\n const diff = new PNG({ width: imgA.width, height: imgA.height });\n const diffPixels = pixelmatch(\n imgA.data,\n imgB.data,\n diff.data,\n imgA.width,\n imgA.height,\n { threshold: 0.1 },\n );\n return { diffPixels, diffImage: PNG.sync.write(diff) };\n}\n","import { Ajv } from \"ajv\";\nimport * as ajvFormatsModule from \"ajv-formats\";\nimport type { FormatsPlugin } from \"ajv-formats\";\nimport schema from \"./manifest.schema.json\" with { type: \"json\" };\n\n// See validateFileConfig.ts for why `.default` has to be unwrapped by hand.\nconst addFormats = (ajvFormatsModule as unknown as { default: FormatsPlugin })\n .default;\n\nconst ajv = new Ajv({ allErrors: true, strict: true });\naddFormats(ajv);\nconst validate = ajv.compile(schema);\n\n/**\n * Validates a parsed `test/golden/manifest.json` against `manifest.schema.json`.\n * Throws with every violation listed — callers must not silently coerce or\n * drop invalid entries.\n */\nexport function validateGoldenManifest(data: unknown, path: string): void {\n if (validate(data)) return;\n\n const errors = (validate.errors ?? [])\n .map((error) => {\n const extra = error.params?.additionalProperty\n ? ` '${error.params.additionalProperty}'`\n : \"\";\n return ` - ${error.instancePath || \"root\"} ${error.message}${extra}`;\n })\n .join(\"\\n\");\n throw new Error(`Invalid ${path}:\\n${errors}`);\n}\n","import {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\nexport interface GoldenManifestEntry {\n createdAt: string;\n sourceOfTruthCreatedAt?: string;\n}\n\nexport type GoldenManifest = Record<string, GoldenManifestEntry>;\n\nexport function manifestPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json\");\n}\n\nfunction manifestLockPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json.lock\");\n}\n\nexport function goldenImagePath(goldenDir: string, storyId: string): string {\n return join(goldenDir, `${storyId}.png`);\n}\n\n/** Returns `{}` if no manifest exists yet — a fresh adapter with no goldens\n * captured is the normal starting state, not an error. */\nexport function loadManifest(goldenDir: string): GoldenManifest {\n const path = manifestPath(goldenDir);\n if (!existsSync(path)) return {};\n const data = JSON.parse(readFileSync(path, \"utf8\"));\n validateGoldenManifest(data, path);\n return data;\n}\n\n/** Validates before writing, and sorts keys so the diff on a reviewed PR is\n * stable regardless of the order stories happened to run in. Writes to a\n * temp file and renames over the real one — `rename` is atomic, so a\n * concurrent `loadManifest` (running in another Playwright worker) never\n * observes a half-written file. */\nexport function saveManifest(\n goldenDir: string,\n manifest: GoldenManifest,\n): void {\n const path = manifestPath(goldenDir);\n validateGoldenManifest(manifest, path);\n const sorted: GoldenManifest = {};\n for (const key of Object.keys(manifest).sort()) {\n sorted[key] = manifest[key]!;\n }\n mkdirSync(goldenDir, { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n writeFileSync(tmpPath, JSON.stringify(sorted, null, 2) + \"\\n\");\n renameSync(tmpPath, path);\n}\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_TIMEOUT_MS = 15_000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Exclusive-create the lock file, spin-retrying until it's free. `wx` fails\n * atomically (`EEXIST`) if another worker process already holds it — that's\n * the only signal we need, no third-party lock library required for a\n * same-machine, same-run lock like this. */\nasync function acquireManifestLock(goldenDir: string): Promise<void> {\n mkdirSync(goldenDir, { recursive: true });\n const path = manifestLockPath(goldenDir);\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n for (;;) {\n try {\n closeSync(openSync(path, \"wx\"));\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the manifest lock at \"${path}\" — delete it if a previous run crashed while holding it.`,\n );\n }\n await sleep(LOCK_RETRY_MS);\n }\n }\n}\n\nfunction releaseManifestLock(goldenDir: string): void {\n rmSync(manifestLockPath(goldenDir), { force: true });\n}\n\n/** Runs `updater` against this story's manifest entry under an exclusive\n * lock on `manifest.json`: reloads the manifest fresh, applies `updater`,\n * and saves it back, all before releasing the lock. Concurrent Playwright\n * workers each own a different story, so this is the only section that\n * needs to serialize — everything else about a story (its screenshot, its\n * golden image file, its diff) is independent of every other story. */\nexport async function updateManifestEntry(\n goldenDir: string,\n storyId: string,\n updater: (\n entry: GoldenManifestEntry | undefined,\n ) => GoldenManifestEntry | undefined,\n): Promise<GoldenManifestEntry | undefined> {\n await acquireManifestLock(goldenDir);\n try {\n const manifest = loadManifest(goldenDir);\n const nextEntry = updater(manifest[storyId]);\n if (nextEntry === undefined) {\n delete manifest[storyId];\n } else {\n manifest[storyId] = nextEntry;\n }\n saveManifest(goldenDir, manifest);\n return nextEntry;\n } finally {\n releaseManifestLock(goldenDir);\n }\n}\n\nexport function saveGoldenImage(\n goldenDir: string,\n storyId: string,\n buffer: Buffer,\n): void {\n mkdirSync(goldenDir, { recursive: true });\n writeFileSync(goldenImagePath(goldenDir, storyId), buffer);\n}\n\n/** Removes the golden `.png` + manifest entry for every story id in the\n * manifest that isn't in `currentStoryIds` (e.g. a story renamed or deleted\n * from Storybook) — otherwise those never get cleaned up on their own,\n * since a run only ever adds/updates entries for stories it actually saw.\n * Returns the pruned ids, for the caller to report. Both the file removal\n * and the manifest delete are idempotent, so it's safe for this to run\n * redundantly from more than one Playwright worker. */\nexport async function pruneOrphanedGoldens(\n goldenDir: string,\n currentStoryIds: ReadonlySet<string>,\n): Promise<string[]> {\n const manifest = loadManifest(goldenDir);\n const orphanIds = Object.keys(manifest).filter(\n (id) => !currentStoryIds.has(id),\n );\n for (const id of orphanIds) {\n const imagePath = goldenImagePath(goldenDir, id);\n if (existsSync(imagePath)) unlinkSync(imagePath);\n await updateManifestEntry(goldenDir, id, () => undefined);\n }\n return orphanIds;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SourceOfTruthGoldenLocation } from \"../config.js\";\nimport {\n goldenImagePath,\n loadManifest,\n manifestPath,\n type GoldenManifest,\n} from \"./manifestStore.js\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\nconst GITHUB_REPO = \"borderux/recursica\";\n\nexport interface SourceOfTruthGolden {\n manifest: GoldenManifest;\n /** Returns the golden PNG bytes for a story, or `null` if the source of\n * truth has no golden captured for it yet. */\n readImage(storyId: string): Promise<Buffer | null>;\n}\n\nasync function resolveNpmVersion(\n packageName: string,\n versionSpec: string,\n): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n if (!response.ok) {\n throw new Error(\n `Could not reach npm registry for ${packageName}: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, unknown>;\n };\n const resolved =\n data[\"dist-tags\"]?.[versionSpec] ??\n (data.versions?.[versionSpec] ? versionSpec : undefined);\n if (!resolved) {\n throw new Error(\n `${packageName} has no version or dist-tag \"${versionSpec}\" on the npm registry.`,\n );\n }\n return resolved;\n}\n\n// This monorepo's packages all live at `packages/<unscoped-name>` — mirrors\n// the same convention `mantineSourceOfTruthHarness` and every existing\n// `packages/*/package.json`'s `repository.directory` field already assume.\nfunction packageDirectory(packageName: string): string {\n return `packages/${packageName.split(\"/\").pop()}`;\n}\n\n/**\n * Resolves the source-of-truth adapter's golden images for the divergence\n * check. Never boots a Storybook — both location types resolve to plain\n * files, fetched once and cached, not re-diffed per pixel over the wire.\n *\n * `location.type === \"local\"`: a sibling package already checked out (this\n * monorepo's own `sourceOfTruth.type: \"url\"` mode) — read its\n * `test/golden/` directly, including any uncommitted local changes.\n *\n * `location.type === \"npm\"`: no local checkout (the default, standalone-repo\n * mode) — resolve the installed version against the npm registry, then fetch\n * that exact version's `test/golden/` from the public GitHub repo at the\n * matching release tag (changesets tags every release as\n * `<packageName>@<version>`), caching what's downloaded under `cacheDir`.\n *\n * Returns `null` — degrading the divergence check to a skip, not a failure —\n * when no golden baseline exists yet for this version, or the registry/repo\n * is unreachable.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden | null> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n console.warn(\n `No golden baseline found yet at ${location.dir} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\n }\n const manifest = loadManifest(location.dir);\n return {\n manifest,\n async readImage(storyId) {\n const path = goldenImagePath(location.dir, storyId);\n return existsSync(path) ? readFileSync(path) : null;\n },\n };\n }\n\n let version: string;\n try {\n version = await resolveNpmVersion(\n location.packageName,\n location.versionSpec,\n );\n } catch (error) {\n console.warn(\n `Could not resolve ${location.packageName}@${location.versionSpec} — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n\n const cacheDir = join(location.cacheDir, version);\n const tag = `${location.packageName}@${version}`;\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/${packageDirectory(location.packageName)}/test/golden`;\n\n let manifest: GoldenManifest;\n const cachedManifestPath = manifestPath(cacheDir);\n if (existsSync(cachedManifestPath)) {\n manifest = loadManifest(cacheDir);\n } else {\n let response: Response;\n try {\n response = await fetch(`${rawBase}/manifest.json`);\n } catch (error) {\n console.warn(\n `Could not reach GitHub to fetch ${tag}'s golden baseline — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n if (!response.ok) {\n console.warn(\n `No golden baseline published for ${tag} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\n }\n const text = await response.text();\n const parsed = JSON.parse(text);\n validateGoldenManifest(parsed, `${rawBase}/manifest.json`);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedManifestPath, text);\n manifest = parsed;\n }\n\n return {\n manifest,\n async readImage(storyId) {\n const cachedImagePath = goldenImagePath(cacheDir, storyId);\n if (existsSync(cachedImagePath)) return readFileSync(cachedImagePath);\n const response = await fetch(`${rawBase}/${storyId}.png`);\n if (!response.ok) return null;\n const buffer = Buffer.from(await response.arrayBuffer());\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedImagePath, buffer);\n return buffer;\n },\n };\n}\n","import { expect } from \"@playwright/test\";\nimport type { Browser, TestInfo } from \"@playwright/test\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AdapterTesterConfig } from \"../config.js\";\nimport { diffPngBuffers } from \"../golden/diffPng.js\";\nimport {\n type GoldenManifestEntry,\n goldenImagePath,\n loadManifest,\n pruneOrphanedGoldens,\n saveGoldenImage,\n updateManifestEntry,\n} from \"../golden/manifestStore.js\";\nimport { resolveSourceOfTruthGolden } from \"../golden/resolveSourceOfTruthGolden.js\";\n\nconst DEFAULT_EXCLUDE_TITLE_PREFIXES = [\"Theme\", \"Tokens\", \"Introduction\"];\n\ninterface StorybookEntry {\n type: string;\n id: string;\n name: string;\n title: string;\n}\n\nfunction matchesPrefix(id: string, prefix: string): boolean {\n return id === prefix || id.startsWith(prefix);\n}\n\n/** Fetches every story `target`'s Storybook currently has, filtered only by\n * `excludeTitlePrefixes` — not `stories.<id>.exclude`, so callers can still\n * tell an excluded story apart from one that's genuinely missing. */\nasync function fetchStories(\n target: { name: string; url: string },\n excludeTitlePrefixes: string[],\n): Promise<StorybookEntry[]> {\n let stories: StorybookEntry[];\n try {\n const response = await fetch(`${target.url}/index.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Storybook index: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as any;\n const entries = data.entries || {};\n stories = Object.values(entries).filter(\n (entry: any) =>\n entry.type === \"story\" &&\n !excludeTitlePrefixes.some(\n (prefix) =>\n entry.title === prefix || entry.title.startsWith(`${prefix}/`),\n ),\n ) as StorybookEntry[];\n stories.sort((a, b) => a.id.localeCompare(b.id));\n } catch (error) {\n console.error(\n \"Failed to load Storybook index from\",\n `${target.url}/index.json`,\n error,\n );\n throw new Error(\n `Storybook target \"${target.name}\" is not responsive or index.json is missing. Please ensure its Storybook is running.`,\n );\n }\n return stories;\n}\n\n/** Resolves the diff threshold for `storyId`: the longest (most specific)\n * `storyThresholds` key matching by prefix, falling back to\n * `defaultThresholdPixels` when nothing matches. */\nfunction resolveThreshold(\n storyId: string,\n storyThresholds: Record<string, number>,\n defaultThresholdPixels: number,\n): number {\n let bestMatch: string | undefined;\n for (const prefix of Object.keys(storyThresholds)) {\n if (\n matchesPrefix(storyId, prefix) &&\n (!bestMatch || prefix.length > bestMatch.length)\n ) {\n bestMatch = prefix;\n }\n }\n return bestMatch !== undefined\n ? storyThresholds[bestMatch]!\n : defaultThresholdPixels;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Story ids the source-of-truth adapter has a golden for but this\n * project's own Storybook doesn't — empty outside `checkMode: \"divergence\"`\n * or when `sourceOfTruthGolden` didn't resolve. Excludes ids covered by a\n * `stories.<id>.exclude` entry: an intentional gap, not a sync failure. */\n missingFromSourceOfTruth: string[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/**\n * Resolves the golden-image plan for `config`'s own target (the one target\n * in `config.targets` not marked `sourceOfTruth`).\n *\n * Two independent checks per story, gated by `config.checkMode`. Neither\n * boots the source-of-truth adapter's own Storybook — its side of both\n * checks is always a stored golden file, never a live page:\n *\n * 1. **Own-drift (`checkMode: \"own\"`, the default; hard fail):** this run's\n * live render vs this project's own stored `test/golden/<story-id>.png`.\n * No golden yet for a story is not a failure — one is captured from this\n * run instead (same as `--update-golden`, scoped to just that story), in\n * either mode.\n * 2. **Source-of-truth divergence (`checkMode: \"divergence\"`; hard fail):**\n * this run's live render vs the source-of-truth's stored golden (`config`'s\n * `sourceOfTruthGolden`) — always fresh, no `--update-golden` step needed\n * first. Skipped entirely when `config.isSourceOfTruthAdapter` is true —\n * the source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when the source of truth has no baseline for it yet.\n * A once-flagged divergence stays quiet after `--approve-divergence`,\n * until the source of truth's own golden changes again.\n */\nexport async function resolveVisualRegressionPlan(\n config: AdapterTesterConfig,\n): Promise<VisualRegressionPlan> {\n const ownTarget = config.isSourceOfTruthAdapter\n ? config.targets[0]\n : config.targets.find((target) => !target.sourceOfTruth);\n if (!ownTarget) {\n throw new Error(\n \"adapter-tester config has no non-sourceOfTruth target to run the golden check against.\",\n );\n }\n const excludeTitlePrefixes =\n config.excludeTitlePrefixes ?? DEFAULT_EXCLUDE_TITLE_PREFIXES;\n const storyOverrides = config.stories ?? {};\n const excludeStoryIds = Object.keys(storyOverrides).filter(\n (id) => storyOverrides[id]!.exclude,\n );\n const goldenStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.goldenThreshold !== undefined)\n .map(([id, override]) => [id, override.goldenThreshold!]),\n );\n const sourceOfTruthStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.sourceOfTruthThreshold !== undefined)\n .map(([id, override]) => [id, override.sourceOfTruthThreshold!]),\n );\n const goldenDir = config.goldenDir;\n const goldenMode = config.goldenMode;\n const checkMode = config.checkMode;\n\n // Fetched with only excludeTitlePrefixes applied — not excludeStoryIds —\n // so the source-of-truth story-parity check below can tell an excluded\n // story apart from one that's genuinely missing from this Storybook.\n const ownStories = await fetchStories(ownTarget, excludeTitlePrefixes);\n const stories = ownStories.filter(\n (entry) =>\n !excludeStoryIds.some((prefix) => matchesPrefix(entry.id, prefix)),\n );\n\n // `--update-golden` redefines this project's own baseline, so it's also\n // the point a renamed/removed story's now-orphaned golden gets cleaned up\n // — otherwise nothing ever prunes it, since a run only ever adds/updates\n // entries for stories it actually saw in this pass. Uses the full current\n // story list (not narrowed by any `--grep` Playwright itself applies), so\n // this catches every orphan regardless of how the run is scoped.\n if (goldenMode === \"update-golden\") {\n const prunedStoryIds = await pruneOrphanedGoldens(\n goldenDir,\n new Set(stories.map((story) => story.id)),\n );\n if (prunedStoryIds.length > 0) {\n console.warn(\n `Pruned ${prunedStoryIds.length} orphaned golden(s) no longer in Storybook: ${prunedStoryIds.join(\", \")}`,\n );\n }\n }\n\n const sourceOfTruthGolden =\n checkMode !== \"divergence\" ||\n config.isSourceOfTruthAdapter ||\n !config.sourceOfTruthGolden\n ? null\n : await resolveSourceOfTruthGolden(config.sourceOfTruthGolden);\n\n // Checked against `ownStories` (title-prefix-excluded only), not `stories`\n // — a story marked `exclude: true` still counts as \"present\", it's just\n // not diffed. Only a story the source of truth has that this adapter\n // never built at all, and hasn't acknowledged via `exclude`, is missing.\n const ownStoryIds = new Set(ownStories.map((entry) => entry.id));\n const missingFromSourceOfTruth = sourceOfTruthGolden\n ? Object.keys(sourceOfTruthGolden.manifest)\n .filter(\n (id) =>\n !ownStoryIds.has(id) &&\n !excludeStoryIds.some((prefix) => matchesPrefix(id, prefix)),\n )\n .sort()\n : [];\n\n if (missingFromSourceOfTruth.length > 0) {\n console.error(\n `[adapter-tester] ${missingFromSourceOfTruth.length} stor(y/ies) exist in the source of truth but are missing here: ${missingFromSourceOfTruth.join(\", \")}. Add the missing story, or mark it \\`exclude: true\\` under \\`stories\\` in adapter-tester.config.json if intentional.`,\n );\n }\n\n console.log(\n [\n `[adapter-tester] target: \"${ownTarget.name}\" (${ownTarget.url})`,\n `[adapter-tester] checkMode: \"${checkMode}\" (${checkMode === \"divergence\" ? \"live render vs source-of-truth's golden\" : \"live render vs this project's own golden\"})`,\n `[adapter-tester] goldenMode: \"${goldenMode}\"`,\n `[adapter-tester] goldenThresholdPixels: ${config.goldenThresholdPixels}`,\n `[adapter-tester] sourceOfTruthThresholdPixels: ${config.sourceOfTruthThresholdPixels}`,\n checkMode === \"divergence\"\n ? config.isSourceOfTruthAdapter\n ? `[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from`\n : !config.sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured`\n : sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(sourceOfTruthGolden.manifest).length} golden(s) available (config: ${JSON.stringify(config.sourceOfTruthGolden)})`\n : `[adapter-tester] sourceOfTruthGolden: unavailable — no baseline found or unreachable (config: ${JSON.stringify(config.sourceOfTruthGolden)}); divergence check will skip every story`\n : `[adapter-tester] sourceOfTruthGolden: not used in \"own\" checkMode`,\n `[adapter-tester] stories: ${stories.length} to check (excluded: ${excludeStoryIds.length}, title prefixes excluded: ${excludeTitlePrefixes.join(\", \") || \"none\"})`,\n `[adapter-tester] story parity with source of truth: ${missingFromSourceOfTruth.length === 0 ? \"OK\" : `${missingFromSourceOfTruth.length} missing (see error above)`}`,\n ].join(\"\\n\"),\n );\n\n const suiteLabel =\n checkMode === \"divergence\"\n ? \"Source-of-Truth Divergence Check\"\n : \"Own-Drift Golden Image Check\";\n\n return {\n ownTargetName: ownTarget.name,\n suiteLabel,\n stories,\n missingFromSourceOfTruth,\n checkStory: async (story, browser, testInfo) => {\n const page = await browser.newPage();\n await page.setViewportSize({ width: 800, height: 600 });\n await page.goto(\n `${ownTarget.url}/iframe.html?id=${story.id}&viewMode=story`,\n { waitUntil: \"networkidle\" },\n );\n await page.waitForSelector(\"#storybook-root\");\n await page.addStyleTag({\n content: `* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }`,\n });\n await page.waitForTimeout(300);\n const liveBuffer = await page.screenshot();\n\n const imagePath = goldenImagePath(goldenDir, story.id);\n // Only this worker ever touches this story's key, so reading it here\n // (outside the lock `updateManifestEntry` takes at the end) can't\n // race another worker — they're all reading/writing different keys.\n const entry = loadManifest(goldenDir)[story.id];\n const capturingNewGolden =\n goldenMode !== \"check\" || !entry || !existsSync(imagePath);\n\n let currentEntry: GoldenManifestEntry;\n if (capturingNewGolden) {\n saveGoldenImage(goldenDir, story.id, liveBuffer);\n currentEntry = entry?.sourceOfTruthCreatedAt\n ? {\n createdAt: new Date().toISOString(),\n sourceOfTruthCreatedAt: entry.sourceOfTruthCreatedAt,\n }\n : { createdAt: new Date().toISOString() };\n if (!entry) {\n testInfo.annotations.push({\n type: \"golden-created\",\n description: `No golden existed yet for \"${story.id}\" — captured one from this run.`,\n });\n }\n } else {\n currentEntry = entry;\n if (checkMode === \"own\") {\n const goldenBuffer = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n goldenBuffer,\n );\n const threshold = resolveThreshold(\n story.id,\n goldenStoryThresholds,\n config.goldenThresholdPixels,\n );\n if (diffPixels >= threshold) {\n await testInfo.attach(\"expected\", {\n body: goldenBuffer,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n }\n expect\n .soft(\n diffPixels,\n `\"${story.id}\" has drifted from its own golden image (${diffPixels} mismatched pixels, threshold ${threshold})`,\n )\n .toBeLessThan(threshold);\n }\n }\n\n if (sourceOfTruthGolden) {\n const sourceOfTruthEntry = sourceOfTruthGolden.manifest[story.id];\n const sourceOfTruthImage = sourceOfTruthEntry\n ? await sourceOfTruthGolden.readImage(story.id)\n : null;\n\n if (sourceOfTruthEntry && sourceOfTruthImage) {\n if (goldenMode === \"approve-divergence\") {\n currentEntry = {\n ...currentEntry,\n sourceOfTruthCreatedAt: sourceOfTruthEntry.createdAt,\n };\n } else {\n // Always this run's live render, never the stored own-drift\n // golden — divergence should reflect what's on screen right now,\n // not whatever was last captured via --update-golden.\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n sourceOfTruthImage,\n );\n const threshold = resolveThreshold(\n story.id,\n sourceOfTruthStoryThresholds,\n config.sourceOfTruthThresholdPixels,\n );\n const approvedAt = currentEntry.sourceOfTruthCreatedAt;\n const isKnownDivergence =\n diffPixels < threshold ||\n (approvedAt !== undefined &&\n approvedAt >= sourceOfTruthEntry.createdAt);\n if (!isKnownDivergence) {\n await testInfo.attach(\"expected\", {\n body: sourceOfTruthImage,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n testInfo.annotations.push({\n type: \"source-of-truth-divergence\",\n description: `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n });\n }\n expect\n .soft(\n isKnownDivergence,\n `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n )\n .toBe(true);\n }\n }\n }\n\n // Locked read-modify-write of just this story's entry — see\n // `updateManifestEntry` for why that's enough to make this safe\n // across concurrent Playwright workers.\n await updateManifestEntry(goldenDir, story.id, () => currentEntry);\n },\n };\n}\n"],"names":["diffPngBuffers","a","b","imgA","PNG","imgB","diff","pixelmatch","addFormats","ajvFormatsModule.default","ajv","Ajv","validate","schema","validateGoldenManifest","data","path","errors","error","extra","_a","manifestPath","goldenDir","join","manifestLockPath","goldenImagePath","storyId","loadManifest","existsSync","readFileSync","saveManifest","manifest","sorted","key","mkdirSync","tmpPath","writeFileSync","renameSync","LOCK_RETRY_MS","LOCK_TIMEOUT_MS","sleep","ms","resolve","acquireManifestLock","deadline","closeSync","openSync","releaseManifestLock","rmSync","updateManifestEntry","updater","nextEntry","saveGoldenImage","buffer","pruneOrphanedGoldens","currentStoryIds","orphanIds","id","imagePath","unlinkSync","GITHUB_REPO","resolveNpmVersion","packageName","versionSpec","response","resolved","_b","packageDirectory","resolveSourceOfTruthGolden","location","version","cacheDir","tag","rawBase","cachedManifestPath","text","parsed","cachedImagePath","DEFAULT_EXCLUDE_TITLE_PREFIXES","matchesPrefix","prefix","fetchStories","target","excludeTitlePrefixes","stories","entries","entry","resolveThreshold","storyThresholds","defaultThresholdPixels","bestMatch","resolveVisualRegressionPlan","config","ownTarget","storyOverrides","excludeStoryIds","goldenStoryThresholds","override","sourceOfTruthStoryThresholds","goldenMode","checkMode","ownStories","prunedStoryIds","story","sourceOfTruthGolden","ownStoryIds","missingFromSourceOfTruth","suiteLabel","browser","testInfo","page","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","approvedAt","isKnownDivergence"],"mappings":"6OAeO,SAASA,EAAeC,EAAWC,EAA0B,CAClE,MAAMC,EAAOC,EAAAA,IAAI,KAAK,KAAKH,CAAC,EACtBI,EAAOD,EAAAA,IAAI,KAAK,KAAKF,CAAC,EAC5B,GAAIC,EAAK,QAAUE,EAAK,OAASF,EAAK,SAAWE,EAAK,OACpD,MAAO,CAAE,WAAY,IAAU,UAAW,IAAA,EAE5C,MAAMC,EAAO,IAAIF,EAAAA,IAAI,CAAE,MAAOD,EAAK,MAAO,OAAQA,EAAK,OAAQ,EAS/D,MAAO,CAAE,WARUI,EACjBJ,EAAK,KACLE,EAAK,KACLC,EAAK,KACLH,EAAK,MACLA,EAAK,OACL,CAAE,UAAW,EAAA,CAAI,EAEE,UAAWC,EAAAA,IAAI,KAAK,MAAME,CAAI,CAAA,CACrD,irCCzBME,GAAcC,EAAAA,MAGdC,EAAM,IAAIC,EAAAA,WAAAA,IAAI,CAAE,UAAW,GAAM,OAAQ,GAAM,EACrDH,GAAWE,CAAG,EACd,MAAME,EAAWF,EAAI,QAAQG,EAAM,EAO5B,SAASC,EAAuBC,EAAeC,EAAoB,CACxE,GAAIJ,EAASG,CAAI,EAAG,OAEpB,MAAME,GAAUL,EAAS,QAAU,CAAA,GAChC,IAAKM,GAAU,OACd,MAAMC,GAAQC,EAAAF,EAAM,SAAN,MAAAE,EAAc,mBACxB,KAAKF,EAAM,OAAO,kBAAkB,I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BC,EACxB,GAAIrB,IAAe,qBACjBc,EAAe,CACb,GAAGA,EACH,uBAAwBM,EAAmB,SAAA,MAExC,CAIL,KAAM,CAAE,WAAAJ,EAAY,UAAAC,CAAA,EAAcpH,EAChC+G,EACAS,CAAA,EAEIH,EAAY9B,EAChBgB,EAAM,GACNL,EACAN,EAAO,4BAAA,EAEH6B,EAAaR,EAAa,uBAC1BS,EACJP,EAAaE,GACZI,IAAe,QACdA,GAAcF,EAAmB,UAChCG,IACH,MAAMb,EAAS,OAAO,WAAY,CAChC,KAAMW,EACN,YAAa,WAAA,CACd,EACD,MAAMX,EAAS,OAAO,SAAU,CAC9B,KAAME,EACN,YAAa,WAAA,CACd,EACGK,GACF,MAAMP,EAAS,OAAO,OAAQ,CAC5B,KAAMO,EACN,YAAa,WAAA,CACd,EAEHP,EAAS,YAAY,KAAK,CACxB,KAAM,6BACN,YAAa,IAAIN,EAAM,EAAE,kDAAkDY,CAAU,iCAAiCE,CAAS,gHAAA,CAChI,GAEHC,EAAAA,OACG,KACCI,EACA,IAAInB,EAAM,EAAE,kDAAkDY,CAAU,iCAAiCE,CAAS,gHAAA,EAEnH,KAAK,EAAI,CACd,CAEJ,CAKA,MAAMpE,EAAoB3B,EAAWiF,EAAM,GAAI,IAAMU,CAAY,CACnE,CAAA,CAEJ"}
|
|
1
|
+
{"version":3,"file":"testing.cjs","sources":["../src/golden/diffPng.ts","../src/golden/validateManifest.ts","../src/golden/manifestStore.ts","../src/golden/resolveSourceOfTruthGolden.ts","../src/testing/runVisualRegression.ts"],"sourcesContent":["import pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\nexport interface PngDiffResult {\n /** Mismatched-pixel count, or `Infinity` if the two images aren't even the\n * same dimensions — pixelmatch itself throws on a size mismatch, and a size\n * mismatch is itself a real difference, not something to swallow. */\n diffPixels: number;\n /** Visual highlight of the mismatched pixels, encoded as a PNG buffer.\n * `null` when `diffPixels` is `Infinity` — there's no pixel-aligned diff to\n * render across two different-sized images. */\n diffImage: Buffer | null;\n}\n\n/** Pixel-diffs two PNG buffers. */\nexport function diffPngBuffers(a: Buffer, b: Buffer): PngDiffResult {\n const imgA = PNG.sync.read(a);\n const imgB = PNG.sync.read(b);\n if (imgA.width !== imgB.width || imgA.height !== imgB.height) {\n return { diffPixels: Infinity, diffImage: null };\n }\n const diff = new PNG({ width: imgA.width, height: imgA.height });\n const diffPixels = pixelmatch(\n imgA.data,\n imgB.data,\n diff.data,\n imgA.width,\n imgA.height,\n { threshold: 0.1 },\n );\n return { diffPixels, diffImage: PNG.sync.write(diff) };\n}\n","import { Ajv } from \"ajv\";\nimport * as ajvFormatsModule from \"ajv-formats\";\nimport type { FormatsPlugin } from \"ajv-formats\";\nimport schema from \"./manifest.schema.json\" with { type: \"json\" };\n\n// See validateFileConfig.ts for why `.default` has to be unwrapped by hand.\nconst addFormats = (ajvFormatsModule as unknown as { default: FormatsPlugin })\n .default;\n\nconst ajv = new Ajv({ allErrors: true, strict: true });\naddFormats(ajv);\nconst validate = ajv.compile(schema);\n\n/**\n * Validates a parsed `test/golden/manifest.json` against `manifest.schema.json`.\n * Throws with every violation listed — callers must not silently coerce or\n * drop invalid entries.\n */\nexport function validateGoldenManifest(data: unknown, path: string): void {\n if (validate(data)) return;\n\n const errors = (validate.errors ?? [])\n .map((error) => {\n const extra = error.params?.additionalProperty\n ? ` '${error.params.additionalProperty}'`\n : \"\";\n return ` - ${error.instancePath || \"root\"} ${error.message}${extra}`;\n })\n .join(\"\\n\");\n throw new Error(`Invalid ${path}:\\n${errors}`);\n}\n","import {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\nexport interface GoldenManifestEntry {\n createdAt: string;\n sourceOfTruthCreatedAt?: string;\n}\n\nexport type GoldenManifest = Record<string, GoldenManifestEntry>;\n\nexport function manifestPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json\");\n}\n\nfunction manifestLockPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json.lock\");\n}\n\nexport function goldenImagePath(goldenDir: string, storyId: string): string {\n return join(goldenDir, `${storyId}.png`);\n}\n\n/** Returns `{}` if no manifest exists yet — a fresh adapter with no goldens\n * captured is the normal starting state, not an error. */\nexport function loadManifest(goldenDir: string): GoldenManifest {\n const path = manifestPath(goldenDir);\n if (!existsSync(path)) return {};\n const data = JSON.parse(readFileSync(path, \"utf8\"));\n validateGoldenManifest(data, path);\n return data;\n}\n\n/** Validates before writing, and sorts keys so the diff on a reviewed PR is\n * stable regardless of the order stories happened to run in. Writes to a\n * temp file and renames over the real one — `rename` is atomic, so a\n * concurrent `loadManifest` (running in another Playwright worker) never\n * observes a half-written file. */\nexport function saveManifest(\n goldenDir: string,\n manifest: GoldenManifest,\n): void {\n const path = manifestPath(goldenDir);\n validateGoldenManifest(manifest, path);\n const sorted: GoldenManifest = {};\n for (const key of Object.keys(manifest).sort()) {\n sorted[key] = manifest[key]!;\n }\n mkdirSync(goldenDir, { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n writeFileSync(tmpPath, JSON.stringify(sorted, null, 2) + \"\\n\");\n renameSync(tmpPath, path);\n}\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_TIMEOUT_MS = 15_000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Exclusive-create the lock file, spin-retrying until it's free. `wx` fails\n * atomically (`EEXIST`) if another worker process already holds it — that's\n * the only signal we need, no third-party lock library required for a\n * same-machine, same-run lock like this. */\nasync function acquireManifestLock(goldenDir: string): Promise<void> {\n mkdirSync(goldenDir, { recursive: true });\n const path = manifestLockPath(goldenDir);\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n for (;;) {\n try {\n closeSync(openSync(path, \"wx\"));\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the manifest lock at \"${path}\" — delete it if a previous run crashed while holding it.`,\n );\n }\n await sleep(LOCK_RETRY_MS);\n }\n }\n}\n\nfunction releaseManifestLock(goldenDir: string): void {\n rmSync(manifestLockPath(goldenDir), { force: true });\n}\n\n/** Runs `updater` against this story's manifest entry under an exclusive\n * lock on `manifest.json`: reloads the manifest fresh, applies `updater`,\n * and saves it back, all before releasing the lock. Concurrent Playwright\n * workers each own a different story, so this is the only section that\n * needs to serialize — everything else about a story (its screenshot, its\n * golden image file, its diff) is independent of every other story. */\nexport async function updateManifestEntry(\n goldenDir: string,\n storyId: string,\n updater: (\n entry: GoldenManifestEntry | undefined,\n ) => GoldenManifestEntry | undefined,\n): Promise<GoldenManifestEntry | undefined> {\n await acquireManifestLock(goldenDir);\n try {\n const manifest = loadManifest(goldenDir);\n const nextEntry = updater(manifest[storyId]);\n if (nextEntry === undefined) {\n delete manifest[storyId];\n } else {\n manifest[storyId] = nextEntry;\n }\n saveManifest(goldenDir, manifest);\n return nextEntry;\n } finally {\n releaseManifestLock(goldenDir);\n }\n}\n\nexport function saveGoldenImage(\n goldenDir: string,\n storyId: string,\n buffer: Buffer,\n): void {\n mkdirSync(goldenDir, { recursive: true });\n writeFileSync(goldenImagePath(goldenDir, storyId), buffer);\n}\n\n/** Removes the golden `.png` + manifest entry for every story id in the\n * manifest that isn't in `currentStoryIds` (e.g. a story renamed or deleted\n * from Storybook) — otherwise those never get cleaned up on their own,\n * since a run only ever adds/updates entries for stories it actually saw.\n * Returns the pruned ids, for the caller to report. Both the file removal\n * and the manifest delete are idempotent, so it's safe for this to run\n * redundantly from more than one Playwright worker. */\nexport async function pruneOrphanedGoldens(\n goldenDir: string,\n currentStoryIds: ReadonlySet<string>,\n): Promise<string[]> {\n const manifest = loadManifest(goldenDir);\n const orphanIds = Object.keys(manifest).filter(\n (id) => !currentStoryIds.has(id),\n );\n for (const id of orphanIds) {\n const imagePath = goldenImagePath(goldenDir, id);\n if (existsSync(imagePath)) unlinkSync(imagePath);\n await updateManifestEntry(goldenDir, id, () => undefined);\n }\n return orphanIds;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SourceOfTruthGoldenLocation } from \"../config.js\";\nimport {\n goldenImagePath,\n loadManifest,\n manifestPath,\n type GoldenManifest,\n} from \"./manifestStore.js\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\n// The source-of-truth adapter (Mantine) lives in its own standalone repo, not\n// this monorepo — its golden images are fetched from here, not from borderux/recursica.\nconst GITHUB_REPO = \"borderux/recursica-adapter-mantine-v8\";\n\nexport interface SourceOfTruthGolden {\n manifest: GoldenManifest;\n /** Returns the golden PNG bytes for a story, or `null` if the source of\n * truth has no golden captured for it yet. */\n readImage(storyId: string): Promise<Buffer | null>;\n}\n\nasync function resolveNpmVersion(\n packageName: string,\n versionSpec: string,\n): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n if (!response.ok) {\n throw new Error(\n `Could not reach npm registry for ${packageName}: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, unknown>;\n };\n const resolved =\n data[\"dist-tags\"]?.[versionSpec] ??\n (data.versions?.[versionSpec] ? versionSpec : undefined);\n if (!resolved) {\n throw new Error(\n `${packageName} has no version or dist-tag \"${versionSpec}\" on the npm registry.`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves the source-of-truth adapter's golden images for the divergence\n * check. Never boots a Storybook — both location types resolve to plain\n * files, fetched once and cached, not re-diffed per pixel over the wire.\n *\n * `location.type === \"local\"`: a sibling package already checked out (this\n * monorepo's own `sourceOfTruth.type: \"url\"` mode) — read its\n * `test/golden/` directly, including any uncommitted local changes.\n *\n * `location.type === \"npm\"`: no local checkout (the default, standalone-repo\n * mode) — resolve the installed version against the npm registry, then fetch\n * that exact version's `test/golden/` from the public GitHub repo at the\n * matching release tag (changesets tags every release as\n * `<packageName>@<version>`), caching what's downloaded under `cacheDir`.\n *\n * Returns `null` — degrading the divergence check to a skip, not a failure —\n * when no golden baseline exists yet for this version, or the registry/repo\n * is unreachable.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden | null> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n console.warn(\n `No golden baseline found yet at ${location.dir} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\n }\n const manifest = loadManifest(location.dir);\n return {\n manifest,\n async readImage(storyId) {\n const path = goldenImagePath(location.dir, storyId);\n return existsSync(path) ? readFileSync(path) : null;\n },\n };\n }\n\n let version: string;\n try {\n version = await resolveNpmVersion(\n location.packageName,\n location.versionSpec,\n );\n } catch (error) {\n console.warn(\n `Could not resolve ${location.packageName}@${location.versionSpec} — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n\n const cacheDir = join(location.cacheDir, version);\n const tag = `${location.packageName}@${version}`;\n // @recursica/adapter-mantine-v8 is a standalone single-package repo (unlike\n // the old @recursica/mantine-adapter, which lived at `packages/<name>`\n // inside this monorepo) — its `test/golden/` sits directly at the repo root.\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/test/golden`;\n\n let manifest: GoldenManifest;\n const cachedManifestPath = manifestPath(cacheDir);\n if (existsSync(cachedManifestPath)) {\n manifest = loadManifest(cacheDir);\n } else {\n let response: Response;\n try {\n response = await fetch(`${rawBase}/manifest.json`);\n } catch (error) {\n console.warn(\n `Could not reach GitHub to fetch ${tag}'s golden baseline — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n if (!response.ok) {\n console.warn(\n `No golden baseline published for ${tag} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\n }\n const text = await response.text();\n const parsed = JSON.parse(text);\n validateGoldenManifest(parsed, `${rawBase}/manifest.json`);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedManifestPath, text);\n manifest = parsed;\n }\n\n return {\n manifest,\n async readImage(storyId) {\n const cachedImagePath = goldenImagePath(cacheDir, storyId);\n if (existsSync(cachedImagePath)) return readFileSync(cachedImagePath);\n const response = await fetch(`${rawBase}/${storyId}.png`);\n if (!response.ok) return null;\n const buffer = Buffer.from(await response.arrayBuffer());\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedImagePath, buffer);\n return buffer;\n },\n };\n}\n","import { expect } from \"@playwright/test\";\nimport type { Browser, TestInfo } from \"@playwright/test\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AdapterTesterConfig } from \"../config.js\";\nimport { diffPngBuffers } from \"../golden/diffPng.js\";\nimport {\n type GoldenManifestEntry,\n goldenImagePath,\n loadManifest,\n pruneOrphanedGoldens,\n saveGoldenImage,\n updateManifestEntry,\n} from \"../golden/manifestStore.js\";\nimport { resolveSourceOfTruthGolden } from \"../golden/resolveSourceOfTruthGolden.js\";\n\nconst DEFAULT_EXCLUDE_TITLE_PREFIXES = [\"Theme\", \"Tokens\", \"Introduction\"];\n\ninterface StorybookEntry {\n type: string;\n id: string;\n name: string;\n title: string;\n}\n\nfunction matchesPrefix(id: string, prefix: string): boolean {\n return id === prefix || id.startsWith(prefix);\n}\n\n/** Fetches every story `target`'s Storybook currently has, filtered only by\n * `excludeTitlePrefixes` — not `stories.<id>.exclude`, so callers can still\n * tell an excluded story apart from one that's genuinely missing. */\nasync function fetchStories(\n target: { name: string; url: string },\n excludeTitlePrefixes: string[],\n): Promise<StorybookEntry[]> {\n let stories: StorybookEntry[];\n try {\n const response = await fetch(`${target.url}/index.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Storybook index: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as any;\n const entries = data.entries || {};\n stories = Object.values(entries).filter(\n (entry: any) =>\n entry.type === \"story\" &&\n !excludeTitlePrefixes.some(\n (prefix) =>\n entry.title === prefix || entry.title.startsWith(`${prefix}/`),\n ),\n ) as StorybookEntry[];\n stories.sort((a, b) => a.id.localeCompare(b.id));\n } catch (error) {\n console.error(\n \"Failed to load Storybook index from\",\n `${target.url}/index.json`,\n error,\n );\n throw new Error(\n `Storybook target \"${target.name}\" is not responsive or index.json is missing. Please ensure its Storybook is running.`,\n );\n }\n return stories;\n}\n\n/** Resolves the diff threshold for `storyId`: the longest (most specific)\n * `storyThresholds` key matching by prefix, falling back to\n * `defaultThresholdPixels` when nothing matches. */\nfunction resolveThreshold(\n storyId: string,\n storyThresholds: Record<string, number>,\n defaultThresholdPixels: number,\n): number {\n let bestMatch: string | undefined;\n for (const prefix of Object.keys(storyThresholds)) {\n if (\n matchesPrefix(storyId, prefix) &&\n (!bestMatch || prefix.length > bestMatch.length)\n ) {\n bestMatch = prefix;\n }\n }\n return bestMatch !== undefined\n ? storyThresholds[bestMatch]!\n : defaultThresholdPixels;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Story ids the source-of-truth adapter has a golden for but this\n * project's own Storybook doesn't — empty outside `checkMode: \"divergence\"`\n * or when `sourceOfTruthGolden` didn't resolve. Excludes ids covered by a\n * `stories.<id>.exclude` entry: an intentional gap, not a sync failure. */\n missingFromSourceOfTruth: string[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/**\n * Resolves the golden-image plan for `config`'s own target (the one target\n * in `config.targets` not marked `sourceOfTruth`).\n *\n * Two independent checks per story, gated by `config.checkMode`. Neither\n * boots the source-of-truth adapter's own Storybook — its side of both\n * checks is always a stored golden file, never a live page:\n *\n * 1. **Own-drift (`checkMode: \"own\"`, the default; hard fail):** this run's\n * live render vs this project's own stored `test/golden/<story-id>.png`.\n * No golden yet for a story is not a failure — one is captured from this\n * run instead (same as `--update-golden`, scoped to just that story), in\n * either mode.\n * 2. **Source-of-truth divergence (`checkMode: \"divergence\"`; hard fail):**\n * this run's live render vs the source-of-truth's stored golden (`config`'s\n * `sourceOfTruthGolden`) — always fresh, no `--update-golden` step needed\n * first. Skipped entirely when `config.isSourceOfTruthAdapter` is true —\n * the source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when the source of truth has no baseline for it yet.\n * A once-flagged divergence stays quiet after `--approve-divergence`,\n * until the source of truth's own golden changes again.\n */\nexport async function resolveVisualRegressionPlan(\n config: AdapterTesterConfig,\n): Promise<VisualRegressionPlan> {\n const ownTarget = config.isSourceOfTruthAdapter\n ? config.targets[0]\n : config.targets.find((target) => !target.sourceOfTruth);\n if (!ownTarget) {\n throw new Error(\n \"adapter-tester config has no non-sourceOfTruth target to run the golden check against.\",\n );\n }\n const excludeTitlePrefixes =\n config.excludeTitlePrefixes ?? DEFAULT_EXCLUDE_TITLE_PREFIXES;\n const storyOverrides = config.stories ?? {};\n const excludeStoryIds = Object.keys(storyOverrides).filter(\n (id) => storyOverrides[id]!.exclude,\n );\n const goldenStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.goldenThreshold !== undefined)\n .map(([id, override]) => [id, override.goldenThreshold!]),\n );\n const sourceOfTruthStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.sourceOfTruthThreshold !== undefined)\n .map(([id, override]) => [id, override.sourceOfTruthThreshold!]),\n );\n const goldenDir = config.goldenDir;\n const goldenMode = config.goldenMode;\n const checkMode = config.checkMode;\n\n // Fetched with only excludeTitlePrefixes applied — not excludeStoryIds —\n // so the source-of-truth story-parity check below can tell an excluded\n // story apart from one that's genuinely missing from this Storybook.\n const ownStories = await fetchStories(ownTarget, excludeTitlePrefixes);\n const stories = ownStories.filter(\n (entry) =>\n !excludeStoryIds.some((prefix) => matchesPrefix(entry.id, prefix)),\n );\n\n // `--update-golden` redefines this project's own baseline, so it's also\n // the point a renamed/removed story's now-orphaned golden gets cleaned up\n // — otherwise nothing ever prunes it, since a run only ever adds/updates\n // entries for stories it actually saw in this pass. Uses the full current\n // story list (not narrowed by any `--grep` Playwright itself applies), so\n // this catches every orphan regardless of how the run is scoped.\n if (goldenMode === \"update-golden\") {\n const prunedStoryIds = await pruneOrphanedGoldens(\n goldenDir,\n new Set(stories.map((story) => story.id)),\n );\n if (prunedStoryIds.length > 0) {\n console.warn(\n `Pruned ${prunedStoryIds.length} orphaned golden(s) no longer in Storybook: ${prunedStoryIds.join(\", \")}`,\n );\n }\n }\n\n const sourceOfTruthGolden =\n checkMode !== \"divergence\" ||\n config.isSourceOfTruthAdapter ||\n !config.sourceOfTruthGolden\n ? null\n : await resolveSourceOfTruthGolden(config.sourceOfTruthGolden);\n\n // Checked against `ownStories` (title-prefix-excluded only), not `stories`\n // — a story marked `exclude: true` still counts as \"present\", it's just\n // not diffed. Only a story the source of truth has that this adapter\n // never built at all, and hasn't acknowledged via `exclude`, is missing.\n const ownStoryIds = new Set(ownStories.map((entry) => entry.id));\n const missingFromSourceOfTruth = sourceOfTruthGolden\n ? Object.keys(sourceOfTruthGolden.manifest)\n .filter(\n (id) =>\n !ownStoryIds.has(id) &&\n !excludeStoryIds.some((prefix) => matchesPrefix(id, prefix)),\n )\n .sort()\n : [];\n\n if (missingFromSourceOfTruth.length > 0) {\n console.error(\n `[adapter-tester] ${missingFromSourceOfTruth.length} stor(y/ies) exist in the source of truth but are missing here: ${missingFromSourceOfTruth.join(\", \")}. Add the missing story, or mark it \\`exclude: true\\` under \\`stories\\` in adapter-tester.config.json if intentional.`,\n );\n }\n\n console.log(\n [\n `[adapter-tester] target: \"${ownTarget.name}\" (${ownTarget.url})`,\n `[adapter-tester] checkMode: \"${checkMode}\" (${checkMode === \"divergence\" ? \"live render vs source-of-truth's golden\" : \"live render vs this project's own golden\"})`,\n `[adapter-tester] goldenMode: \"${goldenMode}\"`,\n `[adapter-tester] goldenThresholdPixels: ${config.goldenThresholdPixels}`,\n `[adapter-tester] sourceOfTruthThresholdPixels: ${config.sourceOfTruthThresholdPixels}`,\n checkMode === \"divergence\"\n ? config.isSourceOfTruthAdapter\n ? `[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from`\n : !config.sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured`\n : sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(sourceOfTruthGolden.manifest).length} golden(s) available (config: ${JSON.stringify(config.sourceOfTruthGolden)})`\n : `[adapter-tester] sourceOfTruthGolden: unavailable — no baseline found or unreachable (config: ${JSON.stringify(config.sourceOfTruthGolden)}); divergence check will skip every story`\n : `[adapter-tester] sourceOfTruthGolden: not used in \"own\" checkMode`,\n `[adapter-tester] stories: ${stories.length} to check (excluded: ${excludeStoryIds.length}, title prefixes excluded: ${excludeTitlePrefixes.join(\", \") || \"none\"})`,\n `[adapter-tester] story parity with source of truth: ${missingFromSourceOfTruth.length === 0 ? \"OK\" : `${missingFromSourceOfTruth.length} missing (see error above)`}`,\n ].join(\"\\n\"),\n );\n\n const suiteLabel =\n checkMode === \"divergence\"\n ? \"Source-of-Truth Divergence Check\"\n : \"Own-Drift Golden Image Check\";\n\n return {\n ownTargetName: ownTarget.name,\n suiteLabel,\n stories,\n missingFromSourceOfTruth,\n checkStory: async (story, browser, testInfo) => {\n const page = await browser.newPage();\n await page.setViewportSize({ width: 800, height: 600 });\n await page.goto(\n `${ownTarget.url}/iframe.html?id=${story.id}&viewMode=story`,\n { waitUntil: \"networkidle\" },\n );\n await page.waitForSelector(\"#storybook-root\");\n await page.addStyleTag({\n content: `* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }`,\n });\n // Web fonts (e.g. `withRecursicaFonts`'s Google Fonts `<link>`s, injected\n // from a React effect after this page's `networkidle` already fired) can\n // still be mid-download here. Wait for any `<link>` stylesheet that's\n // still loading to settle — so the browser has parsed its `@font-face`\n // rules and started the actual font-file fetches `document.fonts.ready`\n // below needs to know about — then for the fonts themselves. Without\n // this, the very first golden capture of a newly-introduced font family\n // is a coin flip between the real font and its fallback, depending on\n // how fast the network happens to be.\n await page.evaluate(() =>\n Promise.all(\n Array.from(\n document.querySelectorAll<HTMLLinkElement>(\n 'link[rel=\"stylesheet\"]',\n ),\n ).map((link) =>\n link.sheet\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n link.addEventListener(\"load\", () => resolve(), {\n once: true,\n });\n link.addEventListener(\"error\", () => resolve(), {\n once: true,\n });\n }),\n ),\n ).then(() => document.fonts.ready),\n );\n await page.waitForTimeout(300);\n const liveBuffer = await page.screenshot();\n\n const imagePath = goldenImagePath(goldenDir, story.id);\n // Only this worker ever touches this story's key, so reading it here\n // (outside the lock `updateManifestEntry` takes at the end) can't\n // race another worker — they're all reading/writing different keys.\n const entry = loadManifest(goldenDir)[story.id];\n const capturingNewGolden =\n goldenMode !== \"check\" || !entry || !existsSync(imagePath);\n\n let currentEntry: GoldenManifestEntry;\n if (capturingNewGolden) {\n saveGoldenImage(goldenDir, story.id, liveBuffer);\n currentEntry = entry?.sourceOfTruthCreatedAt\n ? {\n createdAt: new Date().toISOString(),\n sourceOfTruthCreatedAt: entry.sourceOfTruthCreatedAt,\n }\n : { createdAt: new Date().toISOString() };\n if (!entry) {\n testInfo.annotations.push({\n type: \"golden-created\",\n description: `No golden existed yet for \"${story.id}\" — captured one from this run.`,\n });\n }\n } else {\n currentEntry = entry;\n if (checkMode === \"own\") {\n const goldenBuffer = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n goldenBuffer,\n );\n const threshold = resolveThreshold(\n story.id,\n goldenStoryThresholds,\n config.goldenThresholdPixels,\n );\n if (diffPixels >= threshold) {\n await testInfo.attach(\"expected\", {\n body: goldenBuffer,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n }\n expect\n .soft(\n diffPixels,\n `\"${story.id}\" has drifted from its own golden image (${diffPixels} mismatched pixels, threshold ${threshold})`,\n )\n .toBeLessThan(threshold);\n }\n }\n\n if (sourceOfTruthGolden) {\n const sourceOfTruthEntry = sourceOfTruthGolden.manifest[story.id];\n const sourceOfTruthImage = sourceOfTruthEntry\n ? await sourceOfTruthGolden.readImage(story.id)\n : null;\n\n if (sourceOfTruthEntry && sourceOfTruthImage) {\n if (goldenMode === \"approve-divergence\") {\n currentEntry = {\n ...currentEntry,\n sourceOfTruthCreatedAt: sourceOfTruthEntry.createdAt,\n };\n } else {\n // Always this run's live render, never the stored own-drift\n // golden — divergence should reflect what's on screen right now,\n // not whatever was last captured via --update-golden.\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n sourceOfTruthImage,\n );\n const threshold = resolveThreshold(\n story.id,\n sourceOfTruthStoryThresholds,\n config.sourceOfTruthThresholdPixels,\n );\n const approvedAt = currentEntry.sourceOfTruthCreatedAt;\n const isKnownDivergence =\n diffPixels < threshold ||\n (approvedAt !== undefined &&\n approvedAt >= sourceOfTruthEntry.createdAt);\n if (!isKnownDivergence) {\n await testInfo.attach(\"expected\", {\n body: sourceOfTruthImage,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n testInfo.annotations.push({\n type: \"source-of-truth-divergence\",\n description: `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n });\n }\n expect\n .soft(\n isKnownDivergence,\n `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n )\n .toBe(true);\n }\n }\n }\n\n // Locked read-modify-write of just this story's entry — see\n // `updateManifestEntry` for why that's enough to make this safe\n // across concurrent Playwright workers.\n await updateManifestEntry(goldenDir, story.id, () => currentEntry);\n },\n };\n}\n"],"names":["diffPngBuffers","a","b","imgA","PNG","imgB","diff","pixelmatch","addFormats","ajvFormatsModule.default","ajv","Ajv","validate","schema","validateGoldenManifest","data","path","errors","error","extra","_a","manifestPath","goldenDir","join","manifestLockPath","goldenImagePath","storyId","loadManifest","existsSync","readFileSync","saveManifest","manifest","sorted","key","mkdirSync","tmpPath","writeFileSync","renameSync","LOCK_RETRY_MS","LOCK_TIMEOUT_MS","sleep","ms","resolve","acquireManifestLock","deadline","closeSync","openSync","releaseManifestLock","rmSync","updateManifestEntry","updater","nextEntry","saveGoldenImage","buffer","pruneOrphanedGoldens","currentStoryIds","orphanIds","id","imagePath","unlinkSync","GITHUB_REPO","resolveNpmVersion","packageName","versionSpec","response","resolved","_b","resolveSourceOfTruthGolden","location","version","cacheDir","tag","rawBase","cachedManifestPath","text","parsed","cachedImagePath","DEFAULT_EXCLUDE_TITLE_PREFIXES","matchesPrefix","prefix","fetchStories","target","excludeTitlePrefixes","stories","entries","entry","resolveThreshold","storyThresholds","defaultThresholdPixels","bestMatch","resolveVisualRegressionPlan","config","ownTarget","storyOverrides","excludeStoryIds","goldenStoryThresholds","override","sourceOfTruthStoryThresholds","goldenMode","checkMode","ownStories","prunedStoryIds","story","sourceOfTruthGolden","ownStoryIds","missingFromSourceOfTruth","suiteLabel","browser","testInfo","page","link","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","approvedAt","isKnownDivergence"],"mappings":"6OAeO,SAASA,EAAeC,EAAWC,EAA0B,CAClE,MAAMC,EAAOC,EAAAA,IAAI,KAAK,KAAKH,CAAC,EACtBI,EAAOD,EAAAA,IAAI,KAAK,KAAKF,CAAC,EAC5B,GAAIC,EAAK,QAAUE,EAAK,OAASF,EAAK,SAAWE,EAAK,OACpD,MAAO,CAAE,WAAY,IAAU,UAAW,IAAA,EAE5C,MAAMC,EAAO,IAAIF,EAAAA,IAAI,CAAE,MAAOD,EAAK,MAAO,OAAQA,EAAK,OAAQ,EAS/D,MAAO,CAAE,WARUI,EACjBJ,EAAK,KACLE,EAAK,KACLC,EAAK,KACLH,EAAK,MACLA,EAAK,OACL,CAAE,UAAW,EAAA,CAAI,EAEE,UAAWC,EAAAA,IAAI,KAAK,MAAME,CAAI,CAAA,CACrD,irCCzBME,GAAcC,E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G,KACCI,EACA,IAAIpB,EAAM,EAAE,kDAAkDa,CAAU,iCAAiCE,CAAS,gHAAA,EAEnH,KAAK,EAAI,CACd,CAEJ,CAKA,MAAMpE,EAAoB3B,EAAWgF,EAAM,GAAI,IAAMW,CAAY,CACnE,CAAA,CAEJ"}
|
package/dist/testing.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { expect as D } from "@playwright/test";
|
|
2
|
-
import { existsSync as
|
|
2
|
+
import { existsSync as v, unlinkSync as H, readFileSync as E, mkdirSync as b, writeFileSync as A, closeSync as Y, openSync as Q, renameSync as Z, rmSync as ee } from "node:fs";
|
|
3
3
|
import te from "pixelmatch";
|
|
4
|
-
import { PNG as
|
|
4
|
+
import { PNG as j } from "pngjs";
|
|
5
5
|
import { join as M } from "node:path";
|
|
6
6
|
import { a as re, i as oe } from "./index-DqQzFSAH.js";
|
|
7
7
|
function J(e, t) {
|
|
8
|
-
const o =
|
|
8
|
+
const o = j.sync.read(e), r = j.sync.read(t);
|
|
9
9
|
if (o.width !== r.width || o.height !== r.height)
|
|
10
10
|
return { diffPixels: 1 / 0, diffImage: null };
|
|
11
|
-
const s = new
|
|
11
|
+
const s = new j({ width: o.width, height: o.height });
|
|
12
12
|
return { diffPixels: te(
|
|
13
13
|
o.data,
|
|
14
14
|
r.data,
|
|
@@ -16,7 +16,7 @@ function J(e, t) {
|
|
|
16
16
|
o.width,
|
|
17
17
|
o.height,
|
|
18
18
|
{ threshold: 0.1 }
|
|
19
|
-
), diffImage:
|
|
19
|
+
), diffImage: j.sync.write(s) };
|
|
20
20
|
}
|
|
21
21
|
const ne = "http://json-schema.org/draft-07/schema#", se = "https://github.com/borderux/recursica/tree/main/packages/adapter-tester/src/golden/manifest.schema.json", ie = "test/golden/manifest.json", ae = "Tracks golden (baseline) image metadata for @recursica/adapter-tester's golden-image visual regression checks. One manifest lives alongside its adapter's test/golden/<story-id>.png files, keyed by story id.", ce = "object", de = { type: "object", additionalProperties: !1, required: ["createdAt"], properties: { createdAt: { type: "string", format: "date-time", description: "When this story's own golden PNG was last captured, via --update-golden, --approve-divergence, or first-run auto-create." }, sourceOfTruthCreatedAt: { type: "string", format: "date-time", description: "The source-of-truth adapter's (mantine) manifest `createdAt` for this story at the time this adapter's divergence from it was last reviewed via --approve-divergence. Omitted on the source-of-truth adapter's own manifest, and omitted here until the first approval. If mantine's current `createdAt` for this story is newer than this value, the divergence is flagged again for re-review." } } }, he = {
|
|
22
22
|
$schema: ne,
|
|
@@ -28,7 +28,7 @@ const ne = "http://json-schema.org/draft-07/schema#", se = "https://github.com/b
|
|
|
28
28
|
}, ue = oe, K = new re.Ajv({ allErrors: !0, strict: !0 });
|
|
29
29
|
ue(K);
|
|
30
30
|
const R = K.compile(he);
|
|
31
|
-
function
|
|
31
|
+
function L(e, t) {
|
|
32
32
|
if (R(e)) return;
|
|
33
33
|
const o = (R.errors ?? []).map((r) => {
|
|
34
34
|
var i;
|
|
@@ -42,21 +42,21 @@ ${o}`);
|
|
|
42
42
|
function G(e) {
|
|
43
43
|
return M(e, "manifest.json");
|
|
44
44
|
}
|
|
45
|
-
function
|
|
45
|
+
function q(e) {
|
|
46
46
|
return M(e, "manifest.json.lock");
|
|
47
47
|
}
|
|
48
48
|
function S(e, t) {
|
|
49
49
|
return M(e, `${t}.png`);
|
|
50
50
|
}
|
|
51
|
-
function
|
|
51
|
+
function P(e) {
|
|
52
52
|
const t = G(e);
|
|
53
|
-
if (!
|
|
53
|
+
if (!v(t)) return {};
|
|
54
54
|
const o = JSON.parse(E(t, "utf8"));
|
|
55
|
-
return
|
|
55
|
+
return L(o, t), o;
|
|
56
56
|
}
|
|
57
57
|
function le(e, t) {
|
|
58
58
|
const o = G(e);
|
|
59
|
-
|
|
59
|
+
L(t, o);
|
|
60
60
|
const r = {};
|
|
61
61
|
for (const i of Object.keys(t).sort())
|
|
62
62
|
r[i] = t[i];
|
|
@@ -66,12 +66,12 @@ function le(e, t) {
|
|
|
66
66
|
`), Z(s, o);
|
|
67
67
|
}
|
|
68
68
|
const fe = 25, pe = 15e3;
|
|
69
|
-
function
|
|
69
|
+
function me(e) {
|
|
70
70
|
return new Promise((t) => setTimeout(t, e));
|
|
71
71
|
}
|
|
72
|
-
async function
|
|
72
|
+
async function ge(e) {
|
|
73
73
|
b(e, { recursive: !0 });
|
|
74
|
-
const t =
|
|
74
|
+
const t = q(e), o = Date.now() + pe;
|
|
75
75
|
for (; ; )
|
|
76
76
|
try {
|
|
77
77
|
Y(Q(t, "wx"));
|
|
@@ -82,16 +82,16 @@ async function me(e) {
|
|
|
82
82
|
throw new Error(
|
|
83
83
|
`Timed out waiting for the manifest lock at "${t}" — delete it if a previous run crashed while holding it.`
|
|
84
84
|
);
|
|
85
|
-
await
|
|
85
|
+
await me(fe);
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
function we(e) {
|
|
89
|
-
ee(
|
|
89
|
+
ee(q(e), { force: !0 });
|
|
90
90
|
}
|
|
91
|
-
async function
|
|
92
|
-
await
|
|
91
|
+
async function V(e, t, o) {
|
|
92
|
+
await ge(e);
|
|
93
93
|
try {
|
|
94
|
-
const r =
|
|
94
|
+
const r = P(e), s = o(r[t]);
|
|
95
95
|
return s === void 0 ? delete r[t] : r[t] = s, le(e, r), s;
|
|
96
96
|
} finally {
|
|
97
97
|
we(e);
|
|
@@ -101,17 +101,17 @@ function ye(e, t, o) {
|
|
|
101
101
|
b(e, { recursive: !0 }), A(S(e, t), o);
|
|
102
102
|
}
|
|
103
103
|
async function ve(e, t) {
|
|
104
|
-
const o =
|
|
104
|
+
const o = P(e), r = Object.keys(o).filter(
|
|
105
105
|
(s) => !t.has(s)
|
|
106
106
|
);
|
|
107
107
|
for (const s of r) {
|
|
108
108
|
const i = S(e, s);
|
|
109
|
-
|
|
109
|
+
v(i) && H(i), await V(e, s, () => {
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
112
|
return r;
|
|
113
113
|
}
|
|
114
|
-
const Te = "borderux/recursica";
|
|
114
|
+
const Te = "borderux/recursica-adapter-mantine-v8";
|
|
115
115
|
async function $e(e, t) {
|
|
116
116
|
var i, d;
|
|
117
117
|
const o = await fetch(`https://registry.npmjs.org/${e}`);
|
|
@@ -126,16 +126,13 @@ async function $e(e, t) {
|
|
|
126
126
|
);
|
|
127
127
|
return s;
|
|
128
128
|
}
|
|
129
|
-
function Oe(e) {
|
|
130
|
-
return `packages/${e.split("/").pop()}`;
|
|
131
|
-
}
|
|
132
|
-
async function ke(e) {
|
|
129
|
+
async function Oe(e) {
|
|
133
130
|
if (e.type === "local")
|
|
134
|
-
return
|
|
135
|
-
manifest:
|
|
131
|
+
return v(G(e.dir)) ? {
|
|
132
|
+
manifest: P(e.dir),
|
|
136
133
|
async readImage(h) {
|
|
137
134
|
const c = S(e.dir, h);
|
|
138
|
-
return
|
|
135
|
+
return v(c) ? E(c) : null;
|
|
139
136
|
}
|
|
140
137
|
} : (console.warn(
|
|
141
138
|
`No golden baseline found yet at ${e.dir} — source-of-truth divergence check skipped for this run.`
|
|
@@ -152,19 +149,19 @@ async function ke(e) {
|
|
|
152
149
|
a
|
|
153
150
|
), null;
|
|
154
151
|
}
|
|
155
|
-
const o = M(e.cacheDir, t), r = `${e.packageName}@${t}`, s = `https://raw.githubusercontent.com/${Te}/${r}
|
|
152
|
+
const o = M(e.cacheDir, t), r = `${e.packageName}@${t}`, s = `https://raw.githubusercontent.com/${Te}/${r}/test/golden`;
|
|
156
153
|
let i;
|
|
157
154
|
const d = G(o);
|
|
158
|
-
if (
|
|
159
|
-
i =
|
|
155
|
+
if (v(d))
|
|
156
|
+
i = P(o);
|
|
160
157
|
else {
|
|
161
158
|
let a;
|
|
162
159
|
try {
|
|
163
160
|
a = await fetch(`${s}/manifest.json`);
|
|
164
|
-
} catch (
|
|
161
|
+
} catch (m) {
|
|
165
162
|
return console.warn(
|
|
166
163
|
`Could not reach GitHub to fetch ${r}'s golden baseline — source-of-truth divergence check skipped for this run.`,
|
|
167
|
-
|
|
164
|
+
m
|
|
168
165
|
), null;
|
|
169
166
|
}
|
|
170
167
|
if (!a.ok)
|
|
@@ -172,25 +169,25 @@ async function ke(e) {
|
|
|
172
169
|
`No golden baseline published for ${r} — source-of-truth divergence check skipped for this run.`
|
|
173
170
|
), null;
|
|
174
171
|
const h = await a.text(), c = JSON.parse(h);
|
|
175
|
-
|
|
172
|
+
L(c, `${s}/manifest.json`), b(o, { recursive: !0 }), A(d, h), i = c;
|
|
176
173
|
}
|
|
177
174
|
return {
|
|
178
175
|
manifest: i,
|
|
179
176
|
async readImage(a) {
|
|
180
177
|
const h = S(o, a);
|
|
181
|
-
if (
|
|
178
|
+
if (v(h)) return E(h);
|
|
182
179
|
const c = await fetch(`${s}/${a}.png`);
|
|
183
180
|
if (!c.ok) return null;
|
|
184
|
-
const
|
|
185
|
-
return b(o, { recursive: !0 }), A(h,
|
|
181
|
+
const m = Buffer.from(await c.arrayBuffer());
|
|
182
|
+
return b(o, { recursive: !0 }), A(h, m), m;
|
|
186
183
|
}
|
|
187
184
|
};
|
|
188
185
|
}
|
|
189
|
-
const
|
|
186
|
+
const ke = ["Theme", "Tokens", "Introduction"];
|
|
190
187
|
function N(e, t) {
|
|
191
188
|
return e === t || e.startsWith(t);
|
|
192
189
|
}
|
|
193
|
-
async function
|
|
190
|
+
async function xe(e, t) {
|
|
194
191
|
let o;
|
|
195
192
|
try {
|
|
196
193
|
const r = await fetch(`${e.url}/index.json`);
|
|
@@ -221,19 +218,19 @@ function U(e, t, o) {
|
|
|
221
218
|
N(e, s) && (!r || s.length > r.length) && (r = s);
|
|
222
219
|
return r !== void 0 ? t[r] : o;
|
|
223
220
|
}
|
|
224
|
-
async function
|
|
221
|
+
async function Ge(e) {
|
|
225
222
|
const t = e.isSourceOfTruthAdapter ? e.targets[0] : e.targets.find((n) => !n.sourceOfTruth);
|
|
226
223
|
if (!t)
|
|
227
224
|
throw new Error(
|
|
228
225
|
"adapter-tester config has no non-sourceOfTruth target to run the golden check against."
|
|
229
226
|
);
|
|
230
|
-
const o = e.excludeTitlePrefixes ??
|
|
227
|
+
const o = e.excludeTitlePrefixes ?? ke, r = e.stories ?? {}, s = Object.keys(r).filter(
|
|
231
228
|
(n) => r[n].exclude
|
|
232
229
|
), i = Object.fromEntries(
|
|
233
230
|
Object.entries(r).filter(([, n]) => n.goldenThreshold !== void 0).map(([n, u]) => [n, u.goldenThreshold])
|
|
234
231
|
), d = Object.fromEntries(
|
|
235
232
|
Object.entries(r).filter(([, n]) => n.sourceOfTruthThreshold !== void 0).map(([n, u]) => [n, u.sourceOfTruthThreshold])
|
|
236
|
-
), a = e.goldenDir, h = e.goldenMode, c = e.checkMode,
|
|
233
|
+
), a = e.goldenDir, h = e.goldenMode, c = e.checkMode, m = await xe(t, o), I = m.filter(
|
|
237
234
|
(n) => !s.some((u) => N(n.id, u))
|
|
238
235
|
);
|
|
239
236
|
if (h === "update-golden") {
|
|
@@ -245,11 +242,11 @@ async function Me(e) {
|
|
|
245
242
|
`Pruned ${n.length} orphaned golden(s) no longer in Storybook: ${n.join(", ")}`
|
|
246
243
|
);
|
|
247
244
|
}
|
|
248
|
-
const
|
|
249
|
-
(n) => !
|
|
245
|
+
const g = c !== "divergence" || e.isSourceOfTruthAdapter || !e.sourceOfTruthGolden ? null : await Oe(e.sourceOfTruthGolden), W = new Set(m.map((n) => n.id)), T = g ? Object.keys(g.manifest).filter(
|
|
246
|
+
(n) => !W.has(n) && !s.some((u) => N(n, u))
|
|
250
247
|
).sort() : [];
|
|
251
|
-
|
|
252
|
-
`[adapter-tester] ${
|
|
248
|
+
T.length > 0 && console.error(
|
|
249
|
+
`[adapter-tester] ${T.length} stor(y/ies) exist in the source of truth but are missing here: ${T.join(", ")}. Add the missing story, or mark it \`exclude: true\` under \`stories\` in adapter-tester.config.json if intentional.`
|
|
253
250
|
), console.log(
|
|
254
251
|
[
|
|
255
252
|
`[adapter-tester] target: "${t.name}" (${t.url})`,
|
|
@@ -257,86 +254,102 @@ async function Me(e) {
|
|
|
257
254
|
`[adapter-tester] goldenMode: "${h}"`,
|
|
258
255
|
`[adapter-tester] goldenThresholdPixels: ${e.goldenThresholdPixels}`,
|
|
259
256
|
`[adapter-tester] sourceOfTruthThresholdPixels: ${e.sourceOfTruthThresholdPixels}`,
|
|
260
|
-
c === "divergence" ? e.isSourceOfTruthAdapter ? "[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from" : e.sourceOfTruthGolden ?
|
|
257
|
+
c === "divergence" ? e.isSourceOfTruthAdapter ? "[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from" : e.sourceOfTruthGolden ? g ? `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(g.manifest).length} golden(s) available (config: ${JSON.stringify(e.sourceOfTruthGolden)})` : `[adapter-tester] sourceOfTruthGolden: unavailable — no baseline found or unreachable (config: ${JSON.stringify(e.sourceOfTruthGolden)}); divergence check will skip every story` : "[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured" : '[adapter-tester] sourceOfTruthGolden: not used in "own" checkMode',
|
|
261
258
|
`[adapter-tester] stories: ${I.length} to check (excluded: ${s.length}, title prefixes excluded: ${o.join(", ") || "none"})`,
|
|
262
|
-
`[adapter-tester] story parity with source of truth: ${
|
|
259
|
+
`[adapter-tester] story parity with source of truth: ${T.length === 0 ? "OK" : `${T.length} missing (see error above)`}`
|
|
263
260
|
].join(`
|
|
264
261
|
`)
|
|
265
262
|
);
|
|
266
|
-
const
|
|
263
|
+
const X = c === "divergence" ? "Source-of-Truth Divergence Check" : "Own-Drift Golden Image Check";
|
|
267
264
|
return {
|
|
268
265
|
ownTargetName: t.name,
|
|
269
|
-
suiteLabel:
|
|
266
|
+
suiteLabel: X,
|
|
270
267
|
stories: I,
|
|
271
|
-
missingFromSourceOfTruth:
|
|
272
|
-
checkStory: async (n, u,
|
|
273
|
-
const
|
|
274
|
-
await
|
|
268
|
+
missingFromSourceOfTruth: T,
|
|
269
|
+
checkStory: async (n, u, p) => {
|
|
270
|
+
const w = await u.newPage();
|
|
271
|
+
await w.setViewportSize({ width: 800, height: 600 }), await w.goto(
|
|
275
272
|
`${t.url}/iframe.html?id=${n.id}&viewMode=story`,
|
|
276
273
|
{ waitUntil: "networkidle" }
|
|
277
|
-
), await
|
|
274
|
+
), await w.waitForSelector("#storybook-root"), await w.addStyleTag({
|
|
278
275
|
content: "* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }"
|
|
279
|
-
}), await
|
|
280
|
-
|
|
276
|
+
}), await w.evaluate(
|
|
277
|
+
() => Promise.all(
|
|
278
|
+
Array.from(
|
|
279
|
+
document.querySelectorAll(
|
|
280
|
+
'link[rel="stylesheet"]'
|
|
281
|
+
)
|
|
282
|
+
).map(
|
|
283
|
+
(l) => l.sheet ? Promise.resolve() : new Promise((f) => {
|
|
284
|
+
l.addEventListener("load", () => f(), {
|
|
285
|
+
once: !0
|
|
286
|
+
}), l.addEventListener("error", () => f(), {
|
|
287
|
+
once: !0
|
|
288
|
+
});
|
|
289
|
+
})
|
|
290
|
+
)
|
|
291
|
+
).then(() => document.fonts.ready)
|
|
292
|
+
), await w.waitForTimeout(300);
|
|
293
|
+
const x = await w.screenshot(), B = S(a, n.id), y = P(a)[n.id], z = h !== "check" || !y || !v(B);
|
|
281
294
|
let $;
|
|
282
295
|
if (z)
|
|
283
|
-
ye(a, n.id, x), $ =
|
|
296
|
+
ye(a, n.id, x), $ = y != null && y.sourceOfTruthCreatedAt ? {
|
|
284
297
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
285
|
-
sourceOfTruthCreatedAt:
|
|
286
|
-
} : { createdAt: (/* @__PURE__ */ new Date()).toISOString() },
|
|
298
|
+
sourceOfTruthCreatedAt: y.sourceOfTruthCreatedAt
|
|
299
|
+
} : { createdAt: (/* @__PURE__ */ new Date()).toISOString() }, y || p.annotations.push({
|
|
287
300
|
type: "golden-created",
|
|
288
301
|
description: `No golden existed yet for "${n.id}" — captured one from this run.`
|
|
289
302
|
});
|
|
290
|
-
else if ($ =
|
|
291
|
-
const
|
|
303
|
+
else if ($ = y, c === "own") {
|
|
304
|
+
const l = E(B), { diffPixels: f, diffImage: O } = J(
|
|
292
305
|
x,
|
|
293
|
-
|
|
306
|
+
l
|
|
294
307
|
), k = U(
|
|
295
308
|
n.id,
|
|
296
309
|
i,
|
|
297
310
|
e.goldenThresholdPixels
|
|
298
311
|
);
|
|
299
|
-
|
|
300
|
-
body:
|
|
312
|
+
f >= k && (await p.attach("expected", {
|
|
313
|
+
body: l,
|
|
301
314
|
contentType: "image/png"
|
|
302
|
-
}), await
|
|
315
|
+
}), await p.attach("actual", {
|
|
303
316
|
body: x,
|
|
304
317
|
contentType: "image/png"
|
|
305
|
-
}), O && await
|
|
318
|
+
}), O && await p.attach("diff", {
|
|
306
319
|
body: O,
|
|
307
320
|
contentType: "image/png"
|
|
308
321
|
})), D.soft(
|
|
309
|
-
|
|
310
|
-
`"${n.id}" has drifted from its own golden image (${
|
|
322
|
+
f,
|
|
323
|
+
`"${n.id}" has drifted from its own golden image (${f} mismatched pixels, threshold ${k})`
|
|
311
324
|
).toBeLessThan(k);
|
|
312
325
|
}
|
|
313
|
-
if (
|
|
314
|
-
const
|
|
315
|
-
if (
|
|
326
|
+
if (g) {
|
|
327
|
+
const l = g.manifest[n.id], f = l ? await g.readImage(n.id) : null;
|
|
328
|
+
if (l && f)
|
|
316
329
|
if (h === "approve-divergence")
|
|
317
330
|
$ = {
|
|
318
331
|
...$,
|
|
319
|
-
sourceOfTruthCreatedAt:
|
|
332
|
+
sourceOfTruthCreatedAt: l.createdAt
|
|
320
333
|
};
|
|
321
334
|
else {
|
|
322
335
|
const { diffPixels: O, diffImage: k } = J(
|
|
323
336
|
x,
|
|
324
|
-
|
|
337
|
+
f
|
|
325
338
|
), C = U(
|
|
326
339
|
n.id,
|
|
327
340
|
d,
|
|
328
341
|
e.sourceOfTruthThresholdPixels
|
|
329
|
-
),
|
|
330
|
-
_ || (await
|
|
331
|
-
body:
|
|
342
|
+
), F = $.sourceOfTruthCreatedAt, _ = O < C || F !== void 0 && F >= l.createdAt;
|
|
343
|
+
_ || (await p.attach("expected", {
|
|
344
|
+
body: f,
|
|
332
345
|
contentType: "image/png"
|
|
333
|
-
}), await
|
|
346
|
+
}), await p.attach("actual", {
|
|
334
347
|
body: x,
|
|
335
348
|
contentType: "image/png"
|
|
336
|
-
}), k && await
|
|
349
|
+
}), k && await p.attach("diff", {
|
|
337
350
|
body: k,
|
|
338
351
|
contentType: "image/png"
|
|
339
|
-
}),
|
|
352
|
+
}), p.annotations.push({
|
|
340
353
|
type: "source-of-truth-divergence",
|
|
341
354
|
description: `"${n.id}" differs from the source of truth's golden by ${O} mismatched pixels (threshold ${C}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`
|
|
342
355
|
})), D.soft(
|
|
@@ -345,11 +358,11 @@ async function Me(e) {
|
|
|
345
358
|
).toBe(!0);
|
|
346
359
|
}
|
|
347
360
|
}
|
|
348
|
-
await
|
|
361
|
+
await V(a, n.id, () => $);
|
|
349
362
|
}
|
|
350
363
|
};
|
|
351
364
|
}
|
|
352
365
|
export {
|
|
353
|
-
|
|
366
|
+
Ge as resolveVisualRegressionPlan
|
|
354
367
|
};
|
|
355
368
|
//# sourceMappingURL=testing.js.map
|