framesheet 0.0.0-stage → 0.2.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 (85) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +247 -2
  3. package/dist/analysis.d.ts +84 -0
  4. package/dist/analysis.d.ts.map +1 -0
  5. package/dist/analysis.js +335 -0
  6. package/dist/analysis.js.map +1 -0
  7. package/dist/checks.d.ts +44 -0
  8. package/dist/checks.d.ts.map +1 -0
  9. package/dist/checks.js +200 -0
  10. package/dist/checks.js.map +1 -0
  11. package/dist/compose.d.ts +130 -0
  12. package/dist/compose.d.ts.map +1 -0
  13. package/dist/compose.js +266 -0
  14. package/dist/compose.js.map +1 -0
  15. package/dist/driver.d.ts +56 -0
  16. package/dist/driver.d.ts.map +1 -0
  17. package/dist/driver.js +94 -0
  18. package/dist/driver.js.map +1 -0
  19. package/dist/generated/assets.d.ts +13 -0
  20. package/dist/generated/assets.d.ts.map +1 -0
  21. package/dist/generated/assets.js +15 -0
  22. package/dist/generated/assets.js.map +1 -0
  23. package/dist/index.d.ts +18 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +17 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/inspect.d.ts +163 -0
  28. package/dist/inspect.d.ts.map +1 -0
  29. package/dist/inspect.js +593 -0
  30. package/dist/inspect.js.map +1 -0
  31. package/dist/marks.d.ts +49 -0
  32. package/dist/marks.d.ts.map +1 -0
  33. package/dist/marks.js +460 -0
  34. package/dist/marks.js.map +1 -0
  35. package/dist/marks.schema.json +307 -0
  36. package/dist/media.d.ts +22 -0
  37. package/dist/media.d.ts.map +1 -0
  38. package/dist/media.js +306 -0
  39. package/dist/media.js.map +1 -0
  40. package/dist/models.d.ts +208 -0
  41. package/dist/models.d.ts.map +1 -0
  42. package/dist/models.js +9 -0
  43. package/dist/models.js.map +1 -0
  44. package/dist/pixels.d.ts +52 -0
  45. package/dist/pixels.d.ts.map +1 -0
  46. package/dist/pixels.js +275 -0
  47. package/dist/pixels.js.map +1 -0
  48. package/dist/pyfmt.d.ts +16 -0
  49. package/dist/pyfmt.d.ts.map +1 -0
  50. package/dist/pyfmt.js +54 -0
  51. package/dist/pyfmt.js.map +1 -0
  52. package/dist/report.schema.json +1326 -0
  53. package/dist/sources.d.ts +43 -0
  54. package/dist/sources.d.ts.map +1 -0
  55. package/dist/sources.js +164 -0
  56. package/dist/sources.js.map +1 -0
  57. package/dist/test.d.ts +46 -0
  58. package/dist/test.d.ts.map +1 -0
  59. package/dist/test.js +58 -0
  60. package/dist/test.js.map +1 -0
  61. package/dist/timing.d.ts +30 -0
  62. package/dist/timing.d.ts.map +1 -0
  63. package/dist/timing.js +128 -0
  64. package/dist/timing.js.map +1 -0
  65. package/dist/video.d.ts +65 -0
  66. package/dist/video.d.ts.map +1 -0
  67. package/dist/video.js +440 -0
  68. package/dist/video.js.map +1 -0
  69. package/package.json +79 -4
  70. package/src/analysis.ts +416 -0
  71. package/src/checks.ts +261 -0
  72. package/src/compose.ts +337 -0
  73. package/src/driver.ts +115 -0
  74. package/src/generated/assets.ts +20 -0
  75. package/src/index.ts +54 -0
  76. package/src/inspect.ts +722 -0
  77. package/src/marks.ts +481 -0
  78. package/src/media.ts +296 -0
  79. package/src/models.ts +225 -0
  80. package/src/pixels.ts +284 -0
  81. package/src/pyfmt.ts +55 -0
  82. package/src/sources.ts +175 -0
  83. package/src/test.ts +100 -0
  84. package/src/timing.ts +133 -0
  85. package/src/video.ts +513 -0
package/src/inspect.ts ADDED
@@ -0,0 +1,722 @@
1
+ /**
2
+ * The inspection pipeline (port of core.py): load, detect duration, sample, check,
3
+ * compose. `inspect()` renders a file/markup/URL in its own browser context;
4
+ * `inspectPage()` inspects a page (or one component) you already have open.
5
+ */
6
+
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import { join, resolve as resolvePath } from "node:path";
9
+ import type { Browser, BrowserContext, ElementHandle, LaunchOptions, Locator, Page } from "playwright-core";
10
+ import { Geometry, runChecks, tracks } from "./analysis.js";
11
+ import { staticFindings as runStaticChecks, parseSource } from "./checks.js";
12
+ import { contactSheet, heatmap, Renderer } from "./compose.js";
13
+ import { type Clip, Driver, type Snapshot } from "./driver.js";
14
+ import type {
15
+ ColorScheme,
16
+ DurationInfo,
17
+ Finding,
18
+ FrameMetrics,
19
+ ImageBuffers,
20
+ ImagePaths,
21
+ LoopInfo,
22
+ Marks,
23
+ Rect,
24
+ Report,
25
+ Severity,
26
+ SourceKind,
27
+ } from "./models.js";
28
+ import { asRect } from "./models.js";
29
+ import { decode, diffStats, type Frame, MotionAccumulator, toCss } from "./pixels.js";
30
+ import { fixed, g, pct, pyRound } from "./pyfmt.js";
31
+ import { defaultSize, resolveSource, type Source, VIRTUAL_ORIGIN } from "./sources.js";
32
+ import { detectDuration, epsilon, parseTimings, sampleTimes } from "./timing.js";
33
+ import { inspectVideo, type TimesSpec } from "./video.js";
34
+ import { loadMarks } from "./marks.js";
35
+
36
+ /** A seam changing fewer than 0.2% of pixels always counts as seamless. */
37
+ export const SEAM_MIN_RATIO = 0.002;
38
+ /** A seam is a jump if it changes this many times more pixels than one normal step. */
39
+ export const SEAM_STEP_FACTOR = 3;
40
+ export const MIN_AUTO_SIDE = 400;
41
+ export const MAX_CONSOLE_ERRORS = 5;
42
+ /** Virtual clock origin (same as Python): 2025-01-01T00:00:00Z. */
43
+ export const EPOCH = Date.UTC(2025, 0, 1);
44
+ /**
45
+ * Chromium flags framesheet launches with. Pass them to your own browser
46
+ * (`launchOptions: { args: LAUNCH_ARGS }`) for byte-stable frames.
47
+ */
48
+ export const LAUNCH_ARGS = [
49
+ // Compositor-thread animations race with pause(): keep them on the main thread.
50
+ "--disable-threaded-animation",
51
+ "--hide-scrollbars",
52
+ "--force-color-profile=srgb",
53
+ "--disable-lcd-text",
54
+ ];
55
+ export const INSTALL_HINT =
56
+ "Chromium for Playwright is not installed. Run `npx playwright install chromium` " +
57
+ "(on a bare Linux host: `npx playwright install --with-deps chromium`).";
58
+
59
+ const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2 };
60
+
61
+ export class BrowserNotInstalledError extends Error {
62
+ constructor(cause?: unknown) {
63
+ super(INSTALL_HINT, { cause });
64
+ this.name = "BrowserNotInstalledError";
65
+ }
66
+ }
67
+
68
+ /** Options shared by {@link inspect} and {@link inspectPage}. */
69
+ export interface SampleOptions {
70
+ /** Number of contact-sheet tiles (2-100), spread over one cycle. Default 12. */
71
+ frames?: number;
72
+ /** Cycle length in seconds; detected from SMIL/CSS/Web Animations if omitted. */
73
+ duration?: number;
74
+ /** Time in seconds of the full-resolution frame `full`. Default 0. */
75
+ at?: number;
76
+ /** Write `full.png`, `sheet.png`, `heatmap.png`, `report.json` here (default: nothing written). */
77
+ out?: string;
78
+ /** Longest side of a contact-sheet tile in px (default: fit 1568 px width). */
79
+ tile?: number;
80
+ /** Contact-sheet columns (default: roughly 4:3 sheet). */
81
+ columns?: number;
82
+ /** Also return (and write to `frames/`) every contact-sheet frame. */
83
+ keepFrames?: boolean;
84
+ /** Extra evenly spaced frames (pixels only) for a continuous heatmap trail. Default 48. */
85
+ heatFrames?: number;
86
+ /** Timeout for navigation and page scripts in ms. Default 30000. */
87
+ timeout?: number;
88
+ }
89
+
90
+ export interface InspectOptions extends SampleOptions {
91
+ /** Viewport `[width, height]` in CSS px (default: SVG size/viewBox, or 1280x720). */
92
+ size?: [number, number];
93
+ /** Device scale factor (default 1; tiny SVGs without `size` get more). */
94
+ scale?: number;
95
+ /** `prefers-color-scheme`. Default `light`. */
96
+ colorScheme?: ColorScheme;
97
+ /** Reuse a browser (a new context is created and closed). Default: launch Chromium. */
98
+ browser?: Browser;
99
+ /** Passed to `chromium.launch()` when no `browser` is given (args are added to LAUNCH_ARGS). */
100
+ launchOptions?: LaunchOptions;
101
+ /**
102
+ * Abort every HTTP(S) request except the input itself (`data:`/`blob:` URLs still work)
103
+ * and close every WebSocket. Recommended for untrusted markup (e.g. agent output in a
104
+ * server). Default false.
105
+ */
106
+ blockNetwork?: boolean;
107
+ /** Videos: one tile every this many seconds (instead of `frames`). */
108
+ every?: number;
109
+ /** Videos: explicit tile times (s), or `"marks"`: each point's t, each region's/span's midpoint. */
110
+ times?: TimesSpec;
111
+ /** Videos: start of the inspected range (s). Default 0. */
112
+ start?: number;
113
+ /** Videos: end of the inspected range (s). Default: the media duration. */
114
+ end?: number;
115
+ /** Videos: marks to draw (path to marks.json, JSON string or object; see marks.schema.json). */
116
+ marks?: string | Marks | Record<string, unknown>;
117
+ /** Videos: seconds without visible change reported as `video-static-stretch`. Default 2. */
118
+ staticStretch?: number;
119
+ }
120
+
121
+ export interface InspectPageOptions extends SampleOptions {
122
+ /** Inspect only this element (a component); default: the whole page/viewport. */
123
+ locator?: Locator;
124
+ /** Header title of the sheet/heatmap (default: locator or URL path; keep stable for snapshots). */
125
+ title?: string;
126
+ /**
127
+ * Whether Playwright's fake clock drives JS time. Default: auto (true if `prepare(page)`
128
+ * ran before navigation). Without it, SMIL/CSS/Web Animations are still frame-accurate,
129
+ * but rAF/timer-driven motion keeps running in real time.
130
+ */
131
+ clock?: boolean;
132
+ /**
133
+ * Called after time is frozen and before t=0 is captured, e.g. `() => button.click()`
134
+ * to start an "open" animation from its first frame.
135
+ */
136
+ trigger?: () => Promise<unknown>;
137
+ /** Extra space (CSS px) around the locator's box in the images. Default 0. */
138
+ padding?: number;
139
+ /** Run static source checks on the locator's/page's serialised markup. Default false. */
140
+ staticChecks?: boolean;
141
+ }
142
+
143
+ /** Everything framesheet found out about one input. */
144
+ export class Inspection {
145
+ constructor(
146
+ /** The report (same schema as the Python package's report.json). */
147
+ readonly report: Report,
148
+ /** PNG bytes. */
149
+ readonly images: ImageBuffers,
150
+ /** Written files (only with `out`). */
151
+ readonly files: ImagePaths | null,
152
+ ) {}
153
+
154
+ get findings(): Finding[] {
155
+ return this.report.findings;
156
+ }
157
+
158
+ get errors(): Finding[] {
159
+ return this.report.findings.filter((f) => f.severity === "error");
160
+ }
161
+
162
+ get warnings(): Finding[] {
163
+ return this.report.findings.filter((f) => f.severity === "warning");
164
+ }
165
+
166
+ /** All finding codes, handy for assertions. */
167
+ codes(): Set<string> {
168
+ return new Set(this.report.findings.map((f) => f.code));
169
+ }
170
+
171
+ /** Concise multi-line text for humans and agents (what the Python CLI prints). */
172
+ summary(): string {
173
+ return summarize(this.report);
174
+ }
175
+
176
+ /** `report.json` content. */
177
+ toJSON(): Report {
178
+ return this.report;
179
+ }
180
+ }
181
+
182
+ /** Concise multi-line text for a report (same format as the Python package). */
183
+ export function summarize(r: Report): string {
184
+ const [w, h] = r.viewport;
185
+ const d = r.duration;
186
+ const lines = [
187
+ `framesheet: ${r.source} (${r.kind}, ${w}x${h} @${g(r.device_scale_factor)}x)`,
188
+ `duration: ${g(d.seconds)}s ${d.method}: ${d.detail}${d.looping ? " [looping]" : ""}`,
189
+ ];
190
+ const v = r.video;
191
+ if (v) {
192
+ let facts = `${v.container} ${v.codec || "?"} ${v.width}x${v.height}`;
193
+ if (v.fps) facts += ` ${g(v.fps)}fps`;
194
+ if (v.frame_count) facts += `, ${v.frame_count} frames`;
195
+ lines.push(`video: ${facts}; range ${g(v.start)}-${g(v.end)}s, ${v.samples.length} samples`);
196
+ }
197
+ const busiest = r.frames.reduce((a, b) => (b.changed_ratio > a.changed_ratio ? b : a));
198
+ const motion = busiest.changed_ratio
199
+ ? `max change ${pct(busiest.changed_ratio, 1)} at t=${fixed(busiest.t, 2)}s`
200
+ : "no pixel changes";
201
+ lines.push(`frames: ${r.times.length} at t=${fixed(r.times[0], 2)}..${fixed(r.times[r.times.length - 1], 2)}s; ${motion}`);
202
+ if (r.loop.checked) lines.push(`loop: ${r.loop.seamless ? "seamless" : "NOT seamless"} (${r.loop.detail})`);
203
+ else lines.push(`loop: not checked (${r.loop.detail})`);
204
+ const moving = r.elements.slice(0, 8).map((e) => e.element);
205
+ if (moving.length) {
206
+ const more = r.elements.length > 8 ? ` (+${r.elements.length - 8} more)` : "";
207
+ lines.push(`animated elements: ${moving.join(", ")}${more}`);
208
+ }
209
+ const count = (s: Severity) => r.findings.filter((f) => f.severity === s).length;
210
+ lines.push(`findings: ${count("error")} error(s), ${count("warning")} warning(s), ${count("info")} info`);
211
+ const tags: Record<Severity, string> = { error: "ERROR", warning: "WARN ", info: "INFO " };
212
+ for (const f of r.findings) lines.push(` ${tags[f.severity]} [${f.check}] ${f.code}: ${f.message}`);
213
+ lines.push(
214
+ "images:",
215
+ ` full ${r.images.full} (t=${g(r.full_at)}s: layout, text, margins)`,
216
+ ` sheet ${r.images.sheet} ${v ? "(tiles over the range + timeline)" : "(motion over one cycle)"}`,
217
+ ` heatmap ${r.images.heatmap} (what moves at all)`,
218
+ ` report ${r.images.report}`,
219
+ );
220
+ return lines.join("\n");
221
+ }
222
+
223
+ function validate(opts: SampleOptions): void {
224
+ const frames = opts.frames ?? 12;
225
+ if (!(frames >= 2 && frames <= 100) || !Number.isInteger(frames)) {
226
+ throw new RangeError("frames must be an integer between 2 and 100");
227
+ }
228
+ if (opts.duration != null && !(opts.duration > 0)) throw new RangeError("duration must be positive");
229
+ if (opts.at != null && !(opts.at >= 0)) throw new RangeError("at must be >= 0");
230
+ if (opts.heatFrames != null && !(opts.heatFrames >= 0)) throw new RangeError("heatFrames must be >= 0");
231
+ }
232
+
233
+ /** Tiny SVGs (icons) get a higher device scale factor so frames stay legible. */
234
+ function autoScale(size: [number, number]): number {
235
+ const longest = Math.max(...size);
236
+ return longest < MIN_AUTO_SIDE ? Math.min(8, Math.ceil(MIN_AUTO_SIDE / longest)) : 1;
237
+ }
238
+
239
+ function isMissingBrowser(err: unknown): boolean {
240
+ const msg = String((err as Error)?.message ?? err);
241
+ return msg.includes("Executable doesn't exist") || msg.includes("playwright install");
242
+ }
243
+
244
+ async function launch(options?: LaunchOptions): Promise<Browser> {
245
+ const { chromium } = await import("playwright-core");
246
+ try {
247
+ return await chromium.launch({ ...options, args: [...LAUNCH_ARGS, ...(options?.args ?? [])] });
248
+ } catch (err) {
249
+ if (isMissingBrowser(err)) throw new BrowserNotInstalledError(err);
250
+ throw err;
251
+ }
252
+ }
253
+
254
+ function listenForErrors(page: Page, sink: string[]): () => void {
255
+ const onPageError = (err: Error) => sink.push(`pageerror: ${err.message}`);
256
+ const onConsole = (msg: import("playwright-core").ConsoleMessage) => {
257
+ if (msg.type() === "error") sink.push(`console.${msg.type()}: ${msg.text()}`);
258
+ };
259
+ page.on("pageerror", onPageError);
260
+ page.on("console", onConsole);
261
+ return () => {
262
+ page.off("pageerror", onPageError);
263
+ page.off("console", onConsole);
264
+ };
265
+ }
266
+
267
+ function titleOf(label: string): string {
268
+ if (label === "-" || label === "<snippet>") return "stdin";
269
+ const parts = label.split("/").filter(Boolean);
270
+ return parts[parts.length - 1] ?? label;
271
+ }
272
+
273
+ /**
274
+ * Render an animated SVG/HTML at evenly spaced virtual times and check it.
275
+ *
276
+ * @param source Path to an `.svg`/`.html` file, an `http(s)://` URL, or a markup string
277
+ * starting with `<`.
278
+ */
279
+ export async function inspect(source: string, options: InspectOptions = {}): Promise<Inspection> {
280
+ validate(options);
281
+ const src = await resolveSource(source);
282
+ const videoOnly = (["every", "times", "start", "end", "marks"] as const).filter((k) => options[k] !== undefined);
283
+ if (src.kind !== "video" && videoOnly.length) throw new RangeError(`${videoOnly.join(", ")}: only for video inputs`);
284
+ if (options.staticStretch !== undefined && !(options.staticStretch > 0)) throw new RangeError("staticStretch must be positive");
285
+ const marks = src.kind === "video" && options.marks !== undefined ? loadMarks(options.marks) : null;
286
+ const browser = options.browser ?? (await launch(options.launchOptions));
287
+ const ownsBrowser = !options.browser;
288
+ let renderer: Renderer | null = null;
289
+ let context: BrowserContext | null = null;
290
+ try {
291
+ renderer = await Renderer.open(browser);
292
+ if (src.kind === "video") {
293
+ const built = await inspectVideo(src, browser, renderer, { ...options, marks }, autoScale);
294
+ return new Inspection(built.report, built.images, built.paths);
295
+ }
296
+ const parsed = src.text ? await parseSource(renderer.page, src.text, src.kind) : null;
297
+ const viewport = options.size ?? defaultSize(src.kind, parsed);
298
+ const dsf = options.scale ?? (options.size ? 1 : autoScale(viewport));
299
+ context = await browser.newContext({
300
+ viewport: { width: viewport[0], height: viewport[1] },
301
+ deviceScaleFactor: dsf,
302
+ colorScheme: options.colorScheme ?? "light",
303
+ reducedMotion: "no-preference",
304
+ locale: "en-US",
305
+ timezoneId: "UTC",
306
+ });
307
+ const page = await context.newPage();
308
+ page.setDefaultTimeout(options.timeout ?? 30_000);
309
+ const consoleErrors: string[] = [];
310
+ listenForErrors(page, consoleErrors);
311
+ await serve(context, src, options.blockNetwork ?? false);
312
+ // pauseAt() installs the fake clock itself. A separate install() first would let the
313
+ // real time between the two calls leak into performance.now() (Playwright replays it
314
+ // as running time), shifting rAF-driven frames from run to run.
315
+ await page.clock.pauseAt(EPOCH + 1000);
316
+ const response = await page.goto(src.url, { waitUntil: "load" });
317
+ let text = src.text;
318
+ if (text === null && response) text = await response.text().catch(() => null);
319
+ const driver = new Driver(page, page.mainFrame(), true);
320
+ await driver.inject();
321
+ await driver.start();
322
+ const isSvgDoc = Boolean(await driver.js("window.__framesheet.isSvgDoc"));
323
+ const findings = text ? await runStaticChecks(renderer.page, src.kind, text) : [];
324
+ return await pipeline({
325
+ driver,
326
+ renderer,
327
+ label: src.label,
328
+ title: titleOf(src.label),
329
+ kind: src.kind,
330
+ viewport,
331
+ dsf,
332
+ isSvgDoc,
333
+ staticFindings: findings,
334
+ consoleErrors,
335
+ overflow: src.kind === "html",
336
+ options,
337
+ });
338
+ } catch (err) {
339
+ if (isMissingBrowser(err)) throw new BrowserNotInstalledError(err);
340
+ throw err;
341
+ } finally {
342
+ await context?.close().catch(() => undefined);
343
+ await renderer?.close();
344
+ if (ownsBrowser) await browser.close().catch(() => undefined);
345
+ }
346
+ }
347
+
348
+ async function serve(context: BrowserContext, src: Source, blockNetwork: boolean): Promise<void> {
349
+ if (src.body !== undefined) {
350
+ const body = src.body;
351
+ const type = src.kind === "svg" ? "image/svg+xml" : "text/html";
352
+ await context.route(src.url, (route) => route.fulfill({ status: 200, contentType: `${type}; charset=utf-8`, body }));
353
+ }
354
+ if (blockNetwork) {
355
+ await context.route(
356
+ (url) => url.href !== src.url && !url.href.startsWith(`${VIRTUAL_ORIGIN}/input.`),
357
+ (route) => route.abort("blockedbyclient"),
358
+ );
359
+ // route() only sees HTTP(S); WebSockets need their own handler (Playwright >= 1.48).
360
+ if (typeof context.routeWebSocket === "function") {
361
+ await context.routeWebSocket(/.*/, (ws) => ws.close({ code: 1008, reason: "blocked by framesheet" }));
362
+ }
363
+ }
364
+ }
365
+
366
+ const PREPARED_FLAG = "__framesheetPrepared";
367
+
368
+ export interface PrepareOptions {
369
+ /**
370
+ * Freeze time from navigation on, exactly like `inspect()` does: JS-driven motion that
371
+ * starts on load is captured from its first frame, byte for byte. The page's timers,
372
+ * rAF and `Date` stand still until an inspection (or `page.clock.runFor`) advances
373
+ * them, which suits component pages and stories better than whole apps.
374
+ * Default false: the fake clock follows real time and the app behaves normally.
375
+ */
376
+ paused?: boolean;
377
+ }
378
+
379
+ /**
380
+ * Install Playwright's fake clock on a page **before navigation** (`goto`), so that
381
+ * `inspectPage` can also step JavaScript-driven motion (requestAnimationFrame, timers,
382
+ * `Date`, `performance.now`: canvas, rAF/spring animation libraries) frame by frame.
383
+ *
384
+ * By default the clock keeps running in real time until an inspection pauses it, so the
385
+ * app behaves normally; after each inspection it runs on again. With `paused: true` time
386
+ * is frozen from the start (see {@link PrepareOptions.paused}). Not needed for SMIL, CSS
387
+ * animations/transitions or Web Animations, which are seeked directly on any page.
388
+ */
389
+ export async function prepare(page: Page, options: PrepareOptions = {}): Promise<void> {
390
+ const mode = options.paused ? "paused" : "running";
391
+ if (options.paused) {
392
+ // pauseAt() installs the clock; no install() first (see inspect()).
393
+ await page.clock.pauseAt(EPOCH + 1000);
394
+ } else {
395
+ await page.clock.install();
396
+ }
397
+ await page.addInitScript(`window.${PREPARED_FLAG} = ${JSON.stringify(mode)};`);
398
+ }
399
+
400
+ async function scopeBox(handle: ElementHandle<Element>, padding: number, page: Page): Promise<Clip> {
401
+ await handle.scrollIntoViewIfNeeded().catch(() => undefined);
402
+ const box = await handle.boundingBox();
403
+ if (!box) throw new Error("inspectPage: the locator is not visible (no bounding box)");
404
+ const vp = page.viewportSize() ?? (await page.evaluate(() => ({ width: innerWidth, height: innerHeight })));
405
+ const x0 = Math.max(0, Math.floor(box.x - padding));
406
+ const y0 = Math.max(0, Math.floor(box.y - padding));
407
+ const x1 = Math.min(vp.width, Math.ceil(box.x + box.width + padding));
408
+ const y1 = Math.min(vp.height, Math.ceil(box.y + box.height + padding));
409
+ if (x1 <= x0 || y1 <= y0) throw new Error("inspectPage: the locator is outside the viewport");
410
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
411
+ }
412
+
413
+ /**
414
+ * Inspect a page you already have open (e.g. in a Playwright test), or one component of it
415
+ * (`locator`). Same sampling, checks, images and report as {@link inspect}.
416
+ *
417
+ * Works on any page for SMIL, CSS animations/transitions and Web Animations. For JS-driven
418
+ * motion call {@link prepare} before navigating. The page is handed back afterwards
419
+ * (animations resumed, fake clock running again), but seeked animations continue from
420
+ * where the inspection left them.
421
+ */
422
+ export async function inspectPage(page: Page, options: InspectPageOptions = {}): Promise<Inspection> {
423
+ validate(options);
424
+ const locator = options.locator;
425
+ const prepared = (await page.evaluate(`window.${PREPARED_FLAG} || null`)) as "paused" | "running" | null;
426
+ const clockControlled = options.clock ?? prepared !== null;
427
+ const consoleErrors: string[] = [];
428
+ const unlisten = listenForErrors(page, consoleErrors);
429
+ const browser = page.context().browser();
430
+ const renderer = await Renderer.open(browser ?? page.context());
431
+ let handle: ElementHandle<Element> | null = null;
432
+ let driver: Driver | null = null;
433
+ let paused = false;
434
+ try {
435
+ if (clockControlled && prepared !== "paused") {
436
+ // Pause on a 16 ms tick boundary a little in the future (the jump fires due timers
437
+ // once): fake rAF callbacks are aligned to ticks % 16, so this gives the same frame
438
+ // phase on every run. Date.now() - performance.now() is constant on the fake clock,
439
+ // so the target does not depend on how long this round trip takes.
440
+ const [date, perf] = (await page.evaluate("[Date.now(), performance.now()]")) as [number, number];
441
+ const ticks = Math.ceil((perf + 250) / 16) * 16;
442
+ await page.clock.pauseAt(date - perf + ticks);
443
+ paused = true;
444
+ }
445
+ if (options.trigger) await options.trigger();
446
+ handle = locator
447
+ ? ((await locator.elementHandle({ timeout: options.timeout ?? 30_000 })) as ElementHandle<Element>)
448
+ : null;
449
+ const frame = handle ? ((await handle.ownerFrame()) ?? page.mainFrame()) : page.mainFrame();
450
+ driver = new Driver(page, frame, clockControlled);
451
+ await driver.inject();
452
+ await driver.scope(handle);
453
+ await driver.start();
454
+ if (handle) driver.clip = await scopeBox(handle, options.padding ?? 0, page);
455
+ const vp = page.viewportSize() ?? { width: 0, height: 0 };
456
+ const dsf = Number(await page.evaluate("window.devicePixelRatio")) || 1;
457
+ const scopeIsSvg = handle ? await handle.evaluate((el) => el instanceof SVGElement) : false;
458
+ const isSvgDoc = scopeIsSvg || Boolean(await driver.js("window.__framesheet.isSvgDoc"));
459
+ const kind: SourceKind = isSvgDoc ? "svg" : "html";
460
+ let findings: Finding[] = [];
461
+ if (options.staticChecks) {
462
+ const markup = handle
463
+ ? await handle.evaluate((el) => el.outerHTML)
464
+ : await frame.evaluate(() => document.documentElement.outerHTML);
465
+ findings = await runStaticChecks(renderer.page, kind, markup);
466
+ }
467
+ const url = frame.url();
468
+ const label = locator ? `${url} ${String(locator)}` : url;
469
+ return await pipeline({
470
+ driver,
471
+ renderer,
472
+ label,
473
+ title: options.title ?? (locator ? String(locator) : safePath(url)),
474
+ kind,
475
+ viewport: [vp.width, vp.height],
476
+ dsf,
477
+ isSvgDoc,
478
+ staticFindings: findings,
479
+ consoleErrors,
480
+ overflow: true,
481
+ options,
482
+ });
483
+ } finally {
484
+ unlisten();
485
+ await driver?.resume();
486
+ if (paused) await page.clock.resume().catch(() => undefined);
487
+ await handle?.dispose().catch(() => undefined);
488
+ await renderer.close();
489
+ }
490
+ }
491
+
492
+ function safePath(url: string): string {
493
+ try {
494
+ const u = new URL(url);
495
+ return u.protocol.startsWith("http") ? u.pathname : titleOf(url);
496
+ } catch {
497
+ return url;
498
+ }
499
+ }
500
+
501
+ interface PipelineInput {
502
+ driver: Driver;
503
+ renderer: Renderer;
504
+ label: string;
505
+ title: string;
506
+ kind: SourceKind;
507
+ viewport: [number, number];
508
+ dsf: number;
509
+ isSvgDoc: boolean;
510
+ staticFindings: Finding[];
511
+ consoleErrors: string[];
512
+ overflow: boolean;
513
+ options: SampleOptions;
514
+ }
515
+
516
+ async function pipeline(p: PipelineInput): Promise<Inspection> {
517
+ const { driver: s, options } = p;
518
+ const frames = options.frames ?? 12;
519
+ const at = options.at ?? 0;
520
+ const heatFrames = options.heatFrames ?? 48;
521
+ const findings = [...p.staticFindings];
522
+ const animations = parseTimings(await s.js<unknown[]>("window.__framesheet.timings()"));
523
+ const info = detectDuration(animations, options.duration);
524
+ const times = sampleTimes(info.seconds, frames);
525
+ const eps = pyRound(epsilon(info.seconds), 4);
526
+ const description = await s.js<import("./analysis.js").Description[]>("window.__framesheet.describe()");
527
+ const targets = await s.js<Record<string, string[]>>("window.__framesheet.animatedTargets()");
528
+ const canvas = asRect(await s.js<number[]>("window.__framesheet.canvasRect()"));
529
+ const viewbox = await s.js<number[] | null>("window.__framesheet.viewBox()");
530
+
531
+ const measured = new Set([...times, eps, at]);
532
+ const extra = new Set(Array.from({ length: heatFrames }, (_, i) => pyRound((info.seconds * i) / heatFrames, 4)));
533
+ const last = times[times.length - 1];
534
+ const snaps = new Map<number, Snapshot>();
535
+ const decoded = new Map<number, Frame>();
536
+ const motion = new MotionAccumulator();
537
+ for (const t of [...new Set([...measured, ...extra])].sort((a, b) => a - b)) {
538
+ let png: Buffer;
539
+ if (measured.has(t)) {
540
+ const snap = await s.snapshot(t, p.overflow);
541
+ snaps.set(t, snap);
542
+ png = snap.png;
543
+ } else {
544
+ png = await s.screenshot(t);
545
+ }
546
+ const isSheetFrame = measured.has(t);
547
+ if (t <= last || isSheetFrame) {
548
+ const frame = decode(png);
549
+ if (isSheetFrame) decoded.set(t, frame);
550
+ if (t <= last) motion.add(frame);
551
+ }
552
+ }
553
+ const consoleErrors = [...p.consoleErrors];
554
+
555
+ const sheetSnaps = times.map((t) => snaps.get(t)!);
556
+ const sheetFrames = times.map((t) => decoded.get(t)!);
557
+ const metrics = frameMetrics(sheetFrames, times, p.dsf);
558
+ const moving = metrics.some((m) => m.changed_ratio > 0);
559
+ findings.push(...motionFindings(info, moving));
560
+ const loop = loopInfo(info, moving, decoded.get(times[0])!, decoded.get(eps)!, sheetFrames[sheetFrames.length - 1], p.dsf);
561
+ if (loop.checked && loop.seamless === false) {
562
+ findings.push({
563
+ severity: "warning",
564
+ code: "non-seamless-loop",
565
+ message: `The loop jumps at the cycle end: ${loop.detail}.`,
566
+ check: "render",
567
+ element: null,
568
+ times: [last, 0],
569
+ });
570
+ }
571
+ const geo = Geometry.build(description, sheetSnaps, {
572
+ canvas,
573
+ viewbox: viewbox ? asRect(viewbox) : null,
574
+ targets,
575
+ animations,
576
+ isSvgDoc: p.isSvgDoc,
577
+ });
578
+ findings.push(...runChecks(geo));
579
+ for (const msg of consoleErrors.slice(0, MAX_CONSOLE_ERRORS)) {
580
+ findings.push({ severity: "warning", code: "console-error", message: msg, check: "render", element: null, times: null });
581
+ }
582
+ findings.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
583
+
584
+ // Images.
585
+ const span = `${times.length} frames over 0-${g(info.seconds)}s`;
586
+ const how = { override: "set by --duration", detected: "detected", fallback: "fallback", media: "media" }[info.method];
587
+ const looping = info.looping ? "looping" : "not looping";
588
+ const sheet = await contactSheet(
589
+ p.renderer,
590
+ sheetSnaps.map((snap, i) => ({ png: snap.png, width: sheetFrames[i].width, height: sheetFrames[i].height })),
591
+ times.map((t, i) => sheetLabel(t, i, times.length)),
592
+ {
593
+ title: p.title,
594
+ subtitle: `${span} (${how}, ${looping}); last tile = 1 frame before the end`,
595
+ tile: options.tile,
596
+ columns: options.columns,
597
+ highlight: [0, times.length - 1],
598
+ },
599
+ );
600
+ const heat = await heatmap(p.renderer, motion.first!, motion.acc!, {
601
+ title: `${p.title}: motion heatmap`,
602
+ subtitle: `pixels that change across ${motion.count} frames over 0-${g(info.seconds)}s; background = t=0, dimmed`,
603
+ boxes: motion.box ? [motion.box] : [],
604
+ });
605
+ const images: ImageBuffers = { full: snaps.get(at)!.png, sheet, heatmap: heat };
606
+ if (options.keepFrames) images.frames = sheetSnaps.map((snap) => snap.png);
607
+
608
+ const out = options.out ? resolvePath(options.out) : null;
609
+ const paths: ImagePaths = out
610
+ ? {
611
+ full: join(out, "full.png"),
612
+ sheet: join(out, "sheet.png"),
613
+ heatmap: join(out, "heatmap.png"),
614
+ report: join(out, "report.json"),
615
+ }
616
+ : { full: "full.png", sheet: "sheet.png", heatmap: "heatmap.png", report: "report.json" };
617
+ if (options.keepFrames) {
618
+ for (const m of metrics) m.path = join(out ?? "", "frames", `frame_${String(m.index).padStart(3, "0")}.png`);
619
+ }
620
+ const report: Report = {
621
+ source: p.label,
622
+ kind: p.kind,
623
+ viewport: p.viewport,
624
+ device_scale_factor: p.dsf,
625
+ canvas,
626
+ duration: info,
627
+ times,
628
+ full_at: at,
629
+ images: paths,
630
+ findings,
631
+ frames: metrics,
632
+ elements: tracks(geo),
633
+ loop,
634
+ console_errors: consoleErrors,
635
+ video: null,
636
+ marks: null,
637
+ };
638
+ if (out) {
639
+ mkdirSync(out, { recursive: true });
640
+ writeFileSync(paths.full, images.full);
641
+ writeFileSync(paths.sheet, images.sheet);
642
+ writeFileSync(paths.heatmap, images.heatmap);
643
+ if (images.frames) {
644
+ mkdirSync(join(out, "frames"), { recursive: true });
645
+ images.frames.forEach((png, i) => writeFileSync(join(out, "frames", `frame_${String(i).padStart(3, "0")}.png`), png));
646
+ }
647
+ writeFileSync(paths.report, `${JSON.stringify(report, null, 2)}\n`);
648
+ }
649
+ return new Inspection(report, images, out ? paths : null);
650
+ }
651
+
652
+ function sheetLabel(t: number, i: number, count: number): string {
653
+ const label = `t=${fixed(t, 2)}s`;
654
+ if (i === 0) return `${label} start`;
655
+ if (i === count - 1) return `${label} end`;
656
+ return label;
657
+ }
658
+
659
+ function frameMetrics(frames: Frame[], times: number[], scale: number): FrameMetrics[] {
660
+ const out: FrameMetrics[] = [{ index: 0, t: times[0], changed_ratio: 0, changed_box: null, path: null }];
661
+ for (let i = 1; i < frames.length; i++) {
662
+ const [ratio, box] = diffStats(frames[i - 1], frames[i]);
663
+ out.push({ index: i, t: times[i], changed_ratio: pyRound(ratio, 5), changed_box: toCss(box, scale), path: null });
664
+ }
665
+ return out;
666
+ }
667
+
668
+ function motionFindings(info: DurationInfo, moving: boolean): Finding[] {
669
+ const finding = (severity: Severity, code: string, message: string): Finding => ({
670
+ severity,
671
+ code,
672
+ message,
673
+ check: "render",
674
+ element: null,
675
+ times: null,
676
+ });
677
+ if (info.method === "fallback" && moving) {
678
+ info.looping = true;
679
+ return [
680
+ finding(
681
+ "warning",
682
+ "js-driven-motion",
683
+ "Pixels change but no SMIL/CSS/Web Animation was found: motion is JS-driven " +
684
+ `(rAF/canvas/timers). Sampled ${g(info.seconds)}s; pass --duration with the ` +
685
+ "real cycle length.",
686
+ ),
687
+ ];
688
+ }
689
+ if (!moving && info.animations.length) {
690
+ return [
691
+ finding(
692
+ "info",
693
+ "no-visible-motion",
694
+ `${info.animations.length} animation(s) declared, but no pixel changed between sampled frames.`,
695
+ ),
696
+ ];
697
+ }
698
+ if (!moving) return [finding("info", "no-motion", "No animation found and no pixel changed: static.")];
699
+ return [];
700
+ }
701
+
702
+ function loopInfo(info: DurationInfo, moving: boolean, first: Frame, afterFirst: Frame, last: Frame, scale: number): LoopInfo {
703
+ const base = { seamless: null, seam_ratio: null, step_ratio: null, seam_box: null };
704
+ if (!moving) return { checked: false, ...base, detail: "no motion" };
705
+ if (!info.looping) return { checked: false, ...base, detail: "finite animation (does not repeat)" };
706
+ if (info.method === "fallback") {
707
+ return { checked: false, ...base, detail: "cycle length unknown (JS-driven); pass --duration" };
708
+ }
709
+ const [seam, box] = diffStats(last, first);
710
+ const [step] = diffStats(first, afterFirst);
711
+ const seamless = seam <= SEAM_MIN_RATIO || seam <= SEAM_STEP_FACTOR * step + SEAM_MIN_RATIO / 2;
712
+ const detail = `last frame -> first frame changes ${pct(seam, 2)} of pixels, one normal step changes ${pct(step, 2)}`;
713
+ const seamBox: Rect | null = seamless ? null : toCss(box, scale);
714
+ return {
715
+ checked: true,
716
+ seamless,
717
+ seam_ratio: pyRound(seam, 5),
718
+ step_ratio: pyRound(step, 5),
719
+ seam_box: seamBox,
720
+ detail,
721
+ };
722
+ }