uidex 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/cli.cjs +1273 -343
- package/dist/cli/cli.cjs.map +1 -1
- package/dist/headless/index.cjs +3 -0
- package/dist/headless/index.cjs.map +1 -1
- package/dist/headless/index.d.cts +19 -13
- package/dist/headless/index.d.ts +19 -13
- package/dist/headless/index.js +3 -0
- package/dist/headless/index.js.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -13
- package/dist/index.d.ts +19 -13
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/playwright/index.cjs +36 -7
- package/dist/playwright/index.cjs.map +1 -1
- package/dist/playwright/index.js +36 -7
- package/dist/playwright/index.js.map +1 -1
- package/dist/playwright/states-reporter.cjs +36 -7
- package/dist/playwright/states-reporter.cjs.map +1 -1
- package/dist/playwright/states-reporter.d.cts +15 -0
- package/dist/playwright/states-reporter.d.ts +15 -0
- package/dist/playwright/states-reporter.js +36 -7
- package/dist/playwright/states-reporter.js.map +1 -1
- package/dist/playwright/states.cjs +8 -0
- package/dist/playwright/states.cjs.map +1 -1
- package/dist/playwright/states.d.cts +44 -1
- package/dist/playwright/states.d.ts +44 -1
- package/dist/playwright/states.js +7 -0
- package/dist/playwright/states.js.map +1 -1
- package/dist/react/index.cjs +3 -0
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +19 -13
- package/dist/react/index.d.ts +19 -13
- package/dist/react/index.js +3 -0
- package/dist/react/index.js.map +1 -1
- package/dist/scan/index.cjs +1217 -257
- package/dist/scan/index.cjs.map +1 -1
- package/dist/scan/index.d.cts +410 -104
- package/dist/scan/index.d.ts +410 -104
- package/dist/scan/index.js +1197 -253
- package/dist/scan/index.js.map +1 -1
- package/package.json +17 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/playwright/states-reporter.ts","../../src/integrations/playwright/states.ts"],"sourcesContent":["import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport type {\n FullResult,\n Reporter,\n TestCase,\n TestResult,\n} from \"@playwright/test/reporter\"\nimport {\n STATES_ATTACHMENT,\n type StateRecord,\n type StatesPayload,\n} from \"./states\"\n\n/**\n * Aggregates `uidex-states` attachments across a run into `uidex-states.json` —\n * the manifest the scanner's state-capture completeness gate reads. The shape\n * matches the scanner's `CapturedStatesManifest` structurally (kept decoupled:\n * no cross-subpath import, so the playwright bundle stays free of scan code).\n *\n * Variants collapse: many theme × width shots of one `entity/state` become a\n * single captured entry, because the gate asks \"was this state produced at\n * all?\", not \"how many variants?\".\n */\n\nexport interface CapturedStateEntry {\n entity: string\n kind?: string\n state: string\n /** Canonical matrix kind (loading/empty/populated/error/variant). */\n stateKind?: string\n /** Observed URL pathname (first variant); the page-coverage gate matches it. */\n url?: string\n /** Explicit route pattern, when the capture supplied one. */\n route?: string\n}\n\nexport interface CapturedStatesManifestOut {\n captured: CapturedStateEntry[]\n /** Every distinct theme/width/path variant, for tooling that wants detail. */\n variants: StateRecord[]\n}\n\nexport interface UidexStatesReporterOptions {\n outputPath?: string\n silent?: boolean\n}\n\nfunction keyOf(r: StateRecord): string {\n // Collapses pure theme/width variants, but keeps distinct routes/urls/kinds\n // so a state captured on two routes (or with vs. without stateKind) is not lost.\n return JSON.stringify([\n r.kind ?? null,\n r.entity,\n r.state,\n r.route ?? null,\n r.url ?? null,\n r.stateKind ?? null,\n ])\n}\n\n/** Pure aggregation — the reporter's core, exported for tests. */\nexport function aggregateStates(\n variants: StateRecord[]\n): CapturedStatesManifestOut {\n const seen = new Map<string, CapturedStateEntry>()\n for (const v of variants) {\n const k = keyOf(v)\n if (seen.has(k)) continue\n seen.set(k, {\n entity: v.entity,\n state: v.state,\n ...(v.kind ? { kind: v.kind } : {}),\n ...(v.stateKind ? { stateKind: v.stateKind } : {}),\n ...(v.route ? { route: v.route } : {}),\n ...(v.url ? { url: v.url } : {}),\n })\n }\n const captured = [...seen.values()].sort(\n (a, b) => a.entity.localeCompare(b.entity) || a.state.localeCompare(b.state)\n )\n const sortedVariants = [...variants].sort(\n (a, b) =>\n a.entity.localeCompare(b.entity) ||\n a.state.localeCompare(b.state) ||\n (a.theme ?? \"\").localeCompare(b.theme ?? \"\") ||\n (a.width ?? \"\").localeCompare(b.width ?? \"\")\n )\n return { captured, variants: sortedVariants }\n}\n\nfunction parsePayload(raw: string): StateRecord[] {\n try {\n const parsed = JSON.parse(raw) as Partial<StatesPayload>\n if (!parsed || !Array.isArray(parsed.records)) return []\n return parsed.records.filter(\n (r): r is StateRecord =>\n !!r && typeof r.entity === \"string\" && typeof r.state === \"string\"\n )\n } catch {\n return []\n }\n}\n\nexport default class UidexStatesReporter implements Reporter {\n private readonly outputPath: string\n private readonly silent: boolean\n private readonly variants: StateRecord[] = []\n\n constructor(options: UidexStatesReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-states.json\"\n this.silent = options.silent ?? false\n }\n\n onTestEnd(_test: TestCase, result: TestResult): void {\n for (const attachment of result.attachments) {\n if (attachment.name !== STATES_ATTACHMENT) continue\n if (!attachment.body) continue\n this.variants.push(...parsePayload(attachment.body.toString()))\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const manifest = aggregateStates(this.variants)\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(manifest, null, 2) + \"\\n\"\n )\n if (!this.silent) {\n const entities = new Set(manifest.captured.map((c) => c.entity)).size\n console.log(\n `uidex states: captured ${manifest.captured.length} state(s) across ${entities} entit${entities === 1 ? \"y\" : \"ies\"} (${manifest.variants.length} variants) → ${this.outputPath}`\n )\n }\n }\n}\n","import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;;;ACoBf,IAAM,oBAAoB;;;AD2BjC,SAAS,MAAM,GAAwB;AAGrC,SAAO,KAAK,UAAU;AAAA,IACpB,EAAE,QAAQ;AAAA,IACV,EAAE;AAAA,IACF,EAAE;AAAA,IACF,EAAE,SAAS;AAAA,IACX,EAAE,OAAO;AAAA,IACT,EAAE,aAAa;AAAA,EACjB,CAAC;AACH;AAGO,SAAS,gBACd,UAC2B;AAC3B,QAAM,OAAO,oBAAI,IAAgC;AACjD,aAAW,KAAK,UAAU;AACxB,UAAM,IAAI,MAAM,CAAC;AACjB,QAAI,KAAK,IAAI,CAAC,EAAG;AACjB,SAAK,IAAI,GAAG;AAAA,MACV,QAAQ,EAAE;AAAA,MACV,OAAO,EAAE;AAAA,MACT,GAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;AAAA,MACjC,GAAI,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,IAAI,CAAC;AAAA,MAChD,GAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAAA,MACpC,GAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC;AAAA,IAChC,CAAC;AAAA,EACH;AACA,QAAM,WAAW,CAAC,GAAG,KAAK,OAAO,CAAC,EAAE;AAAA,IAClC,CAAC,GAAG,MAAM,EAAE,OAAO,cAAc,EAAE,MAAM,KAAK,EA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G;AAAA,MACI,aAAQ,KAAK,UAAU;AAAA,MAC5B,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI;AAAA,IACtC;AACA,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,WAAW,IAAI,IAAI,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;AACjE,cAAQ;AAAA,QACN,0BAA0B,SAAS,SAAS,MAAM,oBAAoB,QAAQ,SAAS,aAAa,IAAI,MAAM,KAAK,KAAK,SAAS,SAAS,MAAM,qBAAgB,KAAK,UAAU;AAAA,MACjL;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/playwright/states-reporter.ts","../../src/integrations/playwright/states.ts"],"sourcesContent":["import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport type {\n FullResult,\n Reporter,\n TestCase,\n TestResult,\n} from \"@playwright/test/reporter\"\nimport {\n STATES_ATTACHMENT,\n type StateRecord,\n type StatesPayload,\n} from \"./states\"\n\n/**\n * Aggregates `uidex-states` attachments across a run into `uidex-states.json` —\n * the manifest the scanner's state-capture completeness gate reads. The shape\n * matches the scanner's `CapturedStatesManifest` structurally (kept decoupled:\n * no cross-subpath import, so the playwright bundle stays free of scan code).\n *\n * Variants collapse: many theme × width shots of one `entity/state` become a\n * single captured entry, because the gate asks \"was this state produced at\n * all?\", not \"how many variants?\".\n */\n\nexport interface CapturedStateEntry {\n entity: string\n kind?: string\n state: string\n /** Canonical matrix kind (loading/empty/populated/error/variant). */\n stateKind?: string\n /** Observed URL pathname (first variant); the page-coverage gate matches it. */\n url?: string\n /** Explicit route pattern, when the capture supplied one. */\n route?: string\n}\n\nexport interface CapturedStatesManifestOut {\n captured: CapturedStateEntry[]\n /** Every distinct theme/width/path variant, for tooling that wants detail. */\n variants: StateRecord[]\n /**\n * ISO timestamp of the run that wrote this manifest. The scanner compares it\n * to the mtimes of the files declaring states, so a manifest that predates a\n * declaration edit is reported as stale rather than silently trusted.\n */\n generatedAt?: string\n}\n\nexport interface UidexStatesReporterOptions {\n outputPath?: string\n silent?: boolean\n /**\n * Write to `<outputPath>` even when the run captured FEWER states than the\n * manifest already on disk. Off by default: a filtered (`--grep`) or flaky\n * run legitimately produces a subset, and blindly overwriting turns that into\n * silent coverage loss — the run exits non-zero, but the manifest is already\n * gone. See the shrink guard in `onEnd`.\n */\n allowShrink?: boolean\n}\n\n/** Identity of a captured state for shrink comparison. */\nfunction capturedKey(c: CapturedStateEntry): string {\n return `${c.kind ?? \"page\"}\u0000${c.entity}\u0000${c.state}`\n}\n\nfunction readExisting(p: string): CapturedStatesManifestOut | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(p, \"utf8\")) as unknown\n if (!parsed || typeof parsed !== \"object\") return null\n const m = parsed as Partial<CapturedStatesManifestOut>\n return Array.isArray(m.captured)\n ? { captured: m.captured, variants: m.variants ?? [] }\n : null\n } catch {\n return null // absent or unreadable → nothing to protect\n }\n}\n\nfunction keyOf(r: StateRecord): string {\n // Collapses pure theme/width variants, but keeps distinct routes/urls/kinds\n // so a state captured on two routes (or with vs. without stateKind) is not lost.\n return JSON.stringify([\n r.kind ?? null,\n r.entity,\n r.state,\n r.route ?? null,\n r.url ?? null,\n r.stateKind ?? null,\n ])\n}\n\n/** Pure aggregation — the reporter's core, exported for tests. */\nexport function aggregateStates(\n variants: StateRecord[]\n): CapturedStatesManifestOut {\n const seen = new Map<string, CapturedStateEntry>()\n for (const v of variants) {\n const k = keyOf(v)\n if (seen.has(k)) continue\n seen.set(k, {\n entity: v.entity,\n state: v.state,\n ...(v.kind ? { kind: v.kind } : {}),\n ...(v.stateKind ? { stateKind: v.stateKind } : {}),\n ...(v.route ? { route: v.route } : {}),\n ...(v.url ? { url: v.url } : {}),\n })\n }\n const captured = [...seen.values()].sort(\n (a, b) => a.entity.localeCompare(b.entity) || a.state.localeCompare(b.state)\n )\n const sortedVariants = [...variants].sort(\n (a, b) =>\n a.entity.localeCompare(b.entity) ||\n a.state.localeCompare(b.state) ||\n (a.theme ?? \"\").localeCompare(b.theme ?? \"\") ||\n (a.width ?? \"\").localeCompare(b.width ?? \"\")\n )\n return { captured, variants: sortedVariants }\n}\n\nfunction parsePayload(raw: string): StateRecord[] {\n try {\n const parsed = JSON.parse(raw) as Partial<StatesPayload>\n if (!parsed || !Array.isArray(parsed.records)) return []\n return parsed.records.filter(\n (r): r is StateRecord =>\n !!r && typeof r.entity === \"string\" && typeof r.state === \"string\"\n )\n } catch {\n return []\n }\n}\n\nexport default class UidexStatesReporter implements Reporter {\n private readonly outputPath: string\n private readonly silent: boolean\n private readonly allowShrink: boolean\n private readonly variants: StateRecord[] = []\n\n constructor(options: UidexStatesReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-states.json\"\n this.silent = options.silent ?? false\n this.allowShrink = options.allowShrink ?? false\n }\n\n onTestEnd(_test: TestCase, result: TestResult): void {\n for (const attachment of result.attachments) {\n if (attachment.name !== STATES_ATTACHMENT) continue\n if (!attachment.body) continue\n this.variants.push(...parsePayload(attachment.body.toString()))\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const manifest = aggregateStates(this.variants)\n manifest.generatedAt = new Date().toISOString()\n const target = path.resolve(this.outputPath)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n\n // ---- Shrink guard ----\n // A filtered or flaky run captures a SUBSET. Writing it over the committed\n // manifest silently deletes coverage: the states simply vanish, the gate\n // then agrees nothing is missing, and the only signal is a state count you\n // had to be watching. So when the run would drop states, divert it to\n // `<name>.partial.json`, leave the committed manifest untouched, and name\n // the dropped keys — the caller decides whether it was flake or a real\n // removal (for a deliberate removal, copy the partial over, or re-run with\n // `allowShrink`).\n const existing = this.allowShrink ? null : readExisting(target)\n const dropped = existing\n ? (() => {\n const now = new Set(manifest.captured.map(capturedKey))\n return existing.captured\n .map(capturedKey)\n .filter((k) => !now.has(k))\n .sort()\n })()\n : []\n\n const shrunk = dropped.length > 0\n const out = shrunk\n ? target.replace(/\\.json$/i, \"\") + \".partial.json\"\n : target\n fs.writeFileSync(out, JSON.stringify(manifest, null, 2) + \"\\n\")\n\n if (shrunk) {\n console.error(\n `uidex states: ⚠ run captured ${manifest.captured.length} state(s) but ${existing!.captured.length} are committed — ${dropped.length} would be DROPPED, so ${path.basename(target)} was left untouched and this run went to ${path.basename(out)}.`\n )\n console.error(` dropped: ${dropped.join(\", \")}`)\n console.error(\n ` A consistent count across two runs is a genuinely broken spec; a varying one is flake. For a deliberate removal, copy the partial over or set allowShrink.`\n )\n return\n }\n\n if (!this.silent) {\n const entities = new Set(manifest.captured.map((c) => c.entity)).size\n console.log(\n `uidex states: captured ${manifest.captured.length} state(s) across ${entities} entit${entities === 1 ? \"y\" : \"ies\"} (${manifest.variants.length} variants) → ${this.outputPath}`\n )\n }\n }\n}\n","import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n\n/**\n * The declared state space a generated `UidexStates` describes: entity kind →\n * entity id → that entity's own state names.\n */\nexport type StateSpace = {\n [K in StateEntityKind]: Record<string, string> | never\n}\n\n/**\n * Capture options narrowed to ONE entity of one kind, with only the states that\n * entity actually declares. Built as a union over (kind, entity) pairs so the\n * three fields are checked together — picking `widget`/`gate-badge` restricts\n * `state` to gate-badge's own names, and a page id is not assignable at all.\n */\nexport type TypedCaptureOptions<M> = {\n [K in keyof M & StateEntityKind]: M[K] extends Record<string, string>\n ? {\n [E in keyof M[K] & string]: Omit<\n CaptureStateOptions,\n \"entity\" | \"kind\" | \"state\"\n > & { kind: K; entity: E; state: M[K][E] }\n }[keyof M[K] & string]\n : never\n}[keyof M & StateEntityKind]\n\nexport interface TypedStateCapture<M> {\n captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: TypedCaptureOptions<M>\n ): Promise<StateRecord[]>\n recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>\n}\n\n/**\n * Bind the capture helpers to a project's generated state space:\n *\n * ```ts\n * // e2e/states/capture.ts — the ONE place e2e meets the registry\n * import { createStateCapture } from \"uidex/playwright\"\n * import type { UidexStates } from \"@/uidex.gen\"\n * export const { captureState } = createStateCapture<UidexStates>()\n * ```\n *\n * Purely a type-level narrowing — the runtime is the untyped `captureState`.\n * Its value is closing the loop that let capture ids drift from the registry:\n * before this, `entity` was a free string, so a spec could invent a name the\n * registry had never heard of and nothing failed until a lint pass noticed the\n * mismatch (or, when the entity kind was also wrong, never noticed at all).\n */\nexport function createStateCapture<\n M extends Partial<StateSpace>,\n>(): TypedStateCapture<M> {\n return {\n captureState: (page, testInfo, opts) =>\n captureState(page, testInfo, opts as unknown as CaptureStateOptions),\n recordStates,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;;;ACoBf,IAAM,oBAAoB;;;AD0CjC,SAAS,YAAY,GAA+B;AAClD,SAAO,GAAG,EAAE,QAAQ,MAAM,KAAI,EAAE,MAAM,KAAI,EAAE,KAAK;AACnD;AAEA,SAAS,aAAa,GAA6C;AACjE,MAAI;AACF,UAAM,SAAS,KAAK,MAAS,gBAAa,GAAG,MAAM,CAAC;AACpD,QAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,UAAM,IAAI;AACV,WAAO,MAAM,QAAQ,EAAE,QAAQ,IAC3B,EAAE,UAAU,EAAE,UAAU,UAAU,EAAE,YAAY,CAAC,EAAE,IACnD;AAAA,EACN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UAAM,SAAS,QAAQ,SAAS;AAChC,UAAM,MAAM,SACR,OAAO,QAAQ,YAAY,EAAE,IAAI,kBACjC;AACJ,IAAG,iBAAc,KAAK,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;AAE9D,QAAI,QAAQ;AACV,cAAQ;AAAA,QACN,qCAAgC,SAAS,SAAS,MAAM,iBAAiB,SAAU,SAAS,MAAM,yBAAoB,QAAQ,MAAM,yBAA8B,cAAS,MAAM,CAAC,4CAAiD,cAAS,GAAG,CAAC;AAAA,MAClP;AACA,cAAQ,MAAM,cAAc,QAAQ,KAAK,IAAI,CAAC,EAAE;AAChD,cAAQ;AAAA,QACN;AAAA,MACF;AACA;AAAA,IACF;AAEA,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,WAAW,IAAI,IAAI,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;AACjE,cAAQ;AAAA,QACN,0BAA0B,SAAS,SAAS,MAAM,oBAAoB,QAAQ,SAAS,aAAa,IAAI,MAAM,KAAK,KAAK,SAAS,SAAS,MAAM,qBAAgB,KAAK,UAAU;AAAA,MACjL;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -27,16 +27,31 @@ interface CapturedStatesManifestOut {
|
|
|
27
27
|
captured: CapturedStateEntry[];
|
|
28
28
|
/** Every distinct theme/width/path variant, for tooling that wants detail. */
|
|
29
29
|
variants: StateRecord[];
|
|
30
|
+
/**
|
|
31
|
+
* ISO timestamp of the run that wrote this manifest. The scanner compares it
|
|
32
|
+
* to the mtimes of the files declaring states, so a manifest that predates a
|
|
33
|
+
* declaration edit is reported as stale rather than silently trusted.
|
|
34
|
+
*/
|
|
35
|
+
generatedAt?: string;
|
|
30
36
|
}
|
|
31
37
|
interface UidexStatesReporterOptions {
|
|
32
38
|
outputPath?: string;
|
|
33
39
|
silent?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Write to `<outputPath>` even when the run captured FEWER states than the
|
|
42
|
+
* manifest already on disk. Off by default: a filtered (`--grep`) or flaky
|
|
43
|
+
* run legitimately produces a subset, and blindly overwriting turns that into
|
|
44
|
+
* silent coverage loss — the run exits non-zero, but the manifest is already
|
|
45
|
+
* gone. See the shrink guard in `onEnd`.
|
|
46
|
+
*/
|
|
47
|
+
allowShrink?: boolean;
|
|
34
48
|
}
|
|
35
49
|
/** Pure aggregation — the reporter's core, exported for tests. */
|
|
36
50
|
declare function aggregateStates(variants: StateRecord[]): CapturedStatesManifestOut;
|
|
37
51
|
declare class UidexStatesReporter implements Reporter {
|
|
38
52
|
private readonly outputPath;
|
|
39
53
|
private readonly silent;
|
|
54
|
+
private readonly allowShrink;
|
|
40
55
|
private readonly variants;
|
|
41
56
|
constructor(options?: UidexStatesReporterOptions);
|
|
42
57
|
onTestEnd(_test: TestCase, result: TestResult): void;
|
|
@@ -27,16 +27,31 @@ interface CapturedStatesManifestOut {
|
|
|
27
27
|
captured: CapturedStateEntry[];
|
|
28
28
|
/** Every distinct theme/width/path variant, for tooling that wants detail. */
|
|
29
29
|
variants: StateRecord[];
|
|
30
|
+
/**
|
|
31
|
+
* ISO timestamp of the run that wrote this manifest. The scanner compares it
|
|
32
|
+
* to the mtimes of the files declaring states, so a manifest that predates a
|
|
33
|
+
* declaration edit is reported as stale rather than silently trusted.
|
|
34
|
+
*/
|
|
35
|
+
generatedAt?: string;
|
|
30
36
|
}
|
|
31
37
|
interface UidexStatesReporterOptions {
|
|
32
38
|
outputPath?: string;
|
|
33
39
|
silent?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Write to `<outputPath>` even when the run captured FEWER states than the
|
|
42
|
+
* manifest already on disk. Off by default: a filtered (`--grep`) or flaky
|
|
43
|
+
* run legitimately produces a subset, and blindly overwriting turns that into
|
|
44
|
+
* silent coverage loss — the run exits non-zero, but the manifest is already
|
|
45
|
+
* gone. See the shrink guard in `onEnd`.
|
|
46
|
+
*/
|
|
47
|
+
allowShrink?: boolean;
|
|
34
48
|
}
|
|
35
49
|
/** Pure aggregation — the reporter's core, exported for tests. */
|
|
36
50
|
declare function aggregateStates(variants: StateRecord[]): CapturedStatesManifestOut;
|
|
37
51
|
declare class UidexStatesReporter implements Reporter {
|
|
38
52
|
private readonly outputPath;
|
|
39
53
|
private readonly silent;
|
|
54
|
+
private readonly allowShrink;
|
|
40
55
|
private readonly variants;
|
|
41
56
|
constructor(options?: UidexStatesReporterOptions);
|
|
42
57
|
onTestEnd(_test: TestCase, result: TestResult): void;
|
|
@@ -6,6 +6,19 @@ import * as path from "path";
|
|
|
6
6
|
var STATES_ATTACHMENT = "uidex-states";
|
|
7
7
|
|
|
8
8
|
// src/integrations/playwright/states-reporter.ts
|
|
9
|
+
function capturedKey(c) {
|
|
10
|
+
return `${c.kind ?? "page"}\0${c.entity}\0${c.state}`;
|
|
11
|
+
}
|
|
12
|
+
function readExisting(p) {
|
|
13
|
+
try {
|
|
14
|
+
const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
15
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
16
|
+
const m = parsed;
|
|
17
|
+
return Array.isArray(m.captured) ? { captured: m.captured, variants: m.variants ?? [] } : null;
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
9
22
|
function keyOf(r) {
|
|
10
23
|
return JSON.stringify([
|
|
11
24
|
r.kind ?? null,
|
|
@@ -52,10 +65,12 @@ function parsePayload(raw) {
|
|
|
52
65
|
var UidexStatesReporter = class {
|
|
53
66
|
outputPath;
|
|
54
67
|
silent;
|
|
68
|
+
allowShrink;
|
|
55
69
|
variants = [];
|
|
56
70
|
constructor(options = {}) {
|
|
57
71
|
this.outputPath = options.outputPath ?? "uidex-states.json";
|
|
58
72
|
this.silent = options.silent ?? false;
|
|
73
|
+
this.allowShrink = options.allowShrink ?? false;
|
|
59
74
|
}
|
|
60
75
|
onTestEnd(_test, result) {
|
|
61
76
|
for (const attachment of result.attachments) {
|
|
@@ -66,13 +81,27 @@ var UidexStatesReporter = class {
|
|
|
66
81
|
}
|
|
67
82
|
async onEnd(_result) {
|
|
68
83
|
const manifest = aggregateStates(this.variants);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
84
|
+
manifest.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
85
|
+
const target = path.resolve(this.outputPath);
|
|
86
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
87
|
+
const existing = this.allowShrink ? null : readExisting(target);
|
|
88
|
+
const dropped = existing ? (() => {
|
|
89
|
+
const now = new Set(manifest.captured.map(capturedKey));
|
|
90
|
+
return existing.captured.map(capturedKey).filter((k) => !now.has(k)).sort();
|
|
91
|
+
})() : [];
|
|
92
|
+
const shrunk = dropped.length > 0;
|
|
93
|
+
const out = shrunk ? target.replace(/\.json$/i, "") + ".partial.json" : target;
|
|
94
|
+
fs.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
|
|
95
|
+
if (shrunk) {
|
|
96
|
+
console.error(
|
|
97
|
+
`uidex states: \u26A0 run captured ${manifest.captured.length} state(s) but ${existing.captured.length} are committed \u2014 ${dropped.length} would be DROPPED, so ${path.basename(target)} was left untouched and this run went to ${path.basename(out)}.`
|
|
98
|
+
);
|
|
99
|
+
console.error(` dropped: ${dropped.join(", ")}`);
|
|
100
|
+
console.error(
|
|
101
|
+
` A consistent count across two runs is a genuinely broken spec; a varying one is flake. For a deliberate removal, copy the partial over or set allowShrink.`
|
|
102
|
+
);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
76
105
|
if (!this.silent) {
|
|
77
106
|
const entities = new Set(manifest.captured.map((c) => c.entity)).size;
|
|
78
107
|
console.log(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/playwright/states-reporter.ts","../../src/integrations/playwright/states.ts"],"sourcesContent":["import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport type {\n FullResult,\n Reporter,\n TestCase,\n TestResult,\n} from \"@playwright/test/reporter\"\nimport {\n STATES_ATTACHMENT,\n type StateRecord,\n type StatesPayload,\n} from \"./states\"\n\n/**\n * Aggregates `uidex-states` attachments across a run into `uidex-states.json` —\n * the manifest the scanner's state-capture completeness gate reads. The shape\n * matches the scanner's `CapturedStatesManifest` structurally (kept decoupled:\n * no cross-subpath import, so the playwright bundle stays free of scan code).\n *\n * Variants collapse: many theme × width shots of one `entity/state` become a\n * single captured entry, because the gate asks \"was this state produced at\n * all?\", not \"how many variants?\".\n */\n\nexport interface CapturedStateEntry {\n entity: string\n kind?: string\n state: string\n /** Canonical matrix kind (loading/empty/populated/error/variant). */\n stateKind?: string\n /** Observed URL pathname (first variant); the page-coverage gate matches it. */\n url?: string\n /** Explicit route pattern, when the capture supplied one. */\n route?: string\n}\n\nexport interface CapturedStatesManifestOut {\n captured: CapturedStateEntry[]\n /** Every distinct theme/width/path variant, for tooling that wants detail. */\n variants: StateRecord[]\n}\n\nexport interface UidexStatesReporterOptions {\n outputPath?: string\n silent?: boolean\n}\n\nfunction keyOf(r: StateRecord): string {\n // Collapses pure theme/width variants, but keeps distinct routes/urls/kinds\n // so a state captured on two routes (or with vs. without stateKind) is not lost.\n return JSON.stringify([\n r.kind ?? null,\n r.entity,\n r.state,\n r.route ?? null,\n r.url ?? null,\n r.stateKind ?? null,\n ])\n}\n\n/** Pure aggregation — the reporter's core, exported for tests. */\nexport function aggregateStates(\n variants: StateRecord[]\n): CapturedStatesManifestOut {\n const seen = new Map<string, CapturedStateEntry>()\n for (const v of variants) {\n const k = keyOf(v)\n if (seen.has(k)) continue\n seen.set(k, {\n entity: v.entity,\n state: v.state,\n ...(v.kind ? { kind: v.kind } : {}),\n ...(v.stateKind ? { stateKind: v.stateKind } : {}),\n ...(v.route ? { route: v.route } : {}),\n ...(v.url ? { url: v.url } : {}),\n })\n }\n const captured = [...seen.values()].sort(\n (a, b) => a.entity.localeCompare(b.entity) || a.state.localeCompare(b.state)\n )\n const sortedVariants = [...variants].sort(\n (a, b) =>\n a.entity.localeCompare(b.entity) ||\n a.state.localeCompare(b.state) ||\n (a.theme ?? \"\").localeCompare(b.theme ?? \"\") ||\n (a.width ?? \"\").localeCompare(b.width ?? \"\")\n )\n return { captured, variants: sortedVariants }\n}\n\nfunction parsePayload(raw: string): StateRecord[] {\n try {\n const parsed = JSON.parse(raw) as Partial<StatesPayload>\n if (!parsed || !Array.isArray(parsed.records)) return []\n return parsed.records.filter(\n (r): r is StateRecord =>\n !!r && typeof r.entity === \"string\" && typeof r.state === \"string\"\n )\n } catch {\n return []\n }\n}\n\nexport default class UidexStatesReporter implements Reporter {\n private readonly outputPath: string\n private readonly silent: boolean\n private readonly variants: StateRecord[] = []\n\n constructor(options: UidexStatesReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-states.json\"\n this.silent = options.silent ?? false\n }\n\n onTestEnd(_test: TestCase, result: TestResult): void {\n for (const attachment of result.attachments) {\n if (attachment.name !== STATES_ATTACHMENT) continue\n if (!attachment.body) continue\n this.variants.push(...parsePayload(attachment.body.toString()))\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const manifest = aggregateStates(this.variants)\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(manifest, null, 2) + \"\\n\"\n )\n if (!this.silent) {\n const entities = new Set(manifest.captured.map((c) => c.entity)).size\n console.log(\n `uidex states: captured ${manifest.captured.length} state(s) across ${entities} entit${entities === 1 ? \"y\" : \"ies\"} (${manifest.variants.length} variants) → ${this.outputPath}`\n )\n }\n }\n}\n","import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACoBf,IAAM,oBAAoB;;;AD2BjC,SAAS,MAAM,GAAwB;AAGrC,SAAO,KAAK,UAAU;AAAA,IACpB,EAAE,QAAQ;AAAA,IACV,EAAE;AAAA,IACF,EAAE;AAAA,IACF,EAAE,SAAS;AAAA,IACX,EAAE,OAAO;AAAA,IACT,EAAE,aAAa;AAAA,EACjB,CAAC;AACH;AAGO,SAAS,gBACd,UAC2B;AAC3B,QAAM,OAAO,oBAAI,IAAgC;AACjD,aAAW,KAAK,UAAU;AACxB,UAAM,IAAI,MAAM,CAAC;AACjB,QAAI,KAAK,IAAI,CAAC,EAAG;AACjB,SAAK,IAAI,GAAG;AAAA,MACV,QAAQ,EAAE;AAAA,MACV,OAAO,EAAE;AAAA,MACT,GAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;AAAA,MACjC,GAAI,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,IAAI,CAAC;AAAA,MAChD,GAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAAA,MACpC,GAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC;AAAA,IAChC,CAAC;AAAA,EACH;AACA,QAAM,WAAW,CAAC,GAAG,KAAK,OAAO,CAAC,EAAE;AAAA,IAClC,CAAC,GAAG,MAAM,EAAE,OAAO,cAAc,EAAE,MAAM,KAAK,EAAE,MAAM,cAAc,EAAE,KAAK;AAAA,EAC7E;AACA,QAAM,iBAAiB,CAAC,GAAG,QAAQ,EAAE;AAAA,IACnC,CAAC,GAAG,MACF,EAAE,OAAO,cAAc,EAAE,M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W,IAAI,IAAI,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;AACjE,cAAQ;AAAA,QACN,0BAA0B,SAAS,SAAS,MAAM,oBAAoB,QAAQ,SAAS,aAAa,IAAI,MAAM,KAAK,KAAK,SAAS,SAAS,MAAM,qBAAgB,KAAK,UAAU;AAAA,MACjL;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/playwright/states-reporter.ts","../../src/integrations/playwright/states.ts"],"sourcesContent":["import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport type {\n FullResult,\n Reporter,\n TestCase,\n TestResult,\n} from \"@playwright/test/reporter\"\nimport {\n STATES_ATTACHMENT,\n type StateRecord,\n type StatesPayload,\n} from \"./states\"\n\n/**\n * Aggregates `uidex-states` attachments across a run into `uidex-states.json` —\n * the manifest the scanner's state-capture completeness gate reads. The shape\n * matches the scanner's `CapturedStatesManifest` structurally (kept decoupled:\n * no cross-subpath import, so the playwright bundle stays free of scan code).\n *\n * Variants collapse: many theme × width shots of one `entity/state` become a\n * single captured entry, because the gate asks \"was this state produced at\n * all?\", not \"how many variants?\".\n */\n\nexport interface CapturedStateEntry {\n entity: string\n kind?: string\n state: string\n /** Canonical matrix kind (loading/empty/populated/error/variant). */\n stateKind?: string\n /** Observed URL pathname (first variant); the page-coverage gate matches it. */\n url?: string\n /** Explicit route pattern, when the capture supplied one. */\n route?: string\n}\n\nexport interface CapturedStatesManifestOut {\n captured: CapturedStateEntry[]\n /** Every distinct theme/width/path variant, for tooling that wants detail. */\n variants: StateRecord[]\n /**\n * ISO timestamp of the run that wrote this manifest. The scanner compares it\n * to the mtimes of the files declaring states, so a manifest that predates a\n * declaration edit is reported as stale rather than silently trusted.\n */\n generatedAt?: string\n}\n\nexport interface UidexStatesReporterOptions {\n outputPath?: string\n silent?: boolean\n /**\n * Write to `<outputPath>` even when the run captured FEWER states than the\n * manifest already on disk. Off by default: a filtered (`--grep`) or flaky\n * run legitimately produces a subset, and blindly overwriting turns that into\n * silent coverage loss — the run exits non-zero, but the manifest is already\n * gone. See the shrink guard in `onEnd`.\n */\n allowShrink?: boolean\n}\n\n/** Identity of a captured state for shrink comparison. */\nfunction capturedKey(c: CapturedStateEntry): string {\n return `${c.kind ?? \"page\"}\u0000${c.entity}\u0000${c.state}`\n}\n\nfunction readExisting(p: string): CapturedStatesManifestOut | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(p, \"utf8\")) as unknown\n if (!parsed || typeof parsed !== \"object\") return null\n const m = parsed as Partial<CapturedStatesManifestOut>\n return Array.isArray(m.captured)\n ? { captured: m.captured, variants: m.variants ?? [] }\n : null\n } catch {\n return null // absent or unreadable → nothing to protect\n }\n}\n\nfunction keyOf(r: StateRecord): string {\n // Collapses pure theme/width variants, but keeps distinct routes/urls/kinds\n // so a state captured on two routes (or with vs. without stateKind) is not lost.\n return JSON.stringify([\n r.kind ?? null,\n r.entity,\n r.state,\n r.route ?? null,\n r.url ?? null,\n r.stateKind ?? null,\n ])\n}\n\n/** Pure aggregation — the reporter's core, exported for tests. */\nexport function aggregateStates(\n variants: StateRecord[]\n): CapturedStatesManifestOut {\n const seen = new Map<string, CapturedStateEntry>()\n for (const v of variants) {\n const k = keyOf(v)\n if (seen.has(k)) continue\n seen.set(k, {\n entity: v.entity,\n state: v.state,\n ...(v.kind ? { kind: v.kind } : {}),\n ...(v.stateKind ? { stateKind: v.stateKind } : {}),\n ...(v.route ? { route: v.route } : {}),\n ...(v.url ? { url: v.url } : {}),\n })\n }\n const captured = [...seen.values()].sort(\n (a, b) => a.entity.localeCompare(b.entity) || a.state.localeCompare(b.state)\n )\n const sortedVariants = [...variants].sort(\n (a, b) =>\n a.entity.localeCompare(b.entity) ||\n a.state.localeCompare(b.state) ||\n (a.theme ?? \"\").localeCompare(b.theme ?? \"\") ||\n (a.width ?? \"\").localeCompare(b.width ?? \"\")\n )\n return { captured, variants: sortedVariants }\n}\n\nfunction parsePayload(raw: string): StateRecord[] {\n try {\n const parsed = JSON.parse(raw) as Partial<StatesPayload>\n if (!parsed || !Array.isArray(parsed.records)) return []\n return parsed.records.filter(\n (r): r is StateRecord =>\n !!r && typeof r.entity === \"string\" && typeof r.state === \"string\"\n )\n } catch {\n return []\n }\n}\n\nexport default class UidexStatesReporter implements Reporter {\n private readonly outputPath: string\n private readonly silent: boolean\n private readonly allowShrink: boolean\n private readonly variants: StateRecord[] = []\n\n constructor(options: UidexStatesReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-states.json\"\n this.silent = options.silent ?? false\n this.allowShrink = options.allowShrink ?? false\n }\n\n onTestEnd(_test: TestCase, result: TestResult): void {\n for (const attachment of result.attachments) {\n if (attachment.name !== STATES_ATTACHMENT) continue\n if (!attachment.body) continue\n this.variants.push(...parsePayload(attachment.body.toString()))\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const manifest = aggregateStates(this.variants)\n manifest.generatedAt = new Date().toISOString()\n const target = path.resolve(this.outputPath)\n fs.mkdirSync(path.dirname(target), { recursive: true })\n\n // ---- Shrink guard ----\n // A filtered or flaky run captures a SUBSET. Writing it over the committed\n // manifest silently deletes coverage: the states simply vanish, the gate\n // then agrees nothing is missing, and the only signal is a state count you\n // had to be watching. So when the run would drop states, divert it to\n // `<name>.partial.json`, leave the committed manifest untouched, and name\n // the dropped keys — the caller decides whether it was flake or a real\n // removal (for a deliberate removal, copy the partial over, or re-run with\n // `allowShrink`).\n const existing = this.allowShrink ? null : readExisting(target)\n const dropped = existing\n ? (() => {\n const now = new Set(manifest.captured.map(capturedKey))\n return existing.captured\n .map(capturedKey)\n .filter((k) => !now.has(k))\n .sort()\n })()\n : []\n\n const shrunk = dropped.length > 0\n const out = shrunk\n ? target.replace(/\\.json$/i, \"\") + \".partial.json\"\n : target\n fs.writeFileSync(out, JSON.stringify(manifest, null, 2) + \"\\n\")\n\n if (shrunk) {\n console.error(\n `uidex states: ⚠ run captured ${manifest.captured.length} state(s) but ${existing!.captured.length} are committed — ${dropped.length} would be DROPPED, so ${path.basename(target)} was left untouched and this run went to ${path.basename(out)}.`\n )\n console.error(` dropped: ${dropped.join(\", \")}`)\n console.error(\n ` A consistent count across two runs is a genuinely broken spec; a varying one is flake. For a deliberate removal, copy the partial over or set allowShrink.`\n )\n return\n }\n\n if (!this.silent) {\n const entities = new Set(manifest.captured.map((c) => c.entity)).size\n console.log(\n `uidex states: captured ${manifest.captured.length} state(s) across ${entities} entit${entities === 1 ? \"y\" : \"ies\"} (${manifest.variants.length} variants) → ${this.outputPath}`\n )\n }\n }\n}\n","import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n\n/**\n * The declared state space a generated `UidexStates` describes: entity kind →\n * entity id → that entity's own state names.\n */\nexport type StateSpace = {\n [K in StateEntityKind]: Record<string, string> | never\n}\n\n/**\n * Capture options narrowed to ONE entity of one kind, with only the states that\n * entity actually declares. Built as a union over (kind, entity) pairs so the\n * three fields are checked together — picking `widget`/`gate-badge` restricts\n * `state` to gate-badge's own names, and a page id is not assignable at all.\n */\nexport type TypedCaptureOptions<M> = {\n [K in keyof M & StateEntityKind]: M[K] extends Record<string, string>\n ? {\n [E in keyof M[K] & string]: Omit<\n CaptureStateOptions,\n \"entity\" | \"kind\" | \"state\"\n > & { kind: K; entity: E; state: M[K][E] }\n }[keyof M[K] & string]\n : never\n}[keyof M & StateEntityKind]\n\nexport interface TypedStateCapture<M> {\n captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: TypedCaptureOptions<M>\n ): Promise<StateRecord[]>\n recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>\n}\n\n/**\n * Bind the capture helpers to a project's generated state space:\n *\n * ```ts\n * // e2e/states/capture.ts — the ONE place e2e meets the registry\n * import { createStateCapture } from \"uidex/playwright\"\n * import type { UidexStates } from \"@/uidex.gen\"\n * export const { captureState } = createStateCapture<UidexStates>()\n * ```\n *\n * Purely a type-level narrowing — the runtime is the untyped `captureState`.\n * Its value is closing the loop that let capture ids drift from the registry:\n * before this, `entity` was a free string, so a spec could invent a name the\n * registry had never heard of and nothing failed until a lint pass noticed the\n * mismatch (or, when the entity kind was also wrong, never noticed at all).\n */\nexport function createStateCapture<\n M extends Partial<StateSpace>,\n>(): TypedStateCapture<M> {\n return {\n captureState: (page, testInfo, opts) =>\n captureState(page, testInfo, opts as unknown as CaptureStateOptions),\n recordStates,\n }\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACoBf,IAAM,oBAAoB;;;AD0CjC,SAAS,YAAY,GAA+B;AAClD,SAAO,GAAG,EAAE,QAAQ,MAAM,KAAI,EAAE,MAAM,KAAI,EAAE,KAAK;AACnD;AAEA,SAAS,aAAa,GAA6C;AACjE,MAAI;AACF,UAAM,SAAS,KAAK,MAAS,gBAAa,GAAG,MAAM,CAAC;AACpD,QAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,UAAM,IAAI;AACV,WAAO,MAAM,QAAQ,EAAE,QAAQ,IAC3B,EAAE,UAAU,EAAE,UAAU,UAAU,EAAE,YAAY,CAAC,EAAE,IACnD;AAAA,EACN,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,MAAM,GAAwB;AAGrC,SAAO,KAAK,UAAU;AAAA,IACpB,EAAE,QAAQ;AAAA,IACV,EAAE;AAAA,IACF,EAAE;AAAA,IACF,EAAE,SAAS;AAAA,IACX,EAAE,OAAO;AAAA,IACT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AAgC,SAAS,SAAS,MAAM,iBAAiB,SAAU,SAAS,MAAM,yBAAoB,QAAQ,MAAM,yBAA8B,cAAS,MAAM,CAAC,4CAAiD,cAAS,GAAG,CAAC;AAAA,MAClP;AACA,cAAQ,MAAM,cAAc,QAAQ,KAAK,IAAI,CAAC,EAAE;AAChD,cAAQ;AAAA,QACN;AAAA,MACF;AACA;AAAA,IACF;AAEA,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,WAAW,IAAI,IAAI,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;AACjE,cAAQ;AAAA,QACN,0BAA0B,SAAS,SAAS,MAAM,oBAAoB,QAAQ,SAAS,aAAa,IAAI,MAAM,KAAK,KAAK,SAAS,SAAS,MAAM,qBAAgB,KAAK,UAAU;AAAA,MACjL;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -25,6 +25,7 @@ __export(states_exports, {
|
|
|
25
25
|
THEMES: () => THEMES,
|
|
26
26
|
WIDTHS: () => WIDTHS,
|
|
27
27
|
captureState: () => captureState,
|
|
28
|
+
createStateCapture: () => createStateCapture,
|
|
28
29
|
recordStates: () => recordStates
|
|
29
30
|
});
|
|
30
31
|
module.exports = __toCommonJS(states_exports);
|
|
@@ -106,6 +107,12 @@ async function captureState(page, testInfo, opts) {
|
|
|
106
107
|
await recordStates(testInfo, records);
|
|
107
108
|
return records;
|
|
108
109
|
}
|
|
110
|
+
function createStateCapture() {
|
|
111
|
+
return {
|
|
112
|
+
captureState: (page, testInfo, opts) => captureState(page, testInfo, opts),
|
|
113
|
+
recordStates
|
|
114
|
+
};
|
|
115
|
+
}
|
|
109
116
|
// Annotate the CommonJS export names for ESM import in node:
|
|
110
117
|
0 && (module.exports = {
|
|
111
118
|
CORE_STATE_KINDS,
|
|
@@ -113,6 +120,7 @@ async function captureState(page, testInfo, opts) {
|
|
|
113
120
|
THEMES,
|
|
114
121
|
WIDTHS,
|
|
115
122
|
captureState,
|
|
123
|
+
createStateCapture,
|
|
116
124
|
recordStates
|
|
117
125
|
});
|
|
118
126
|
//# sourceMappingURL=states.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/playwright/states.ts"],"sourcesContent":["import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,IAAM,oBAAoB;AAG1B,IAAM,SAAS,CAAC,SAAS,MAAM;AAE/B,IAAM,SAAS,EAAE,SAAS,MAAM,QAAQ,IAAI;AAO5C,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA0CA,eAAsB,aACpB,UACA,SACe;AACf,MAAI,QAAQ,WAAW,EAAG;AAC1B,QAAM,UAAyB,EAAE,QAAQ;AACzC,QAAM,SAAS,OAAO,mBAAmB;AAAA,IACvC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B,aAAa;AAAA,EACf,CAAC;AACH;AA4CA,SAAS,gBAAgB,MAAgC;AACvD,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,gBAAgB,MAAY,OAA6B;AACtE,QAAM,KAAK,aAAa,EAAE,aAAa,MAAM,CAAC;AAChD;AAG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AAW,CAAC;AAChE,cAAM,KAAK,WAAW;AAAA,UACpB;AAAA,UACA,UAAU,KAAK,YAAY;AAAA,UAC3B,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,UACtD,GAAI,KAAK,MAAM,SACX;AAAA,YACE,MAAM,KAAK,KAAK,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC;AAAA,YAC1C,WAAW;AAAA,UACb,IACA,CAAC;AAAA,QACP,CAAC;AACD,eAAO,OAAO;AAAA,MAChB;AACA,cAAQ,KAAK,MAAM;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,aAAa,UAAU,OAAO;AACpC,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/playwright/states.ts"],"sourcesContent":["import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n\n/**\n * The declared state space a generated `UidexStates` describes: entity kind →\n * entity id → that entity's own state names.\n */\nexport type StateSpace = {\n [K in StateEntityKind]: Record<string, string> | never\n}\n\n/**\n * Capture options narrowed to ONE entity of one kind, with only the states that\n * entity actually declares. Built as a union over (kind, entity) pairs so the\n * three fields are checked together — picking `widget`/`gate-badge` restricts\n * `state` to gate-badge's own names, and a page id is not assignable at all.\n */\nexport type TypedCaptureOptions<M> = {\n [K in keyof M & StateEntityKind]: M[K] extends Record<string, string>\n ? {\n [E in keyof M[K] & string]: Omit<\n CaptureStateOptions,\n \"entity\" | \"kind\" | \"state\"\n > & { kind: K; entity: E; state: M[K][E] }\n }[keyof M[K] & string]\n : never\n}[keyof M & StateEntityKind]\n\nexport interface TypedStateCapture<M> {\n captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: TypedCaptureOptions<M>\n ): Promise<StateRecord[]>\n recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>\n}\n\n/**\n * Bind the capture helpers to a project's generated state space:\n *\n * ```ts\n * // e2e/states/capture.ts — the ONE place e2e meets the registry\n * import { createStateCapture } from \"uidex/playwright\"\n * import type { UidexStates } from \"@/uidex.gen\"\n * export const { captureState } = createStateCapture<UidexStates>()\n * ```\n *\n * Purely a type-level narrowing — the runtime is the untyped `captureState`.\n * Its value is closing the loop that let capture ids drift from the registry:\n * before this, `entity` was a free string, so a spec could invent a name the\n * registry had never heard of and nothing failed until a lint pass noticed the\n * mismatch (or, when the entity kind was also wrong, never noticed at all).\n */\nexport function createStateCapture<\n M extends Partial<StateSpace>,\n>(): TypedStateCapture<M> {\n return {\n captureState: (page, testInfo, opts) =>\n captureState(page, testInfo, opts as unknown as CaptureStateOptions),\n recordStates,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,IAAM,oBAAoB;AAG1B,IAAM,SAAS,CAAC,SAAS,MAAM;AAE/B,IAAM,SAAS,EAAE,SAAS,MAAM,QAAQ,IAAI;AAO5C,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA0CA,eAAsB,aACpB,UACA,SACe;AACf,MAAI,QAAQ,WAAW,EAAG;AAC1B,QAAM,UAAyB,EAAE,QAAQ;AACzC,QAAM,SAAS,OAAO,mBAAmB;AAAA,IACvC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B,aAAa;AAAA,EACf,CAAC;AACH;AA4CA,SAAS,gBAAgB,MAAgC;AACvD,MA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QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,QAC1C,GAAI,cAAc,EAAE,KAAK,YAAY,IAAI,CAAC;AAAA,MAC5C;AACA,UAAI,KAAK;AACP,cAAM,OAAO,GAAG,GAAG,IAAI,SAAS,MAAM,OAAO,OAAO,WAAW,CAAC;AAChE,cAAM,KAAK,WAAW;AAAA,UACpB;AAAA,UACA,UAAU,KAAK,YAAY;AAAA,UAC3B,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,UACtD,GAAI,KAAK,MAAM,SACX;AAAA,YACE,MAAM,KAAK,KAAK,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC;AAAA,YAC1C,WAAW;AAAA,UACb,IACA,CAAC;AAAA,QACP,CAAC;AACD,eAAO,OAAO;AAAA,MAChB;AACA,cAAQ,KAAK,MAAM;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,aAAa,UAAU,OAAO;AACpC,SAAO;AACT;AAoDO,SAAS,qBAEU;AACxB,SAAO;AAAA,IACL,cAAc,CAAC,MAAM,UAAU,SAC7B,aAAa,MAAM,UAAU,IAAsC;AAAA,IACrE;AAAA,EACF;AACF;","names":[]}
|
|
@@ -116,5 +116,48 @@ interface CaptureStateOptions {
|
|
|
116
116
|
* it attached (also handy in tests).
|
|
117
117
|
*/
|
|
118
118
|
declare function captureState(page: Page, testInfo: TestInfoLike, opts: CaptureStateOptions): Promise<StateRecord[]>;
|
|
119
|
+
/**
|
|
120
|
+
* The declared state space a generated `UidexStates` describes: entity kind →
|
|
121
|
+
* entity id → that entity's own state names.
|
|
122
|
+
*/
|
|
123
|
+
type StateSpace = {
|
|
124
|
+
[K in StateEntityKind]: Record<string, string> | never;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Capture options narrowed to ONE entity of one kind, with only the states that
|
|
128
|
+
* entity actually declares. Built as a union over (kind, entity) pairs so the
|
|
129
|
+
* three fields are checked together — picking `widget`/`gate-badge` restricts
|
|
130
|
+
* `state` to gate-badge's own names, and a page id is not assignable at all.
|
|
131
|
+
*/
|
|
132
|
+
type TypedCaptureOptions<M> = {
|
|
133
|
+
[K in keyof M & StateEntityKind]: M[K] extends Record<string, string> ? {
|
|
134
|
+
[E in keyof M[K] & string]: Omit<CaptureStateOptions, "entity" | "kind" | "state"> & {
|
|
135
|
+
kind: K;
|
|
136
|
+
entity: E;
|
|
137
|
+
state: M[K][E];
|
|
138
|
+
};
|
|
139
|
+
}[keyof M[K] & string] : never;
|
|
140
|
+
}[keyof M & StateEntityKind];
|
|
141
|
+
interface TypedStateCapture<M> {
|
|
142
|
+
captureState(page: Page, testInfo: TestInfoLike, opts: TypedCaptureOptions<M>): Promise<StateRecord[]>;
|
|
143
|
+
recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Bind the capture helpers to a project's generated state space:
|
|
147
|
+
*
|
|
148
|
+
* ```ts
|
|
149
|
+
* // e2e/states/capture.ts — the ONE place e2e meets the registry
|
|
150
|
+
* import { createStateCapture } from "uidex/playwright"
|
|
151
|
+
* import type { UidexStates } from "@/uidex.gen"
|
|
152
|
+
* export const { captureState } = createStateCapture<UidexStates>()
|
|
153
|
+
* ```
|
|
154
|
+
*
|
|
155
|
+
* Purely a type-level narrowing — the runtime is the untyped `captureState`.
|
|
156
|
+
* Its value is closing the loop that let capture ids drift from the registry:
|
|
157
|
+
* before this, `entity` was a free string, so a spec could invent a name the
|
|
158
|
+
* registry had never heard of and nothing failed until a lint pass noticed the
|
|
159
|
+
* mismatch (or, when the entity kind was also wrong, never noticed at all).
|
|
160
|
+
*/
|
|
161
|
+
declare function createStateCapture<M extends Partial<StateSpace>>(): TypedStateCapture<M>;
|
|
119
162
|
|
|
120
|
-
export { CORE_STATE_KINDS, type CaptureStateOptions, type CoreStateKind, STATES_ATTACHMENT, type StateEntityKind, type StateKind, type StateRecord, type StatesPayload, THEMES, type Theme, WIDTHS, type WidthLabel, captureState, recordStates };
|
|
163
|
+
export { CORE_STATE_KINDS, type CaptureStateOptions, type CoreStateKind, STATES_ATTACHMENT, type StateEntityKind, type StateKind, type StateRecord, type StateSpace, type StatesPayload, THEMES, type Theme, type TypedCaptureOptions, type TypedStateCapture, WIDTHS, type WidthLabel, captureState, createStateCapture, recordStates };
|
|
@@ -116,5 +116,48 @@ interface CaptureStateOptions {
|
|
|
116
116
|
* it attached (also handy in tests).
|
|
117
117
|
*/
|
|
118
118
|
declare function captureState(page: Page, testInfo: TestInfoLike, opts: CaptureStateOptions): Promise<StateRecord[]>;
|
|
119
|
+
/**
|
|
120
|
+
* The declared state space a generated `UidexStates` describes: entity kind →
|
|
121
|
+
* entity id → that entity's own state names.
|
|
122
|
+
*/
|
|
123
|
+
type StateSpace = {
|
|
124
|
+
[K in StateEntityKind]: Record<string, string> | never;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Capture options narrowed to ONE entity of one kind, with only the states that
|
|
128
|
+
* entity actually declares. Built as a union over (kind, entity) pairs so the
|
|
129
|
+
* three fields are checked together — picking `widget`/`gate-badge` restricts
|
|
130
|
+
* `state` to gate-badge's own names, and a page id is not assignable at all.
|
|
131
|
+
*/
|
|
132
|
+
type TypedCaptureOptions<M> = {
|
|
133
|
+
[K in keyof M & StateEntityKind]: M[K] extends Record<string, string> ? {
|
|
134
|
+
[E in keyof M[K] & string]: Omit<CaptureStateOptions, "entity" | "kind" | "state"> & {
|
|
135
|
+
kind: K;
|
|
136
|
+
entity: E;
|
|
137
|
+
state: M[K][E];
|
|
138
|
+
};
|
|
139
|
+
}[keyof M[K] & string] : never;
|
|
140
|
+
}[keyof M & StateEntityKind];
|
|
141
|
+
interface TypedStateCapture<M> {
|
|
142
|
+
captureState(page: Page, testInfo: TestInfoLike, opts: TypedCaptureOptions<M>): Promise<StateRecord[]>;
|
|
143
|
+
recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Bind the capture helpers to a project's generated state space:
|
|
147
|
+
*
|
|
148
|
+
* ```ts
|
|
149
|
+
* // e2e/states/capture.ts — the ONE place e2e meets the registry
|
|
150
|
+
* import { createStateCapture } from "uidex/playwright"
|
|
151
|
+
* import type { UidexStates } from "@/uidex.gen"
|
|
152
|
+
* export const { captureState } = createStateCapture<UidexStates>()
|
|
153
|
+
* ```
|
|
154
|
+
*
|
|
155
|
+
* Purely a type-level narrowing — the runtime is the untyped `captureState`.
|
|
156
|
+
* Its value is closing the loop that let capture ids drift from the registry:
|
|
157
|
+
* before this, `entity` was a free string, so a spec could invent a name the
|
|
158
|
+
* registry had never heard of and nothing failed until a lint pass noticed the
|
|
159
|
+
* mismatch (or, when the entity kind was also wrong, never noticed at all).
|
|
160
|
+
*/
|
|
161
|
+
declare function createStateCapture<M extends Partial<StateSpace>>(): TypedStateCapture<M>;
|
|
119
162
|
|
|
120
|
-
export { CORE_STATE_KINDS, type CaptureStateOptions, type CoreStateKind, STATES_ATTACHMENT, type StateEntityKind, type StateKind, type StateRecord, type StatesPayload, THEMES, type Theme, WIDTHS, type WidthLabel, captureState, recordStates };
|
|
163
|
+
export { CORE_STATE_KINDS, type CaptureStateOptions, type CoreStateKind, STATES_ATTACHMENT, type StateEntityKind, type StateKind, type StateRecord, type StateSpace, type StatesPayload, THEMES, type Theme, type TypedCaptureOptions, type TypedStateCapture, WIDTHS, type WidthLabel, captureState, createStateCapture, recordStates };
|
|
@@ -77,12 +77,19 @@ async function captureState(page, testInfo, opts) {
|
|
|
77
77
|
await recordStates(testInfo, records);
|
|
78
78
|
return records;
|
|
79
79
|
}
|
|
80
|
+
function createStateCapture() {
|
|
81
|
+
return {
|
|
82
|
+
captureState: (page, testInfo, opts) => captureState(page, testInfo, opts),
|
|
83
|
+
recordStates
|
|
84
|
+
};
|
|
85
|
+
}
|
|
80
86
|
export {
|
|
81
87
|
CORE_STATE_KINDS,
|
|
82
88
|
STATES_ATTACHMENT,
|
|
83
89
|
THEMES,
|
|
84
90
|
WIDTHS,
|
|
85
91
|
captureState,
|
|
92
|
+
createStateCapture,
|
|
86
93
|
recordStates
|
|
87
94
|
};
|
|
88
95
|
//# sourceMappingURL=states.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/playwright/states.ts"],"sourcesContent":["import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n"],"mappings":";AAqBO,IAAM,oBAAoB;AAG1B,IAAM,SAAS,CAAC,SAAS,MAAM;AAE/B,IAAM,SAAS,EAAE,SAAS,MAAM,QAAQ,IAAI;AAO5C,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA0CA,eAAsB,aACpB,UACA,SACe;AACf,MAAI,QAAQ,WAAW,EAAG;AAC1B,QAAM,UAAyB,EAAE,QAAQ;AACzC,QAAM,SAAS,OAAO,mBAAmB;AAAA,IACvC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B,aAAa;AAAA,EACf,CAAC;AACH;AA4CA,SAAS,gBAAgB,MAAgC;AACvD,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,gBAAgB,MAAY,OAA6B;AACtE,QAAM,KAAK,aAAa,EAAE,aAAa,MAAM,CAAC;AAChD;AAGA,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W,CAAC;AAChE,cAAM,KAAK,WAAW;AAAA,UACpB;AAAA,UACA,UAAU,KAAK,YAAY;AAAA,UAC3B,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,UACtD,GAAI,KAAK,MAAM,SACX;AAAA,YACE,MAAM,KAAK,KAAK,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC;AAAA,YAC1C,WAAW;AAAA,UACb,IACA,CAAC;AAAA,QACP,CAAC;AACD,eAAO,OAAO;AAAA,MAChB;AACA,cAAQ,KAAK,MAAM;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,aAAa,UAAU,OAAO;AACpC,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/playwright/states.ts"],"sourcesContent":["import type { Page, TestInfo } from \"@playwright/test\"\n\n/**\n * Deterministic render-state capture for `uidex/playwright`.\n *\n * Two jobs, deliberately split:\n * 1. RECORD which `entity/state` a test captured (a `uidex-states`\n * attachment) — the reporter aggregates these into `uidex-states.json`,\n * which the scanner's completeness gate cross-checks against the states\n * declared in `export const uidex = { states: [...] }`.\n * 2. SHOOT the pixels — a thin wrapper over native `page.screenshot`. The\n * determinism knobs are Playwright's own: `animations: \"disabled\"` and\n * `caret: \"hide\"` are defaults, `style`/`stylePath` pierces the shadow DOM\n * to hide dev chrome, `mask` covers non-deterministic regions, and the\n * frozen clock / locale / timezone / colour-scheme live in the project's\n * `use` block. uidex does not re-implement `settle()`.\n *\n * The recording is the load-bearing half: even a spec that shoots nothing can\n * call `recordState` so the gate knows the state exists.\n */\n\nexport const STATES_ATTACHMENT = \"uidex-states\"\n\n/** Default light + dark; many surfaces use theme-dependent colours. */\nexport const THEMES = [\"light\", \"dark\"] as const\n/** Desktop is primary; narrow exercises the responsive reflow. */\nexport const WIDTHS = { desktop: 1440, narrow: 430 } as const\n\nexport type Theme = (typeof THEMES)[number]\nexport type WidthLabel = keyof typeof WIDTHS\nexport type StateEntityKind = \"page\" | \"feature\" | \"widget\"\n\n/** The four kinds the state-matrix gate expects every captured route to cover. */\nexport const CORE_STATE_KINDS = [\n \"loading\",\n \"empty\",\n \"populated\",\n \"error\",\n] as const\nexport type CoreStateKind = (typeof CORE_STATE_KINDS)[number]\n/** `variant` = any state outside the matrix (dialog, wizard step, multi-currency…). */\nexport type StateKind = CoreStateKind | \"variant\"\n\n/** One captured `entity/state` variant. */\nexport interface StateRecord {\n /** Registry entity id whose state was rendered (e.g. \"products\"). */\n entity: string\n /** Entity kind, so the gate can disambiguate a page vs feature of the same id. */\n kind?: StateEntityKind\n /** Declared state name (e.g. \"new-filled\"). */\n state: string\n /** Canonical kind for the state-matrix axis (defaults inferred from the name). */\n stateKind?: StateKind\n theme?: string\n width?: string\n /** Screenshot path, when one was written. */\n path?: string\n /**\n * The URL pathname the capture ran against, observed from `page.url()`. The\n * page-coverage gate normalizes it to a derived route pattern — so which route\n * a capture exercised is observed, never hand-declared. A `/shots/*` harness\n * URL matches no real route and gates nothing (correct for component captures).\n */\n url?: string\n /** Explicit route pattern override, when the observed URL can't be trusted. */\n route?: string\n}\n\n/** The `uidex-states` attachment body — an array of records from one test. */\nexport interface StatesPayload {\n records: StateRecord[]\n}\n\ntype TestInfoLike = Pick<TestInfo, \"attach\">\n\n/**\n * Attach one or more captured-state records to the test. Idempotent per call;\n * the reporter concatenates every test's records. Use directly when you shoot\n * with your own screenshot call and only need the state registered for the gate.\n */\nexport async function recordStates(\n testInfo: TestInfoLike,\n records: StateRecord[]\n): Promise<void> {\n if (records.length === 0) return\n const payload: StatesPayload = { records }\n await testInfo.attach(STATES_ATTACHMENT, {\n body: JSON.stringify(payload),\n contentType: \"application/json\",\n })\n}\n\nexport interface CaptureStateOptions {\n /** Registry entity id whose state this is. */\n entity: string\n kind?: StateEntityKind\n /** Declared state name (must match a name in the entity's `states`). */\n state: string\n /**\n * Canonical state kind for the matrix. Defaults to the state name when it is\n * itself a core kind (`loading`/`empty`/`populated`/`error`), else `variant`.\n */\n stateKind?: StateKind\n /**\n * Output dir for PNGs; defaults to `process.env.UIDEX_SHOTS_DIR`. When unset\n * the capture only RECORDS the state (no screenshot) — so a spec left in the\n * normal suite is a no-op beyond the attachment.\n */\n dir?: string\n themes?: readonly Theme[]\n widths?: readonly WidthLabel[]\n /** Awaited after each theme/width change, before the shutter (the state's tell). */\n ready?: (page: Page) => Promise<unknown>\n /**\n * Switch the app's theme. App-specific (next-themes uses localStorage + a\n * reload; others a class or cookie), so it is injected. Defaults to\n * Playwright's `emulateMedia({ colorScheme })`, which suits prefers-color-scheme.\n */\n setTheme?: (page: Page, theme: Theme) => Promise<void>\n /** CSS selectors to mask (opaque box) — for legitimately non-deterministic regions. */\n mask?: string[]\n /** Path to a stylesheet injected before the shot (hide dev chrome; pierces shadow DOM). */\n stylePath?: string\n fullPage?: boolean\n /**\n * Explicit route pattern this capture covers (e.g. \"/[scope]/products\"). By\n * default the observed `page.url()` pathname is recorded and the gate matches\n * it; pass `route` only when the observed URL is unreliable (e.g. a `/shots`\n * harness standing in for a real route).\n */\n route?: string\n}\n\n/** The URL pathname the page is currently on, for route observation. */\nfunction currentPathname(page: Page): string | undefined {\n try {\n return new URL(page.url()).pathname\n } catch {\n return undefined\n }\n}\n\nasync function defaultSetTheme(page: Page, theme: Theme): Promise<void> {\n await page.emulateMedia({ colorScheme: theme })\n}\n\n/** Infer the matrix kind: the state name if it is itself a core kind, else variant. */\nfunction inferStateKind(state: string, explicit?: StateKind): StateKind {\n if (explicit) return explicit\n return (CORE_STATE_KINDS as readonly string[]).includes(state)\n ? (state as StateKind)\n : \"variant\"\n}\n\nfunction shotName(\n opts: CaptureStateOptions,\n theme: Theme,\n label: WidthLabel,\n suffixWidth: boolean\n): string {\n const base = `${opts.entity}/${opts.state}`\n return suffixWidth ? `${base}-${theme}-${label}` : `${base}-${theme}`\n}\n\n/**\n * Capture one declared state across themes × widths, then record every variant\n * for the gate. Screenshot mechanics are native Playwright; determinism knobs\n * come from the project `use` block and the options above. Returns the records\n * it attached (also handy in tests).\n */\nexport async function captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: CaptureStateOptions\n): Promise<StateRecord[]> {\n const themes = opts.themes ?? THEMES\n const widths = opts.widths ?? ([\"desktop\"] as WidthLabel[])\n const suffixWidth = widths.length > 1\n const dir = opts.dir ?? process.env.UIDEX_SHOTS_DIR\n const setTheme = opts.setTheme ?? defaultSetTheme\n const observedUrl = currentPathname(page)\n const records: StateRecord[] = []\n\n for (const theme of themes) {\n await setTheme(page, theme)\n if (opts.ready) await opts.ready(page)\n for (const label of widths) {\n await page.setViewportSize({ width: WIDTHS[label], height: 900 })\n if (opts.ready) await opts.ready(page)\n const record: StateRecord = {\n entity: opts.entity,\n state: opts.state,\n stateKind: inferStateKind(opts.state, opts.stateKind),\n theme,\n width: label,\n ...(opts.kind ? { kind: opts.kind } : {}),\n ...(opts.route ? { route: opts.route } : {}),\n ...(observedUrl ? { url: observedUrl } : {}),\n }\n if (dir) {\n const path = `${dir}/${shotName(opts, theme, label, suffixWidth)}.png`\n await page.screenshot({\n path,\n fullPage: opts.fullPage ?? true,\n ...(opts.stylePath ? { stylePath: opts.stylePath } : {}),\n ...(opts.mask?.length\n ? {\n mask: opts.mask.map((s) => page.locator(s)),\n maskColor: \"#000000\",\n }\n : {}),\n })\n record.path = path\n }\n records.push(record)\n }\n }\n\n await recordStates(testInfo, records)\n return records\n}\n\n/**\n * The declared state space a generated `UidexStates` describes: entity kind →\n * entity id → that entity's own state names.\n */\nexport type StateSpace = {\n [K in StateEntityKind]: Record<string, string> | never\n}\n\n/**\n * Capture options narrowed to ONE entity of one kind, with only the states that\n * entity actually declares. Built as a union over (kind, entity) pairs so the\n * three fields are checked together — picking `widget`/`gate-badge` restricts\n * `state` to gate-badge's own names, and a page id is not assignable at all.\n */\nexport type TypedCaptureOptions<M> = {\n [K in keyof M & StateEntityKind]: M[K] extends Record<string, string>\n ? {\n [E in keyof M[K] & string]: Omit<\n CaptureStateOptions,\n \"entity\" | \"kind\" | \"state\"\n > & { kind: K; entity: E; state: M[K][E] }\n }[keyof M[K] & string]\n : never\n}[keyof M & StateEntityKind]\n\nexport interface TypedStateCapture<M> {\n captureState(\n page: Page,\n testInfo: TestInfoLike,\n opts: TypedCaptureOptions<M>\n ): Promise<StateRecord[]>\n recordStates(testInfo: TestInfoLike, records: StateRecord[]): Promise<void>\n}\n\n/**\n * Bind the capture helpers to a project's generated state space:\n *\n * ```ts\n * // e2e/states/capture.ts — the ONE place e2e meets the registry\n * import { createStateCapture } from \"uidex/playwright\"\n * import type { UidexStates } from \"@/uidex.gen\"\n * export const { captureState } = createStateCapture<UidexStates>()\n * ```\n *\n * Purely a type-level narrowing — the runtime is the untyped `captureState`.\n * Its value is closing the loop that let capture ids drift from the registry:\n * before this, `entity` was a free string, so a spec could invent a name the\n * registry had never heard of and nothing failed until a lint pass noticed the\n * mismatch (or, when the entity kind was also wrong, never noticed at all).\n */\nexport function createStateCapture<\n M extends Partial<StateSpace>,\n>(): TypedStateCapture<M> {\n return {\n captureState: (page, testInfo, opts) =>\n captureState(page, testInfo, opts as unknown as CaptureStateOptions),\n recordStates,\n }\n}\n"],"mappings":";AAqBO,IAAM,oBAAoB;AAG1B,IAAM,SAAS,CAAC,SAAS,MAAM;AAE/B,IAAM,SAAS,EAAE,SAAS,MAAM,QAAQ,IAAI;AAO5C,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA0CA,eAAsB,aACpB,UACA,SACe;AACf,MAAI,QAAQ,WAAW,EAAG;AAC1B,QAAM,UAAyB,EAAE,QAAQ;AACzC,QAAM,SAAS,OAAO,mBAAmB;AAAA,IACvC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B,aAAa;AAAA,EACf,CAAC;AACH;AA4CA,SAAS,gBAAgB,MAAgC;AACvD,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT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