strata-react 0.1.5 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -9
- package/bin/strata-visual.js +6 -0
- package/dist/components/active-list.d.ts +46 -0
- package/dist/components/button.d.ts +9 -0
- package/dist/components/checkbox.d.ts +14 -0
- package/dist/components/data-table.d.ts +14 -0
- package/dist/components/hotkeys.d.ts +29 -0
- package/dist/components/infinite-list.d.ts +29 -0
- package/dist/components/line-chart.d.ts +24 -3
- package/dist/components/selection.d.ts +22 -0
- package/dist/components/undo.d.ts +51 -8
- package/dist/components/virtual-list.d.ts +5 -1
- package/dist/index.d.ts +9 -4
- package/dist/index.js +857 -79
- package/dist/index.js.map +1 -1
- package/dist/query/index.d.ts +2 -1
- package/dist/query/infinite.d.ts +47 -0
- package/dist/{query-CmdlXVW_.js → query-5469ipOC.js} +4 -3
- package/dist/{query-CmdlXVW_.js.map → query-5469ipOC.js.map} +1 -1
- package/dist/run-CLQi924v.js +605 -0
- package/dist/run-CLQi924v.js.map +1 -0
- package/dist/testing.js +1 -1
- package/dist/visual/capture.d.ts +22 -0
- package/dist/visual/cli.d.ts +5 -0
- package/dist/visual/compare.d.ts +31 -0
- package/dist/visual/index.d.ts +17 -0
- package/dist/visual/run.d.ts +22 -0
- package/dist/visual/serve.d.ts +11 -0
- package/dist/visual/targets.d.ts +17 -0
- package/dist/visual/types.d.ts +158 -0
- package/dist/visual-cli.js +118 -0
- package/dist/visual-cli.js.map +1 -0
- package/dist/visual.js +1 -0
- package/package.json +32 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-CLQi924v.js","names":[],"sources":["../src/visual/capture.ts","../src/visual/compare.ts","../src/visual/serve.ts","../src/visual/types.ts","../src/visual/targets.ts","../src/visual/run.ts"],"sourcesContent":["// Taking one shot. Everything here is about determinism: a fresh browser context per shot so\n// shots cannot affect each other, reduced motion and frozen animations so the settled state is\n// what is captured, fonts awaited, the theme set both as the colour scheme and as the class the\n// app reads, the clock optionally frozen, and, for routes, every request the page makes answered\n// by MSW handlers in Node, so the screenshot depends on nothing outside the suite.\nimport type { Browser, BrowserContext, Page, Request as PlaywrightRequest, Route as PlaywrightRoute } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\nimport type { Shot } from \"./types\";\n\n// Animations and transitions off, caret hidden: a screenshot is of the settled state.\nconst freeze = `*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }`;\n\n/** Options shared by every shot of a run. */\nexport interface CaptureOptions {\n /** Where `shot.path` resolves, ending in `/`. */\n baseUrl: string;\n time?: string | number | Date;\n timezone?: string;\n locale?: string;\n /** Block service workers (an app's own MSW worker or PWA cache would bypass the handlers). */\n blockServiceWorkers?: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n}\n\n/** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */\nexport function resolveShotUrl(path: string, baseUrl: string): string {\n if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return path;\n return new URL(path.replace(/^\\/+/, \"\"), baseUrl).href;\n}\n\n/** Converts a request the page made into a Fetch `Request` MSW can match. */\nexport function toFetchRequest(request: Pick<PlaywrightRequest, \"url\" | \"method\" | \"headers\" | \"postDataBuffer\">): Request {\n const method = request.method();\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : (request.postDataBuffer() ?? undefined);\n return new Request(request.url(), { method, headers: request.headers(), body: body ? new Uint8Array(body) : undefined });\n}\n\nasync function answerWithHandlers(\n context: BrowserContext,\n handlers: readonly RequestHandler[],\n baseUrl: string,\n unhandled: \"error\" | \"bypass\",\n problems: string[],\n) {\n const msw = await import(\"msw\").catch(() => {\n throw new Error(\"route shots with handlers need msw: npm install -D msw\");\n });\n const origin = new URL(baseUrl).origin;\n await context.route(\"**/*\", async (route: PlaywrightRoute) => {\n const request = route.request();\n const response = await msw.getResponse([...handlers], toFetchRequest(request), { baseUrl: origin, quiet: true });\n if (response && response.headers.get(\"x-msw-intention\") !== \"passthrough\") {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => (headers[key] = value));\n await route.fulfill({ status: response.status, headers, body: Buffer.from(await response.arrayBuffer()) });\n return;\n }\n if (!response && unhandled === \"error\" && [\"fetch\", \"xhr\", \"eventsource\", \"websocket\"].includes(request.resourceType())) {\n const url = new URL(request.url());\n problems.push(`no handler for ${request.method()} ${url.origin === origin ? \"\" : url.origin}${url.pathname}${url.search}`);\n }\n await route.continue();\n });\n}\n\n/** Takes one shot and returns its PNG, or throws with what went wrong. Page and console errors are returned as problems. */\nexport async function capture(browser: Browser, shot: Shot, options: CaptureOptions): Promise<{ png: Buffer; problems: string[] }> {\n const context = await browser.newContext({\n viewport: shot.viewport,\n deviceScaleFactor: 1,\n reducedMotion: \"reduce\",\n colorScheme: shot.theme,\n timezoneId: options.timezone ?? \"UTC\",\n locale: options.locale ?? \"en-US\",\n serviceWorkers: options.blockServiceWorkers ? \"block\" : \"allow\",\n });\n const problems: string[] = [];\n try {\n if (options.time !== undefined) await context.clock.setFixedTime(options.time);\n if (shot.darkClass) {\n await context.addInitScript(\n ({ cls, dark }) => {\n const apply = () => document.documentElement?.classList.toggle(cls, dark);\n apply();\n document.addEventListener(\"DOMContentLoaded\", apply);\n },\n { cls: shot.darkClass, dark: shot.theme === \"dark\" },\n );\n }\n if (shot.handlers?.length || options.onUnhandledRequest === \"error\") {\n await answerWithHandlers(context, shot.handlers ?? [], options.baseUrl, options.onUnhandledRequest ?? \"bypass\", problems);\n }\n const page = await context.newPage();\n page.on(\"pageerror\", (e) => problems.push(e.message));\n // Error responses a state serves on purpose (4xx/5xx) are logged by Chromium; not a fault.\n page.on(\"console\", (m) => {\n if (m.type() === \"error\" && !m.text().startsWith(\"Failed to load resource\")) problems.push(m.text());\n });\n await page.goto(resolveShotUrl(shot.path, options.baseUrl), { waitUntil: \"load\" });\n await page.addStyleTag({ content: freeze });\n await page.waitForFunction((root) => (document.querySelector(root)?.childElementCount ?? 0) > 0, shot.root, { timeout: 15_000 }).catch(() => {\n throw new Error(`${shot.root} stayed empty for 15s`);\n });\n if (shot.waitFor) await page.locator(shot.waitFor).first().waitFor({ state: \"visible\", timeout: 15_000 });\n await settle(page);\n if (shot.setup) {\n await shot.setup(page, shot);\n await settle(page);\n }\n let png: Buffer;\n if (shot.clip === \"page\") {\n png = await page.screenshot({ fullPage: true, animations: \"disabled\" });\n } else {\n const clip = await page.evaluate(paintedBox, { root: shot.root, margin: 8 });\n if (!clip) throw new Error(\"rendered nothing visible\");\n png = await page.screenshot({ fullPage: true, clip, animations: \"disabled\" });\n }\n return { png, problems };\n } finally {\n await context.close();\n }\n}\n\nasync function settle(page: Page) {\n // A state that is meant to stay loading keeps a request open, so networkidle may not come.\n await page.waitForLoadState(\"networkidle\", { timeout: 3_000 }).catch(() => undefined);\n await page.evaluate(() => document.fonts.ready.then(() => undefined));\n await page.waitForTimeout(250);\n}\n\n// Runs in the page. The box around what the root actually paints: text, replaced and form\n// elements, SVGs, and any box with a background, border or shadow, each cut to the scroll\n// containers it sits in. So a row of buttons is cropped to the buttons, not the full-width div\n// holding them, and fixed elements (an undo bar) count wherever they are. The screenshot is\n// fullPage, so the box may extend past the viewport and a large component is captured whole.\nfunction paintedBox({ root: selector, margin }: { root: string; margin: number }) {\n const root = document.querySelector(selector);\n if (!root) return null;\n const replaced = new Set([\"IMG\", \"INPUT\", \"SELECT\", \"TEXTAREA\", \"CANVAS\", \"VIDEO\", \"svg\", \"HR\"]);\n const transparent = (c: string) => c === \"transparent\" || /rgba\\(.*,\\s*0\\)$/.test(c) || /\\/\\s*0\\)$/.test(c);\n const paints = (el: Element) => {\n const cs = getComputedStyle(el);\n if (replaced.has(el.tagName)) return true;\n if (!transparent(cs.backgroundColor) || cs.backgroundImage !== \"none\" || cs.boxShadow !== \"none\") return true;\n return ([\"Top\", \"Right\", \"Bottom\", \"Left\"] as const).some(\n (s) => parseFloat(cs[`border${s}Width`]) > 0 && cs[`border${s}Style`] !== \"none\",\n );\n };\n const clipTo = (r: DOMRect, el: Node) => {\n let { left, top, right, bottom } = r;\n for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {\n const cs = getComputedStyle(a);\n if (cs.overflowX !== \"visible\" || cs.overflowY !== \"visible\" || cs.clipPath !== \"none\" || cs.clip !== \"auto\") {\n const b = a.getBoundingClientRect();\n left = Math.max(left, b.left);\n top = Math.max(top, b.top);\n right = Math.min(right, b.right);\n bottom = Math.min(bottom, b.bottom);\n }\n if (cs.position === \"fixed\") break;\n }\n return right - left > 1 && bottom - top > 1 ? { left, top, right, bottom } : null;\n };\n const rects: { left: number; top: number; right: number; bottom: number }[] = [];\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);\n for (let n = walker.nextNode(); n; n = walker.nextNode()) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (!n.textContent?.trim() || !n.parentElement) continue;\n const range = document.createRange();\n range.selectNodeContents(n);\n for (const r of range.getClientRects()) {\n // From the text node itself, so its own element's clip counts too (an sr-only span is a\n // 1px clipped box, and its text paints nothing).\n const c = clipTo(r, n);\n if (c) rects.push(c);\n }\n continue;\n }\n const el = n as Element;\n if (el.closest(\"svg\") && el.tagName !== \"svg\") continue;\n if (getComputedStyle(el).visibility === \"hidden\" || !paints(el)) continue;\n const c = clipTo(el.getBoundingClientRect(), el);\n if (c) rects.push(c);\n }\n if (!rects.length) return null;\n const x0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.left)) + scrollX - margin));\n const y0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.top)) + scrollY - margin));\n const x1 = Math.min(document.documentElement.scrollWidth, Math.ceil(Math.max(...rects.map((r) => r.right)) + scrollX + margin));\n const y1 = Math.min(document.documentElement.scrollHeight, Math.ceil(Math.max(...rects.map((r) => r.bottom)) + scrollY + margin));\n return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\n}\n","// PNG decode and pixelmatch comparison, kept apart from the browser so it is unit tested without\n// one. The numbers are the ones every Strata suite uses, so a baseline means the same thing in\n// the library and in an app: anti-aliased pixels ignored, a few stray pixels of rasterisation\n// noise tolerated, and a size change always a change (the layout moved).\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Per-pixel colour distance pixelmatch treats as equal (0–1). Anti-aliased pixels are ignored. */\nexport const THRESHOLD = 0.1;\n/** Differing pixels tolerated before a screenshot counts as changed: sub-pixel text rasterisation\n * noise between machines, never a real change (a 1px border on a button is far more). */\nexport const MAX_DIFF_PIXELS = 20;\n\n/** A decoded RGBA image. */\nexport interface Image {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/** The result of comparing a screenshot with its baseline. */\nexport interface CompareResult {\n /** Within tolerance: the screenshot matches. */\n same: boolean;\n /** Pixels that differ beyond the threshold (Infinity when the size changed). */\n diffPixels: number;\n /** One line for a report: what changed. */\n reason: string;\n /** A PNG highlighting the differing pixels, when the images differ in content. */\n diff?: Buffer;\n}\n\n/** Decodes a PNG file's bytes. */\nexport function decode(buffer: Buffer | Uint8Array): Image {\n return PNG.sync.read(Buffer.from(buffer));\n}\n\n/** Encodes an RGBA image as PNG bytes. */\nexport function encode({ width, height, data }: Image): Buffer {\n const png = new PNG({ width, height });\n png.data = Buffer.from(data);\n return PNG.sync.write(png);\n}\n\n/** Compares two decoded PNGs with pixelmatch. A size change is always a change. */\nexport function compare(\n expected: Image,\n actual: Image,\n { threshold = THRESHOLD, maxDiffPixels = MAX_DIFF_PIXELS }: { threshold?: number; maxDiffPixels?: number } = {},\n): CompareResult {\n if (expected.width !== actual.width || expected.height !== actual.height) {\n return {\n same: false,\n diffPixels: Number.POSITIVE_INFINITY,\n reason: `size ${expected.width}×${expected.height} → ${actual.width}×${actual.height}`,\n };\n }\n const { width, height } = expected;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(expected.data, actual.data, diff.data, width, height, { threshold, includeAA: false });\n const same = diffPixels <= maxDiffPixels;\n return {\n same,\n diffPixels,\n reason: `${diffPixels} pixels differ (${((diffPixels / (width * height)) * 100).toFixed(3)}%)`,\n diff: same ? undefined : PNG.sync.write(diff),\n };\n}\n","// A static file server for a build folder, on a free local port. Storybook needs nothing more;\n// an app's build also needs history fallback (a request for /review that asks for HTML gets\n// index.html, as a host like Pages or Netlify would serve it) and its Vite `base`. Requests that\n// do not ask for HTML are never given index.html, so a missed API route fails loudly as a 404\n// instead of a JSON parse error.\nimport { createServer } from \"node:http\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { extname, join, normalize, resolve, sep } from \"node:path\";\n\nconst types: Record<string, string> = {\n \".html\": \"text/html\",\n \".js\": \"text/javascript\",\n \".mjs\": \"text/javascript\",\n \".css\": \"text/css\",\n \".json\": \"application/json\",\n \".map\": \"application/json\",\n \".webmanifest\": \"application/manifest+json\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".gif\": \"image/gif\",\n \".ico\": \"image/x-icon\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".ttf\": \"font/ttf\",\n \".txt\": \"text/plain\",\n \".wasm\": \"application/wasm\",\n};\n\n/** A running server: its origin plus base, and how to stop it. */\nexport interface StaticServer {\n /** e.g. `http://127.0.0.1:53121/app/` (always ends in `/`). */\n url: string;\n close(): Promise<void>;\n}\n\n/** Serves `dir` on 127.0.0.1 under `base`, with history fallback to `index.html` when `spa` is set. */\nexport async function serveStatic(dir: string, { spa = false, base = \"/\" }: { spa?: boolean; base?: string } = {}): Promise<StaticServer> {\n const root = resolve(dir);\n const prefix = `/${base.replace(/^\\/+|\\/+$/g, \"\")}/`.replace(/^\\/\\/$/, \"/\");\n const server = createServer((req, res) => {\n const pathname = decodeURIComponent(new URL(req.url ?? \"/\", \"http://x\").pathname);\n if (!pathname.startsWith(prefix) && `${pathname}/` !== prefix) {\n res.writeHead(404).end();\n return;\n }\n const rel = normalize(pathname.slice(prefix.length)).replace(/^([/\\\\])+/, \"\");\n let file = join(root, rel || \"index.html\");\n if (file !== root && !file.startsWith(root + sep)) {\n res.writeHead(404).end();\n return;\n }\n if (existsSync(file) && statSync(file).isDirectory()) file = join(file, \"index.html\");\n if (!existsSync(file)) {\n const wantsHtml = (req.headers.accept ?? \"\").includes(\"text/html\");\n if (!spa || !wantsHtml || !existsSync(join(root, \"index.html\"))) {\n res.writeHead(404).end();\n return;\n }\n file = join(root, \"index.html\");\n }\n res.writeHead(200, { \"Content-Type\": types[extname(file)] ?? \"application/octet-stream\", \"Service-Worker-Allowed\": \"/\" });\n createReadStream(file).pipe(res);\n });\n await new Promise<void>((r) => server.listen(0, \"127.0.0.1\", r));\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n return {\n url: `http://127.0.0.1:${port}${prefix}`,\n close: () => new Promise((r) => server.close(() => r())),\n };\n}\n","// The shapes a visual suite is written in. One Shot is one PNG: a URL, a theme, a viewport, how to\n// tell it has rendered, and what to cut out. Storybook stories and app routes are both turned into\n// shots, so capture, comparison and baselines are the same code for a component library and for\n// an app's screens (strata-react issue #13).\nimport type { Page } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\n\n/** The two colour schemes every shot is taken in. */\nexport type Theme = \"light\" | \"dark\";\n\n/** A viewport in CSS pixels. Screenshots are taken at a device scale factor of 1. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n\n/** A named viewport (see {@link viewports}) or an explicit size. */\nexport type ViewportChoice = keyof typeof viewports | Viewport;\n\n/**\n * Named viewports. `wide` and `phone` are what the Storybook tags `visual-wide` and\n * `visual-phone` select; `default` is a laptop-sized screen for routes. (Untagged stories render\n * 1024 wide and 200 tall and grow with the component, see {@link storybookShots}.)\n */\nexport const viewports = {\n default: { width: 1024, height: 768 },\n wide: { width: 1440, height: 900 },\n phone: { width: 390, height: 844 },\n} as const satisfies Record<string, Viewport>;\n\n/**\n * What a screenshot covers. `paint` is the union of what the root element paints (text,\n * controls, SVGs, and boxes with a background, border or shadow) plus 8px, so a component's\n * baseline shows the component and not the empty canvas. `page` is the whole page, for screens.\n */\nexport type Clip = \"paint\" | \"page\";\n\n/** A step run after a shot has rendered and before it is captured: open a menu, focus a field. */\nexport type Setup = (page: Page, shot: Shot) => Promise<void> | void;\n\n/** One screenshot: everything the runner needs to take it and to name its baseline. */\nexport interface Shot {\n /** The baseline's file name without `.png`, e.g. `review--empty--wide--dark`. */\n name: string;\n /** Path and query under the served base (`/review?tab=queue`), or an absolute URL. */\n path: string;\n theme: Theme;\n viewport: Viewport;\n /** Selector of the element the app renders into; the shot waits until it has children. */\n root: string;\n clip: Clip;\n /** A Playwright selector that must be visible before the shot is taken (see {@link RouteState.waitFor}). */\n waitFor?: string;\n /** MSW handlers answering the page's requests, first match wins. Route shots only. */\n handlers?: readonly RequestHandler[];\n /** Class put on `<html>` in the dark theme (Strata's `dark:` variant reads `.dark`). */\n darkClass?: string | false;\n setup?: Setup;\n}\n\n/** An app's built Storybook. */\nexport interface StorybookTarget {\n /** The `storybook build` output folder. Default `storybook-static`. */\n dir?: string;\n /** The Storybook global the preview reads the theme from. Default `theme`, as Strata's preview. */\n themeGlobal?: string;\n}\n\n/** One state of a route: the MSW handlers that put the server into it, and optional steps. */\nexport interface RouteState {\n /** Handlers tried before the target's base handlers (like `server.use(...)` in a test). */\n handlers?: readonly RequestHandler[];\n /** A different path for this state, e.g. the same screen with `?tab=sync`. */\n path?: string;\n /**\n * A Playwright selector that must be visible before the shot is taken, such as `role=alert` or\n * `text=Try again`. Needed when a state takes longer than the network to show: an error after\n * the query client's retry, a toast after a timer.\n */\n waitFor?: string;\n setup?: Setup;\n}\n\n/** A screen of the app, screenshotted in each of its states. */\nexport interface Route {\n /** Names the baselines: lower-case letters, digits and dashes. */\n name: string;\n /** Path and query under the app's base, e.g. `/review` or `/library?sort=-added`. */\n path: string;\n /**\n * The server states to capture, by name. A list of handlers is shorthand for `{ handlers }`.\n * Default: one state, `default`, served by the base handlers alone.\n */\n states?: Record<string, readonly RequestHandler[] | RouteState>;\n viewports?: readonly ViewportChoice[];\n clip?: Clip;\n root?: string;\n waitFor?: string;\n setup?: Setup;\n}\n\n/** An app served from its production build (or a running server), screenshotted route by route. */\nexport interface AppTarget {\n /** The build folder to serve, e.g. `dist`. Unknown paths that ask for HTML get `index.html`. */\n dir?: string;\n /** Or a server that is already running, e.g. `http://localhost:4173`. */\n url?: string;\n /** The app's base path (Vite's `base`). Default `/`. */\n base?: string;\n /** MSW handlers for every route: the healthy server, usually the app's `handlers.ts`. */\n handlers?: readonly RequestHandler[];\n /** Default `#root`. */\n root?: string;\n /** Default `[\"wide\"]`. Every route is taken at each. */\n viewports?: readonly ViewportChoice[];\n /** Default `page`. */\n clip?: Clip;\n /** Default `dark`; `false` to rely on `prefers-color-scheme` alone. */\n darkClass?: string | false;\n /**\n * A `fetch` or XHR request no handler answers: `error` (default) fails the shot, because a\n * screenshot that depends on a real server is not a baseline; `bypass` lets it through.\n */\n onUnhandledRequest?: \"error\" | \"bypass\";\n routes: readonly Route[];\n}\n\n/** A visual suite: where baselines live and what to screenshot. Paths are relative to the config file. */\nexport interface VisualConfig {\n /** Committed baselines. Default `tests/visual/baselines`. */\n baselines?: string;\n /** Actual, expected and diff PNGs of changed shots (uploaded by CI). Default `tests/visual/output`. */\n output?: string;\n /** Default `[\"light\", \"dark\"]`. */\n themes?: readonly Theme[];\n /** Freeze the page's clock at this time, so \"3 minutes ago\" and today's date stay put. */\n time?: string | number | Date;\n /** The page's time zone. Default `UTC`, so a date renders the same on every machine. */\n timezone?: string;\n /** The page's locale (`navigator.language`, `Intl` defaults). Default `en-US`. */\n locale?: string;\n /** Pages captured at once. Default 4. */\n concurrency?: number;\n storybook?: StorybookTarget | string;\n app?: AppTarget;\n}\n\n/** What a run found. */\nexport interface VisualReport {\n /** Shots taken. */\n total: number;\n same: number;\n /** `name.png: reason` for each shot that differs from its baseline. */\n changed: string[];\n /** Shots with no baseline yet (written, and copied to the output folder). */\n added: string[];\n /** Baselines no shot produced (removed when updating). */\n obsolete: string[];\n /** Shots that failed: page errors, console errors, unhandled requests, nothing rendered. */\n errors: string[];\n /** Things that make baselines less trustworthy, such as an unpinned Playwright. */\n warnings: string[];\n updated: boolean;\n /** Whether the run should fail (in CI a missing baseline fails too). */\n failed: boolean;\n}\n","// Turning what an app has into shots. A component library has stories; an app may have only\n// screens (strata-listory has Review, Library and Settings and no stories), so routes are a\n// first-class target: each route is taken in each server state, viewport and theme, with the\n// state set by MSW handlers, the same handlers its unit tests use. Names are stable and readable\n// (`review--empty--phone--dark.png`) because a person reviews baselines by file name in a diff.\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { viewports, type AppTarget, type Route, type RouteState, type Shot, type StorybookTarget, type Theme, type Viewport, type ViewportChoice } from \"./types\";\n\n/** The light and dark themes, the default for every target. */\nexport const defaultThemes: readonly Theme[] = [\"light\", \"dark\"];\n\n// Untagged stories lay out in a 1024-wide, 200-tall frame and the clip grows with the component,\n// so a short component's fixed elements (the undo bar) sit near it rather than 768px down.\nconst storyViewport: Viewport = { width: 1024, height: 200 };\n\ninterface IndexEntry {\n id: string;\n type: string;\n title?: string;\n name?: string;\n tags?: string[];\n}\n\n/**\n * Shots for every story in a built Storybook (its `index.json`), in each theme. Tags pick the\n * viewport: `visual-phone` 390×844, `visual-wide` 1440×900, otherwise 1024 wide; `no-visual`\n * skips the story. A story's own tag beats its file's, since Storybook merges both.\n */\nexport function storybookShots(target: StorybookTarget & { dir: string }, themes: readonly Theme[] = defaultThemes): Shot[] {\n const index = JSON.parse(readFileSync(join(target.dir, \"index.json\"), \"utf8\")) as { entries: Record<string, IndexEntry> };\n const global = target.themeGlobal ?? \"theme\";\n return Object.values(index.entries)\n .filter((e) => e.type === \"story\" && !e.tags?.includes(\"no-visual\"))\n .flatMap((story) => {\n const tag = [\"visual-phone\", \"visual-wide\"].find((t) => story.tags?.includes(t));\n const viewport = tag === \"visual-phone\" ? viewports.phone : tag === \"visual-wide\" ? viewports.wide : storyViewport;\n return themes.map((theme) => ({\n name: `${story.id}--${theme}`,\n path: `iframe.html?id=${story.id}&viewMode=story&globals=${global}:${theme}`,\n theme,\n viewport: { ...viewport },\n root: \"#storybook-root\",\n clip: \"paint\" as const,\n darkClass: false as const,\n }));\n });\n}\n\nconst slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nfunction viewportName(v: ViewportChoice): string {\n return typeof v === \"string\" ? v : `${v.width}x${v.height}`;\n}\n\nfunction viewportSize(v: ViewportChoice): Viewport {\n if (typeof v !== \"string\") return { width: v.width, height: v.height };\n const size = viewports[v];\n if (!size) throw new Error(`unknown viewport \"${String(v)}\": use ${Object.keys(viewports).join(\", \")} or { width, height }`);\n return { ...size };\n}\n\nfunction stateOf(value: readonly unknown[] | RouteState): RouteState {\n return Array.isArray(value) ? { handlers: value as RouteState[\"handlers\"] } : (value as RouteState);\n}\n\n/**\n * Shots for every route of an app in each state, viewport and theme, named\n * `route--state--viewport--theme`. A state's handlers come before the target's base handlers, as\n * `server.use(...)` would put them.\n */\nexport function routeShots(app: AppTarget, themes: readonly Theme[] = defaultThemes): Shot[] {\n const shots: Shot[] = [];\n for (const route of app.routes as readonly Route[]) {\n if (!slug.test(route.name)) throw new Error(`route name \"${route.name}\" must be lower-case letters, digits and dashes`);\n const states = Object.entries(route.states ?? { default: [] });\n if (!states.length) throw new Error(`route \"${route.name}\" has an empty states object: leave it out for one default state`);\n const chosen = route.viewports ?? app.viewports ?? [\"wide\"];\n for (const [stateName, value] of states) {\n if (!slug.test(stateName)) throw new Error(`state \"${stateName}\" of route \"${route.name}\" must be lower-case letters, digits and dashes`);\n const state = stateOf(value);\n const setups = [route.setup, state.setup].filter((s) => s !== undefined);\n for (const v of chosen) {\n for (const theme of themes) {\n shots.push({\n name: `${route.name}--${stateName}--${viewportName(v)}--${theme}`,\n path: state.path ?? route.path,\n theme,\n viewport: viewportSize(v),\n root: route.root ?? app.root ?? \"#root\",\n clip: route.clip ?? app.clip ?? \"page\",\n waitFor: state.waitFor ?? route.waitFor,\n handlers: [...(state.handlers ?? []), ...(app.handlers ?? [])],\n darkClass: app.darkClass ?? \"dark\",\n setup: setups.length ? async (page, shot) => { for (const s of setups) await s(page, shot); } : undefined,\n });\n }\n }\n }\n }\n return shots;\n}\n","// Running a suite: serve each target, take its shots a few at a time in one Chromium, compare\n// each with its committed baseline, and report. The rules are the library's own, so an app's\n// suite fails for the same reasons Strata's does: a changed screenshot, a page or console\n// error, an unanswered request, and in CI a shot with no baseline (it was added without one).\n//\n// Baselines are only comparable when written by the same Chromium on the same platform, which\n// is why Playwright is pinned to an exact version. A run records both next to the baselines\n// (`.strata-visual.json`) when it writes them, and says so when a later run differs.\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Browser } from \"playwright\";\nimport { capture } from \"./capture\";\nimport { compare, decode } from \"./compare\";\nimport { serveStatic, type StaticServer } from \"./serve\";\nimport { defaultThemes, routeShots, storybookShots } from \"./targets\";\nimport type { Shot, VisualConfig, VisualReport } from \"./types\";\n\n/** Returns the config unchanged; it exists so a config file is type-checked. */\nexport function defineVisualConfig(config: VisualConfig): VisualConfig {\n return config;\n}\n\n/** Options for one run, usually from the command line. */\nexport interface RunOptions {\n /** Folder the config's paths are relative to. Default `process.cwd()`. */\n cwd?: string;\n /** Write the screenshots as the baselines and remove obsolete ones, instead of comparing. */\n update?: boolean;\n /** Only shots whose name contains this text (obsolete baselines are then not reported). */\n filter?: string;\n /** Fail when a shot has no baseline. Default: when the `CI` environment variable is set. */\n ci?: boolean;\n /** Progress lines; default none. */\n log?: (line: string) => void;\n}\n\nconst metaFile = \".strata-visual.json\";\ninterface Meta {\n chromium: string;\n platform: string;\n}\n\ninterface Batch {\n shots: Shot[];\n server?: StaticServer;\n baseUrl: string;\n blockServiceWorkers: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n}\n\n/** Screenshots every shot the config describes, compares with the baselines, and reports. */\nexport async function runVisual(config: VisualConfig, options: RunOptions = {}): Promise<VisualReport> {\n const cwd = resolve(options.cwd ?? process.cwd());\n const baselineDir = resolve(cwd, config.baselines ?? \"tests/visual/baselines\");\n const outputDir = resolve(cwd, config.output ?? \"tests/visual/output\");\n const themes = config.themes ?? defaultThemes;\n const update = options.update ?? false;\n const ci = options.ci ?? Boolean(process.env.CI);\n const log = options.log ?? (() => undefined);\n const concurrency = config.concurrency ?? 4;\n // A worker count that is not a positive integer would start no workers and report an empty,\n // passing run, so it is refused up front.\n if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a whole number of pages, 1 or more (got ${String(config.concurrency)})`);\n const report: VisualReport = { total: 0, same: 0, changed: [], added: [], obsolete: [], errors: [], warnings: pinWarnings(cwd), updated: update, failed: false };\n\n const batches: Batch[] = [];\n try {\n if (config.storybook !== undefined) {\n const target = typeof config.storybook === \"string\" ? { dir: config.storybook } : config.storybook;\n const dir = resolve(cwd, target.dir ?? \"storybook-static\");\n if (!existsSync(join(dir, \"index.json\"))) throw new Error(`${join(dir, \"index.json\")} not found: build Storybook first (storybook build)`);\n // Shots first: if building them throws, no server is left running to hold the process open.\n const shots = storybookShots({ ...target, dir }, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: false };\n batches.push(batch);\n batch.server = await serveStatic(dir);\n batch.baseUrl = batch.server.url;\n }\n if (config.app !== undefined) {\n const app = config.app;\n if (!app.dir === !app.url) throw new Error(\"app needs exactly one of dir (a build to serve) or url (a running server)\");\n const shots = routeShots(app, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: true, onUnhandledRequest: app.onUnhandledRequest ?? \"error\" };\n batches.push(batch);\n if (app.dir) {\n const dir = resolve(cwd, app.dir);\n if (!existsSync(join(dir, \"index.html\"))) throw new Error(`${join(dir, \"index.html\")} not found: build the app first`);\n batch.server = await serveStatic(dir, { spa: true, base: app.base });\n batch.baseUrl = batch.server.url;\n } else {\n batch.baseUrl = new URL(`${(app.base ?? \"/\").replace(/^\\/*/, \"/\").replace(/\\/*$/, \"/\")}`, app.url).href;\n }\n }\n if (!batches.length) throw new Error(\"nothing to screenshot: the config needs storybook or app\");\n\n const all = batches.flatMap((b) => b.shots);\n const names = new Set<string>();\n for (const s of all) {\n if (names.has(s.name)) throw new Error(`two shots are named ${s.name}: give routes and states distinct names`);\n names.add(s.name);\n }\n for (const b of batches) b.shots = b.shots.filter((s) => !options.filter || s.name.includes(options.filter));\n report.total = batches.reduce((n, b) => n + b.shots.length, 0);\n\n mkdirSync(baselineDir, { recursive: true });\n rmSync(outputDir, { recursive: true, force: true });\n mkdirSync(outputDir, { recursive: true });\n\n const { chromium } = await import(\"playwright\").catch(() => {\n throw new Error(\"strata-visual needs Playwright: npm install -D -E playwright, then npx playwright install chromium\");\n });\n // Font hinting and LCD anti-aliasing off and an sRGB profile: the same pixels on every machine.\n const browser = await chromium.launch({ args: [\"--font-render-hinting=none\", \"--disable-lcd-text\", \"--force-color-profile=srgb\"] });\n const meta: Meta = { chromium: browser.version(), platform: `${process.platform}-${process.arch}` };\n try {\n for (const batch of batches) await runBatch(browser, batch, { config, baselineDir, outputDir, update, report, log });\n } finally {\n await browser.close();\n }\n\n const pngs = readdirSync(baselineDir).filter((f) => f.endsWith(\".png\"));\n report.obsolete = options.filter ? [] : pngs.filter((f) => !names.has(f.slice(0, -4)));\n if (update) {\n for (const f of report.obsolete) rmSync(join(baselineDir, f));\n if (!options.filter) writeFileSync(join(baselineDir, metaFile), `${JSON.stringify(meta, null, 2)}\\n`);\n } else if (report.changed.length) {\n const written = readMeta(baselineDir);\n if (written && (written.chromium !== meta.chromium || written.platform !== meta.platform)) {\n report.warnings.push(\n `the baselines were written by Chromium ${written.chromium} on ${written.platform}; this run used Chromium ${meta.chromium} on ${meta.platform}, so some differences may be the browser, not the app`,\n );\n }\n }\n } finally {\n for (const b of batches) await b.server?.close();\n }\n report.failed = Boolean(report.errors.length || report.changed.length || (ci && !update && report.added.length));\n return report;\n}\n\nasync function runBatch(\n browser: Browser,\n batch: Batch,\n ctx: { config: VisualConfig; baselineDir: string; outputDir: string; update: boolean; report: VisualReport; log: (l: string) => void },\n) {\n const { baselineDir, outputDir, update, report } = ctx;\n const shoot = async (shot: Shot) => {\n const file = `${shot.name}.png`;\n try {\n const { png, problems } = await capture(browser, shot, {\n baseUrl: batch.baseUrl,\n time: ctx.config.time,\n timezone: ctx.config.timezone,\n locale: ctx.config.locale,\n blockServiceWorkers: batch.blockServiceWorkers,\n onUnhandledRequest: batch.onUnhandledRequest,\n });\n if (problems.length) report.errors.push(`${file}: ${problems.join(\" | \")}`);\n const baselinePath = join(baselineDir, file);\n if (update || !existsSync(baselinePath)) {\n if (!update) report.added.push(file);\n writeFileSync(baselinePath, png);\n if (!update) writeFileSync(join(outputDir, file), png);\n return;\n }\n const expected = readFileSync(baselinePath);\n const result = compare(decode(expected), decode(png));\n if (result.same) {\n report.same++;\n return;\n }\n report.changed.push(`${file}: ${result.reason}`);\n writeFileSync(join(outputDir, `${shot.name}.actual.png`), png);\n writeFileSync(join(outputDir, `${shot.name}.expected.png`), expected);\n if (result.diff) writeFileSync(join(outputDir, `${shot.name}.diff.png`), result.diff);\n } catch (e) {\n report.errors.push(`${file}: ${(e instanceof Error ? e.message : String(e)).split(\"\\n\")[0]}`);\n } finally {\n ctx.log(file);\n }\n };\n // A few pages at once: each shot has its own context, so they cannot affect each other.\n const queue = [...batch.shots];\n await Promise.all(\n Array.from({ length: ctx.config.concurrency ?? 4 }, async () => {\n for (let shot = queue.shift(); shot; shot = queue.shift()) await shoot(shot);\n }),\n );\n}\n\nfunction readMeta(dir: string): Meta | undefined {\n try {\n return JSON.parse(readFileSync(join(dir, metaFile), \"utf8\")) as Meta;\n } catch {\n return undefined;\n }\n}\n\n/** A warning when the app's package.json lets Playwright float, since each version brings its own Chromium. */\nexport function pinWarnings(cwd: string): string[] {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\"));\n } catch {\n return [];\n }\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return [\"playwright\", \"@playwright/test\"]\n .filter((name) => deps[name] !== undefined && !/^\\d+\\.\\d+\\.\\d+$/.test(deps[name]))\n .map(\n (name) =>\n `${name} is \"${deps[name]}\" in package.json: pin an exact version (npm install -D -E ${name}) so CI and the machine that wrote the baselines render with the same Chromium`,\n );\n}\n\n/** The report as the lines the command prints. */\nexport function formatReport(report: VisualReport): string {\n const lines = [\n report.updated\n ? `Wrote ${report.total} baselines${report.obsolete.length ? `, removed ${report.obsolete.length} obsolete` : \"\"}.`\n : `${report.same} of ${report.total} screenshots match their baselines.`,\n ...report.changed.map((l) => `changed ${l}`),\n ...report.added.map((l) => `new ${l} (baseline written; commit it)`),\n ...report.obsolete.map((l) => `obsolete ${l}${report.updated ? \" (removed)\" : \" (run with --update to remove)\"}`),\n ...report.errors.map((l) => `error ${l}`),\n ...report.warnings.map((l) => `warning ${l}`),\n ];\n if (report.failed) {\n lines.push(\"\", \"Diffs are in the output folder (tests/visual/output by default). Look at them; if the change is intended, run with --update and commit the baselines.\");\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;AAUA,IAAM,SAAS;;AAef,SAAgB,eAAe,MAAc,SAAyB;CACpE,IAAI,uBAAuB,KAAK,IAAI,GAAG,OAAO;CAC9C,OAAO,IAAI,IAAI,KAAK,QAAQ,QAAQ,EAAE,GAAG,OAAO,CAAC,CAAC;AACpD;;AAGA,SAAgB,eAAe,SAA4F;CACzH,MAAM,SAAS,QAAQ,OAAO;CAC9B,MAAM,OAAO,WAAW,SAAS,WAAW,SAAS,KAAA,IAAa,QAAQ,eAAe,KAAK,KAAA;CAC9F,OAAO,IAAI,QAAQ,QAAQ,IAAI,GAAG;EAAE;EAAQ,SAAS,QAAQ,QAAQ;EAAG,MAAM,OAAO,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K,MAAM,YAAY,GAAG;EAC5C,GAAG,OAAO,MAAM,KAAK,MAAM,YAAY,EAAE,+BAA+B;EACxE,GAAG,OAAO,SAAS,KAAK,MAAM,YAAY,IAAI,OAAO,UAAU,eAAe,kCAAkC;EAChH,GAAG,OAAO,OAAO,KAAK,MAAM,YAAY,GAAG;EAC3C,GAAG,OAAO,SAAS,KAAK,MAAM,YAAY,GAAG;CAC/C;CACA,IAAI,OAAO,QACT,MAAM,KAAK,IAAI,uJAAuJ;CAExK,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as ThemeProvider, n as createQueryClient, t as StrataQueryProvider } from "./query-
|
|
1
|
+
import { c as ThemeProvider, n as createQueryClient, t as StrataQueryProvider } from "./query-5469ipOC.js";
|
|
2
2
|
import "react";
|
|
3
3
|
import { jsx } from "react/jsx-runtime";
|
|
4
4
|
import { MemoryRouter } from "react-router";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Browser, Request as PlaywrightRequest } from 'playwright';
|
|
2
|
+
import { Shot } from './types';
|
|
3
|
+
/** Options shared by every shot of a run. */
|
|
4
|
+
export interface CaptureOptions {
|
|
5
|
+
/** Where `shot.path` resolves, ending in `/`. */
|
|
6
|
+
baseUrl: string;
|
|
7
|
+
time?: string | number | Date;
|
|
8
|
+
timezone?: string;
|
|
9
|
+
locale?: string;
|
|
10
|
+
/** Block service workers (an app's own MSW worker or PWA cache would bypass the handlers). */
|
|
11
|
+
blockServiceWorkers?: boolean;
|
|
12
|
+
onUnhandledRequest?: "error" | "bypass";
|
|
13
|
+
}
|
|
14
|
+
/** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */
|
|
15
|
+
export declare function resolveShotUrl(path: string, baseUrl: string): string;
|
|
16
|
+
/** Converts a request the page made into a Fetch `Request` MSW can match. */
|
|
17
|
+
export declare function toFetchRequest(request: Pick<PlaywrightRequest, "url" | "method" | "headers" | "postDataBuffer">): Request;
|
|
18
|
+
/** Takes one shot and returns its PNG, or throws with what went wrong. Page and console errors are returned as problems. */
|
|
19
|
+
export declare function capture(browser: Browser, shot: Shot, options: CaptureOptions): Promise<{
|
|
20
|
+
png: Buffer;
|
|
21
|
+
problems: string[];
|
|
22
|
+
}>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { VisualConfig } from './types';
|
|
2
|
+
/** Loads a config file's default export. */
|
|
3
|
+
export declare function loadConfig(file: string): Promise<VisualConfig>;
|
|
4
|
+
/** Runs the command with the given arguments and returns the exit code. */
|
|
5
|
+
export declare function main(argv: readonly string[], cwd?: string): Promise<number>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Per-pixel colour distance pixelmatch treats as equal (0–1). Anti-aliased pixels are ignored. */
|
|
2
|
+
export declare const THRESHOLD = 0.1;
|
|
3
|
+
/** Differing pixels tolerated before a screenshot counts as changed: sub-pixel text rasterisation
|
|
4
|
+
* noise between machines, never a real change (a 1px border on a button is far more). */
|
|
5
|
+
export declare const MAX_DIFF_PIXELS = 20;
|
|
6
|
+
/** A decoded RGBA image. */
|
|
7
|
+
export interface Image {
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
data: Uint8Array;
|
|
11
|
+
}
|
|
12
|
+
/** The result of comparing a screenshot with its baseline. */
|
|
13
|
+
export interface CompareResult {
|
|
14
|
+
/** Within tolerance: the screenshot matches. */
|
|
15
|
+
same: boolean;
|
|
16
|
+
/** Pixels that differ beyond the threshold (Infinity when the size changed). */
|
|
17
|
+
diffPixels: number;
|
|
18
|
+
/** One line for a report: what changed. */
|
|
19
|
+
reason: string;
|
|
20
|
+
/** A PNG highlighting the differing pixels, when the images differ in content. */
|
|
21
|
+
diff?: Buffer;
|
|
22
|
+
}
|
|
23
|
+
/** Decodes a PNG file's bytes. */
|
|
24
|
+
export declare function decode(buffer: Buffer | Uint8Array): Image;
|
|
25
|
+
/** Encodes an RGBA image as PNG bytes. */
|
|
26
|
+
export declare function encode({ width, height, data }: Image): Buffer;
|
|
27
|
+
/** Compares two decoded PNGs with pixelmatch. A size change is always a change. */
|
|
28
|
+
export declare function compare(expected: Image, actual: Image, { threshold, maxDiffPixels }?: {
|
|
29
|
+
threshold?: number;
|
|
30
|
+
maxDiffPixels?: number;
|
|
31
|
+
}): CompareResult;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Visual regression for Strata apps: the runner strata-react tests itself with, for an app's own
|
|
3
|
+
* Storybook build and for its routes, each route in the server states its MSW handlers describe.
|
|
4
|
+
* Every shot is taken light and dark in Playwright's Chromium, compared with a baseline committed
|
|
5
|
+
* in the app's repo using pixelmatch, and reported as matching, changed, new or failed. Run it
|
|
6
|
+
* with the `strata-visual` command, or call {@link runVisual}.
|
|
7
|
+
*
|
|
8
|
+
* Needs `playwright` (pinned to an exact version) and, for routes with handlers, `msw`.
|
|
9
|
+
*
|
|
10
|
+
* @module strata-react/visual
|
|
11
|
+
*/
|
|
12
|
+
export { runVisual, defineVisualConfig, formatReport, pinWarnings, type RunOptions } from './run';
|
|
13
|
+
export { storybookShots, routeShots, defaultThemes } from './targets';
|
|
14
|
+
export { capture, resolveShotUrl, toFetchRequest, type CaptureOptions } from './capture';
|
|
15
|
+
export { serveStatic, type StaticServer } from './serve';
|
|
16
|
+
export { compare, decode, encode, THRESHOLD, MAX_DIFF_PIXELS, type Image, type CompareResult } from './compare';
|
|
17
|
+
export { viewports, type Theme, type Viewport, type ViewportChoice, type Clip, type Setup, type Shot, type StorybookTarget, type RouteState, type Route, type AppTarget, type VisualConfig, type VisualReport, } from './types';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { VisualConfig, VisualReport } from './types';
|
|
2
|
+
/** Returns the config unchanged; it exists so a config file is type-checked. */
|
|
3
|
+
export declare function defineVisualConfig(config: VisualConfig): VisualConfig;
|
|
4
|
+
/** Options for one run, usually from the command line. */
|
|
5
|
+
export interface RunOptions {
|
|
6
|
+
/** Folder the config's paths are relative to. Default `process.cwd()`. */
|
|
7
|
+
cwd?: string;
|
|
8
|
+
/** Write the screenshots as the baselines and remove obsolete ones, instead of comparing. */
|
|
9
|
+
update?: boolean;
|
|
10
|
+
/** Only shots whose name contains this text (obsolete baselines are then not reported). */
|
|
11
|
+
filter?: string;
|
|
12
|
+
/** Fail when a shot has no baseline. Default: when the `CI` environment variable is set. */
|
|
13
|
+
ci?: boolean;
|
|
14
|
+
/** Progress lines; default none. */
|
|
15
|
+
log?: (line: string) => void;
|
|
16
|
+
}
|
|
17
|
+
/** Screenshots every shot the config describes, compares with the baselines, and reports. */
|
|
18
|
+
export declare function runVisual(config: VisualConfig, options?: RunOptions): Promise<VisualReport>;
|
|
19
|
+
/** A warning when the app's package.json lets Playwright float, since each version brings its own Chromium. */
|
|
20
|
+
export declare function pinWarnings(cwd: string): string[];
|
|
21
|
+
/** The report as the lines the command prints. */
|
|
22
|
+
export declare function formatReport(report: VisualReport): string;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** A running server: its origin plus base, and how to stop it. */
|
|
2
|
+
export interface StaticServer {
|
|
3
|
+
/** e.g. `http://127.0.0.1:53121/app/` (always ends in `/`). */
|
|
4
|
+
url: string;
|
|
5
|
+
close(): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
/** Serves `dir` on 127.0.0.1 under `base`, with history fallback to `index.html` when `spa` is set. */
|
|
8
|
+
export declare function serveStatic(dir: string, { spa, base }?: {
|
|
9
|
+
spa?: boolean;
|
|
10
|
+
base?: string;
|
|
11
|
+
}): Promise<StaticServer>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AppTarget, Shot, StorybookTarget, Theme } from './types';
|
|
2
|
+
/** The light and dark themes, the default for every target. */
|
|
3
|
+
export declare const defaultThemes: readonly Theme[];
|
|
4
|
+
/**
|
|
5
|
+
* Shots for every story in a built Storybook (its `index.json`), in each theme. Tags pick the
|
|
6
|
+
* viewport: `visual-phone` 390×844, `visual-wide` 1440×900, otherwise 1024 wide; `no-visual`
|
|
7
|
+
* skips the story. A story's own tag beats its file's, since Storybook merges both.
|
|
8
|
+
*/
|
|
9
|
+
export declare function storybookShots(target: StorybookTarget & {
|
|
10
|
+
dir: string;
|
|
11
|
+
}, themes?: readonly Theme[]): Shot[];
|
|
12
|
+
/**
|
|
13
|
+
* Shots for every route of an app in each state, viewport and theme, named
|
|
14
|
+
* `route--state--viewport--theme`. A state's handlers come before the target's base handlers, as
|
|
15
|
+
* `server.use(...)` would put them.
|
|
16
|
+
*/
|
|
17
|
+
export declare function routeShots(app: AppTarget, themes?: readonly Theme[]): Shot[];
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { Page } from 'playwright';
|
|
2
|
+
import { RequestHandler } from 'msw';
|
|
3
|
+
/** The two colour schemes every shot is taken in. */
|
|
4
|
+
export type Theme = "light" | "dark";
|
|
5
|
+
/** A viewport in CSS pixels. Screenshots are taken at a device scale factor of 1. */
|
|
6
|
+
export interface Viewport {
|
|
7
|
+
width: number;
|
|
8
|
+
height: number;
|
|
9
|
+
}
|
|
10
|
+
/** A named viewport (see {@link viewports}) or an explicit size. */
|
|
11
|
+
export type ViewportChoice = keyof typeof viewports | Viewport;
|
|
12
|
+
/**
|
|
13
|
+
* Named viewports. `wide` and `phone` are what the Storybook tags `visual-wide` and
|
|
14
|
+
* `visual-phone` select; `default` is a laptop-sized screen for routes. (Untagged stories render
|
|
15
|
+
* 1024 wide and 200 tall and grow with the component, see {@link storybookShots}.)
|
|
16
|
+
*/
|
|
17
|
+
export declare const viewports: {
|
|
18
|
+
readonly default: {
|
|
19
|
+
readonly width: 1024;
|
|
20
|
+
readonly height: 768;
|
|
21
|
+
};
|
|
22
|
+
readonly wide: {
|
|
23
|
+
readonly width: 1440;
|
|
24
|
+
readonly height: 900;
|
|
25
|
+
};
|
|
26
|
+
readonly phone: {
|
|
27
|
+
readonly width: 390;
|
|
28
|
+
readonly height: 844;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* What a screenshot covers. `paint` is the union of what the root element paints (text,
|
|
33
|
+
* controls, SVGs, and boxes with a background, border or shadow) plus 8px, so a component's
|
|
34
|
+
* baseline shows the component and not the empty canvas. `page` is the whole page, for screens.
|
|
35
|
+
*/
|
|
36
|
+
export type Clip = "paint" | "page";
|
|
37
|
+
/** A step run after a shot has rendered and before it is captured: open a menu, focus a field. */
|
|
38
|
+
export type Setup = (page: Page, shot: Shot) => Promise<void> | void;
|
|
39
|
+
/** One screenshot: everything the runner needs to take it and to name its baseline. */
|
|
40
|
+
export interface Shot {
|
|
41
|
+
/** The baseline's file name without `.png`, e.g. `review--empty--wide--dark`. */
|
|
42
|
+
name: string;
|
|
43
|
+
/** Path and query under the served base (`/review?tab=queue`), or an absolute URL. */
|
|
44
|
+
path: string;
|
|
45
|
+
theme: Theme;
|
|
46
|
+
viewport: Viewport;
|
|
47
|
+
/** Selector of the element the app renders into; the shot waits until it has children. */
|
|
48
|
+
root: string;
|
|
49
|
+
clip: Clip;
|
|
50
|
+
/** A Playwright selector that must be visible before the shot is taken (see {@link RouteState.waitFor}). */
|
|
51
|
+
waitFor?: string;
|
|
52
|
+
/** MSW handlers answering the page's requests, first match wins. Route shots only. */
|
|
53
|
+
handlers?: readonly RequestHandler[];
|
|
54
|
+
/** Class put on `<html>` in the dark theme (Strata's `dark:` variant reads `.dark`). */
|
|
55
|
+
darkClass?: string | false;
|
|
56
|
+
setup?: Setup;
|
|
57
|
+
}
|
|
58
|
+
/** An app's built Storybook. */
|
|
59
|
+
export interface StorybookTarget {
|
|
60
|
+
/** The `storybook build` output folder. Default `storybook-static`. */
|
|
61
|
+
dir?: string;
|
|
62
|
+
/** The Storybook global the preview reads the theme from. Default `theme`, as Strata's preview. */
|
|
63
|
+
themeGlobal?: string;
|
|
64
|
+
}
|
|
65
|
+
/** One state of a route: the MSW handlers that put the server into it, and optional steps. */
|
|
66
|
+
export interface RouteState {
|
|
67
|
+
/** Handlers tried before the target's base handlers (like `server.use(...)` in a test). */
|
|
68
|
+
handlers?: readonly RequestHandler[];
|
|
69
|
+
/** A different path for this state, e.g. the same screen with `?tab=sync`. */
|
|
70
|
+
path?: string;
|
|
71
|
+
/**
|
|
72
|
+
* A Playwright selector that must be visible before the shot is taken, such as `role=alert` or
|
|
73
|
+
* `text=Try again`. Needed when a state takes longer than the network to show: an error after
|
|
74
|
+
* the query client's retry, a toast after a timer.
|
|
75
|
+
*/
|
|
76
|
+
waitFor?: string;
|
|
77
|
+
setup?: Setup;
|
|
78
|
+
}
|
|
79
|
+
/** A screen of the app, screenshotted in each of its states. */
|
|
80
|
+
export interface Route {
|
|
81
|
+
/** Names the baselines: lower-case letters, digits and dashes. */
|
|
82
|
+
name: string;
|
|
83
|
+
/** Path and query under the app's base, e.g. `/review` or `/library?sort=-added`. */
|
|
84
|
+
path: string;
|
|
85
|
+
/**
|
|
86
|
+
* The server states to capture, by name. A list of handlers is shorthand for `{ handlers }`.
|
|
87
|
+
* Default: one state, `default`, served by the base handlers alone.
|
|
88
|
+
*/
|
|
89
|
+
states?: Record<string, readonly RequestHandler[] | RouteState>;
|
|
90
|
+
viewports?: readonly ViewportChoice[];
|
|
91
|
+
clip?: Clip;
|
|
92
|
+
root?: string;
|
|
93
|
+
waitFor?: string;
|
|
94
|
+
setup?: Setup;
|
|
95
|
+
}
|
|
96
|
+
/** An app served from its production build (or a running server), screenshotted route by route. */
|
|
97
|
+
export interface AppTarget {
|
|
98
|
+
/** The build folder to serve, e.g. `dist`. Unknown paths that ask for HTML get `index.html`. */
|
|
99
|
+
dir?: string;
|
|
100
|
+
/** Or a server that is already running, e.g. `http://localhost:4173`. */
|
|
101
|
+
url?: string;
|
|
102
|
+
/** The app's base path (Vite's `base`). Default `/`. */
|
|
103
|
+
base?: string;
|
|
104
|
+
/** MSW handlers for every route: the healthy server, usually the app's `handlers.ts`. */
|
|
105
|
+
handlers?: readonly RequestHandler[];
|
|
106
|
+
/** Default `#root`. */
|
|
107
|
+
root?: string;
|
|
108
|
+
/** Default `["wide"]`. Every route is taken at each. */
|
|
109
|
+
viewports?: readonly ViewportChoice[];
|
|
110
|
+
/** Default `page`. */
|
|
111
|
+
clip?: Clip;
|
|
112
|
+
/** Default `dark`; `false` to rely on `prefers-color-scheme` alone. */
|
|
113
|
+
darkClass?: string | false;
|
|
114
|
+
/**
|
|
115
|
+
* A `fetch` or XHR request no handler answers: `error` (default) fails the shot, because a
|
|
116
|
+
* screenshot that depends on a real server is not a baseline; `bypass` lets it through.
|
|
117
|
+
*/
|
|
118
|
+
onUnhandledRequest?: "error" | "bypass";
|
|
119
|
+
routes: readonly Route[];
|
|
120
|
+
}
|
|
121
|
+
/** A visual suite: where baselines live and what to screenshot. Paths are relative to the config file. */
|
|
122
|
+
export interface VisualConfig {
|
|
123
|
+
/** Committed baselines. Default `tests/visual/baselines`. */
|
|
124
|
+
baselines?: string;
|
|
125
|
+
/** Actual, expected and diff PNGs of changed shots (uploaded by CI). Default `tests/visual/output`. */
|
|
126
|
+
output?: string;
|
|
127
|
+
/** Default `["light", "dark"]`. */
|
|
128
|
+
themes?: readonly Theme[];
|
|
129
|
+
/** Freeze the page's clock at this time, so "3 minutes ago" and today's date stay put. */
|
|
130
|
+
time?: string | number | Date;
|
|
131
|
+
/** The page's time zone. Default `UTC`, so a date renders the same on every machine. */
|
|
132
|
+
timezone?: string;
|
|
133
|
+
/** The page's locale (`navigator.language`, `Intl` defaults). Default `en-US`. */
|
|
134
|
+
locale?: string;
|
|
135
|
+
/** Pages captured at once. Default 4. */
|
|
136
|
+
concurrency?: number;
|
|
137
|
+
storybook?: StorybookTarget | string;
|
|
138
|
+
app?: AppTarget;
|
|
139
|
+
}
|
|
140
|
+
/** What a run found. */
|
|
141
|
+
export interface VisualReport {
|
|
142
|
+
/** Shots taken. */
|
|
143
|
+
total: number;
|
|
144
|
+
same: number;
|
|
145
|
+
/** `name.png: reason` for each shot that differs from its baseline. */
|
|
146
|
+
changed: string[];
|
|
147
|
+
/** Shots with no baseline yet (written, and copied to the output folder). */
|
|
148
|
+
added: string[];
|
|
149
|
+
/** Baselines no shot produced (removed when updating). */
|
|
150
|
+
obsolete: string[];
|
|
151
|
+
/** Shots that failed: page errors, console errors, unhandled requests, nothing rendered. */
|
|
152
|
+
errors: string[];
|
|
153
|
+
/** Things that make baselines less trustworthy, such as an unpinned Playwright. */
|
|
154
|
+
warnings: string[];
|
|
155
|
+
updated: boolean;
|
|
156
|
+
/** Whether the run should fail (in CI a missing baseline fails too). */
|
|
157
|
+
failed: boolean;
|
|
158
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { i as runVisual, n as formatReport } from "./run-CLQi924v.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
// src/visual/cli.ts
|
|
7
|
+
var usage = `Usage: strata-visual [options]
|
|
8
|
+
|
|
9
|
+
Screenshots a built Storybook and/or an app's routes in light and dark, and compares each
|
|
10
|
+
with its committed baseline (Playwright Chromium + pixelmatch).
|
|
11
|
+
|
|
12
|
+
--config <file> config file (default: strata-visual.config.{ts,mts,js,mjs} here)
|
|
13
|
+
--storybook <dir> screenshot this Storybook build (overrides the config's storybook)
|
|
14
|
+
--update write the screenshots as the baselines and remove obsolete ones
|
|
15
|
+
--filter <text> only shots whose name contains the text
|
|
16
|
+
--baselines <dir> where baselines live (default tests/visual/baselines)
|
|
17
|
+
--output <dir> where diffs go (default tests/visual/output)
|
|
18
|
+
--concurrency <n> pages at once (default 4)
|
|
19
|
+
--help show this
|
|
20
|
+
`;
|
|
21
|
+
var configNames = [
|
|
22
|
+
"strata-visual.config.ts",
|
|
23
|
+
"strata-visual.config.mts",
|
|
24
|
+
"strata-visual.config.js",
|
|
25
|
+
"strata-visual.config.mjs"
|
|
26
|
+
];
|
|
27
|
+
/** Loads a config file's default export. */
|
|
28
|
+
async function loadConfig(file) {
|
|
29
|
+
if (/\.[cm]?ts$/.test(file)) {
|
|
30
|
+
const vite = await import("vite").catch(() => void 0);
|
|
31
|
+
if (vite?.runnerImport) {
|
|
32
|
+
const { module } = await vite.runnerImport(file);
|
|
33
|
+
return module.default;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return (await import(pathToFileURL(file).href)).default;
|
|
37
|
+
}
|
|
38
|
+
/** Runs the command with the given arguments and returns the exit code. */
|
|
39
|
+
async function main(argv, cwd = process.cwd()) {
|
|
40
|
+
let values;
|
|
41
|
+
try {
|
|
42
|
+
({values} = parseArgs({
|
|
43
|
+
args: [...argv],
|
|
44
|
+
options: {
|
|
45
|
+
config: { type: "string" },
|
|
46
|
+
storybook: { type: "string" },
|
|
47
|
+
update: { type: "boolean" },
|
|
48
|
+
filter: { type: "string" },
|
|
49
|
+
baselines: { type: "string" },
|
|
50
|
+
output: { type: "string" },
|
|
51
|
+
concurrency: { type: "string" },
|
|
52
|
+
help: { type: "boolean" }
|
|
53
|
+
}
|
|
54
|
+
}));
|
|
55
|
+
} catch (e) {
|
|
56
|
+
console.error(`${e.message}\n\n${usage}`);
|
|
57
|
+
return 2;
|
|
58
|
+
}
|
|
59
|
+
if (values.help) {
|
|
60
|
+
console.log(usage);
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
let config = {};
|
|
64
|
+
let base = cwd;
|
|
65
|
+
const file = values.config ? resolve(cwd, values.config) : configNames.map((n) => resolve(cwd, n)).find((f) => existsSync(f));
|
|
66
|
+
if (values.config && !existsSync(file)) {
|
|
67
|
+
console.error(`strata-visual: ${values.config} not found`);
|
|
68
|
+
return 2;
|
|
69
|
+
}
|
|
70
|
+
if (file) {
|
|
71
|
+
config = await loadConfig(file);
|
|
72
|
+
base = resolve(file, "..");
|
|
73
|
+
}
|
|
74
|
+
if (values.storybook) config = {
|
|
75
|
+
...config,
|
|
76
|
+
storybook: {
|
|
77
|
+
...typeof config.storybook === "object" ? config.storybook : {},
|
|
78
|
+
dir: resolve(cwd, values.storybook)
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
if (values.baselines) config = {
|
|
82
|
+
...config,
|
|
83
|
+
baselines: resolve(cwd, values.baselines)
|
|
84
|
+
};
|
|
85
|
+
if (values.output) config = {
|
|
86
|
+
...config,
|
|
87
|
+
output: resolve(cwd, values.output)
|
|
88
|
+
};
|
|
89
|
+
if (values.concurrency) config = {
|
|
90
|
+
...config,
|
|
91
|
+
concurrency: Number(values.concurrency)
|
|
92
|
+
};
|
|
93
|
+
if (config.storybook === void 0 && config.app === void 0) {
|
|
94
|
+
if (existsSync(resolve(cwd, "storybook-static/index.json"))) config = {
|
|
95
|
+
...config,
|
|
96
|
+
storybook: "storybook-static"
|
|
97
|
+
};
|
|
98
|
+
else {
|
|
99
|
+
console.error(`strata-visual: no config file and no Storybook build here.\n\n${usage}`);
|
|
100
|
+
return 2;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
const report = await runVisual(config, {
|
|
105
|
+
cwd: base,
|
|
106
|
+
update: values.update,
|
|
107
|
+
filter: values.filter
|
|
108
|
+
});
|
|
109
|
+
console.log(formatReport(report));
|
|
110
|
+
return report.failed ? 1 : 0;
|
|
111
|
+
} catch (e) {
|
|
112
|
+
console.error(`strata-visual: ${e.message}`);
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
export { loadConfig, main };
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=visual-cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"visual-cli.js","names":[],"sources":["../src/visual/cli.ts"],"sourcesContent":["// The strata-visual command. With no arguments it reads strata-visual.config.(ts|mts|js|mjs)\n// from the current folder; `--storybook <dir>` screenshots a built Storybook with no config at\n// all (that is how strata-react runs its own suite). A TypeScript config is loaded through Vite's\n// module runner when Vite is installed, so it can import the app's MSW handlers and fixtures\n// with the same extensionless imports and aliases the app's code uses.\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport { formatReport, runVisual } from \"./run\";\nimport type { VisualConfig } from \"./types\";\n\nconst usage = `Usage: strata-visual [options]\n\nScreenshots a built Storybook and/or an app's routes in light and dark, and compares each\nwith its committed baseline (Playwright Chromium + pixelmatch).\n\n --config <file> config file (default: strata-visual.config.{ts,mts,js,mjs} here)\n --storybook <dir> screenshot this Storybook build (overrides the config's storybook)\n --update write the screenshots as the baselines and remove obsolete ones\n --filter <text> only shots whose name contains the text\n --baselines <dir> where baselines live (default tests/visual/baselines)\n --output <dir> where diffs go (default tests/visual/output)\n --concurrency <n> pages at once (default 4)\n --help show this\n`;\n\nconst configNames = [\"strata-visual.config.ts\", \"strata-visual.config.mts\", \"strata-visual.config.js\", \"strata-visual.config.mjs\"];\n\n/** Loads a config file's default export. */\nexport async function loadConfig(file: string): Promise<VisualConfig> {\n if (/\\.[cm]?ts$/.test(file)) {\n const vite = await import(\"vite\").catch(() => undefined);\n if (vite?.runnerImport) {\n const { module } = await vite.runnerImport<{ default: VisualConfig }>(file);\n return module.default;\n }\n }\n const mod = (await import(pathToFileURL(file).href)) as { default: VisualConfig };\n return mod.default;\n}\n\n/** Runs the command with the given arguments and returns the exit code. */\nexport async function main(argv: readonly string[], cwd = process.cwd()): Promise<number> {\n let values;\n try {\n ({ values } = parseArgs({\n args: [...argv],\n options: {\n config: { type: \"string\" },\n storybook: { type: \"string\" },\n update: { type: \"boolean\" },\n filter: { type: \"string\" },\n baselines: { type: \"string\" },\n output: { type: \"string\" },\n concurrency: { type: \"string\" },\n help: { type: \"boolean\" },\n },\n }));\n } catch (e) {\n console.error(`${(e as Error).message}\\n\\n${usage}`);\n return 2;\n }\n if (values.help) {\n console.log(usage);\n return 0;\n }\n\n let config: VisualConfig = {};\n let base = cwd;\n const file = values.config ? resolve(cwd, values.config) : configNames.map((n) => resolve(cwd, n)).find((f) => existsSync(f));\n if (values.config && !existsSync(file!)) {\n console.error(`strata-visual: ${values.config} not found`);\n return 2;\n }\n if (file) {\n config = await loadConfig(file);\n base = resolve(file, \"..\");\n }\n if (values.storybook) config = { ...config, storybook: { ...(typeof config.storybook === \"object\" ? config.storybook : {}), dir: resolve(cwd, values.storybook) } };\n if (values.baselines) config = { ...config, baselines: resolve(cwd, values.baselines) };\n if (values.output) config = { ...config, output: resolve(cwd, values.output) };\n if (values.concurrency) config = { ...config, concurrency: Number(values.concurrency) };\n if (config.storybook === undefined && config.app === undefined) {\n if (existsSync(resolve(cwd, \"storybook-static/index.json\"))) config = { ...config, storybook: \"storybook-static\" };\n else {\n console.error(`strata-visual: no config file and no Storybook build here.\\n\\n${usage}`);\n return 2;\n }\n }\n\n try {\n const report = await runVisual(config, { cwd: base, update: values.update, filter: values.filter });\n console.log(formatReport(report));\n return report.failed ? 1 : 0;\n } catch (e) {\n console.error(`strata-visual: ${(e as Error).message}`);\n return 1;\n }\n}\n"],"mappings":";;;;;;AAYA,IAAM,QAAQ;;;;;;;;;;;;;;AAed,IAAM,cAAc;CAAC;CAA2B;CAA4B;CAA2B;AAA0B;;AAGjI,eAAsB,WAAW,MAAqC;CACpE,IAAI,aAAa,KAAK,IAAI,GAAG;EAC3B,MAAM,OAAO,MAAM,OAAO,OAAO,CAAC,YAAY,KAAA,CAAS;EACvD,IAAI,MAAM,cAAc;GACtB,MAAM,EAAE,WAAW,MAAM,KAAK,aAAwC,IAAI;GAC1E,OAAO,OAAO;EAChB;CACF;CAEA,QAAO,MADY,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CACnC;AACb;;AAGA,eAAsB,KAAK,MAAyB,MAAM,QAAQ,IAAI,GAAoB;CACxF,IAAI;CACJ,IAAI;EACF,CAAC,CAAE,UAAW,UAAU;GACtB,MAAM,CAAC,GAAG,IAAI;GACd,SAAS;IACP,QAAQ,EAAE,MAAM,SAAS;IACzB,WAAW,EAA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AC9D,IAAI,WAAW,QAAQ,KAAK,6BAA6B,CAAC,GAAG,SAAS;GAAE,GAAG;GAAQ,WAAW;EAAmB;OAC5G;GACH,QAAQ,MAAM,iEAAiE,OAAO;GACtF,OAAO;EACT;CACF;CAEA,IAAI;EACF,MAAM,SAAS,MAAM,UAAU,QAAQ;GAAE,KAAK;GAAM,QAAQ,OAAO;GAAQ,QAAQ,OAAO;EAAO,CAAC;EAClG,QAAQ,IAAI,aAAa,MAAM,CAAC;EAChC,OAAO,OAAO,SAAS,IAAI;CAC7B,SAAS,GAAG;EACV,QAAQ,MAAM,kBAAmB,EAAY,SAAS;EACtD,OAAO;CACT;AACF"}
|
package/dist/visual.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { u as MAX_DIFF_PIXELS, d as THRESHOLD, h as capture, f as compare, p as decode, a as defaultThemes, t as defineVisualConfig, m as encode, n as formatReport, r as pinWarnings, g as resolveShotUrl, o as routeShots, i as runVisual, l as serveStatic, s as storybookShots, _ as toFetchRequest, c as viewports } from "./run-CLQi924v.js";
|