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.
- package/LICENSE +22 -0
- package/README.md +247 -2
- package/dist/analysis.d.ts +84 -0
- package/dist/analysis.d.ts.map +1 -0
- package/dist/analysis.js +335 -0
- package/dist/analysis.js.map +1 -0
- package/dist/checks.d.ts +44 -0
- package/dist/checks.d.ts.map +1 -0
- package/dist/checks.js +200 -0
- package/dist/checks.js.map +1 -0
- package/dist/compose.d.ts +130 -0
- package/dist/compose.d.ts.map +1 -0
- package/dist/compose.js +266 -0
- package/dist/compose.js.map +1 -0
- package/dist/driver.d.ts +56 -0
- package/dist/driver.d.ts.map +1 -0
- package/dist/driver.js +94 -0
- package/dist/driver.js.map +1 -0
- package/dist/generated/assets.d.ts +13 -0
- package/dist/generated/assets.d.ts.map +1 -0
- package/dist/generated/assets.js +15 -0
- package/dist/generated/assets.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/inspect.d.ts +163 -0
- package/dist/inspect.d.ts.map +1 -0
- package/dist/inspect.js +593 -0
- package/dist/inspect.js.map +1 -0
- package/dist/marks.d.ts +49 -0
- package/dist/marks.d.ts.map +1 -0
- package/dist/marks.js +460 -0
- package/dist/marks.js.map +1 -0
- package/dist/marks.schema.json +307 -0
- package/dist/media.d.ts +22 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +306 -0
- package/dist/media.js.map +1 -0
- package/dist/models.d.ts +208 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +9 -0
- package/dist/models.js.map +1 -0
- package/dist/pixels.d.ts +52 -0
- package/dist/pixels.d.ts.map +1 -0
- package/dist/pixels.js +275 -0
- package/dist/pixels.js.map +1 -0
- package/dist/pyfmt.d.ts +16 -0
- package/dist/pyfmt.d.ts.map +1 -0
- package/dist/pyfmt.js +54 -0
- package/dist/pyfmt.js.map +1 -0
- package/dist/report.schema.json +1326 -0
- package/dist/sources.d.ts +43 -0
- package/dist/sources.d.ts.map +1 -0
- package/dist/sources.js +164 -0
- package/dist/sources.js.map +1 -0
- package/dist/test.d.ts +46 -0
- package/dist/test.d.ts.map +1 -0
- package/dist/test.js +58 -0
- package/dist/test.js.map +1 -0
- package/dist/timing.d.ts +30 -0
- package/dist/timing.d.ts.map +1 -0
- package/dist/timing.js +128 -0
- package/dist/timing.js.map +1 -0
- package/dist/video.d.ts +65 -0
- package/dist/video.d.ts.map +1 -0
- package/dist/video.js +440 -0
- package/dist/video.js.map +1 -0
- package/package.json +79 -4
- package/src/analysis.ts +416 -0
- package/src/checks.ts +261 -0
- package/src/compose.ts +337 -0
- package/src/driver.ts +115 -0
- package/src/generated/assets.ts +20 -0
- package/src/index.ts +54 -0
- package/src/inspect.ts +722 -0
- package/src/marks.ts +481 -0
- package/src/media.ts +296 -0
- package/src/models.ts +225 -0
- package/src/pixels.ts +284 -0
- package/src/pyfmt.ts +55 -0
- package/src/sources.ts +175 -0
- package/src/test.ts +100 -0
- package/src/timing.ts +133 -0
- package/src/video.ts +513 -0
package/src/pixels.ts
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixel math on decoded frames (pure JS, pngjs): diff stats, motion map, heat overlay.
|
|
3
|
+
* Same thresholds and colour ramp as compose.py.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { PNG } from "pngjs";
|
|
7
|
+
import type { Rect } from "./models.js";
|
|
8
|
+
import { pyRound } from "./pyfmt.js";
|
|
9
|
+
|
|
10
|
+
/** Per-channel difference (0-255) below which a pixel counts as unchanged. */
|
|
11
|
+
export const DIFF_THRESHOLD = 8;
|
|
12
|
+
|
|
13
|
+
/** A decoded RGBA frame. */
|
|
14
|
+
export interface Frame {
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
data: Uint8Array;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Device-px bounding box `[x0, y0, x1, y1)` (exclusive right/bottom, like Pillow's getbbox). */
|
|
21
|
+
export type Box = [number, number, number, number];
|
|
22
|
+
|
|
23
|
+
export function decode(png: Buffer): Frame {
|
|
24
|
+
const img = PNG.sync.read(png);
|
|
25
|
+
return { width: img.width, height: img.height, data: img.data };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function encode(frame: Frame): Buffer {
|
|
29
|
+
const png = new PNG({ width: frame.width, height: frame.height });
|
|
30
|
+
png.data = Buffer.from(frame.data.buffer, frame.data.byteOffset, frame.data.byteLength);
|
|
31
|
+
return PNG.sync.write(png, { colorType: 2, inputHasAlpha: true, deflateLevel: 6 });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sameSize(a: Frame, b: Frame): void {
|
|
35
|
+
if (a.width !== b.width || a.height !== b.height) {
|
|
36
|
+
throw new Error(`Frame sizes differ: ${a.width}x${a.height} vs ${b.width}x${b.height}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Per-pixel max RGB channel difference between two frames. */
|
|
41
|
+
export function changeMask(a: Frame, b: Frame): Uint8Array {
|
|
42
|
+
sameSize(a, b);
|
|
43
|
+
const n = a.width * a.height;
|
|
44
|
+
const out = new Uint8Array(n);
|
|
45
|
+
const da = a.data;
|
|
46
|
+
const db = b.data;
|
|
47
|
+
for (let i = 0, p = 0; i < n; i++, p += 4) {
|
|
48
|
+
const r = Math.abs(da[p] - db[p]);
|
|
49
|
+
const g = Math.abs(da[p + 1] - db[p + 1]);
|
|
50
|
+
const bl = Math.abs(da[p + 2] - db[p + 2]);
|
|
51
|
+
out[i] = r > g ? (r > bl ? r : bl) : g > bl ? g : bl;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Share of changed pixels and the bounding box (device px) of the change. */
|
|
57
|
+
export function diffStats(a: Frame, b: Frame): [number, Box | null] {
|
|
58
|
+
sameSize(a, b);
|
|
59
|
+
const da = a.data;
|
|
60
|
+
const db = b.data;
|
|
61
|
+
const w = a.width;
|
|
62
|
+
const n = a.width * a.height;
|
|
63
|
+
let count = 0;
|
|
64
|
+
let x0 = Infinity;
|
|
65
|
+
let y0 = Infinity;
|
|
66
|
+
let x1 = -1;
|
|
67
|
+
let y1 = -1;
|
|
68
|
+
for (let i = 0, p = 0; i < n; i++, p += 4) {
|
|
69
|
+
let m = Math.abs(da[p] - db[p]);
|
|
70
|
+
let d = Math.abs(da[p + 1] - db[p + 1]);
|
|
71
|
+
if (d > m) m = d;
|
|
72
|
+
d = Math.abs(da[p + 2] - db[p + 2]);
|
|
73
|
+
if (d > m) m = d;
|
|
74
|
+
if (m > DIFF_THRESHOLD) {
|
|
75
|
+
count++;
|
|
76
|
+
const x = i % w;
|
|
77
|
+
const y = (i - x) / w;
|
|
78
|
+
if (x < x0) x0 = x;
|
|
79
|
+
if (x > x1) x1 = x;
|
|
80
|
+
if (y < y0) y0 = y;
|
|
81
|
+
if (y > y1) y1 = y;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return [count / n, count ? [x0, y0, x1 + 1, y1 + 1] : null];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function toCss(box: Box | null, scale: number): Rect | null {
|
|
88
|
+
if (box === null) return null;
|
|
89
|
+
const [x0, y0, x1, y1] = box;
|
|
90
|
+
return [pyRound(x0 / scale, 1), pyRound(y0 / scale, 1), pyRound((x1 - x0) / scale, 1), pyRound((y1 - y0) / scale, 1)];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function union(a: Box, b: Box): Box {
|
|
94
|
+
return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Incremental motion map: per-pixel max change between consecutive frames and vs. the
|
|
99
|
+
* first frame, plus the union of consecutive changed boxes. Frames are fed in time order,
|
|
100
|
+
* so they need not be kept in memory.
|
|
101
|
+
*/
|
|
102
|
+
export class MotionAccumulator {
|
|
103
|
+
first: Frame | null = null;
|
|
104
|
+
private prev: Frame | null = null;
|
|
105
|
+
acc: Uint8Array | null = null;
|
|
106
|
+
box: Box | null = null;
|
|
107
|
+
count = 0;
|
|
108
|
+
|
|
109
|
+
add(frame: Frame): void {
|
|
110
|
+
this.count++;
|
|
111
|
+
if (!this.first) {
|
|
112
|
+
this.first = frame;
|
|
113
|
+
this.prev = frame;
|
|
114
|
+
this.acc = new Uint8Array(frame.width * frame.height);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
sameSize(this.first, frame);
|
|
118
|
+
const acc = this.acc!;
|
|
119
|
+
const a = this.prev!.data;
|
|
120
|
+
const f0 = this.first.data;
|
|
121
|
+
const c = frame.data;
|
|
122
|
+
const w = frame.width;
|
|
123
|
+
let x0 = Infinity;
|
|
124
|
+
let y0 = Infinity;
|
|
125
|
+
let x1 = -1;
|
|
126
|
+
let y1 = -1;
|
|
127
|
+
// Fused: max channel diff vs. the previous frame (step) and vs. the first frame.
|
|
128
|
+
for (let i = 0, p = 0; i < acc.length; i++, p += 4) {
|
|
129
|
+
const r = c[p];
|
|
130
|
+
const g = c[p + 1];
|
|
131
|
+
const b = c[p + 2];
|
|
132
|
+
let s = Math.abs(r - a[p]);
|
|
133
|
+
let d = Math.abs(g - a[p + 1]);
|
|
134
|
+
if (d > s) s = d;
|
|
135
|
+
d = Math.abs(b - a[p + 2]);
|
|
136
|
+
if (d > s) s = d;
|
|
137
|
+
let m = Math.abs(r - f0[p]);
|
|
138
|
+
d = Math.abs(g - f0[p + 1]);
|
|
139
|
+
if (d > m) m = d;
|
|
140
|
+
d = Math.abs(b - f0[p + 2]);
|
|
141
|
+
if (d > m) m = d;
|
|
142
|
+
if (s > m) m = s;
|
|
143
|
+
if (m > acc[i]) acc[i] = m;
|
|
144
|
+
if (s > DIFF_THRESHOLD) {
|
|
145
|
+
const x = i % w;
|
|
146
|
+
const y = (i - x) / w;
|
|
147
|
+
if (x < x0) x0 = x;
|
|
148
|
+
if (x > x1) x1 = x;
|
|
149
|
+
if (y < y0) y0 = y;
|
|
150
|
+
if (y > y1) y1 = y;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (x1 >= 0) {
|
|
154
|
+
const b: Box = [x0, y0, x1 + 1, y1 + 1];
|
|
155
|
+
this.box = this.box ? union(this.box, b) : b;
|
|
156
|
+
}
|
|
157
|
+
this.prev = frame;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Colour ramp for change strength: violet (subtle) -> red -> orange -> yellow (strong). */
|
|
162
|
+
function heatLut(): { rgb: [number, number, number][]; alpha: number[] } {
|
|
163
|
+
const stops: [number, [number, number, number]][] = [
|
|
164
|
+
[0.0, [168, 85, 247]],
|
|
165
|
+
[0.4, [239, 68, 68]],
|
|
166
|
+
[0.7, [249, 115, 22]],
|
|
167
|
+
[1.0, [253, 230, 80]],
|
|
168
|
+
];
|
|
169
|
+
const rgb: [number, number, number][] = [];
|
|
170
|
+
const alpha: number[] = [];
|
|
171
|
+
for (let v = 0; v < 256; v++) {
|
|
172
|
+
if (v <= DIFF_THRESHOLD) {
|
|
173
|
+
rgb.push([0, 0, 0]);
|
|
174
|
+
alpha.push(0);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const s = Math.min(1, (v - DIFF_THRESHOLD) / 120) ** 0.5;
|
|
178
|
+
let color: [number, number, number] = stops[stops.length - 1][1];
|
|
179
|
+
for (let k = 0; k < stops.length - 1; k++) {
|
|
180
|
+
const [p0, c0] = stops[k];
|
|
181
|
+
const [p1, c1] = stops[k + 1];
|
|
182
|
+
if (s <= p1) {
|
|
183
|
+
const f = (s - p0) / (p1 - p0);
|
|
184
|
+
color = [0, 1, 2].map((j) => pyRound(c0[j] + (c1[j] - c0[j]) * f)) as [number, number, number];
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
rgb.push(color);
|
|
189
|
+
alpha.push(pyRound(170 + 85 * s));
|
|
190
|
+
}
|
|
191
|
+
return { rgb, alpha };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export const HEAT_LUT = heatLut();
|
|
195
|
+
const BASE_LUT = Array.from({ length: 256 }, (_, v) => pyRound(28 + v * 0.32));
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Coloured motion overlay on a dimmed, desaturated first frame (full resolution), with
|
|
199
|
+
* `boxes` outlined. Returns an RGBA frame (opaque).
|
|
200
|
+
*/
|
|
201
|
+
export function heatOverlay(first: Frame, motion: Uint8Array, boxes: Box[], boxColor: [number, number, number]): Frame {
|
|
202
|
+
const { width, height } = first;
|
|
203
|
+
const out = new Uint8Array(width * height * 4);
|
|
204
|
+
const src = first.data;
|
|
205
|
+
const { rgb, alpha } = HEAT_LUT;
|
|
206
|
+
for (let i = 0, p = 0; i < motion.length; i++, p += 4) {
|
|
207
|
+
// Pillow's "L" conversion (ITU-R 601-2 luma, fixed point), then the dim ramp.
|
|
208
|
+
const l = (src[p] * 19595 + src[p + 1] * 38470 + src[p + 2] * 7471 + 0x8000) >> 16;
|
|
209
|
+
const base = BASE_LUT[l];
|
|
210
|
+
const a = alpha[motion[i]];
|
|
211
|
+
if (a === 0) {
|
|
212
|
+
out[p] = out[p + 1] = out[p + 2] = base;
|
|
213
|
+
} else {
|
|
214
|
+
const c = rgb[motion[i]];
|
|
215
|
+
out[p] = Math.round((c[0] * a + base * (255 - a)) / 255);
|
|
216
|
+
out[p + 1] = Math.round((c[1] * a + base * (255 - a)) / 255);
|
|
217
|
+
out[p + 2] = Math.round((c[2] * a + base * (255 - a)) / 255);
|
|
218
|
+
}
|
|
219
|
+
out[p + 3] = 255;
|
|
220
|
+
}
|
|
221
|
+
const stroke = Math.max(2, pyRound(Math.max(width, height) / 300));
|
|
222
|
+
for (const [bx0, by0, bx1, by1] of boxes) outline(out, width, height, [bx0, by0, bx1, by1], stroke, boxColor);
|
|
223
|
+
return { width, height, data: out };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Pillow's `rectangle(box, outline=, width=)`: inclusive corners, stroke drawn inward. */
|
|
227
|
+
function outline(
|
|
228
|
+
data: Uint8Array,
|
|
229
|
+
width: number,
|
|
230
|
+
height: number,
|
|
231
|
+
[x0, y0, x1, y1]: Box,
|
|
232
|
+
stroke: number,
|
|
233
|
+
color: [number, number, number],
|
|
234
|
+
): void {
|
|
235
|
+
const set = (x: number, y: number) => {
|
|
236
|
+
if (x < 0 || y < 0 || x >= width || y >= height) return;
|
|
237
|
+
const p = (y * width + x) * 4;
|
|
238
|
+
data[p] = color[0];
|
|
239
|
+
data[p + 1] = color[1];
|
|
240
|
+
data[p + 2] = color[2];
|
|
241
|
+
};
|
|
242
|
+
for (let y = y0; y <= y1; y++) {
|
|
243
|
+
for (let x = x0; x <= x1; x++) {
|
|
244
|
+
const edge = x - x0 < stroke || x1 - x < stroke || y - y0 < stroke || y1 - y < stroke;
|
|
245
|
+
if (edge) set(x, y);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A frame is black/blank if this share of pixels has one colour (4 bits per channel). */
|
|
251
|
+
export const UNIFORM_SHARE = 0.995;
|
|
252
|
+
|
|
253
|
+
/** `[black, blank]`: one colour (4 bits/channel) covers >= 99.5% of the pixels (= video.py). */
|
|
254
|
+
export function frameStats(frame: Frame): [boolean, boolean] {
|
|
255
|
+
const counts = new Uint32Array(4096);
|
|
256
|
+
const d = frame.data;
|
|
257
|
+
const n = frame.width * frame.height;
|
|
258
|
+
for (let i = 0, p = 0; i < n; i++, p += 4) counts[((d[p] >> 4) << 8) | ((d[p + 1] >> 4) << 4) | (d[p + 2] >> 4)]++;
|
|
259
|
+
// Python: max((count, (r, g, b))) -> ties go to the larger colour.
|
|
260
|
+
let best = 0;
|
|
261
|
+
for (let b = 1; b < 4096; b++) if (counts[b] >= counts[best]) best = b;
|
|
262
|
+
const uniform = counts[best] / n >= UNIFORM_SHARE;
|
|
263
|
+
const black = uniform && Math.max(best >> 8, (best >> 4) & 15, best & 15) <= 1;
|
|
264
|
+
return [black, uniform && !black];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Mean absolute luma gradient (`|dx| + |dy|` per pixel, 0-510), Pillow "L" luma. */
|
|
268
|
+
export function sharpness(frame: Frame): number {
|
|
269
|
+
const { width: w, height: h, data: d } = frame;
|
|
270
|
+
const luma = new Uint8Array(w * h);
|
|
271
|
+
for (let i = 0, p = 0; i < luma.length; i++, p += 4) {
|
|
272
|
+
luma[i] = (d[p] * 19595 + d[p + 1] * 38470 + d[p + 2] * 7471 + 0x8000) >> 16;
|
|
273
|
+
}
|
|
274
|
+
let total = 0;
|
|
275
|
+
for (let y = 0; y < h; y++) {
|
|
276
|
+
const row = y * w;
|
|
277
|
+
for (let x = 0; x < w; x++) {
|
|
278
|
+
const v = luma[row + x];
|
|
279
|
+
if (x + 1 < w) total += Math.abs(luma[row + x + 1] - v);
|
|
280
|
+
if (y + 1 < h) total += Math.abs(luma[row + w + x] - v);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return pyRound(total / (w * h), 3);
|
|
284
|
+
}
|
package/src/pyfmt.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Number rounding/formatting with Python semantics, so reports and summaries match the
|
|
3
|
+
* Python implementation (`round(x, n)`, `f"{x:.2f}"`, `f"{x:g}"`, `f"{x:.1%}"`).
|
|
4
|
+
*
|
|
5
|
+
* Python rounds the exact binary value half-to-even; JavaScript's `toFixed` rounds ties
|
|
6
|
+
* away from zero. Ties only matter for exactly representable halves (0.125, 2.5, ...).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Exact decimal expansion digits after the point (enough for |x| >= 1e-30). */
|
|
10
|
+
function isExactTie(x: number, digits: number): boolean {
|
|
11
|
+
const s = Math.abs(x).toFixed(Math.min(100, digits + 60));
|
|
12
|
+
const frac = s.split(".")[1] ?? "";
|
|
13
|
+
const rest = frac.slice(digits);
|
|
14
|
+
return rest.length > 0 && rest[0] === "5" && /^50*$/.test(rest);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Python's `round(x, digits)` (half to even on the exact value). */
|
|
18
|
+
export function pyRound(x: number, digits = 0): number {
|
|
19
|
+
if (!Number.isFinite(x)) return x;
|
|
20
|
+
if (isExactTie(x, digits)) {
|
|
21
|
+
const factor = 10 ** digits;
|
|
22
|
+
const down = Math.trunc(Math.abs(x) * factor);
|
|
23
|
+
const even = down % 2 === 0 ? down : down + 1;
|
|
24
|
+
const out = (Math.sign(x) * even) / factor;
|
|
25
|
+
return Object.is(out, -0) ? 0 : out;
|
|
26
|
+
}
|
|
27
|
+
const out = Number(x.toFixed(digits));
|
|
28
|
+
return Object.is(out, -0) ? 0 : out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Python's `f"{x:.{digits}f}"`. */
|
|
32
|
+
export function fixed(x: number, digits: number): string {
|
|
33
|
+
return pyRound(x, digits).toFixed(digits);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Python's `f"{x:g}"` (6 significant digits, trailing zeros stripped). */
|
|
37
|
+
export function g(x: number): string {
|
|
38
|
+
if (x === 0) return Object.is(x, -0) ? "-0" : "0";
|
|
39
|
+
if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf";
|
|
40
|
+
const precision = 6;
|
|
41
|
+
const [mantissa, expPart] = x.toExponential(precision - 1).split("e");
|
|
42
|
+
const exp = Number(expPart);
|
|
43
|
+
if (exp < -4 || exp >= precision) {
|
|
44
|
+
const m = mantissa.includes(".") ? mantissa.replace(/\.?0+$/, "") : mantissa;
|
|
45
|
+
const sign = exp < 0 ? "-" : "+";
|
|
46
|
+
return `${m}e${sign}${String(Math.abs(exp)).padStart(2, "0")}`;
|
|
47
|
+
}
|
|
48
|
+
const s = fixed(x, Math.max(0, precision - 1 - exp));
|
|
49
|
+
return s.includes(".") ? s.replace(/\.?0+$/, "") : s;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Python's `f"{x:.{digits}%}"`. */
|
|
53
|
+
export function pct(x: number, digits: number): string {
|
|
54
|
+
return `${fixed(x * 100, digits)}%`;
|
|
55
|
+
}
|
package/src/sources.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/** Input handling: files, markup strings and URLs (port of sources.py). */
|
|
2
|
+
|
|
3
|
+
import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
4
|
+
import { extname, resolve as resolvePath } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import type { ParsedDocument } from "./checks.js";
|
|
7
|
+
import { sniff, VIDEO_EXTENSIONS } from "./media.js";
|
|
8
|
+
import type { SourceKind } from "./models.js";
|
|
9
|
+
import { pyRound } from "./pyfmt.js";
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_HTML_SIZE: [number, number] = [1280, 720];
|
|
12
|
+
export const DEFAULT_SVG_SIZE: [number, number] = [960, 540];
|
|
13
|
+
const LENGTH = /^\s*([0-9]*\.?[0-9]+)\s*(px)?\s*$/;
|
|
14
|
+
/** Markup strings are served from this virtual origin (page.route), never from disk. */
|
|
15
|
+
export const VIRTUAL_ORIGIN = "http://framesheet.invalid";
|
|
16
|
+
|
|
17
|
+
/** A resolved input. */
|
|
18
|
+
export interface Source {
|
|
19
|
+
/** What the caller passed (path, URL, or `<snippet>`). */
|
|
20
|
+
label: string;
|
|
21
|
+
kind: SourceKind;
|
|
22
|
+
/** What the browser navigates to. */
|
|
23
|
+
url: string;
|
|
24
|
+
/** Source text if available (static checks, size detection). */
|
|
25
|
+
text: string | null;
|
|
26
|
+
/** Markup served via page.route at `url` (markup-string inputs only). */
|
|
27
|
+
body?: string;
|
|
28
|
+
/** Video/animated image bytes (`kind === "video"`), served to the wrapper page. */
|
|
29
|
+
media?: Buffer;
|
|
30
|
+
/** Video container (`mp4`, `webm`, `gif`, ...) for video sources. */
|
|
31
|
+
container?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Video wrapper pages and media are served from this virtual (secure) origin. */
|
|
35
|
+
export const VIDEO_ORIGIN = "https://framesheet.invalid";
|
|
36
|
+
export const VIDEO_PAGE =
|
|
37
|
+
"<!DOCTYPE html><html><head><meta charset='utf-8'><title>framesheet video</title></head><body></body></html>";
|
|
38
|
+
|
|
39
|
+
/** A video/animated image, played in a wrapper page on {@link VIDEO_ORIGIN}. */
|
|
40
|
+
export function videoSource(label: string, data: Buffer, container: string | null = null): Source {
|
|
41
|
+
const kind = sniff(data) ?? container;
|
|
42
|
+
if (kind === null) throw new Error(`Not a supported video or animated image: ${label}`);
|
|
43
|
+
return { label, kind: "video", url: `${VIDEO_ORIGIN}/video.html`, text: null, media: data, container: kind };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function videoExt(name: string): string | null {
|
|
47
|
+
return VIDEO_EXTENSIONS[extname(name.split("?")[0]).toLowerCase()] ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Download a video URL (errors are raised: there is nothing to inspect without it). */
|
|
51
|
+
export async function fetchBytes(url: string, timeoutMs = 60_000): Promise<Buffer> {
|
|
52
|
+
let response: Response;
|
|
53
|
+
try {
|
|
54
|
+
response = await fetch(url, { headers: { "User-Agent": "framesheet" }, signal: AbortSignal.timeout(timeoutMs) });
|
|
55
|
+
} catch (err) {
|
|
56
|
+
throw new Error(`Cannot download ${url}: ${(err as Error).message}`);
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) throw new Error(`Cannot download ${url}: HTTP ${response.status}`);
|
|
59
|
+
return Buffer.from(await response.arrayBuffer());
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function looksLikeSvg(text: string): boolean {
|
|
63
|
+
let head = text.slice(0, 4096).replace(/<!--[\s\S]*?-->/g, "").trimStart().toLowerCase();
|
|
64
|
+
if (head.startsWith("<?xml")) {
|
|
65
|
+
const i = head.indexOf("?>");
|
|
66
|
+
head = (i >= 0 ? head.slice(i + 2) : "").trimStart();
|
|
67
|
+
}
|
|
68
|
+
if (head.startsWith("<!doctype svg")) return true;
|
|
69
|
+
return head.startsWith("<svg");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Wrap an in-memory SVG/HTML snippet as a source (served from a virtual URL). */
|
|
73
|
+
export function snippet(markup: string, label = "<snippet>"): Source {
|
|
74
|
+
const kind: SourceKind = looksLikeSvg(markup) ? "svg" : "html";
|
|
75
|
+
let text = markup;
|
|
76
|
+
if (kind === "html" && !text.toLowerCase().includes("<html")) {
|
|
77
|
+
text = `<!DOCTYPE html>\n<html><head><meta charset='utf-8'></head><body>${text}</body></html>`;
|
|
78
|
+
}
|
|
79
|
+
return { label, kind, url: `${VIRTUAL_ORIGIN}/input.${kind}`, text, body: text };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Best-effort download of a URL's body (for static checks and SVG size detection). */
|
|
83
|
+
export async function fetchText(url: string, timeoutMs = 15_000): Promise<string | null> {
|
|
84
|
+
try {
|
|
85
|
+
const response = await fetch(url, {
|
|
86
|
+
headers: { "User-Agent": "framesheet" },
|
|
87
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
88
|
+
});
|
|
89
|
+
if (!response.ok) return null;
|
|
90
|
+
return await response.text();
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Turn a path, URL or markup string (starting with `<`) into a {@link Source}. */
|
|
97
|
+
export async function resolveSource(source: string): Promise<Source> {
|
|
98
|
+
if (source.trimStart().startsWith("<")) return snippet(source);
|
|
99
|
+
if (/^https?:\/\//.test(source)) {
|
|
100
|
+
const container = videoExt(source);
|
|
101
|
+
if (container) return videoSource(source, await fetchBytes(source), container);
|
|
102
|
+
const text = await fetchText(source);
|
|
103
|
+
const byName = source.split("?")[0].toLowerCase().endsWith(".svg");
|
|
104
|
+
const kind: SourceKind = byName || (text !== null && looksLikeSvg(text)) ? "svg" : "html";
|
|
105
|
+
return { label: source, kind, url: source, text };
|
|
106
|
+
}
|
|
107
|
+
const path = resolvePath(source.startsWith("file://") ? new URL(source).pathname : source);
|
|
108
|
+
let isFile = false;
|
|
109
|
+
try {
|
|
110
|
+
isFile = statSync(path).isFile();
|
|
111
|
+
} catch {
|
|
112
|
+
isFile = false;
|
|
113
|
+
}
|
|
114
|
+
if (!isFile) throw new Error(`Input not found: ${source}`);
|
|
115
|
+
const head = Buffer.alloc(64);
|
|
116
|
+
const fd = openSync(path, "r");
|
|
117
|
+
try {
|
|
118
|
+
readSync(fd, head, 0, 64, 0);
|
|
119
|
+
} finally {
|
|
120
|
+
closeSync(fd);
|
|
121
|
+
}
|
|
122
|
+
const container = videoExt(path);
|
|
123
|
+
if (container || sniff(head)) return videoSource(source, readFileSync(path), container);
|
|
124
|
+
const text = readFileSync(path, "utf8");
|
|
125
|
+
const ext = extname(path).toLowerCase();
|
|
126
|
+
let kind: SourceKind;
|
|
127
|
+
if (ext === ".svg") kind = "svg";
|
|
128
|
+
else if ([".html", ".htm", ".xhtml"].includes(ext)) kind = "html";
|
|
129
|
+
else kind = looksLikeSvg(text) ? "svg" : "html";
|
|
130
|
+
return { label: source, kind, url: pathToFileURL(path).href, text };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function length(value: string | undefined): number | null {
|
|
134
|
+
if (value == null) return null;
|
|
135
|
+
const m = LENGTH.exec(value);
|
|
136
|
+
return m ? parseFloat(m[1]) : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Intrinsic size of a parsed SVG: absolute width/height attributes, else the viewBox. */
|
|
140
|
+
export function svgSize(doc: ParsedDocument): [number, number] | null {
|
|
141
|
+
if (doc.error !== null || !doc.elements.length) return null;
|
|
142
|
+
const root = doc.elements[0];
|
|
143
|
+
const get = (name: string) => root.attrs.find(([local]) => local === name)?.[2];
|
|
144
|
+
let width = length(get("width"));
|
|
145
|
+
let height = length(get("height"));
|
|
146
|
+
const box = (get("viewBox") ?? "")
|
|
147
|
+
.trim()
|
|
148
|
+
.split(/[\s,]+/)
|
|
149
|
+
.filter(Boolean)
|
|
150
|
+
.map(Number);
|
|
151
|
+
if (box.length === 4 && box[2] > 0 && box[3] > 0) {
|
|
152
|
+
const [, , vbW, vbH] = box;
|
|
153
|
+
if (width && !height) height = (width * vbH) / vbW;
|
|
154
|
+
else if (height && !width) width = (height * vbW) / vbH;
|
|
155
|
+
width = width || vbW;
|
|
156
|
+
height = height || vbH;
|
|
157
|
+
}
|
|
158
|
+
if (width && height) return [Math.max(1, pyRound(width)), Math.max(1, pyRound(height))];
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function defaultSize(kind: SourceKind, parsed: ParsedDocument | null): [number, number] {
|
|
163
|
+
if (kind === "svg" && parsed) {
|
|
164
|
+
const size = svgSize(parsed);
|
|
165
|
+
if (size) return size;
|
|
166
|
+
}
|
|
167
|
+
return kind === "svg" ? DEFAULT_SVG_SIZE : DEFAULT_HTML_SIZE;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Parse `WxH` (e.g. `1280x720`). */
|
|
171
|
+
export function parseSize(value: string): [number, number] {
|
|
172
|
+
const m = /^\s*(\d+)\s*[xX*]\s*(\d+)\s*$/.exec(value);
|
|
173
|
+
if (!m) throw new Error(`Invalid size '${value}'; expected WIDTHxHEIGHT, e.g. 1280x720`);
|
|
174
|
+
return [Number(m[1]), Number(m[2])];
|
|
175
|
+
}
|
package/src/test.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `framesheet/test`: visual regression of animations in a `@playwright/test` suite.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { test } from "@playwright/test";
|
|
6
|
+
* import { expectAnimation } from "framesheet/test";
|
|
7
|
+
*
|
|
8
|
+
* test("mind map opens smoothly", async ({ page }) => {
|
|
9
|
+
* await page.goto("/mindmap");
|
|
10
|
+
* await expectAnimation(page.locator("#mindmap"), "mindmap-open", { frames: 8 });
|
|
11
|
+
* });
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { expect, type Locator, type Page, test } from "@playwright/test";
|
|
16
|
+
import { type Inspection, type InspectPageOptions, inspectPage } from "./inspect.js";
|
|
17
|
+
import type { Finding, Severity } from "./models.js";
|
|
18
|
+
|
|
19
|
+
export { LAUNCH_ARGS, prepare } from "./inspect.js";
|
|
20
|
+
|
|
21
|
+
export interface ExpectAnimationOptions extends Omit<InspectPageOptions, "locator" | "out"> {
|
|
22
|
+
/** Allowed share of differing pixels in the sheet (Playwright `maxDiffPixelRatio`). */
|
|
23
|
+
maxDiffPixelRatio?: number;
|
|
24
|
+
/** Allowed number of differing pixels (Playwright `maxDiffPixels`). */
|
|
25
|
+
maxDiffPixels?: number;
|
|
26
|
+
/** Per-pixel colour distance threshold 0-1 (Playwright `threshold`, default 0.2). */
|
|
27
|
+
threshold?: number;
|
|
28
|
+
/** Also compare the motion heatmap against `<name>-heatmap.png`. Default false. */
|
|
29
|
+
heatmap?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Fail on findings of this severity or worse: `"error"` (default), `"warning"`, or
|
|
32
|
+
* `false` to only compare images.
|
|
33
|
+
*/
|
|
34
|
+
failOn?: Exclude<Severity, "info"> | false;
|
|
35
|
+
/** Finding codes to ignore for `failOn` (e.g. `["console-error"]`). */
|
|
36
|
+
ignore?: string[];
|
|
37
|
+
/** Attach sheet/heatmap/full/report to the test report. Default true. */
|
|
38
|
+
attach?: boolean;
|
|
39
|
+
/** Compare against the stored baseline. Default true; `false` only checks findings. */
|
|
40
|
+
snapshot?: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isPage(target: Page | Locator): target is Page {
|
|
44
|
+
return typeof (target as Page).goto === "function";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function describe(findings: Finding[]): string {
|
|
48
|
+
return findings.map((f) => `${f.severity} ${f.code}: ${f.message}`).join("\n");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Build the contact sheet of an animation (whole page or one component) and compare it
|
|
53
|
+
* with the stored baseline `<name>.png` via Playwright's `toMatchSnapshot` (so
|
|
54
|
+
* `--update-snapshots`, per-platform snapshot names and diff images work as usual).
|
|
55
|
+
* Also fails on error findings unless `failOn: false`. Returns the inspection.
|
|
56
|
+
*/
|
|
57
|
+
export async function expectAnimation(
|
|
58
|
+
target: Page | Locator,
|
|
59
|
+
name: string,
|
|
60
|
+
options: ExpectAnimationOptions = {},
|
|
61
|
+
): Promise<Inspection> {
|
|
62
|
+
const page = isPage(target) ? target : target.page();
|
|
63
|
+
const locator = isPage(target) ? undefined : target;
|
|
64
|
+
const {
|
|
65
|
+
maxDiffPixelRatio,
|
|
66
|
+
maxDiffPixels,
|
|
67
|
+
threshold,
|
|
68
|
+
heatmap,
|
|
69
|
+
failOn = "error",
|
|
70
|
+
ignore = [],
|
|
71
|
+
attach = true,
|
|
72
|
+
snapshot = true,
|
|
73
|
+
...rest
|
|
74
|
+
} = options;
|
|
75
|
+
const result = await inspectPage(page, { ...rest, locator, title: rest.title ?? name });
|
|
76
|
+
const base = name.replace(/\.png$/i, "");
|
|
77
|
+
if (attach) {
|
|
78
|
+
const info = test.info();
|
|
79
|
+
await info.attach(`${base}-sheet.png`, { body: result.images.sheet, contentType: "image/png" });
|
|
80
|
+
await info.attach(`${base}-heatmap.png`, { body: result.images.heatmap, contentType: "image/png" });
|
|
81
|
+
await info.attach(`${base}-full.png`, { body: result.images.full, contentType: "image/png" });
|
|
82
|
+
await info.attach(`${base}-report.json`, {
|
|
83
|
+
body: JSON.stringify(result.report, null, 2),
|
|
84
|
+
contentType: "application/json",
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const compare = Object.fromEntries(
|
|
88
|
+
Object.entries({ maxDiffPixelRatio, maxDiffPixels, threshold }).filter(([, v]) => v !== undefined),
|
|
89
|
+
);
|
|
90
|
+
if (snapshot) {
|
|
91
|
+
expect(result.images.sheet).toMatchSnapshot(`${base}.png`, compare);
|
|
92
|
+
if (heatmap) expect(result.images.heatmap).toMatchSnapshot(`${base}-heatmap.png`, compare);
|
|
93
|
+
}
|
|
94
|
+
if (failOn) {
|
|
95
|
+
const worst = failOn === "warning" ? ["error", "warning"] : ["error"];
|
|
96
|
+
const bad = result.findings.filter((f) => worst.includes(f.severity) && !ignore.includes(f.code));
|
|
97
|
+
expect(bad, `framesheet findings for '${base}':\n${describe(bad)}\n\n${result.summary()}`).toEqual([]);
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
100
|
+
}
|