uidex 0.9.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.
Files changed (43) hide show
  1. package/dist/cli/cli.cjs +1190 -335
  2. package/dist/cli/cli.cjs.map +1 -1
  3. package/dist/headless/index.cjs +3 -0
  4. package/dist/headless/index.cjs.map +1 -1
  5. package/dist/headless/index.d.cts +19 -13
  6. package/dist/headless/index.d.ts +19 -13
  7. package/dist/headless/index.js +3 -0
  8. package/dist/headless/index.js.map +1 -1
  9. package/dist/index.cjs +3 -0
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +19 -13
  12. package/dist/index.d.ts +19 -13
  13. package/dist/index.js +3 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/playwright/index.cjs +36 -7
  16. package/dist/playwright/index.cjs.map +1 -1
  17. package/dist/playwright/index.js +36 -7
  18. package/dist/playwright/index.js.map +1 -1
  19. package/dist/playwright/states-reporter.cjs +36 -7
  20. package/dist/playwright/states-reporter.cjs.map +1 -1
  21. package/dist/playwright/states-reporter.d.cts +15 -0
  22. package/dist/playwright/states-reporter.d.ts +15 -0
  23. package/dist/playwright/states-reporter.js +36 -7
  24. package/dist/playwright/states-reporter.js.map +1 -1
  25. package/dist/playwright/states.cjs +8 -0
  26. package/dist/playwright/states.cjs.map +1 -1
  27. package/dist/playwright/states.d.cts +44 -1
  28. package/dist/playwright/states.d.ts +44 -1
  29. package/dist/playwright/states.js +7 -0
  30. package/dist/playwright/states.js.map +1 -1
  31. package/dist/react/index.cjs +3 -0
  32. package/dist/react/index.cjs.map +1 -1
  33. package/dist/react/index.d.cts +19 -13
  34. package/dist/react/index.d.ts +19 -13
  35. package/dist/react/index.js +3 -0
  36. package/dist/react/index.js.map +1 -1
  37. package/dist/scan/index.cjs +1129 -244
  38. package/dist/scan/index.cjs.map +1 -1
  39. package/dist/scan/index.d.cts +379 -100
  40. package/dist/scan/index.d.ts +379 -100
  41. package/dist/scan/index.js +1109 -240
  42. package/dist/scan/index.js.map +1 -1
  43. package/package.json +1 -1
@@ -288,6 +288,19 @@ async function captureState(page, testInfo, opts) {
288
288
  // src/integrations/playwright/states-reporter.ts
289
289
  var fs2 = __toESM(require("fs"), 1);
290
290
  var path2 = __toESM(require("path"), 1);
291
+ function capturedKey(c) {
292
+ return `${c.kind ?? "page"}\0${c.entity}\0${c.state}`;
293
+ }
294
+ function readExisting(p) {
295
+ try {
296
+ const parsed = JSON.parse(fs2.readFileSync(p, "utf8"));
297
+ if (!parsed || typeof parsed !== "object") return null;
298
+ const m = parsed;
299
+ return Array.isArray(m.captured) ? { captured: m.captured, variants: m.variants ?? [] } : null;
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
291
304
  function keyOf(r) {
292
305
  return JSON.stringify([
293
306
  r.kind ?? null,
@@ -334,10 +347,12 @@ function parsePayload2(raw) {
334
347
  var UidexStatesReporter = class {
335
348
  outputPath;
336
349
  silent;
350
+ allowShrink;
337
351
  variants = [];
338
352
  constructor(options = {}) {
339
353
  this.outputPath = options.outputPath ?? "uidex-states.json";
340
354
  this.silent = options.silent ?? false;
355
+ this.allowShrink = options.allowShrink ?? false;
341
356
  }
342
357
  onTestEnd(_test, result) {
343
358
  for (const attachment of result.attachments) {
@@ -348,13 +363,27 @@ var UidexStatesReporter = class {
348
363
  }
349
364
  async onEnd(_result) {
350
365
  const manifest = aggregateStates(this.variants);
351
- fs2.mkdirSync(path2.dirname(path2.resolve(this.outputPath)), {
352
- recursive: true
353
- });
354
- fs2.writeFileSync(
355
- path2.resolve(this.outputPath),
356
- JSON.stringify(manifest, null, 2) + "\n"
357
- );
366
+ manifest.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
367
+ const target = path2.resolve(this.outputPath);
368
+ fs2.mkdirSync(path2.dirname(target), { recursive: true });
369
+ const existing = this.allowShrink ? null : readExisting(target);
370
+ const dropped = existing ? (() => {
371
+ const now = new Set(manifest.captured.map(capturedKey));
372
+ return existing.captured.map(capturedKey).filter((k) => !now.has(k)).sort();
373
+ })() : [];
374
+ const shrunk = dropped.length > 0;
375
+ const out = shrunk ? target.replace(/\.json$/i, "") + ".partial.json" : target;
376
+ fs2.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
377
+ if (shrunk) {
378
+ console.error(
379
+ `uidex states: \u26A0 run captured ${manifest.captured.length} state(s) but ${existing.captured.length} are committed \u2014 ${dropped.length} would be DROPPED, so ${path2.basename(target)} was left untouched and this run went to ${path2.basename(out)}.`
380
+ );
381
+ console.error(` dropped: ${dropped.join(", ")}`);
382
+ console.error(
383
+ ` 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.`
384
+ );
385
+ return;
386
+ }
358
387
  if (!this.silent) {
359
388
  const entities = new Set(manifest.captured.map((c) => c.entity)).size;
360
389
  console.log(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations/playwright/index.ts","../../src/integrations/playwright/selector.ts","../../src/integrations/playwright/fixture.ts","../../src/integrations/playwright/reporter.ts","../../src/integrations/playwright/states.ts","../../src/integrations/playwright/states-reporter.ts"],"sourcesContent":["export {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n UIDEX_ATTRS,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\nexport { test, expect, resolveFlow, createUidexFixture } from \"./fixture\"\nexport type { UidexFixtures, UidexLocator, UidexFixtureHandle } from \"./fixture\"\nexport {\n default as UidexCoverageReporter,\n type FlowCoverage,\n type UidexCoverageReport,\n type UidexReporterOptions,\n} from \"./reporter\"\nexport {\n STATES_ATTACHMENT,\n THEMES,\n WIDTHS,\n CORE_STATE_KINDS,\n recordStates,\n captureState,\n type Theme,\n type WidthLabel,\n type StateEntityKind,\n type StateKind,\n type CoreStateKind,\n type StateRecord,\n type StatesPayload,\n type CaptureStateOptions,\n} from \"./states\"\nexport {\n default as UidexStatesReporter,\n aggregateStates,\n type CapturedStateEntry,\n type CapturedStatesManifestOut,\n type UidexStatesReporterOptions,\n} from \"./states-reporter\"\n","const ATTRS = [\n \"data-uidex\",\n \"data-uidex-region\",\n \"data-uidex-widget\",\n \"data-uidex-primitive\",\n] as const\n\nexport const UIDEX_ATTRS = ATTRS\n\nexport function uidexSelector(id: string): string {\n const escaped = id.replace(/\"/g, '\\\\\"')\n return ATTRS.map((a) => `[${a}=\"${escaped}\"]`).join(\", \")\n}\n\nexport function kebab(input: string): string {\n return input\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport const FLOW_TAG = \"@uidex:flow\"\nexport const NOT_FLOW_TAG = \"@uidex:not-flow\"\nexport const COVERAGE_ATTACHMENT = \"uidex-coverage\"\n\nexport interface CoveragePayload {\n flow: string | null\n notFlow: boolean\n ids: string[]\n title: string\n}\n","import { test as base, expect } from \"@playwright/test\"\nimport type { Locator, TestInfo } from \"@playwright/test\"\nimport {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n kebab,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\n\nexport type UidexLocator<T extends string = string> = (id: T) => Locator\n\nexport interface UidexFixtures {\n uidex: UidexLocator\n}\n\ninterface FlowResolution {\n flow: string | null\n notFlow: boolean\n}\n\ntype TestInfoLike = Pick<TestInfo, \"tags\" | \"titlePath\" | \"title\">\n\nexport function resolveFlow(testInfo: TestInfoLike): FlowResolution {\n const tags = testInfo.tags ?? []\n const notFlow = tags.includes(NOT_FLOW_TAG)\n if (notFlow) return { flow: null, notFlow: true }\n if (!tags.includes(FLOW_TAG)) return { flow: null, notFlow: false }\n const describes = describeTitles(testInfo.titlePath ?? [], testInfo.title)\n const source =\n describes.length > 0\n ? describes[describes.length - 1]\n : (testInfo.title ?? \"\")\n return { flow: kebab(source) || null, notFlow: false }\n}\n\nconst FILE_RE = /\\.(spec|test)\\.(t|j)sx?$|\\.(t|j)sx?$|[\\\\/]/\n\nfunction describeTitles(titlePath: string[], testTitle: string): string[] {\n const end =\n titlePath.length > 0 && titlePath[titlePath.length - 1] === testTitle\n ? titlePath.length - 1\n : titlePath.length\n const out: string[] = []\n for (let i = 0; i < end; i++) {\n const entry = titlePath[i]\n if (!entry) continue\n if (FILE_RE.test(entry)) continue\n if (i === 0) continue // project name\n out.push(entry)\n }\n return out\n}\n\ninterface PageLike {\n locator: (selector: string) => Locator\n}\n\nexport interface UidexFixtureHandle {\n locator: UidexLocator\n buildPayload: () => CoveragePayload\n}\n\nexport function createUidexFixture(\n page: PageLike,\n testInfo: TestInfoLike\n): UidexFixtureHandle {\n const used = new Set<string>()\n const locator: UidexLocator = (id: string) => {\n used.add(id)\n return page.locator(uidexSelector(id))\n }\n const buildPayload = (): CoveragePayload => {\n const { flow, notFlow } = resolveFlow(testInfo)\n return {\n flow,\n notFlow,\n ids: [...used].sort(),\n title: testInfo.title,\n }\n }\n return { locator, buildPayload }\n}\n\nexport const test = base.extend<UidexFixtures>({\n uidex: async ({ page }, use, testInfo) => {\n const handle = createUidexFixture(page, testInfo)\n // eslint-disable-next-line react-hooks/rules-of-hooks\n await use(handle.locator)\n await testInfo.attach(COVERAGE_ATTACHMENT, {\n body: JSON.stringify(handle.buildPayload()),\n contentType: \"application/json\",\n })\n },\n})\n\nexport { expect }\n","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 { COVERAGE_ATTACHMENT, type CoveragePayload } from \"./selector\"\n\nexport interface UidexReporterOptions {\n outputPath?: string\n entityIds?: readonly string[]\n silent?: boolean\n}\n\nexport interface FlowCoverage {\n flow: string\n ids: string[]\n titles: string[]\n}\n\nexport interface UidexCoverageReport {\n flows: FlowCoverage[]\n untagged: { title: string; ids: string[] }[]\n touched: string[]\n untouched: string[]\n total: number\n percentage: number\n}\n\nexport default class UidexCoverageReporter implements Reporter {\n private readonly outputPath: string\n private readonly entityIds: readonly string[]\n private readonly silent: boolean\n private readonly flows = new Map<\n string,\n { ids: Set<string>; titles: Set<string> }\n >()\n private readonly untagged: { title: string; ids: string[] }[] = []\n private readonly touched = new Set<string>()\n\n constructor(options: UidexReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-coverage.json\"\n this.entityIds = options.entityIds ?? []\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 !== COVERAGE_ATTACHMENT) continue\n if (!attachment.body) continue\n const payload = parsePayload(attachment.body.toString())\n if (!payload) continue\n if (payload.notFlow) continue\n for (const id of payload.ids) this.touched.add(id)\n if (payload.flow) {\n const entry = this.flows.get(payload.flow) ?? {\n ids: new Set<string>(),\n titles: new Set<string>(),\n }\n for (const id of payload.ids) entry.ids.add(id)\n entry.titles.add(payload.title)\n this.flows.set(payload.flow, entry)\n } else {\n this.untagged.push({ title: payload.title, ids: payload.ids })\n }\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const flows: FlowCoverage[] = [...this.flows.entries()]\n .map(([flow, entry]) => ({\n flow,\n ids: [...entry.ids].sort(),\n titles: [...entry.titles].sort(),\n }))\n .sort((a, b) => a.flow.localeCompare(b.flow))\n\n const all = [...this.entityIds]\n const touched = all.filter((id) => this.touched.has(id)).sort()\n const untouched = all.filter((id) => !this.touched.has(id)).sort()\n const total = all.length\n const percentage =\n total > 0 ? Math.round((touched.length / total) * 100) : 0\n\n const report: UidexCoverageReport = {\n flows,\n untagged: this.untagged,\n touched,\n untouched,\n total,\n percentage,\n }\n\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(report, null, 2) + \"\\n\"\n )\n\n if (!this.silent) {\n const line =\n total > 0\n ? `uidex coverage: ${touched.length}/${total} entities (${percentage}%) across ${flows.length} flow(s)`\n : `uidex coverage: ${flows.length} flow(s), ${this.touched.size} entity id(s) touched`\n\n console.log(line)\n }\n }\n}\n\nfunction parsePayload(raw: string): CoveragePayload | null {\n try {\n const parsed = JSON.parse(raw) as Partial<CoveragePayload>\n if (!parsed || !Array.isArray(parsed.ids)) return null\n return {\n flow: typeof parsed.flow === \"string\" ? parsed.flow : null,\n notFlow: Boolean(parsed.notFlow),\n ids: parsed.ids.filter((x): x is string => typeof x === \"string\"),\n title: typeof parsed.title === \"string\" ? parsed.title : \"\",\n }\n } catch {\n return null\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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,QAAQ;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,cAAc;AAEpB,SAAS,cAAc,IAAoB;AAChD,QAAM,UAAU,GAAG,QAAQ,MAAM,KAAK;AACtC,SAAO,MAAM,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,OAAO,IAAI,EAAE,KAAK,IAAI;AAC1D;AAEO,SAAS,MAAM,OAAuB;AAC3C,SAAO,MACJ,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEO,IAAM,WAAW;AACjB,IAAM,eAAe;AACrB,IAAM,sBAAsB;;;ACxBnC,kBAAqC;AAwB9B,SAAS,YAAY,UAAwC;AAClE,QAAM,OAAO,SAAS,QAAQ,CAAC;AAC/B,QAAM,UAAU,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I,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":["base","base","path","fs","path","parsePayload"]}
1
+ {"version":3,"sources":["../../src/integrations/playwright/index.ts","../../src/integrations/playwright/selector.ts","../../src/integrations/playwright/fixture.ts","../../src/integrations/playwright/reporter.ts","../../src/integrations/playwright/states.ts","../../src/integrations/playwright/states-reporter.ts"],"sourcesContent":["export {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n UIDEX_ATTRS,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\nexport { test, expect, resolveFlow, createUidexFixture } from \"./fixture\"\nexport type { UidexFixtures, UidexLocator, UidexFixtureHandle } from \"./fixture\"\nexport {\n default as UidexCoverageReporter,\n type FlowCoverage,\n type UidexCoverageReport,\n type UidexReporterOptions,\n} from \"./reporter\"\nexport {\n STATES_ATTACHMENT,\n THEMES,\n WIDTHS,\n CORE_STATE_KINDS,\n recordStates,\n captureState,\n type Theme,\n type WidthLabel,\n type StateEntityKind,\n type StateKind,\n type CoreStateKind,\n type StateRecord,\n type StatesPayload,\n type CaptureStateOptions,\n} from \"./states\"\nexport {\n default as UidexStatesReporter,\n aggregateStates,\n type CapturedStateEntry,\n type CapturedStatesManifestOut,\n type UidexStatesReporterOptions,\n} from \"./states-reporter\"\n","const ATTRS = [\n \"data-uidex\",\n \"data-uidex-region\",\n \"data-uidex-widget\",\n \"data-uidex-primitive\",\n] as const\n\nexport const UIDEX_ATTRS = ATTRS\n\nexport function uidexSelector(id: string): string {\n const escaped = id.replace(/\"/g, '\\\\\"')\n return ATTRS.map((a) => `[${a}=\"${escaped}\"]`).join(\", \")\n}\n\nexport function kebab(input: string): string {\n return input\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport const FLOW_TAG = \"@uidex:flow\"\nexport const NOT_FLOW_TAG = \"@uidex:not-flow\"\nexport const COVERAGE_ATTACHMENT = \"uidex-coverage\"\n\nexport interface CoveragePayload {\n flow: string | null\n notFlow: boolean\n ids: string[]\n title: string\n}\n","import { test as base, expect } from \"@playwright/test\"\nimport type { Locator, TestInfo } from \"@playwright/test\"\nimport {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n kebab,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\n\nexport type UidexLocator<T extends string = string> = (id: T) => Locator\n\nexport interface UidexFixtures {\n uidex: UidexLocator\n}\n\ninterface FlowResolution {\n flow: string | null\n notFlow: boolean\n}\n\ntype TestInfoLike = Pick<TestInfo, \"tags\" | \"titlePath\" | \"title\">\n\nexport function resolveFlow(testInfo: TestInfoLike): FlowResolution {\n const tags = testInfo.tags ?? []\n const notFlow = tags.includes(NOT_FLOW_TAG)\n if (notFlow) return { flow: null, notFlow: true }\n if (!tags.includes(FLOW_TAG)) return { flow: null, notFlow: false }\n const describes = describeTitles(testInfo.titlePath ?? [], testInfo.title)\n const source =\n describes.length > 0\n ? describes[describes.length - 1]\n : (testInfo.title ?? \"\")\n return { flow: kebab(source) || null, notFlow: false }\n}\n\nconst FILE_RE = /\\.(spec|test)\\.(t|j)sx?$|\\.(t|j)sx?$|[\\\\/]/\n\nfunction describeTitles(titlePath: string[], testTitle: string): string[] {\n const end =\n titlePath.length > 0 && titlePath[titlePath.length - 1] === testTitle\n ? titlePath.length - 1\n : titlePath.length\n const out: string[] = []\n for (let i = 0; i < end; i++) {\n const entry = titlePath[i]\n if (!entry) continue\n if (FILE_RE.test(entry)) continue\n if (i === 0) continue // project name\n out.push(entry)\n }\n return out\n}\n\ninterface PageLike {\n locator: (selector: string) => Locator\n}\n\nexport interface UidexFixtureHandle {\n locator: UidexLocator\n buildPayload: () => CoveragePayload\n}\n\nexport function createUidexFixture(\n page: PageLike,\n testInfo: TestInfoLike\n): UidexFixtureHandle {\n const used = new Set<string>()\n const locator: UidexLocator = (id: string) => {\n used.add(id)\n return page.locator(uidexSelector(id))\n }\n const buildPayload = (): CoveragePayload => {\n const { flow, notFlow } = resolveFlow(testInfo)\n return {\n flow,\n notFlow,\n ids: [...used].sort(),\n title: testInfo.title,\n }\n }\n return { locator, buildPayload }\n}\n\nexport const test = base.extend<UidexFixtures>({\n uidex: async ({ page }, use, testInfo) => {\n const handle = createUidexFixture(page, testInfo)\n // eslint-disable-next-line react-hooks/rules-of-hooks\n await use(handle.locator)\n await testInfo.attach(COVERAGE_ATTACHMENT, {\n body: JSON.stringify(handle.buildPayload()),\n contentType: \"application/json\",\n })\n },\n})\n\nexport { expect }\n","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 { COVERAGE_ATTACHMENT, type CoveragePayload } from \"./selector\"\n\nexport interface UidexReporterOptions {\n outputPath?: string\n entityIds?: readonly string[]\n silent?: boolean\n}\n\nexport interface FlowCoverage {\n flow: string\n ids: string[]\n titles: string[]\n}\n\nexport interface UidexCoverageReport {\n flows: FlowCoverage[]\n untagged: { title: string; ids: string[] }[]\n touched: string[]\n untouched: string[]\n total: number\n percentage: number\n}\n\nexport default class UidexCoverageReporter implements Reporter {\n private readonly outputPath: string\n private readonly entityIds: readonly string[]\n private readonly silent: boolean\n private readonly flows = new Map<\n string,\n { ids: Set<string>; titles: Set<string> }\n >()\n private readonly untagged: { title: string; ids: string[] }[] = []\n private readonly touched = new Set<string>()\n\n constructor(options: UidexReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-coverage.json\"\n this.entityIds = options.entityIds ?? []\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 !== COVERAGE_ATTACHMENT) continue\n if (!attachment.body) continue\n const payload = parsePayload(attachment.body.toString())\n if (!payload) continue\n if (payload.notFlow) continue\n for (const id of payload.ids) this.touched.add(id)\n if (payload.flow) {\n const entry = this.flows.get(payload.flow) ?? {\n ids: new Set<string>(),\n titles: new Set<string>(),\n }\n for (const id of payload.ids) entry.ids.add(id)\n entry.titles.add(payload.title)\n this.flows.set(payload.flow, entry)\n } else {\n this.untagged.push({ title: payload.title, ids: payload.ids })\n }\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const flows: FlowCoverage[] = [...this.flows.entries()]\n .map(([flow, entry]) => ({\n flow,\n ids: [...entry.ids].sort(),\n titles: [...entry.titles].sort(),\n }))\n .sort((a, b) => a.flow.localeCompare(b.flow))\n\n const all = [...this.entityIds]\n const touched = all.filter((id) => this.touched.has(id)).sort()\n const untouched = all.filter((id) => !this.touched.has(id)).sort()\n const total = all.length\n const percentage =\n total > 0 ? Math.round((touched.length / total) * 100) : 0\n\n const report: UidexCoverageReport = {\n flows,\n untagged: this.untagged,\n touched,\n untouched,\n total,\n percentage,\n }\n\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(report, null, 2) + \"\\n\"\n )\n\n if (!this.silent) {\n const line =\n total > 0\n ? `uidex coverage: ${touched.length}/${total} entities (${percentage}%) across ${flows.length} flow(s)`\n : `uidex coverage: ${flows.length} flow(s), ${this.touched.size} entity id(s) touched`\n\n console.log(line)\n }\n }\n}\n\nfunction parsePayload(raw: string): CoveragePayload | null {\n try {\n const parsed = JSON.parse(raw) as Partial<CoveragePayload>\n if (!parsed || !Array.isArray(parsed.ids)) return null\n return {\n flow: typeof parsed.flow === \"string\" ? parsed.flow : null,\n notFlow: Boolean(parsed.notFlow),\n ids: parsed.ids.filter((x): x is string => typeof x === \"string\"),\n title: typeof parsed.title === \"string\" ? parsed.title : \"\",\n }\n } catch {\n return null\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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,QAAQ;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,cAAc;AAEpB,SAAS,cAAc,IAAoB;AAChD,QAAM,UAAU,GAAG,QAAQ,MAAM,KAAK;AACtC,SAAO,MAAM,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,OAAO,IAAI,EAAE,KAAK,IAAI;AAC1D;AAEO,SAAS,MAAM,OAAuB;AAC3C,SAAO,MACJ,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEO,IAAM,WAAW;AACjB,IAAM,eAAe;AACrB,IAAM,sBAAsB;;;ACxBnC,kBAAqC;AAwB9B,SAAS,YAAY,UAAwC;AAClE,QAAM,OAAO,SAAS,QAAQ,CAAC;AAC/B,QAAM,UAAU,KAAK,SAAS,YAAY;AAC1C,MAAI,QAAS,QAAO,EAAE,MAAM,MAAM,SAAS,KAAK;AAChD,MAAI,CAAC,KAAK,SAAS,QAAQ,EAAG,QAAO,EAAE,MAAM,MAAM,SAAS,MAAM;AAClE,QAAM,YAAY,eAAe,SAAS,aAAa,CAAC,GAAG,SAA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@@ -235,6 +235,19 @@ async function captureState(page, testInfo, opts) {
235
235
  // src/integrations/playwright/states-reporter.ts
236
236
  import * as fs2 from "fs";
237
237
  import * as path2 from "path";
238
+ function capturedKey(c) {
239
+ return `${c.kind ?? "page"}\0${c.entity}\0${c.state}`;
240
+ }
241
+ function readExisting(p) {
242
+ try {
243
+ const parsed = JSON.parse(fs2.readFileSync(p, "utf8"));
244
+ if (!parsed || typeof parsed !== "object") return null;
245
+ const m = parsed;
246
+ return Array.isArray(m.captured) ? { captured: m.captured, variants: m.variants ?? [] } : null;
247
+ } catch {
248
+ return null;
249
+ }
250
+ }
238
251
  function keyOf(r) {
239
252
  return JSON.stringify([
240
253
  r.kind ?? null,
@@ -281,10 +294,12 @@ function parsePayload2(raw) {
281
294
  var UidexStatesReporter = class {
282
295
  outputPath;
283
296
  silent;
297
+ allowShrink;
284
298
  variants = [];
285
299
  constructor(options = {}) {
286
300
  this.outputPath = options.outputPath ?? "uidex-states.json";
287
301
  this.silent = options.silent ?? false;
302
+ this.allowShrink = options.allowShrink ?? false;
288
303
  }
289
304
  onTestEnd(_test, result) {
290
305
  for (const attachment of result.attachments) {
@@ -295,13 +310,27 @@ var UidexStatesReporter = class {
295
310
  }
296
311
  async onEnd(_result) {
297
312
  const manifest = aggregateStates(this.variants);
298
- fs2.mkdirSync(path2.dirname(path2.resolve(this.outputPath)), {
299
- recursive: true
300
- });
301
- fs2.writeFileSync(
302
- path2.resolve(this.outputPath),
303
- JSON.stringify(manifest, null, 2) + "\n"
304
- );
313
+ manifest.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
314
+ const target = path2.resolve(this.outputPath);
315
+ fs2.mkdirSync(path2.dirname(target), { recursive: true });
316
+ const existing = this.allowShrink ? null : readExisting(target);
317
+ const dropped = existing ? (() => {
318
+ const now = new Set(manifest.captured.map(capturedKey));
319
+ return existing.captured.map(capturedKey).filter((k) => !now.has(k)).sort();
320
+ })() : [];
321
+ const shrunk = dropped.length > 0;
322
+ const out = shrunk ? target.replace(/\.json$/i, "") + ".partial.json" : target;
323
+ fs2.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
324
+ if (shrunk) {
325
+ console.error(
326
+ `uidex states: \u26A0 run captured ${manifest.captured.length} state(s) but ${existing.captured.length} are committed \u2014 ${dropped.length} would be DROPPED, so ${path2.basename(target)} was left untouched and this run went to ${path2.basename(out)}.`
327
+ );
328
+ console.error(` dropped: ${dropped.join(", ")}`);
329
+ console.error(
330
+ ` 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.`
331
+ );
332
+ return;
333
+ }
305
334
  if (!this.silent) {
306
335
  const entities = new Set(manifest.captured.map((c) => c.entity)).size;
307
336
  console.log(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations/playwright/selector.ts","../../src/integrations/playwright/fixture.ts","../../src/integrations/playwright/reporter.ts","../../src/integrations/playwright/states.ts","../../src/integrations/playwright/states-reporter.ts"],"sourcesContent":["const ATTRS = [\n \"data-uidex\",\n \"data-uidex-region\",\n \"data-uidex-widget\",\n \"data-uidex-primitive\",\n] as const\n\nexport const UIDEX_ATTRS = ATTRS\n\nexport function uidexSelector(id: string): string {\n const escaped = id.replace(/\"/g, '\\\\\"')\n return ATTRS.map((a) => `[${a}=\"${escaped}\"]`).join(\", \")\n}\n\nexport function kebab(input: string): string {\n return input\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport const FLOW_TAG = \"@uidex:flow\"\nexport const NOT_FLOW_TAG = \"@uidex:not-flow\"\nexport const COVERAGE_ATTACHMENT = \"uidex-coverage\"\n\nexport interface CoveragePayload {\n flow: string | null\n notFlow: boolean\n ids: string[]\n title: string\n}\n","import { test as base, expect } from \"@playwright/test\"\nimport type { Locator, TestInfo } from \"@playwright/test\"\nimport {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n kebab,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\n\nexport type UidexLocator<T extends string = string> = (id: T) => Locator\n\nexport interface UidexFixtures {\n uidex: UidexLocator\n}\n\ninterface FlowResolution {\n flow: string | null\n notFlow: boolean\n}\n\ntype TestInfoLike = Pick<TestInfo, \"tags\" | \"titlePath\" | \"title\">\n\nexport function resolveFlow(testInfo: TestInfoLike): FlowResolution {\n const tags = testInfo.tags ?? []\n const notFlow = tags.includes(NOT_FLOW_TAG)\n if (notFlow) return { flow: null, notFlow: true }\n if (!tags.includes(FLOW_TAG)) return { flow: null, notFlow: false }\n const describes = describeTitles(testInfo.titlePath ?? [], testInfo.title)\n const source =\n describes.length > 0\n ? describes[describes.length - 1]\n : (testInfo.title ?? \"\")\n return { flow: kebab(source) || null, notFlow: false }\n}\n\nconst FILE_RE = /\\.(spec|test)\\.(t|j)sx?$|\\.(t|j)sx?$|[\\\\/]/\n\nfunction describeTitles(titlePath: string[], testTitle: string): string[] {\n const end =\n titlePath.length > 0 && titlePath[titlePath.length - 1] === testTitle\n ? titlePath.length - 1\n : titlePath.length\n const out: string[] = []\n for (let i = 0; i < end; i++) {\n const entry = titlePath[i]\n if (!entry) continue\n if (FILE_RE.test(entry)) continue\n if (i === 0) continue // project name\n out.push(entry)\n }\n return out\n}\n\ninterface PageLike {\n locator: (selector: string) => Locator\n}\n\nexport interface UidexFixtureHandle {\n locator: UidexLocator\n buildPayload: () => CoveragePayload\n}\n\nexport function createUidexFixture(\n page: PageLike,\n testInfo: TestInfoLike\n): UidexFixtureHandle {\n const used = new Set<string>()\n const locator: UidexLocator = (id: string) => {\n used.add(id)\n return page.locator(uidexSelector(id))\n }\n const buildPayload = (): CoveragePayload => {\n const { flow, notFlow } = resolveFlow(testInfo)\n return {\n flow,\n notFlow,\n ids: [...used].sort(),\n title: testInfo.title,\n }\n }\n return { locator, buildPayload }\n}\n\nexport const test = base.extend<UidexFixtures>({\n uidex: async ({ page }, use, testInfo) => {\n const handle = createUidexFixture(page, testInfo)\n // eslint-disable-next-line react-hooks/rules-of-hooks\n await use(handle.locator)\n await testInfo.attach(COVERAGE_ATTACHMENT, {\n body: JSON.stringify(handle.buildPayload()),\n contentType: \"application/json\",\n })\n },\n})\n\nexport { expect }\n","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 { COVERAGE_ATTACHMENT, type CoveragePayload } from \"./selector\"\n\nexport interface UidexReporterOptions {\n outputPath?: string\n entityIds?: readonly string[]\n silent?: boolean\n}\n\nexport interface FlowCoverage {\n flow: string\n ids: string[]\n titles: string[]\n}\n\nexport interface UidexCoverageReport {\n flows: FlowCoverage[]\n untagged: { title: string; ids: string[] }[]\n touched: string[]\n untouched: string[]\n total: number\n percentage: number\n}\n\nexport default class UidexCoverageReporter implements Reporter {\n private readonly outputPath: string\n private readonly entityIds: readonly string[]\n private readonly silent: boolean\n private readonly flows = new Map<\n string,\n { ids: Set<string>; titles: Set<string> }\n >()\n private readonly untagged: { title: string; ids: string[] }[] = []\n private readonly touched = new Set<string>()\n\n constructor(options: UidexReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-coverage.json\"\n this.entityIds = options.entityIds ?? []\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 !== COVERAGE_ATTACHMENT) continue\n if (!attachment.body) continue\n const payload = parsePayload(attachment.body.toString())\n if (!payload) continue\n if (payload.notFlow) continue\n for (const id of payload.ids) this.touched.add(id)\n if (payload.flow) {\n const entry = this.flows.get(payload.flow) ?? {\n ids: new Set<string>(),\n titles: new Set<string>(),\n }\n for (const id of payload.ids) entry.ids.add(id)\n entry.titles.add(payload.title)\n this.flows.set(payload.flow, entry)\n } else {\n this.untagged.push({ title: payload.title, ids: payload.ids })\n }\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const flows: FlowCoverage[] = [...this.flows.entries()]\n .map(([flow, entry]) => ({\n flow,\n ids: [...entry.ids].sort(),\n titles: [...entry.titles].sort(),\n }))\n .sort((a, b) => a.flow.localeCompare(b.flow))\n\n const all = [...this.entityIds]\n const touched = all.filter((id) => this.touched.has(id)).sort()\n const untouched = all.filter((id) => !this.touched.has(id)).sort()\n const total = all.length\n const percentage =\n total > 0 ? Math.round((touched.length / total) * 100) : 0\n\n const report: UidexCoverageReport = {\n flows,\n untagged: this.untagged,\n touched,\n untouched,\n total,\n percentage,\n }\n\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(report, null, 2) + \"\\n\"\n )\n\n if (!this.silent) {\n const line =\n total > 0\n ? `uidex coverage: ${touched.length}/${total} entities (${percentage}%) across ${flows.length} flow(s)`\n : `uidex coverage: ${flows.length} flow(s), ${this.touched.size} entity id(s) touched`\n\n console.log(line)\n }\n }\n}\n\nfunction parsePayload(raw: string): CoveragePayload | null {\n try {\n const parsed = JSON.parse(raw) as Partial<CoveragePayload>\n if (!parsed || !Array.isArray(parsed.ids)) return null\n return {\n flow: typeof parsed.flow === \"string\" ? parsed.flow : null,\n notFlow: Boolean(parsed.notFlow),\n ids: parsed.ids.filter((x): x is string => typeof x === \"string\"),\n title: typeof parsed.title === \"string\" ? parsed.title : \"\",\n }\n } catch {\n return null\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","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"],"mappings":";AAAA,IAAM,QAAQ;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,cAAc;AAEpB,SAAS,cAAc,IAAoB;AAChD,QAAM,UAAU,GAAG,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SAAS,kBAAmB;AAC3C,UAAI,CAAC,WAAW,KAAM;AACtB,WAAK,SAAS,KAAK,GAAGA,cAAa,WAAW,KAAK,SAAS,CAAC,CAAC;AAAA,IAChE;AAAA,EACF;AAAA,EAEA,MAAM,MAAM,SAAoC;AAC9C,UAAM,WAAW,gBAAgB,KAAK,QAAQ;AAC9C,IAAG,cAAe,cAAa,cAAQ,KAAK,UAAU,CAAC,GAAG;AAAA,MACxD,WAAW;AAAA,IACb,CAAC;AACD,IAAG;AAAA,MACI,cAAQ,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":["base","path","fs","path","parsePayload"]}
1
+ {"version":3,"sources":["../../src/integrations/playwright/selector.ts","../../src/integrations/playwright/fixture.ts","../../src/integrations/playwright/reporter.ts","../../src/integrations/playwright/states.ts","../../src/integrations/playwright/states-reporter.ts"],"sourcesContent":["const ATTRS = [\n \"data-uidex\",\n \"data-uidex-region\",\n \"data-uidex-widget\",\n \"data-uidex-primitive\",\n] as const\n\nexport const UIDEX_ATTRS = ATTRS\n\nexport function uidexSelector(id: string): string {\n const escaped = id.replace(/\"/g, '\\\\\"')\n return ATTRS.map((a) => `[${a}=\"${escaped}\"]`).join(\", \")\n}\n\nexport function kebab(input: string): string {\n return input\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport const FLOW_TAG = \"@uidex:flow\"\nexport const NOT_FLOW_TAG = \"@uidex:not-flow\"\nexport const COVERAGE_ATTACHMENT = \"uidex-coverage\"\n\nexport interface CoveragePayload {\n flow: string | null\n notFlow: boolean\n ids: string[]\n title: string\n}\n","import { test as base, expect } from \"@playwright/test\"\nimport type { Locator, TestInfo } from \"@playwright/test\"\nimport {\n COVERAGE_ATTACHMENT,\n FLOW_TAG,\n NOT_FLOW_TAG,\n kebab,\n uidexSelector,\n type CoveragePayload,\n} from \"./selector\"\n\nexport type UidexLocator<T extends string = string> = (id: T) => Locator\n\nexport interface UidexFixtures {\n uidex: UidexLocator\n}\n\ninterface FlowResolution {\n flow: string | null\n notFlow: boolean\n}\n\ntype TestInfoLike = Pick<TestInfo, \"tags\" | \"titlePath\" | \"title\">\n\nexport function resolveFlow(testInfo: TestInfoLike): FlowResolution {\n const tags = testInfo.tags ?? []\n const notFlow = tags.includes(NOT_FLOW_TAG)\n if (notFlow) return { flow: null, notFlow: true }\n if (!tags.includes(FLOW_TAG)) return { flow: null, notFlow: false }\n const describes = describeTitles(testInfo.titlePath ?? [], testInfo.title)\n const source =\n describes.length > 0\n ? describes[describes.length - 1]\n : (testInfo.title ?? \"\")\n return { flow: kebab(source) || null, notFlow: false }\n}\n\nconst FILE_RE = /\\.(spec|test)\\.(t|j)sx?$|\\.(t|j)sx?$|[\\\\/]/\n\nfunction describeTitles(titlePath: string[], testTitle: string): string[] {\n const end =\n titlePath.length > 0 && titlePath[titlePath.length - 1] === testTitle\n ? titlePath.length - 1\n : titlePath.length\n const out: string[] = []\n for (let i = 0; i < end; i++) {\n const entry = titlePath[i]\n if (!entry) continue\n if (FILE_RE.test(entry)) continue\n if (i === 0) continue // project name\n out.push(entry)\n }\n return out\n}\n\ninterface PageLike {\n locator: (selector: string) => Locator\n}\n\nexport interface UidexFixtureHandle {\n locator: UidexLocator\n buildPayload: () => CoveragePayload\n}\n\nexport function createUidexFixture(\n page: PageLike,\n testInfo: TestInfoLike\n): UidexFixtureHandle {\n const used = new Set<string>()\n const locator: UidexLocator = (id: string) => {\n used.add(id)\n return page.locator(uidexSelector(id))\n }\n const buildPayload = (): CoveragePayload => {\n const { flow, notFlow } = resolveFlow(testInfo)\n return {\n flow,\n notFlow,\n ids: [...used].sort(),\n title: testInfo.title,\n }\n }\n return { locator, buildPayload }\n}\n\nexport const test = base.extend<UidexFixtures>({\n uidex: async ({ page }, use, testInfo) => {\n const handle = createUidexFixture(page, testInfo)\n // eslint-disable-next-line react-hooks/rules-of-hooks\n await use(handle.locator)\n await testInfo.attach(COVERAGE_ATTACHMENT, {\n body: JSON.stringify(handle.buildPayload()),\n contentType: \"application/json\",\n })\n },\n})\n\nexport { expect }\n","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 { COVERAGE_ATTACHMENT, type CoveragePayload } from \"./selector\"\n\nexport interface UidexReporterOptions {\n outputPath?: string\n entityIds?: readonly string[]\n silent?: boolean\n}\n\nexport interface FlowCoverage {\n flow: string\n ids: string[]\n titles: string[]\n}\n\nexport interface UidexCoverageReport {\n flows: FlowCoverage[]\n untagged: { title: string; ids: string[] }[]\n touched: string[]\n untouched: string[]\n total: number\n percentage: number\n}\n\nexport default class UidexCoverageReporter implements Reporter {\n private readonly outputPath: string\n private readonly entityIds: readonly string[]\n private readonly silent: boolean\n private readonly flows = new Map<\n string,\n { ids: Set<string>; titles: Set<string> }\n >()\n private readonly untagged: { title: string; ids: string[] }[] = []\n private readonly touched = new Set<string>()\n\n constructor(options: UidexReporterOptions = {}) {\n this.outputPath = options.outputPath ?? \"uidex-coverage.json\"\n this.entityIds = options.entityIds ?? []\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 !== COVERAGE_ATTACHMENT) continue\n if (!attachment.body) continue\n const payload = parsePayload(attachment.body.toString())\n if (!payload) continue\n if (payload.notFlow) continue\n for (const id of payload.ids) this.touched.add(id)\n if (payload.flow) {\n const entry = this.flows.get(payload.flow) ?? {\n ids: new Set<string>(),\n titles: new Set<string>(),\n }\n for (const id of payload.ids) entry.ids.add(id)\n entry.titles.add(payload.title)\n this.flows.set(payload.flow, entry)\n } else {\n this.untagged.push({ title: payload.title, ids: payload.ids })\n }\n }\n }\n\n async onEnd(_result: FullResult): Promise<void> {\n const flows: FlowCoverage[] = [...this.flows.entries()]\n .map(([flow, entry]) => ({\n flow,\n ids: [...entry.ids].sort(),\n titles: [...entry.titles].sort(),\n }))\n .sort((a, b) => a.flow.localeCompare(b.flow))\n\n const all = [...this.entityIds]\n const touched = all.filter((id) => this.touched.has(id)).sort()\n const untouched = all.filter((id) => !this.touched.has(id)).sort()\n const total = all.length\n const percentage =\n total > 0 ? Math.round((touched.length / total) * 100) : 0\n\n const report: UidexCoverageReport = {\n flows,\n untagged: this.untagged,\n touched,\n untouched,\n total,\n percentage,\n }\n\n fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {\n recursive: true,\n })\n fs.writeFileSync(\n path.resolve(this.outputPath),\n JSON.stringify(report, null, 2) + \"\\n\"\n )\n\n if (!this.silent) {\n const line =\n total > 0\n ? `uidex coverage: ${touched.length}/${total} entities (${percentage}%) across ${flows.length} flow(s)`\n : `uidex coverage: ${flows.length} flow(s), ${this.touched.size} entity id(s) touched`\n\n console.log(line)\n }\n }\n}\n\nfunction parsePayload(raw: string): CoveragePayload | null {\n try {\n const parsed = JSON.parse(raw) as Partial<CoveragePayload>\n if (!parsed || !Array.isArray(parsed.ids)) return null\n return {\n flow: typeof parsed.flow === \"string\" ? parsed.flow : null,\n notFlow: Boolean(parsed.notFlow),\n ids: parsed.ids.filter((x): x is string => typeof x === \"string\"),\n title: typeof parsed.title === \"string\" ? parsed.title : \"\",\n }\n } catch {\n return null\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","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"],"mappings":";AAAA,IAAM,QAAQ;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,cAAc;AAEpB,SAAS,cAAc,IAAoB;AAChD,QAAM,UAAU,GAAG,QAAQ,MAAM,KAAK;AACtC,SAAO,MAAM,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,OAAO,IAAI,EAAE,KAAK,IAAI;AAC1D;AAEO,SAAS,MAAM,OAAuB;AAC3C,SAAO,MACJ,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AAC3B;AAEO,IAAM,WAAW;AACjB,IAAM,eAAe;AACrB,IAAM,sBAAsB;;;ACxBnC,SAAS,QAAQ,MAAM,cAAc;AAwB9B,SAAS,YAAY,UAAwC;AAClE,QAAM,OAAO,SAAS,QAAQ,CAAC;AAC/B,QAAM,UAAU,KAAK,SAAS,YAAY;AAC1C,MAAI,QAAS,QAAO,EAAE,MAAM,MAAM,SAAS,KAAK;AAChD,MAAI,CAAC,KAAK,SAAS,QAAQ,EAAG,QAAO,EAAE,MAAM,MAAM,SAAS,MAAM;AAClE,QAAM,YAAY,eAAe,SAAS,aAAa,CAAC,GAAG,SAAS,KAAK;AACzE,QAAM,SACJ,UAAU,SAAS,IACf,UAAU,UAAU,SAAS,CAAC,IAC7B,SAAS,SAAS;AACzB,SAAO,EAAE,MAAM,MAAM,MAAM,KAAK,MAAM,SAAS,MAAM;AACvD;AAEA,IAAM,UAAU;AAEhB,SAAS,eAAe,WAAqB,WAA6B;AACxE,QAAM,MACJ,UAAU,SAAS,KAAK,UAAU,UAAU,SAAS,CAAC,MAAM,YACxD,UAAU,SAAS,IACnB,UAAU;AAChB,QAAM,MAAgB,CAAC;AACvB,WAAS,IA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aAAO,SAAS,SACb,IAAI,WAAW,EACf,OAAO,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EACzB,KAAK;AAAA,IACV,GAAG,IACH,CAAC;AAEL,UAAM,SAAS,QAAQ,SAAS;AAChC,UAAM,MAAM,SACR,OAAO,QAAQ,YAAY,EAAE,IAAI,kBACjC;AACJ,IAAG,kBAAc,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,eAAS,MAAM,CAAC,4CAAiD,eAAS,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":["base","path","fs","path","parsePayload"]}
@@ -41,6 +41,19 @@ var path = __toESM(require("path"), 1);
41
41
  var STATES_ATTACHMENT = "uidex-states";
42
42
 
43
43
  // src/integrations/playwright/states-reporter.ts
44
+ function capturedKey(c) {
45
+ return `${c.kind ?? "page"}\0${c.entity}\0${c.state}`;
46
+ }
47
+ function readExisting(p) {
48
+ try {
49
+ const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
50
+ if (!parsed || typeof parsed !== "object") return null;
51
+ const m = parsed;
52
+ return Array.isArray(m.captured) ? { captured: m.captured, variants: m.variants ?? [] } : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
44
57
  function keyOf(r) {
45
58
  return JSON.stringify([
46
59
  r.kind ?? null,
@@ -87,10 +100,12 @@ function parsePayload(raw) {
87
100
  var UidexStatesReporter = class {
88
101
  outputPath;
89
102
  silent;
103
+ allowShrink;
90
104
  variants = [];
91
105
  constructor(options = {}) {
92
106
  this.outputPath = options.outputPath ?? "uidex-states.json";
93
107
  this.silent = options.silent ?? false;
108
+ this.allowShrink = options.allowShrink ?? false;
94
109
  }
95
110
  onTestEnd(_test, result) {
96
111
  for (const attachment of result.attachments) {
@@ -101,13 +116,27 @@ var UidexStatesReporter = class {
101
116
  }
102
117
  async onEnd(_result) {
103
118
  const manifest = aggregateStates(this.variants);
104
- fs.mkdirSync(path.dirname(path.resolve(this.outputPath)), {
105
- recursive: true
106
- });
107
- fs.writeFileSync(
108
- path.resolve(this.outputPath),
109
- JSON.stringify(manifest, null, 2) + "\n"
110
- );
119
+ manifest.generatedAt = (/* @__PURE__ */ new Date()).toISOString();
120
+ const target = path.resolve(this.outputPath);
121
+ fs.mkdirSync(path.dirname(target), { recursive: true });
122
+ const existing = this.allowShrink ? null : readExisting(target);
123
+ const dropped = existing ? (() => {
124
+ const now = new Set(manifest.captured.map(capturedKey));
125
+ return existing.captured.map(capturedKey).filter((k) => !now.has(k)).sort();
126
+ })() : [];
127
+ const shrunk = dropped.length > 0;
128
+ const out = shrunk ? target.replace(/\.json$/i, "") + ".partial.json" : target;
129
+ fs.writeFileSync(out, JSON.stringify(manifest, null, 2) + "\n");
130
+ if (shrunk) {
131
+ console.error(
132
+ `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)}.`
133
+ );
134
+ console.error(` dropped: ${dropped.join(", ")}`);
135
+ console.error(
136
+ ` 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.`
137
+ );
138
+ return;
139
+ }
111
140
  if (!this.silent) {
112
141
  const entities = new Set(manifest.captured.map((c) => c.entity)).size;
113
142
  console.log(