@kerf-js/capture 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ravonus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,82 @@
1
- # Temporary Holding Version
1
+ # @kerf-js/capture
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Drive a built kerf page in headless Chrome on the GPU: repeatable stills at scroll stops, frame times while it
4
+ scrolls, contact sheets, and the bake that renders a scene stage's posters from the scenes themselves. A dev
5
+ dependency only: nothing here goes into a page's bundle.
6
+
7
+ ```bash
8
+ pnpm add -D @kerf-js/capture
9
+ ```
10
+
11
+ It drives the Chrome installed on the machine (`--chrome <path>` for another), with ANGLE on Metal on macOS.
12
+
13
+ ## From a terminal
14
+
15
+ `kerf capture <command>` (or `kerf-capture`). A target is a URL, or a built folder, which is served on 127.0.0.1
16
+ while the command runs; `--path /page.html` picks a page in it.
17
+
18
+ ```bash
19
+ kerf capture stills dist --stops 0,hero@0.5,2@1 \
20
+ --width 1440 --height 900 --dpr 2 --out shots --sheet
21
+ kerf capture frames dist --from pay@0 --seconds 5 \
22
+ --speed 600 --cpu 4 --out frames.json
23
+ kerf capture sheet shots/*.png --out sheet.png --cols 4
24
+ kerf capture bake dist --out src/posters --format avif
25
+ ```
26
+
27
+ A stop is pixels (`1200`), a section at a share of its pass (`hero@0.5`, `2@0`: by id or index), or pixels past a
28
+ section's top (`hero+300`). A section taller than the viewport passes from its top at the viewport's top to its
29
+ bottom at the viewport's bottom; a shorter one from entering below to leaving above. Sections are `section`
30
+ elements unless `sections` names another selector.
31
+
32
+ ## From code
33
+
34
+ ```js
35
+ import { capture, frames, launch } from '@kerf-js/capture'
36
+ import { open, sheet } from '@kerf-js/capture'
37
+
38
+ const browser = await launch()
39
+ const stops = [0, { section: 'hero', at: 0.5 }]
40
+ const { stills } = await capture({ url, browser, stops })
41
+ const tiles = stills.map((s) => s.png)
42
+ const png = await sheet(browser, tiles, { labels: ['top', 'hero'] })
43
+ const page = await open(browser, { url, dpr: 2 })
44
+ const run = await frames(page, { seconds: 5, cpu: 4 })
45
+ await browser.close()
46
+ ```
47
+
48
+ `capture` waits at each stop until the page has settled: every `<Stage>` has drawn at that scroll offset (its
49
+ `data-stage-ready`), transitions have finished and the images in view have decoded. The stage's clock is frozen
50
+ first (`seconds`, default 0), so the same stop on the same GPU gives the same PNG and the same hash.
51
+
52
+ `frames` scrolls from `from` (a stop, default the top) and reports p5 fps, the median and p95 frame time, and
53
+ the frames over 33 and 50 ms, with the machine's load before and after. Headless Chrome caps frames at 60 Hz, so
54
+ read the slow end, not the median. Run one at a time on a quiet machine, and keep the load with the number.
55
+
56
+ ## Baked posters
57
+
58
+ A `<Scene poster="bake" id="...">` gets a still of its own scene. The bake opens the built page at a wide size
59
+ (1440 × 900 at 1×) and a tall one (390 × 844 at 2×), has the stage draw each baked scene alone through its blend
60
+ with the clock stopped, at the scene's `hold` or else where its section fills the viewport, encodes it (AVIF quality 50 by default, or WebP) and writes
61
+ `<id>.<tier>.avif` and `posters.json`. The build then takes them in as assets:
62
+
63
+ ```ts
64
+ // vite.config.ts
65
+ import { posters } from '@kerf-js/capture/vite'
66
+ export default { plugins: [posters({ dir: 'src/posters' })] }
67
+ ```
68
+
69
+ ```tsx
70
+ /// <reference types="@kerf-js/capture/posters" />
71
+ // registers the baked stills before anything renders
72
+ import 'virtual:kerf/posters'
73
+ ```
74
+
75
+ Build, bake, build: the first build has no posters yet, and the second carries them. The stage shows the tall
76
+ still on a tall screen, and on its poster tier (`<Stage tier="auto">` on a phone) the stills are all there is.
77
+
78
+ ## The page contract
79
+
80
+ Any page can be captured. A kerf scene stage adds two things: `data-stage-ready` on its root, the scroll offset
81
+ of the last settled frame (`poster` on the poster tier), and `root[Symbol.for('kerf.stage')]`, a `StageHandle`
82
+ from `@kerf-js/veneer/scenes` that lists the scenes, freezes the clock and draws stills.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs'
3
+
4
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@kerf-js/capture",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@kerf-js/capture: drive a built kerf page in headless Chrome on the GPU for repeatable stills at scroll stops, frame-time runs and contact sheets, and bake scene posters at build time. Dev only.",
5
+ "keywords": [
6
+ "capture",
7
+ "screenshot",
8
+ "poster",
9
+ "kerf"
10
+ ],
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/capture#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Ravonus/kerf.git",
19
+ "directory": "packages/capture"
20
+ },
21
+ "type": "module",
22
+ "bin": {
23
+ "kerf-capture": "./bin/kerf-capture.mjs"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./src/index.d.ts",
28
+ "default": "./src/index.mjs"
29
+ },
30
+ "./cli": "./src/cli.mjs",
31
+ "./vite": {
32
+ "types": "./src/vite.d.ts",
33
+ "default": "./src/vite.mjs"
34
+ },
35
+ "./posters": {
36
+ "types": "./src/posters.d.ts"
37
+ }
38
+ },
39
+ "files": [
40
+ "bin",
41
+ "src",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "dependencies": {
46
+ "@kerf-js/media": "0.1.0",
47
+ "playwright-core": "1.64.1",
48
+ "sharp": "0.35.5"
49
+ },
50
+ "peerDependencies": {
51
+ "@kerf-js/veneer": "^0.1.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@kerf-js/veneer": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "engines": {
59
+ "node": ">=24"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ }
6
64
  }
package/src/bake.mjs ADDED
@@ -0,0 +1,90 @@
1
+ // The poster bake: each `poster="bake"` scene draws itself alone with the clock stopped, wide and tall, and each
2
+ // still is encoded and listed in a manifest the page's build imports.
3
+ import { mkdirSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { encoders, FIXED, hex, MIME } from '@kerf-js/media/build'
6
+ import sharp from 'sharp'
7
+ import { launch, open } from './browser.mjs'
8
+ import { stageReady } from './settle.mjs'
9
+
10
+ /** The sizes a poster is drawn at: a wide screen at 1×, and a phone held upright at 2×. */
11
+ export const TIERS = {
12
+ desktop: { width: 1440, height: 900, dpr: 1 },
13
+ mobile: { width: 390, height: 844, dpr: 2 },
14
+ }
15
+
16
+ /** In the page: the first stage's scenes whose poster is baked. */
17
+ const SCENES = () => {
18
+ const el = document.querySelector('[data-stage]')
19
+ const stage = el && Reflect.get(el, Symbol.for('kerf.stage'))
20
+ if (!stage || stage.tier !== 'live')
21
+ throw new Error('kerf capture: bake needs a page with a <Stage> drawing live scenes')
22
+ return stage.scenes().filter((scene) => scene.bake)
23
+ }
24
+
25
+ /** In the page: one scene alone where its poster is drawn (its hold, else its rest), as a PNG data URL. */
26
+ const STILL = ([index, seconds]) => {
27
+ const el = document.querySelector('[data-stage]')
28
+ const stage = Reflect.get(el, Symbol.for('kerf.stage'))
29
+ return stage.still(index, undefined, seconds)
30
+ }
31
+
32
+ /** Encodes one still and describes it as the media record a `?media` import would give. */
33
+ async function encode(png, file, how) {
34
+ const image = sharp(png)
35
+ const [{ data, info }, stats, tiny] = await Promise.all([
36
+ encoders[how.format](image.clone(), how.quality).toBuffer({ resolveWithObject: true }),
37
+ image.clone().stats(),
38
+ image.clone().resize(16, 16, { fit: 'inside' }).webp({ quality: 40 }).toBuffer(),
39
+ ])
40
+ const record = {
41
+ kind: 'photo',
42
+ src: file,
43
+ width: info.width,
44
+ height: info.height,
45
+ type: MIME[how.format],
46
+ sources: [],
47
+ dominant: hex(stats.dominant),
48
+ placeholder: `data:image/webp;base64,${tiny.toString('base64')}`,
49
+ name: file,
50
+ quality: 'fixed',
51
+ bytes: data.length,
52
+ }
53
+ return { record, data }
54
+ }
55
+
56
+ /** Bakes the stage's posters at `url` into `out`: `<id>.<tier>.<format>` files and `posters.json`. */
57
+ export async function bake(options) {
58
+ const { url, out, format = 'avif', seconds = 0, tiers = TIERS } = options
59
+ const how = { format, quality: options.quality ?? FIXED[format] }
60
+ const browser = options.browser ?? (await launch(options))
61
+ const started = performance.now()
62
+ const posters = {}
63
+ try {
64
+ mkdirSync(out, { recursive: true })
65
+ for (const [tier, size] of Object.entries(tiers)) {
66
+ const page = await open(browser, { url, ...size })
67
+ await stageReady(page, null)
68
+ for (const scene of await page.evaluate(SCENES)) {
69
+ if (!scene.id)
70
+ throw new Error(`kerf capture: scene ${scene.index} bakes a poster but has no id`)
71
+ const shot = performance.now()
72
+ const png = await page.evaluate(STILL, [scene.index, seconds])
73
+ const file = `${scene.id.replace(/[^\w-]+/g, '-')}.${tier}.${format}`
74
+ const { record, data } = await encode(
75
+ Buffer.from(png.split(',')[1] ?? '', 'base64'),
76
+ file,
77
+ how,
78
+ )
79
+ writeFileSync(join(out, file), data)
80
+ ;(posters[scene.id] ??= {})[tier] = { ...record, ms: Math.round(performance.now() - shot) }
81
+ }
82
+ await page.context().close()
83
+ }
84
+ } finally {
85
+ if (!options.browser) await browser.close()
86
+ }
87
+ const manifest = { ...how, seconds, tiers, ms: Math.round(performance.now() - started), posters }
88
+ writeFileSync(join(out, 'posters.json'), `${JSON.stringify(manifest, null, 2)}\n`)
89
+ return manifest
90
+ }
@@ -0,0 +1,69 @@
1
+ // Headless Chrome on the GPU, and a page opened at a device's size. One launch for every driver in this package.
2
+ import { chromium } from 'playwright-core'
3
+
4
+ const PHONE =
5
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'
6
+
7
+ /** Chrome's flags for drawing on the GPU without a window: ANGLE on Metal on macOS, the blocklist off everywhere. */
8
+ export function gpuArgs(platform = process.platform) {
9
+ return [
10
+ ...(platform === 'darwin' ? ['--use-angle=metal'] : []),
11
+ '--enable-gpu',
12
+ '--ignore-gpu-blocklist',
13
+ '--autoplay-policy=no-user-gesture-required',
14
+ ]
15
+ }
16
+
17
+ /** Launches Chrome headless on the GPU: the installed Chrome, or `executablePath`; `tmp` sets a short TMPDIR. */
18
+ export function launch(options = {}) {
19
+ const { headless = true, channel = 'chrome', executablePath, tmp } = options
20
+ return chromium.launch({
21
+ headless,
22
+ ...(executablePath ? { executablePath } : { channel }),
23
+ args: gpuArgs(),
24
+ ...(tmp ? { env: { ...process.env, TMPDIR: tmp } } : {}),
25
+ })
26
+ }
27
+
28
+ /** Opens `url` in a fresh context at a device's size; page and console errors land on `page.problems`. */
29
+ export async function open(browser, options) {
30
+ const {
31
+ url,
32
+ width = 1440,
33
+ height = 900,
34
+ dpr = 1,
35
+ reduced = false,
36
+ mobile = false,
37
+ cpu = 1,
38
+ } = options
39
+ const context = await browser.newContext({
40
+ viewport: { width, height },
41
+ deviceScaleFactor: dpr,
42
+ reducedMotion: reduced ? 'reduce' : 'no-preference',
43
+ ...(mobile ? { isMobile: true, hasTouch: true, userAgent: PHONE } : {}),
44
+ })
45
+ const page = await context.newPage()
46
+ const problems = []
47
+ page.on('pageerror', (e) => problems.push(e.message))
48
+ page.on('console', (m) => {
49
+ if (m.type() === 'error' && !/GL Driver Message/.test(m.text())) problems.push(m.text())
50
+ })
51
+ if (cpu > 1) {
52
+ const cdp = await context.newCDPSession(page)
53
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: cpu })
54
+ }
55
+ await page.goto(url, { waitUntil: 'load' })
56
+ return Object.assign(page, { problems })
57
+ }
58
+
59
+ /** The GPU the page draws with, as WebGL reports it: proof a run was not on a software rasteriser. */
60
+ export function gpuOf(page) {
61
+ return page.evaluate(() => {
62
+ const gl = document.createElement('canvas').getContext('webgl2')
63
+ if (!gl) return null
64
+ const info = gl.getExtension('WEBGL_debug_renderer_info')
65
+ const renderer = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER))
66
+ gl.getExtension('WEBGL_lose_context')?.loseContext()
67
+ return renderer
68
+ })
69
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,192 @@
1
+ // `kerf capture <command>`. A target is a URL, or a built folder served on 127.0.0.1 while the command runs.
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
4
+ import { parseArgs } from 'node:util'
5
+ import { bake } from './bake.mjs'
6
+ import { launch, open } from './browser.mjs'
7
+ import { frames } from './frames.mjs'
8
+ import { serve } from './serve.mjs'
9
+ import { sheet } from './sheet.mjs'
10
+ import { stageReady } from './settle.mjs'
11
+ import { capture } from './stills.mjs'
12
+ import { parseStop, stopName } from './stops.mjs'
13
+
14
+ /** The command's help. */
15
+ export const USAGE = `kerf capture <command> <url | built folder> [options]
16
+
17
+ stills <target> a PNG at each stop --stops 0,hero@0.5,2+300 --out dir --sheet
18
+ frames <target> frame times as JSON --from pay@0 --seconds 5 --speed 600 --cpu 4 --driver scroll|wheel
19
+ --out file
20
+ sheet <png...> one contact sheet --out sheet.png --cols 4 --width 480
21
+ bake <target> scene posters --out posters --format avif|webp --quality 50 --time 0
22
+
23
+ page options --width 1440 --height 900 --dpr 1 --reduced --mobile --path /page.html --chrome <path>`
24
+
25
+ const OPTIONS = {
26
+ out: { type: 'string' },
27
+ stops: { type: 'string' },
28
+ from: { type: 'string' },
29
+ sheet: { type: 'boolean' },
30
+ seconds: { type: 'string' },
31
+ speed: { type: 'string' },
32
+ cpu: { type: 'string' },
33
+ driver: { type: 'string' },
34
+ cols: { type: 'string' },
35
+ format: { type: 'string' },
36
+ quality: { type: 'string' },
37
+ time: { type: 'string' },
38
+ width: { type: 'string' },
39
+ height: { type: 'string' },
40
+ dpr: { type: 'string' },
41
+ reduced: { type: 'boolean' },
42
+ mobile: { type: 'boolean' },
43
+ path: { type: 'string' },
44
+ chrome: { type: 'string' },
45
+ }
46
+
47
+ const num = (v, fallback) => (v === undefined ? fallback : Number(v))
48
+
49
+ /** The page options shared by every command, and the URL: a folder is served first. */
50
+ async function page(target, v) {
51
+ if (!target) throw new Error('kerf capture: name a URL or a built folder')
52
+ const local = existsSync(target) && statSync(target).isDirectory() ? await serve(target) : null
53
+ const url = (local?.url ?? target) + (typeof v.path === 'string' ? v.path : '')
54
+ const size = {
55
+ width: num(v.width, 1440),
56
+ height: num(v.height, 900),
57
+ dpr: num(v.dpr, 1),
58
+ reduced: !!v.reduced,
59
+ mobile: !!v.mobile,
60
+ }
61
+ const chrome = typeof v.chrome === 'string' ? { executablePath: v.chrome } : {}
62
+ return { url, ...size, ...chrome, close: () => local?.close() }
63
+ }
64
+
65
+ function write(file, data) {
66
+ mkdirSync(dirname(file), { recursive: true })
67
+ writeFileSync(file, data)
68
+ }
69
+
70
+ // Each command reads its options untyped: parseArgs has checked their kinds already.
71
+ const COMMANDS = {
72
+ async stills([target], v) {
73
+ const at = await page(target, v)
74
+ const stops = String(v.stops ?? '0')
75
+ .split(',')
76
+ .map(parseStop)
77
+ const browser = await launch(at)
78
+ try {
79
+ const out = v.out ?? 'captures'
80
+ const result = await capture({ ...at, browser, stops, out })
81
+ for (const s of result.stills)
82
+ console.log(`${s.path} y=${s.y} ${s.bytes} B ${s.hash.slice(0, 12)}`)
83
+ if (v.sheet) {
84
+ const labels = result.stills.map((s) => stopName(s.stop))
85
+ write(
86
+ `${out}/sheet.png`,
87
+ await sheet(
88
+ browser,
89
+ result.stills.map((s) => s.png),
90
+ { labels },
91
+ ),
92
+ )
93
+ }
94
+ for (const p of result.problems) console.error(`page: ${p}`)
95
+ } finally {
96
+ await browser.close()
97
+ await at.close()
98
+ }
99
+ },
100
+ async frames([target], v) {
101
+ const at = await page(target, v)
102
+ const browser = await launch(at)
103
+ try {
104
+ const tab = await open(browser, at)
105
+ await stageReady(tab, null)
106
+ const options = {
107
+ seconds: num(v.seconds, 5),
108
+ speed: num(v.speed, 600),
109
+ cpu: num(v.cpu, 1),
110
+ from: parseStop(v.from ?? '0'),
111
+ }
112
+ const result = {
113
+ url: at.url,
114
+ ...(await frames(tab, { ...options, driver: v.driver ?? 'scroll' })),
115
+ }
116
+ const json = `${JSON.stringify(result, null, 2)}\n`
117
+ if (v.out) write(v.out, json)
118
+ else process.stdout.write(json)
119
+ } finally {
120
+ await browser.close()
121
+ await at.close()
122
+ }
123
+ },
124
+ async sheet(files, v) {
125
+ const browser = await launch(typeof v.chrome === 'string' ? { executablePath: v.chrome } : {})
126
+ try {
127
+ const options = {
128
+ cols: num(v.cols, undefined),
129
+ width: num(v.width, undefined),
130
+ labels: files,
131
+ }
132
+ write(
133
+ v.out ?? 'sheet.png',
134
+ await sheet(
135
+ browser,
136
+ files.map((f) => readFileSync(f)),
137
+ options,
138
+ ),
139
+ )
140
+ } finally {
141
+ await browser.close()
142
+ }
143
+ },
144
+ async bake([target], v) {
145
+ const at = await page(target, v)
146
+ try {
147
+ const out = v.out ?? 'posters'
148
+ const quality = num(v.quality, undefined)
149
+ const how = {
150
+ format: v.format ?? 'avif',
151
+ seconds: num(v.time, 0),
152
+ ...(quality ? { quality } : {}),
153
+ }
154
+ const result = await bake({
155
+ url: at.url,
156
+ out,
157
+ ...how,
158
+ ...(v.chrome ? { executablePath: v.chrome } : {}),
159
+ })
160
+ for (const [id, tiers] of Object.entries(result.posters))
161
+ for (const [tier, still] of Object.entries(tiers))
162
+ console.log(
163
+ `${id} ${tier}: ${still.width}x${still.height} ${still.bytes} B in ${still.ms} ms`,
164
+ )
165
+ console.log(`baked in ${result.ms} ms into ${out}/posters.json`)
166
+ } finally {
167
+ await at.close()
168
+ }
169
+ },
170
+ }
171
+
172
+ /** Runs one command; resolves with the exit code. */
173
+ export async function main(argv) {
174
+ const [command, ...rest] = argv
175
+ const run = command ? COMMANDS[command] : undefined
176
+ if (!run) {
177
+ console.error(USAGE)
178
+ return command && command !== 'help' ? 2 : 0
179
+ }
180
+ try {
181
+ const { values, positionals } = parseArgs({
182
+ args: rest,
183
+ options: OPTIONS,
184
+ allowPositionals: true,
185
+ })
186
+ await run(positionals, values)
187
+ return 0
188
+ } catch (error) {
189
+ console.error(error instanceof Error ? error.message : error)
190
+ return 1
191
+ }
192
+ }
package/src/frames.mjs ADDED
@@ -0,0 +1,120 @@
1
+ // Frame times while a page scrolls: the gap between animation frames, the long ones, and the machine's load.
2
+ // Headless Chrome caps frames at 60 Hz, so the median says little: p5 fps and the share over 33 ms carry it.
3
+ import { cpus, loadavg } from 'node:os'
4
+ import { gpuOf } from './browser.mjs'
5
+ import { scrollAndSettle, sections } from './settle.mjs'
6
+ import { resolveStop } from './stops.mjs'
7
+
8
+ const at = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0
9
+ const round = (n, digits = 2) => Number(n.toFixed(digits))
10
+
11
+ /** Summarises frame gaps in ms: p5 fps, median, p95, the longest, and the frames over 33 and 50 ms. */
12
+ export function frameStats(gaps) {
13
+ const sorted = [...gaps].sort((a, b) => a - b)
14
+ const over = (ms) => gaps.filter((g) => g > ms).length
15
+ return {
16
+ count: gaps.length,
17
+ p5Fps: round(1000 / Math.max(at(sorted, 0.95), 0.001), 1),
18
+ medianMs: round(at(sorted, 0.5)),
19
+ p95Ms: round(at(sorted, 0.95)),
20
+ maxMs: round(sorted.at(-1) ?? 0, 1),
21
+ over33: over(33.4),
22
+ over33Share: round(gaps.length ? over(33.4) / gaps.length : 0, 4),
23
+ over50: over(50),
24
+ }
25
+ }
26
+
27
+ /** In the page: records frame gaps and long tasks until `stop` is called through `kerfFrames`. */
28
+ const RECORD = () => {
29
+ const gaps = []
30
+ const tasks = { count: 0, ms: 0 }
31
+ const seen = new PerformanceObserver((list) => {
32
+ for (const e of list.getEntries()) {
33
+ tasks.count++
34
+ tasks.ms += e.duration
35
+ }
36
+ })
37
+ seen.observe({ type: 'longtask' })
38
+ let last = 0
39
+ let on = true
40
+ const step = (now) => {
41
+ if (last) gaps.push(now - last)
42
+ last = now
43
+ if (on) requestAnimationFrame(step)
44
+ }
45
+ requestAnimationFrame(step)
46
+ const y0 = scrollY
47
+ const stop = () => {
48
+ on = false
49
+ seen.disconnect()
50
+ return {
51
+ gaps,
52
+ longTasks: tasks.count,
53
+ longTaskMs: Math.round(tasks.ms),
54
+ scrolled: scrollY - y0,
55
+ }
56
+ }
57
+ Object.assign(globalThis, { kerfFrames: stop })
58
+ }
59
+
60
+ /** In the page: scrolls at `speed` CSS px/s for `seconds`, one step per frame. */
61
+ const GLIDE = ([seconds, speed]) =>
62
+ new Promise((done) => {
63
+ const y0 = scrollY
64
+ const t0 = performance.now()
65
+ const step = (now) => {
66
+ scrollTo({ top: y0 + ((now - t0) / 1000) * speed, behavior: 'instant' })
67
+ if (now - t0 < seconds * 1000) requestAnimationFrame(step)
68
+ else done(undefined)
69
+ }
70
+ requestAnimationFrame(step)
71
+ })
72
+
73
+ // `wheel` sends wheel steps from outside the page, so a smooth scroller in it runs; `scroll` moves it directly.
74
+ /**
75
+ * Frame times while the page scrolls at `speed` CSS px/s for `seconds` from `from` (px or a stop), with the CPU slowed
76
+ * `cpu` times.
77
+ */
78
+ export async function frames(page, options = {}) {
79
+ const { seconds = 5, speed = 600, cpu = 1, from = 0, driver = 'scroll' } = options
80
+ const start =
81
+ typeof from === 'number' ? from : resolveStop(from, await sections(page, options.sections))
82
+ const cdp = await page.context().newCDPSession(page)
83
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: cpu })
84
+ const begun = await scrollAndSettle(page, start)
85
+ const loadBefore = loadavg()[0] ?? 0
86
+ await page.evaluate(RECORD)
87
+ if (driver === 'wheel') {
88
+ await page.mouse.move(10, 10)
89
+ const end = Date.now() + seconds * 1000
90
+ for (let last = Date.now(); Date.now() < end;) {
91
+ await new Promise((done) => {
92
+ setTimeout(done, 16)
93
+ })
94
+ const now = Date.now()
95
+ await page.mouse.wheel(0, ((now - last) / 1000) * speed)
96
+ last = now
97
+ }
98
+ } else await page.evaluate(GLIDE, [seconds, speed])
99
+ const run = await page.evaluate(() => Reflect.get(globalThis, 'kerfFrames')())
100
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 })
101
+ return {
102
+ seconds,
103
+ speed,
104
+ cpu,
105
+ driver,
106
+ from: begun,
107
+ scrolled: Math.round(run.scrolled),
108
+ frames: frameStats(run.gaps),
109
+ longTasks: run.longTasks,
110
+ longTaskMs: run.longTaskMs,
111
+ load: { before: round(loadBefore), after: round(loadavg()[0] ?? 0) },
112
+ machine: {
113
+ cpu: cpus()[0]?.model ?? 'unknown',
114
+ cores: cpus().length,
115
+ platform: process.platform,
116
+ },
117
+ browser: page.context().browser()?.version() ?? null,
118
+ gpu: await gpuOf(page),
119
+ }
120
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,234 @@
1
+ import type { Browser, LaunchOptions as ChromeLaunch, Page } from 'playwright-core'
2
+ import type { ScenePoster } from '@kerf-js/veneer/scenes'
3
+
4
+ /** Pixels from the top, a section (index or id) at a share of its pass, or pixels past a section's top. */
5
+ export type Stop =
6
+ | number
7
+ | { readonly section: number | string; readonly at: number }
8
+ | { readonly section: number | string; readonly px: number }
9
+
10
+ /** A page's sections in document order, in CSS px from the document's top. */
11
+ export interface SectionMap {
12
+ readonly viewportHeight: number
13
+ readonly documentHeight: number
14
+ readonly sections: readonly {
15
+ readonly index: number
16
+ readonly id: string | null
17
+ readonly top: number
18
+ readonly height: number
19
+ }[]
20
+ }
21
+
22
+ /** How Chrome is launched. Default: the installed Chrome, headless, on the GPU. */
23
+ export interface LaunchOptions {
24
+ headless?: boolean
25
+ channel?: string
26
+ executablePath?: string
27
+ /** Chrome's TMPDIR: keep it short, the singleton socket path has a length limit. */
28
+ tmp?: string
29
+ }
30
+
31
+ /** What page to open and how the device looks. */
32
+ export interface PageOptions {
33
+ url: string
34
+ /** CSS px. Default 1440 × 900. */
35
+ width?: number
36
+ height?: number
37
+ /** Default 1. */
38
+ dpr?: number
39
+ reduced?: boolean
40
+ /** A phone: touch and a phone's user agent. */
41
+ mobile?: boolean
42
+ /** Slow the CPU by this factor. */
43
+ cpu?: number
44
+ }
45
+
46
+ /** `capture`'s options. */
47
+ export interface CaptureOptions extends PageOptions, LaunchOptions {
48
+ stops?: readonly Stop[]
49
+ /** Where PNGs go; without it they are only returned. */
50
+ out?: string
51
+ /** The file name's prefix. Default `still`. */
52
+ name?: string
53
+ /** The CSS selector of a section. Default `section`. */
54
+ sections?: string
55
+ /** The clock time every stage freezes at; null leaves the clock running. Default 0. */
56
+ seconds?: number | null
57
+ /** An open browser to reuse; it stays open. */
58
+ browser?: Browser
59
+ }
60
+
61
+ /** One still. */
62
+ export interface Still {
63
+ readonly stop: Stop
64
+ /** The scroll offset the page took. */
65
+ readonly y: number
66
+ readonly name: string
67
+ readonly path: string | null
68
+ readonly png: Buffer
69
+ readonly bytes: number
70
+ /** SHA-256 of the PNG: the same stop and seed on the same GPU give the same hash. */
71
+ readonly hash: string
72
+ }
73
+
74
+ /** Sheet placement. */
75
+ export interface SheetLayout {
76
+ readonly width: number
77
+ readonly height: number
78
+ readonly cells: readonly { readonly x: number; readonly y: number }[]
79
+ }
80
+
81
+ /** `sheet`'s options. */
82
+ export interface SheetOptions {
83
+ /** Columns. Default: the nearest square. */
84
+ cols?: number
85
+ /** Each tile's width in px; its height keeps the first tile's aspect. Default 480 or narrower. */
86
+ width?: number
87
+ gap?: number
88
+ /** A caption under each tile. */
89
+ labels?: readonly string[]
90
+ background?: string
91
+ }
92
+
93
+ /** `frames`' options. */
94
+ export interface FrameOptions {
95
+ seconds?: number
96
+ /** CSS px per second; 0 stands still. Default 600. */
97
+ speed?: number
98
+ cpu?: number
99
+ /** Where the run starts: px, or a stop (`{ section: 'pay', at: 0 }`). Default 0. */
100
+ from?: Stop
101
+ /** The sections a stop names, for `from`. Default `section`. */
102
+ sections?: string
103
+ /** `scroll` moves the page each frame; `wheel` sends wheel steps, so a smooth scroller runs. */
104
+ driver?: 'scroll' | 'wheel'
105
+ }
106
+
107
+ /** Frame gaps summarised. */
108
+ export interface FrameStats {
109
+ readonly count: number
110
+ readonly p5Fps: number
111
+ readonly medianMs: number
112
+ readonly p95Ms: number
113
+ readonly maxMs: number
114
+ readonly over33: number
115
+ readonly over33Share: number
116
+ readonly over50: number
117
+ }
118
+
119
+ /** A baked still: a media record with its encoded size and how long it took. */
120
+ export type BakedStill = ScenePoster['desktop'] & { readonly bytes: number; readonly ms?: number }
121
+
122
+ /** What `bake` wrote into `posters.json`. */
123
+ export interface BakeManifest {
124
+ readonly format: 'avif' | 'webp'
125
+ readonly quality: number
126
+ readonly seconds: number
127
+ readonly ms: number
128
+ readonly tiers: Record<string, { width: number; height: number; dpr: number }>
129
+ /** By scene id, then tier. */
130
+ readonly posters: Record<string, Record<string, BakedStill>>
131
+ }
132
+
133
+ /** `bake`'s options. */
134
+ export interface BakeOptions extends LaunchOptions {
135
+ url: string
136
+ out: string
137
+ format?: 'avif' | 'webp'
138
+ /** Encoder quality. Default AVIF 50, WebP 75. */
139
+ quality?: number
140
+ /** The clock time each still is drawn at. Default 0. */
141
+ seconds?: number
142
+ /** Sizes by tier name. Default `TIERS`. */
143
+ tiers?: Record<string, { width: number; height: number; dpr: number }>
144
+ browser?: Browser
145
+ }
146
+
147
+ /** The sizes a poster is drawn at by default: desktop 1440 × 900 at 1×, mobile 390 × 844 at 2×. */
148
+ export declare const TIERS: Record<
149
+ 'desktop' | 'mobile',
150
+ { width: number; height: number; dpr: number }
151
+ >
152
+
153
+ /** Chrome's flags for drawing on the GPU headless on this platform. */
154
+ export declare function gpuArgs(platform?: NodeJS.Platform): string[]
155
+ /** Launches Chrome headless on the GPU. */
156
+ export declare function launch(options?: LaunchOptions & ChromeLaunch): Promise<Browser>
157
+ /** Opens a page at a device's size; errors land on `page.problems`. */
158
+ export declare function open(
159
+ browser: Browser,
160
+ options: PageOptions,
161
+ ): Promise<Page & { problems: string[] }>
162
+ /** The GPU renderer WebGL reports, or null without WebGL2. */
163
+ export declare function gpuOf(page: Page): Promise<string | null>
164
+
165
+ /** The page's sections. */
166
+ export declare function sections(page: Page, selector?: string): Promise<SectionMap>
167
+ /** Waits for every stage to draw once, then freezes its clock at `seconds` (null: leave it). */
168
+ export declare function stageReady(
169
+ page: Page,
170
+ seconds?: number | null,
171
+ timeout?: number,
172
+ ): Promise<void>
173
+ /** Scrolls to `y` and waits for the page to settle; resolves with the offset taken. */
174
+ export declare function scrollAndSettle(page: Page, y: number, timeout?: number): Promise<number>
175
+
176
+ /** A stop from text: `1200`, `hero@0.5`, `2@0`, `hero+300`. */
177
+ export declare function parseStop(text: string | number): Stop
178
+ /** A stop's scroll offset on a page. */
179
+ export declare function resolveStop(stop: Stop, map: SectionMap): number
180
+ /** A stop as a file name part. */
181
+ export declare function stopName(stop: Stop): string
182
+
183
+ /** Stills at scroll stops. */
184
+ export declare function capture(options: CaptureOptions): Promise<{
185
+ stills: Still[]
186
+ map: SectionMap
187
+ gpu: string | null
188
+ problems: string[]
189
+ browser: string
190
+ }>
191
+
192
+ /** Frame times while the page scrolls, with the machine's load. */
193
+ export declare function frames(
194
+ page: Page,
195
+ options?: FrameOptions,
196
+ ): Promise<{
197
+ seconds: number
198
+ speed: number
199
+ cpu: number
200
+ driver: 'scroll' | 'wheel'
201
+ /** The scroll offset the run started from, in px. */
202
+ from: number
203
+ scrolled: number
204
+ frames: FrameStats
205
+ longTasks: number
206
+ longTaskMs: number
207
+ load: { before: number; after: number }
208
+ machine: { cpu: string; cores: number; platform: string }
209
+ browser: string | null
210
+ gpu: string | null
211
+ }>
212
+ /** Summarises frame gaps in ms. */
213
+ export declare function frameStats(gaps: readonly number[]): FrameStats
214
+
215
+ /** Where each tile of a sheet goes. */
216
+ export declare function sheetLayout(
217
+ count: number,
218
+ options: { tileWidth: number; tileHeight: number; cols?: number; gap?: number; label?: number },
219
+ ): SheetLayout
220
+ /** Lays tiles on one PNG sheet, drawn in the browser. */
221
+ export declare function sheet(
222
+ browser: Browser,
223
+ tiles: readonly Uint8Array[],
224
+ options?: SheetOptions,
225
+ ): Promise<Buffer>
226
+
227
+ /** Bakes each `poster="bake"` scene of the stage at `url` into `out`. */
228
+ export declare function bake(options: BakeOptions): Promise<BakeManifest>
229
+
230
+ /** Serves a built folder on 127.0.0.1. */
231
+ export declare function serve(
232
+ dir: string,
233
+ port?: number,
234
+ ): Promise<{ url: string; close(): Promise<void> }>
package/src/index.mjs ADDED
@@ -0,0 +1,9 @@
1
+ // @kerf-js/capture: stills, frame times, sheets and poster bakes from headless Chrome on the GPU. Dev only.
2
+ export { bake, TIERS } from './bake.mjs'
3
+ export { gpuArgs, gpuOf, launch, open } from './browser.mjs'
4
+ export { frames, frameStats } from './frames.mjs'
5
+ export { serve } from './serve.mjs'
6
+ export { scrollAndSettle, sections, stageReady } from './settle.mjs'
7
+ export { sheet, sheetLayout } from './sheet.mjs'
8
+ export { capture } from './stills.mjs'
9
+ export { parseStop, resolveStop, stopName } from './stops.mjs'
@@ -0,0 +1,8 @@
1
+ // The module `posters()` provides: `/// <reference types="@kerf-js/capture/posters" />` in a page that imports it.
2
+ declare module 'virtual:kerf/posters' {
3
+ import type { ScenePoster } from '@kerf-js/veneer/scenes'
4
+
5
+ const posters: Readonly<Record<string, ScenePoster>>
6
+ /** The baked posters by scene id, already registered with `bakedPosters`. */
7
+ export default posters
8
+ }
package/src/serve.mjs ADDED
@@ -0,0 +1,46 @@
1
+ // A static server for a built page, on 127.0.0.1, so the drivers can open a `dist` folder as a site.
2
+ import { createReadStream, existsSync, statSync } from 'node:fs'
3
+ import { createServer } from 'node:http'
4
+ import { extname, join, resolve, sep } from 'node:path'
5
+
6
+ const TYPES = {
7
+ '.html': 'text/html; charset=utf-8',
8
+ '.js': 'text/javascript',
9
+ '.mjs': 'text/javascript',
10
+ '.css': 'text/css',
11
+ '.json': 'application/json',
12
+ '.svg': 'image/svg+xml',
13
+ '.png': 'image/png',
14
+ '.jpg': 'image/jpeg',
15
+ '.webp': 'image/webp',
16
+ '.avif': 'image/avif',
17
+ '.woff2': 'font/woff2',
18
+ '.wasm': 'application/wasm',
19
+ }
20
+
21
+ /** Serves the files under `dir` on a free port (or `port`). A folder answers with its `index.html`. */
22
+ export async function serve(dir, port = 0) {
23
+ const root = resolve(dir)
24
+ const server = createServer((req, res) => {
25
+ let file = join(root, decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname))
26
+ if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html')
27
+ if ((file !== root && !file.startsWith(root + sep)) || !existsSync(file)) {
28
+ res.writeHead(404).end()
29
+ return
30
+ }
31
+ const type = TYPES[extname(file)]
32
+ res.writeHead(200, { 'content-type': type ?? 'application/octet-stream' })
33
+ createReadStream(file).pipe(res)
34
+ })
35
+ await new Promise((done) => {
36
+ server.listen(port, '127.0.0.1', () => done(undefined))
37
+ })
38
+ const address = server.address()
39
+ return {
40
+ url: `http://127.0.0.1:${address.port}`,
41
+ close: () =>
42
+ new Promise((done) => {
43
+ server.close(() => done(undefined))
44
+ }),
45
+ }
46
+ }
package/src/settle.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // When a page may be captured: a kerf stage says so (`data-stage-ready` is the offset it drew at); any page also
2
+ // waits for its transitions, fonts and the images in view.
3
+
4
+ /** The page's sections, `selector` in document order, in CSS px from the document's top. */
5
+ export function sections(page, selector = 'section') {
6
+ return page.evaluate((sel) => {
7
+ const list = [...document.querySelectorAll(sel)].map((el, index) => {
8
+ const box = el.getBoundingClientRect()
9
+ return {
10
+ index,
11
+ id: el.id || null,
12
+ top: Math.round(box.top + scrollY),
13
+ height: Math.round(box.height),
14
+ }
15
+ })
16
+ const documentHeight = document.documentElement.scrollHeight
17
+ return { viewportHeight: innerHeight, documentHeight, sections: list }
18
+ }, selector)
19
+ }
20
+
21
+ /** Waits for every stage to draw once, then stops its clock at `seconds` (null leaves it running). */
22
+ export async function stageReady(page, seconds = 0, timeout = 60_000) {
23
+ await page.waitForFunction(
24
+ () =>
25
+ [...document.querySelectorAll('[data-stage]')].every((el) =>
26
+ el.hasAttribute('data-stage-ready'),
27
+ ),
28
+ null,
29
+ { timeout },
30
+ )
31
+ if (seconds === null) return
32
+ await page.evaluate((at) => {
33
+ for (const el of document.querySelectorAll('[data-stage]'))
34
+ Reflect.get(el, Symbol.for('kerf.stage'))?.freeze(at)
35
+ }, seconds)
36
+ }
37
+
38
+ /** In the page: fonts, then the images in view, then running CSS transitions, each with a time limit. */
39
+ const QUIET = async (limit) => {
40
+ const cap = (p) =>
41
+ Promise.race([
42
+ p,
43
+ new Promise((done) => {
44
+ setTimeout(done, limit)
45
+ }),
46
+ ])
47
+ await cap(document.fonts.ready)
48
+ const seen = [...document.images].filter((img) => {
49
+ const box = img.getBoundingClientRect()
50
+ return box.bottom > 0 && box.top < innerHeight && box.width > 0
51
+ })
52
+ await cap(Promise.all(seen.map((img) => img.decode().catch(() => {}))))
53
+ const moving = document.getAnimations().filter((a) => a instanceof CSSTransition)
54
+ await cap(Promise.all(moving.map((a) => a.finished.catch(() => {}))))
55
+ }
56
+
57
+ /** Scrolls to `y` at once, waits until the page has settled there, and resolves with the offset it took. */
58
+ export async function scrollAndSettle(page, y, timeout = 30_000) {
59
+ const at = await page.evaluate((top) => {
60
+ scrollTo({ top, behavior: 'instant' })
61
+ return Math.round(scrollY)
62
+ }, y)
63
+ await page.evaluate(
64
+ () =>
65
+ new Promise((done) => {
66
+ requestAnimationFrame(() => requestAnimationFrame(done))
67
+ }),
68
+ )
69
+ await page.waitForFunction(
70
+ (offset) =>
71
+ [...document.querySelectorAll('[data-stage]')].every((el) =>
72
+ ['poster', String(offset)].includes(el.getAttribute('data-stage-ready') ?? ''),
73
+ ),
74
+ at,
75
+ { timeout, polling: 'raf' },
76
+ )
77
+ await page.evaluate(QUIET, 5_000)
78
+ return at
79
+ }
package/src/sheet.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // Contact sheets: tiles laid out on one canvas in the browser, so no image tool has to be installed.
2
+
3
+ /** Where each tile goes: `cols` columns (default near square), `label` px of caption under each, `gap` apart. */
4
+ export function sheetLayout(count, { tileWidth, tileHeight, cols, gap = 4, label = 0 }) {
5
+ const across = Math.max(1, Math.min(count, cols ?? Math.ceil(Math.sqrt(count))))
6
+ const rows = Math.max(1, Math.ceil(count / across))
7
+ const cell = tileHeight + label
8
+ return {
9
+ width: across * tileWidth + (across + 1) * gap,
10
+ height: rows * cell + (rows + 1) * gap,
11
+ cells: Array.from({ length: count }, (_, i) => ({
12
+ x: gap + (i % across) * (tileWidth + gap),
13
+ y: gap + Math.floor(i / across) * (cell + gap),
14
+ })),
15
+ }
16
+ }
17
+
18
+ /** Decodes every tile in the page and reports each one's size. */
19
+ const DECODE = async (data) => {
20
+ const bytes = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
21
+ const tiles = await Promise.all(data.map((b64) => createImageBitmap(new Blob([bytes(b64)]))))
22
+ Object.assign(globalThis, { kerfSheetTiles: tiles })
23
+ return tiles.map((t) => ({ width: t.width, height: t.height }))
24
+ }
25
+
26
+ /** Draws the decoded tiles at their cells, with captions, and returns the sheet as base64 PNG. */
27
+ const DRAW = async (o) => {
28
+ const tiles = Reflect.get(globalThis, 'kerfSheetTiles')
29
+ const canvas = new OffscreenCanvas(o.layout.width, o.layout.height)
30
+ const x = canvas.getContext('2d')
31
+ x.fillStyle = o.background
32
+ x.fillRect(0, 0, canvas.width, canvas.height)
33
+ x.font = `${Math.round(o.label * 0.6)}px ui-monospace, monospace`
34
+ x.textBaseline = 'middle'
35
+ tiles.forEach((tile, i) => {
36
+ const cell = o.layout.cells[i]
37
+ if (!cell) return
38
+ x.drawImage(tile, cell.x, cell.y, o.tileWidth, o.tileHeight)
39
+ x.fillStyle = '#d8d8d8'
40
+ if (o.labels[i]) x.fillText(o.labels[i], cell.x + 4, cell.y + o.tileHeight + o.label / 2)
41
+ })
42
+ const blob = await canvas.convertToBlob({ type: 'image/png' })
43
+ const bytes = new Uint8Array(await blob.arrayBuffer())
44
+ let text = ''
45
+ for (let i = 0; i < bytes.length; i += 0x8000)
46
+ text += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
47
+ return btoa(text)
48
+ }
49
+
50
+ /** Lays PNG or JPEG tiles on one PNG sheet, each at `width` px and the first tile's aspect. */
51
+ export async function sheet(browser, tiles, options = {}) {
52
+ if (!tiles.length) throw new Error('kerf capture: a sheet needs at least one tile')
53
+ const page = await browser.newPage()
54
+ try {
55
+ const sizes = await page.evaluate(
56
+ DECODE,
57
+ tiles.map((t) => Buffer.from(t).toString('base64')),
58
+ )
59
+ const first = sizes[0]
60
+ const tileWidth = options.width ?? Math.min(480, first.width)
61
+ const tileHeight = Math.round((first.height / first.width) * tileWidth)
62
+ const label = options.labels ? 20 : 0
63
+ const { cols, gap } = options
64
+ const layout = sheetLayout(tiles.length, { tileWidth, tileHeight, label, cols, gap })
65
+ const background = options.background ?? '#1e1e1e'
66
+ const labels = options.labels ?? []
67
+ const png = await page.evaluate(DRAW, {
68
+ layout,
69
+ tileWidth,
70
+ tileHeight,
71
+ labels,
72
+ background,
73
+ label,
74
+ })
75
+ return Buffer.from(png, 'base64')
76
+ } finally {
77
+ await page.close()
78
+ }
79
+ }
package/src/stills.mjs ADDED
@@ -0,0 +1,33 @@
1
+ // Stills at scroll stops: a viewport PNG at each settled stop with the clock stopped, so the same stop repeats.
2
+ import { createHash } from 'node:crypto'
3
+ import { mkdirSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { gpuOf, launch, open } from './browser.mjs'
6
+ import { scrollAndSettle, sections, stageReady } from './settle.mjs'
7
+ import { resolveStop, stopName } from './stops.mjs'
8
+
9
+ /** Opens `url` and captures a PNG at each stop, with its offset, bytes and SHA-256, into `out` when given. */
10
+ export async function capture(options) {
11
+ const browser = options.browser ?? (await launch(options))
12
+ try {
13
+ const page = await open(browser, options)
14
+ await stageReady(page, options.seconds === undefined ? 0 : options.seconds)
15
+ const map = await sections(page, options.sections)
16
+ if (options.out) mkdirSync(options.out, { recursive: true })
17
+ const stills = []
18
+ for (const stop of options.stops ?? [0]) {
19
+ const y = await scrollAndSettle(page, resolveStop(stop, map))
20
+ const png = await page.screenshot({ type: 'png' })
21
+ const name = `${options.name ?? 'still'}-${stopName(stop)}.png`
22
+ const path = options.out ? join(options.out, name) : null
23
+ if (path) writeFileSync(path, png)
24
+ const hash = createHash('sha256').update(png).digest('hex')
25
+ stills.push({ stop, y, name, path, png, bytes: png.length, hash })
26
+ }
27
+ const gpu = await gpuOf(page)
28
+ await page.context().close()
29
+ return { stills, map, gpu, problems: page.problems, browser: browser.version() }
30
+ } finally {
31
+ if (!options.browser) await browser.close()
32
+ }
33
+ }
package/src/stops.mjs ADDED
@@ -0,0 +1,43 @@
1
+ // Where a capture scrolls to: pixels, or a place in a section the page's map names. The same stop, the same offset.
2
+
3
+ const key = (text) => (/^\d+$/.test(text) ? Number(text) : text)
4
+
5
+ /** A stop from text: `1200` px, `hero@0.5` or `2@0` (a section's id or index at a share), `hero+300` px past its top. */
6
+ export function parseStop(text) {
7
+ const t = String(text).trim()
8
+ if (/^\d+(\.\d+)?$/.test(t)) return Number(t)
9
+ const at = /^(.+)@(\d*\.?\d+)$/.exec(t)
10
+ if (at) return { section: key(at[1] ?? ''), at: Number(at[2]) }
11
+ const px = /^(.+?)([+-]\d+(?:\.\d+)?)$/.exec(t)
12
+ if (px) return { section: key(px[1] ?? ''), px: Number(px[2]) }
13
+ throw new Error(`kerf capture: a stop is <px>, <section>@<0..1> or <section>+<px>, not "${t}"`)
14
+ }
15
+
16
+ function find(map, section) {
17
+ const found =
18
+ typeof section === 'number' ? map.sections[section] : map.sections.find((s) => s.id === section)
19
+ if (!found) throw new Error(`kerf capture: the page has no section ${JSON.stringify(section)}`)
20
+ return found
21
+ }
22
+
23
+ /** A stop's offset, clamped: a tall section's pass is top-at-top to bottom-at-bottom, a short one's enter to leave. */
24
+ export function resolveStop(stop, map) {
25
+ const vh = map.viewportHeight
26
+ const clamp = (y) => Math.round(Math.min(Math.max(0, map.documentHeight - vh), Math.max(0, y)))
27
+ if (typeof stop === 'number') return clamp(stop)
28
+ const s = find(map, stop.section)
29
+ if ('px' in stop) return clamp(s.top + stop.px)
30
+ const tall = s.height > vh
31
+ const from = tall ? s.top : s.top - vh
32
+ const to = tall ? s.top + s.height - vh : s.top + s.height
33
+ return clamp(from + (to - from) * stop.at)
34
+ }
35
+
36
+ /** A stop as part of a file name: `y1200`, `hero@0.50`, `2+300`. */
37
+ export function stopName(stop) {
38
+ if (typeof stop === 'number') return `y${Math.round(stop)}`
39
+ const name = String(stop.section).replace(/[^\w-]+/g, '-')
40
+ return 'px' in stop
41
+ ? `${name}${stop.px < 0 ? '' : '+'}${stop.px}`
42
+ : `${name}@${stop.at.toFixed(2)}`
43
+ }
package/src/vite.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from 'vite'
2
+ import type { BakeManifest } from './index'
3
+
4
+ /** A Vite plugin: `import 'virtual:kerf/posters'` registers the posters a bake wrote in `dir` (default `posters`). */
5
+ export declare function posters(options?: { dir?: string }): Plugin
6
+ /** The source of the posters module for a manifest in `folder`, or of an empty one. */
7
+ export declare function postersModule(folder: string, manifest: BakeManifest | null): string
package/src/vite.mjs ADDED
@@ -0,0 +1,47 @@
1
+ // The build half of the poster bake: a module that registers the baked stills, each one a hashed build asset.
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { join, resolve } from 'node:path'
4
+
5
+ const ID = 'virtual:kerf/posters'
6
+ const RESOLVED = `\0${ID}`
7
+
8
+ /** The module for a manifest: one asset import per still, and the records under each scene's id. */
9
+ export function postersModule(folder, manifest) {
10
+ const imports = []
11
+ const entries = []
12
+ for (const [id, tiers] of Object.entries(manifest?.posters ?? {})) {
13
+ const fields = []
14
+ for (const [tier, record] of Object.entries(tiers)) {
15
+ const name = `still${imports.length}`
16
+ imports.push(`import ${name} from ${JSON.stringify(join(folder, record.src))}`)
17
+ const { bytes: _bytes, ms: _ms, ...rest } = record
18
+ fields.push(`${JSON.stringify(tier)}: { ...${JSON.stringify(rest)}, src: ${name} }`)
19
+ }
20
+ entries.push(`${JSON.stringify(id)}: { ${fields.join(', ')} }`)
21
+ }
22
+ return [
23
+ `import { bakedPosters } from '@kerf-js/veneer/scenes'`,
24
+ ...imports,
25
+ `export default bakedPosters({ ${entries.join(', ')} })`,
26
+ ].join('\n')
27
+ }
28
+
29
+ /** A Vite plugin: `import 'virtual:kerf/posters'` registers what a bake wrote in `dir` (default `posters`). */
30
+ export function posters(options = {}) {
31
+ let root = process.cwd()
32
+ return {
33
+ name: 'kerf-capture-posters',
34
+ configResolved(config) {
35
+ root = config.root
36
+ },
37
+ resolveId: (id) => (id === ID ? RESOLVED : undefined),
38
+ load(id) {
39
+ if (id !== RESOLVED) return
40
+ const folder = resolve(root, options.dir ?? 'posters')
41
+ const file = join(folder, 'posters.json')
42
+ if (!existsSync(file)) return postersModule(folder, null)
43
+ this.addWatchFile(file)
44
+ return postersModule(folder, JSON.parse(readFileSync(file, 'utf8')))
45
+ },
46
+ }
47
+ }