@stacksjs/docs 0.75.653 → 0.75.657

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,4 +41,4 @@ MIT license. Contributions follow the Stacks repository conventions.
41
41
 
42
42
  `@stacksjs/docs/screenshots` exports `defineScreenshotConfig`, `validateScreenshotConfig` and `captureScreenshots`. Run a configured inventory with `buddy docs:screenshots`; use `--list` to verify template coverage and `--check` to validate saved captures. Each authentication profile owns a separate Bun WebView worker process. See the [screen documentation guide](https://stacksjs.com/docs/guide/screenshots) for readiness hooks, role setup, masks, artifacts and CI examples.
43
43
 
44
- `screensFromViews()` derives that inventory from the application's stx views, so every route is captured without a hand-written list. Add `film` for a walkthrough MP4 per viewport and `docs` for a generated page showing every screen. See `docs/guide/automatic-screens.md`.
44
+ `screensFromViews()` derives that inventory from the application's stx views, so every route is captured without a hand-written list. Add `film` for a walkthrough MP4 per viewport and `docs` for a generated page showing every screen. See `docs/guide/screenshots.md`.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A blank page on localhost: WebCodecs needs a secure context, and localhost
3
+ * is one. `files` maps a path such as `/raw.mp4` to a local file the page may
4
+ * load, with byte ranges so a video element can seek in it.
5
+ */
6
+ export declare function serveFilmStudio(files?: Record<string, string>): { url: string, stop: () => void };
7
+ /**
8
+ * Encode pictures into an MP4 inside a page the caller already controls.
9
+ * `evaluate` must await promises, and the page must be a secure context
10
+ * (https, or localhost: see `serveFilmStudio`).
11
+ */
12
+ export declare function openBrowserFilm(evaluate: FilmEvaluate, options: BrowserFilmOptions): Promise<BrowserFilm>;
13
+ export declare interface BrowserFilmOptions {
14
+ fps: number
15
+ width?: number
16
+ height?: number
17
+ bitrate?: number
18
+ }
19
+ /** A square outline drawn over a recording between two moments, in the recording's own pixels. */
20
+ export declare interface FilmMark { x: number, y: number, size: number, color: string, start: number, end: number }
21
+ export declare interface BrowserFilm {
22
+ add: (picture: Uint8Array | undefined, frames: number) => Promise<void>
23
+ addVideo: (url: string, marks?: FilmMark[]) => Promise<number>
24
+ finish: () => Promise<Uint8Array>
25
+ frames: () => number
26
+ }
27
+ /** Runs a script in a page and resolves with its result, as Bun.WebView and a DevTools session both do. */
28
+ export type FilmEvaluate = (script: string) => Promise<unknown>;
@@ -0,0 +1,97 @@
1
+ // @bun
2
+ import{Mp4Muxer as h}from"@ts-videos/mp4";import{BufferTarget as u}from"ts-videos";function v(e={}){let i=Bun.serve({port:0,hostname:"127.0.0.1",fetch(m){let a=e[new URL(m.url).pathname];if(a)return new Response(Bun.file(a),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${i.port}/`,stop:()=>{i.stop(!0)}}}var w=["6400","4d00","42e0"],p=(e)=>`(() => {
3
+ if (window.__stacksFilm) return true
4
+ const b64 = bytes => { let text = ''; for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(text) }
5
+ const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
6
+ film.start = async (width, height) => {
7
+ if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
8
+ film.width = width; film.height = height
9
+ const level = width * height > 2097152 ? '33' : '28'
10
+ for (const profile of ${JSON.stringify(w)}) {
11
+ const config = { codec: 'avc1.' + profile + level, width, height, bitrate: ${e.bitrate??0} || Math.max(1500000, Math.round(width * height * 3)), framerate: ${e.fps}, avc: { format: 'avc' } }
12
+ const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
13
+ if (!support || !support.supported) continue
14
+ film.canvas = new OffscreenCanvas(width, height)
15
+ film.context = film.canvas.getContext('2d')
16
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, width, height)
17
+ film.encoder = new VideoEncoder({
18
+ output(chunk, meta) {
19
+ const bytes = new Uint8Array(chunk.byteLength); chunk.copyTo(bytes)
20
+ const description = meta && meta.decoderConfig && meta.decoderConfig.description
21
+ if (description) film.description = b64(new Uint8Array(description.buffer || description, description.byteOffset || 0, description.byteLength))
22
+ film.chunks.push([chunk.type === 'key' ? 1 : 0, chunk.timestamp, b64(bytes)])
23
+ },
24
+ error(error) { film.error = String(error && error.message || error) },
25
+ })
26
+ film.encoder.configure(config)
27
+ return
28
+ }
29
+ throw new Error('This browser cannot encode H.264 video at ' + width + ' by ' + height)
30
+ }
31
+ film.add = async (picture, type, frames) => {
32
+ if (picture) {
33
+ const bitmap = await createImageBitmap(await (await fetch('data:' + type + ';base64,' + picture)).blob())
34
+ if (!film.encoder) await film.start(${e.width?Math.ceil(e.width/2)*2:"Math.ceil(bitmap.width / 2) * 2"}, ${e.height?Math.ceil(e.height/2)*2:"Math.ceil(bitmap.height / 2) * 2"})
35
+ const scale = Math.min(film.width / bitmap.width, film.height / bitmap.height, 1)
36
+ const [w, h] = [bitmap.width * scale, bitmap.height * scale]
37
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
38
+ film.context.drawImage(bitmap, (film.width - w) / 2, (film.height - h) / 2, w, h)
39
+ bitmap.close()
40
+ }
41
+ if (!film.encoder) throw new Error('A film starts with a picture')
42
+ for (let i = 0; i < frames; i++) {
43
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
44
+ // A key frame every two seconds keeps seeking quick without costing much.
45
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
46
+ frame.close(); film.frame++
47
+ }
48
+ if (film.encoder.encodeQueueSize > 30) await film.encoder.flush()
49
+ if (film.error) throw new Error(film.error)
50
+ }
51
+ film.open = async (url) => {
52
+ const video = film.video = document.createElement('video')
53
+ video.muted = true; video.playsInline = true; video.preload = 'auto'
54
+ await new Promise((resolve, reject) => {
55
+ video.addEventListener('loadeddata', resolve, { once: true })
56
+ video.addEventListener('error', () => reject(new Error('This browser cannot play the recording')), { once: true })
57
+ video.src = url
58
+ })
59
+ if (!video.videoWidth || !Number.isFinite(video.duration)) throw new Error('The recording has no picture')
60
+ await film.start(Math.ceil(video.videoWidth / 2) * 2, Math.ceil(video.videoHeight / 2) * 2)
61
+ return JSON.stringify({ seconds: video.duration, frames: Math.max(1, Math.round(video.duration * ${e.fps})) })
62
+ }
63
+ // One output frame per tick of this film's clock, each taken from the
64
+ // recording at that moment: a device's variable frame rate becomes steady.
65
+ film.copy = async (from, count, marks) => {
66
+ const video = film.video
67
+ for (let index = from; index < from + count; index++) {
68
+ const time = Math.min(index / ${e.fps}, Math.max(0, video.duration - 0.001))
69
+ if (Math.abs(video.currentTime - time) > 0.0005) {
70
+ await new Promise((resolve, reject) => {
71
+ video.addEventListener('seeked', resolve, { once: true })
72
+ video.addEventListener('error', () => reject(new Error('The recording could not be read')), { once: true })
73
+ video.currentTime = time
74
+ })
75
+ }
76
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
77
+ film.context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
78
+ for (const mark of marks) {
79
+ if (time < mark.start || time > mark.end) continue
80
+ film.context.globalAlpha = 0.9; film.context.strokeStyle = mark.color; film.context.lineWidth = 4
81
+ film.context.strokeRect(Math.round(mark.x - mark.size / 2) + 2, Math.round(mark.y - mark.size / 2) + 2, mark.size - 4, mark.size - 4)
82
+ film.context.globalAlpha = 1
83
+ }
84
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
85
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
86
+ frame.close(); film.frame++
87
+ }
88
+ await film.encoder.flush()
89
+ if (film.error) throw new Error(film.error)
90
+ }
91
+ film.drain = async (last) => {
92
+ if (last && film.encoder) { await film.encoder.flush(); film.encoder.close() }
93
+ if (film.error) throw new Error(film.error)
94
+ return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
+ }
96
+ return true
97
+ })()`,g=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function k(e,i){if(!Number.isInteger(i.fps)||i.fps<1||i.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(p(i));let m=[],a,c={width:0,height:0},f=0,d=async(n)=>{let t=JSON.parse(String(await e(`window.__stacksFilm.drain(${n})`)));if(c={width:t.width,height:t.height},t.description)a=new Uint8Array(Buffer.from(t.description,"base64"));for(let[o,r,s]of t.chunks)m.push([o,r,new Uint8Array(Buffer.from(s,"base64"))])};return{frames:()=>f,async add(n,t){if(!Number.isInteger(t)||t<1)return;let o=n?`${JSON.stringify(Buffer.from(n).toString("base64"))}, ${JSON.stringify(g(n))}`:"null, null";if(await e(`window.__stacksFilm.add(${o}, ${t})`),f+=t,f%(i.fps*20)<t)await d(!1)},async addVideo(n,t=[]){for(let r of t)if(![r.x,r.y,r.size,r.start,r.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(r.color))throw Error("Invalid film mark");let o=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(n)})`)));for(let r=0;r<o.frames;r+=i.fps){let s=Math.min(i.fps,o.frames-r);await e(`window.__stacksFilm.copy(${r}, ${s}, ${JSON.stringify(t)})`),f+=s,await d(!1)}return o.seconds},async finish(){if(await d(!0),!m.length||!a)throw Error("The browser encoded no video");let n=new u,t=new h(n),o=t.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:i.fps,codecDescription:a});for(let[r,s,l]of m)await t.writePacket(o.id,{data:l,timestamp:s/1e6,duration:1/i.fps,isKeyframe:r===1});return await t.finalize(),n.buffer}}}export{k as openBrowserFilm,v as serveFilmStudio};
@@ -1,7 +1,11 @@
1
1
  import type { ScreenshotReport, ScreenshotResult, ScreenshotViewport } from './screenshots';
2
2
  export declare function validateScreenshotPublishing(film: ScreenshotFilmOptions | false | undefined, docs: ScreenshotDocsOptions | undefined, root: string, viewports: ScreenshotViewport[]): void;
3
- /** One MP4 per viewport: every captured screen in inventory order, held for a readable moment. */
4
- export declare function filmScreenshots(output: string, results: ScreenshotResult[], viewports: ScreenshotViewport[], options: ScreenshotFilmOptions): Promise<ScreenshotFilm[]>;
3
+ /**
4
+ * One MP4 per viewport: every captured screen in inventory order, held for a
5
+ * readable moment. The capture's own browser encodes it, so nothing else has
6
+ * to be installed.
7
+ */
8
+ export declare function filmScreenshots(output: string, results: ScreenshotResult[], viewports: ScreenshotViewport[], options: ScreenshotFilmOptions, backend?: 'webkit' | 'chrome'): Promise<ScreenshotFilm[]>;
5
9
  /** The page readers open: the films, then every screen with its explanation and pictures. */
6
10
  export declare function renderScreensPage(report: Pick<ScreenshotReport, 'results' | 'inventory' | 'generatorVersion'> & { films?: ScreenshotFilm[] }, options: ScreenshotDocsOptions): string;
7
11
  export declare function writeScreensPage(root: string, report: Parameters<typeof renderScreensPage>[0], options: ScreenshotDocsOptions): Promise<ScreenshotDocsPage>;
@@ -10,7 +14,6 @@ export declare interface ScreenshotFilmOptions {
10
14
  secondsPerScreen?: number
11
15
  fps?: number
12
16
  viewports?: string[]
13
- ffmpeg?: string
14
17
  }
15
18
  export declare interface ScreenshotDocsOptions {
16
19
  page: string
@@ -1,6 +1,99 @@
1
1
  // @bun
2
- import{createHash as B}from"crypto";import{lstat as N,mkdir as R,mkdtemp as D,readFile as _,rename as P,rm as j}from"fs/promises";import{tmpdir as M}from"os";import{dirname as T,isAbsolute as V,join as m,relative as U,resolve as k}from"path";var E="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",F=(e)=>B("sha256").update(e).digest("hex"),u=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),g=(e)=>u(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1"),x=(e)=>Math.ceil(e/2)*2;function G(e,i,o,s){if(e){let n=e.secondsPerScreen??2;if(!Number.isFinite(n)||n<0.2||n>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let c of e.viewports??[])if(!s.some((v)=>v.name===c))throw Error(`Unknown film viewport: ${c}`)}if(i){let n=k(o,i.page);if(V(i.page)||U(o,n).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function H(e,i,o,s){let n=[],c=s.secondsPerScreen??2,v=s.fps??12,h=await D(m(M(),"stacks-screen-film-"));try{for(let a of o){if(s.viewports?.length&&!s.viewports.includes(a.name))continue;let t=i.filter((w)=>w.status==="captured"&&w.file&&w.viewport.name===a.name);if(!t.length)continue;let l=(w)=>`file '${m(e,w).replaceAll("'","'\\''")}'`,f=[...t.flatMap((w)=>[l(w.file),`duration ${c}`]),l(t.at(-1).file)].join(`
3
- `);await Bun.write(m(h,`${a.name}.txt`),`${f}
4
- `);let[p,d]=[x(a.width),x(a.height)],r=m(h,`${a.name}.mp4`),y;try{y=Bun.spawn([s.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-y","-f","concat","-safe","0","-i",m(h,`${a.name}.txt`),"-an","-vf",`scale=${p}:${d}:force_original_aspect_ratio=decrease,pad=${p}:${d}:(ow-iw)/2:(oh-ih)/2:color=white,format=yuv420p`,"-r",String(v),"-c:v","libx264","-preset","veryfast","-movflags","+faststart",r],{stdin:"ignore",stdout:"ignore",stderr:"pipe"})}catch{throw Error("FFmpeg is required to film the captured screens; install it or set film.ffmpeg")}let A=setTimeout(()=>y.kill(),600000),[b,O]=await Promise.all([y.exited,new Response(y.stderr).text()]);if(clearTimeout(A),b!==0)throw Error(`FFmpeg could not film the ${a.name} screens: ${O.trim().slice(0,400)||`exit ${b}`}`);let S=`film-${a.name}.mp4`;await P(r,m(e,S)).catch(async()=>{await Bun.write(m(e,S),Bun.file(r))}),n.push({viewport:a.name,file:S,sha256:F(new Uint8Array(await Bun.file(m(e,S)).arrayBuffer())),screens:t.length,seconds:t.length*c})}return n}finally{await j(h,{recursive:!0,force:!0})}}function q(e,i){let o=i.base.replace(/\/+$/,""),s=i.title??"Screens",n=e.results.filter((t)=>t.status==="captured"&&t.file),c=["---",`title: ${JSON.stringify(s)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",E,"",`# ${g(s)}`,"",`${new Set(n.map((t)=>t.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let t of e.films??[]){let l=n.find((f)=>f.viewport.name===t.viewport);c.push(`## Walkthrough video (${g(t.viewport)})`,"",`<video controls playsinline preload="none" src="${u(`${o}/${t.file}`)}"${l?` poster="${u(`${o}/${l.file}`)}"`:""} style="width:100%;max-width:${l&&l.viewport.width<600?l.viewport.width:1100}px;height:auto"></video>`,"",`${t.screens} screens in ${Math.round(t.seconds)} seconds. [Download the video](${o}/${t.file}).`,"")}let v=(t)=>t.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",h=new Map;for(let t of e.inventory)h.set(v(t.path),[...h.get(v(t.path))??[],t]);let a=[];for(let[t,l]of[...h].sort(([f],[p])=>f.localeCompare(p))){let f=[];for(let p of l){let d=n.filter((r)=>r.id===p.id);if(!d.length){let r=e.results.find((y)=>y.id===p.id);a.push(`- ${g(p.title)} (\`${p.path}\`): ${p.skip?g(p.skip):r?"the last capture failed.":"not captured yet."}`);continue}f.push(`### ${g(p.title)}`,"",g(d[0].description),"",...d[0].reason?[g(d[0].reason),""]:[],`Address: \`${p.path}\``,"");for(let r of d)f.push("<figure>",` <img src="${u(`${o}/${r.file}`)}" alt="${u(`${r.title}, ${r.viewport.name}`)}" width="${r.viewport.width}" height="${r.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${r.viewport.width}px;height:auto">`,` <figcaption>${u(r.viewport.name)}, ${r.viewport.width} by ${r.viewport.height}${r.profile==="default"?"":`, signed in as ${u(r.profile)}`}</figcaption>`,"</figure>","")}if(f.length)c.push(`## ${g(t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," "))}`,"",...f)}if(a.length)c.push("## Not pictured","","These screens are part of the application and have no picture here.","",...a,"");return`${c.join(`
2
+ import{Mp4Muxer as A}from"@ts-videos/mp4";import{BufferTarget as O}from"ts-videos";function y(e={}){let i=Bun.serve({port:0,hostname:"127.0.0.1",fetch(s){let o=e[new URL(s.url).pathname];if(o)return new Response(Bun.file(o),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${i.port}/`,stop:()=>{i.stop(!0)}}}var P=["6400","4d00","42e0"],B=(e)=>`(() => {
3
+ if (window.__stacksFilm) return true
4
+ const b64 = bytes => { let text = ''; for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(text) }
5
+ const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
6
+ film.start = async (width, height) => {
7
+ if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
8
+ film.width = width; film.height = height
9
+ const level = width * height > 2097152 ? '33' : '28'
10
+ for (const profile of ${JSON.stringify(P)}) {
11
+ const config = { codec: 'avc1.' + profile + level, width, height, bitrate: ${e.bitrate??0} || Math.max(1500000, Math.round(width * height * 3)), framerate: ${e.fps}, avc: { format: 'avc' } }
12
+ const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
13
+ if (!support || !support.supported) continue
14
+ film.canvas = new OffscreenCanvas(width, height)
15
+ film.context = film.canvas.getContext('2d')
16
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, width, height)
17
+ film.encoder = new VideoEncoder({
18
+ output(chunk, meta) {
19
+ const bytes = new Uint8Array(chunk.byteLength); chunk.copyTo(bytes)
20
+ const description = meta && meta.decoderConfig && meta.decoderConfig.description
21
+ if (description) film.description = b64(new Uint8Array(description.buffer || description, description.byteOffset || 0, description.byteLength))
22
+ film.chunks.push([chunk.type === 'key' ? 1 : 0, chunk.timestamp, b64(bytes)])
23
+ },
24
+ error(error) { film.error = String(error && error.message || error) },
25
+ })
26
+ film.encoder.configure(config)
27
+ return
28
+ }
29
+ throw new Error('This browser cannot encode H.264 video at ' + width + ' by ' + height)
30
+ }
31
+ film.add = async (picture, type, frames) => {
32
+ if (picture) {
33
+ const bitmap = await createImageBitmap(await (await fetch('data:' + type + ';base64,' + picture)).blob())
34
+ if (!film.encoder) await film.start(${e.width?Math.ceil(e.width/2)*2:"Math.ceil(bitmap.width / 2) * 2"}, ${e.height?Math.ceil(e.height/2)*2:"Math.ceil(bitmap.height / 2) * 2"})
35
+ const scale = Math.min(film.width / bitmap.width, film.height / bitmap.height, 1)
36
+ const [w, h] = [bitmap.width * scale, bitmap.height * scale]
37
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
38
+ film.context.drawImage(bitmap, (film.width - w) / 2, (film.height - h) / 2, w, h)
39
+ bitmap.close()
40
+ }
41
+ if (!film.encoder) throw new Error('A film starts with a picture')
42
+ for (let i = 0; i < frames; i++) {
43
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
44
+ // A key frame every two seconds keeps seeking quick without costing much.
45
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
46
+ frame.close(); film.frame++
47
+ }
48
+ if (film.encoder.encodeQueueSize > 30) await film.encoder.flush()
49
+ if (film.error) throw new Error(film.error)
50
+ }
51
+ film.open = async (url) => {
52
+ const video = film.video = document.createElement('video')
53
+ video.muted = true; video.playsInline = true; video.preload = 'auto'
54
+ await new Promise((resolve, reject) => {
55
+ video.addEventListener('loadeddata', resolve, { once: true })
56
+ video.addEventListener('error', () => reject(new Error('This browser cannot play the recording')), { once: true })
57
+ video.src = url
58
+ })
59
+ if (!video.videoWidth || !Number.isFinite(video.duration)) throw new Error('The recording has no picture')
60
+ await film.start(Math.ceil(video.videoWidth / 2) * 2, Math.ceil(video.videoHeight / 2) * 2)
61
+ return JSON.stringify({ seconds: video.duration, frames: Math.max(1, Math.round(video.duration * ${e.fps})) })
62
+ }
63
+ // One output frame per tick of this film's clock, each taken from the
64
+ // recording at that moment: a device's variable frame rate becomes steady.
65
+ film.copy = async (from, count, marks) => {
66
+ const video = film.video
67
+ for (let index = from; index < from + count; index++) {
68
+ const time = Math.min(index / ${e.fps}, Math.max(0, video.duration - 0.001))
69
+ if (Math.abs(video.currentTime - time) > 0.0005) {
70
+ await new Promise((resolve, reject) => {
71
+ video.addEventListener('seeked', resolve, { once: true })
72
+ video.addEventListener('error', () => reject(new Error('The recording could not be read')), { once: true })
73
+ video.currentTime = time
74
+ })
75
+ }
76
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
77
+ film.context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
78
+ for (const mark of marks) {
79
+ if (time < mark.start || time > mark.end) continue
80
+ film.context.globalAlpha = 0.9; film.context.strokeStyle = mark.color; film.context.lineWidth = 4
81
+ film.context.strokeRect(Math.round(mark.x - mark.size / 2) + 2, Math.round(mark.y - mark.size / 2) + 2, mark.size - 4, mark.size - 4)
82
+ film.context.globalAlpha = 1
83
+ }
84
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
85
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
86
+ frame.close(); film.frame++
87
+ }
88
+ await film.encoder.flush()
89
+ if (film.error) throw new Error(film.error)
90
+ }
91
+ film.drain = async (last) => {
92
+ if (last && film.encoder) { await film.encoder.flush(); film.encoder.close() }
93
+ if (film.error) throw new Error(film.error)
94
+ return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
+ }
96
+ return true
97
+ })()`,N=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function k(e,i){if(!Number.isInteger(i.fps)||i.fps<1||i.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(B(i));let s=[],o,f={width:0,height:0},m=0,p=async(l)=>{let n=JSON.parse(String(await e(`window.__stacksFilm.drain(${l})`)));if(f={width:n.width,height:n.height},n.description)o=new Uint8Array(Buffer.from(n.description,"base64"));for(let[t,r,a]of n.chunks)s.push([t,r,new Uint8Array(Buffer.from(a,"base64"))])};return{frames:()=>m,async add(l,n){if(!Number.isInteger(n)||n<1)return;let t=l?`${JSON.stringify(Buffer.from(l).toString("base64"))}, ${JSON.stringify(N(l))}`:"null, null";if(await e(`window.__stacksFilm.add(${t}, ${n})`),m+=n,m%(i.fps*20)<n)await p(!1)},async addVideo(l,n=[]){for(let r of n)if(![r.x,r.y,r.size,r.start,r.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(r.color))throw Error("Invalid film mark");let t=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(l)})`)));for(let r=0;r<t.frames;r+=i.fps){let a=Math.min(i.fps,t.frames-r);await e(`window.__stacksFilm.copy(${r}, ${a}, ${JSON.stringify(n)})`),m+=a,await p(!1)}return t.seconds},async finish(){if(await p(!0),!s.length||!o)throw Error("The browser encoded no video");let l=new O,n=new A(l),t=n.addVideoTrack({codec:"h264",width:f.width,height:f.height,frameRate:i.fps,codecDescription:o});for(let[r,a,d]of s)await n.writePacket(t.id,{data:d,timestamp:a/1e6,duration:1/i.fps,isKeyframe:r===1});return await n.finalize(),l.buffer}}}import{createHash as T}from"crypto";import{lstat as U,mkdir as V,readFile as x,rename as S}from"fs/promises";import{dirname as R,isAbsolute as _,join as b,relative as C,resolve as E}from"path";var F="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",M=(e)=>T("sha256").update(e).digest("hex"),g=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),w=(e)=>g(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function q(e,i,s,o){if(e){let f=e.secondsPerScreen??2;if(!Number.isFinite(f)||f<0.2||f>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let m of e.viewports??[])if(!o.some((p)=>p.name===m))throw Error(`Unknown film viewport: ${m}`)}if(i){let f=E(s,i.page);if(_(i.page)||C(s,f).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function G(e,i,s,o,f=process.platform==="darwin"?"webkit":"chrome"){let m=[],p=o.secondsPerScreen??2,l=o.fps??12,n=Math.max(1,Math.round(p*l));if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before filming screens.");let t=y();try{for(let r of s){if(o.viewports?.length&&!o.viewports.includes(r.name))continue;let a=i.filter((h)=>h.status==="captured"&&h.file&&h.viewport.name===r.name);if(!a.length)continue;let d=new Bun.WebView({width:320,height:240,backend:f==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),u;try{await d.navigate(t.url);let h=await k((v)=>d.evaluate(v),{fps:l,width:r.width,height:r.height});for(let v of a)await h.add(new Uint8Array(await x(b(e,v.file))),n);u=await h.finish()}catch(h){throw Error(`The ${r.name} screens could not be filmed: ${h instanceof Error?h.message.slice(0,400):"the browser failed"}`)}finally{d.close()}let c=`film-${r.name}.mp4`;await Bun.write(b(e,`${c}.tmp`),u),await S(b(e,`${c}.tmp`),b(e,c)),m.push({viewport:r.name,file:c,sha256:M(u),screens:a.length,seconds:a.length*n/l})}return m}finally{t.stop()}}function J(e,i){let s=i.base.replace(/\/+$/,""),o=i.title??"Screens",f=e.results.filter((t)=>t.status==="captured"&&t.file),m=["---",`title: ${JSON.stringify(o)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",F,"",`# ${w(o)}`,"",`${new Set(f.map((t)=>t.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let t of e.films??[]){let r=f.find((a)=>a.viewport.name===t.viewport);m.push(`## Walkthrough video (${w(t.viewport)})`,"",`<video controls playsinline preload="none" src="${g(`${s}/${t.file}`)}"${r?` poster="${g(`${s}/${r.file}`)}"`:""} style="width:100%;max-width:${r&&r.viewport.width<600?r.viewport.width:1100}px;height:auto"></video>`,"",`${t.screens} screens in ${Math.round(t.seconds)} seconds. [Download the video](${s}/${t.file}).`,"")}let p=(t)=>t.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",l=new Map;for(let t of e.inventory)l.set(p(t.path),[...l.get(p(t.path))??[],t]);let n=[];for(let[t,r]of[...l].sort(([a],[d])=>a.localeCompare(d))){let a=[];for(let d of r){let u=f.filter((c)=>c.id===d.id);if(!u.length){let c=e.results.find((h)=>h.id===d.id);n.push(`- ${w(d.title)} (\`${d.path}\`): ${d.skip?w(d.skip):c?"the last capture failed.":"not captured yet."}`);continue}a.push(`### ${w(d.title)}`,"",w(u[0].description),"",...u[0].reason?[w(u[0].reason),""]:[],`Address: \`${d.path}\``,"");for(let c of u)a.push("<figure>",` <img src="${g(`${s}/${c.file}`)}" alt="${g(`${c.title}, ${c.viewport.name}`)}" width="${c.viewport.width}" height="${c.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${c.viewport.width}px;height:auto">`,` <figcaption>${g(c.viewport.name)}, ${c.viewport.width} by ${c.viewport.height}${c.profile==="default"?"":`, signed in as ${g(c.profile)}`}</figcaption>`,"</figure>","")}if(a.length)m.push(`## ${w(t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," "))}`,"",...a)}if(n.length)m.push("## Not pictured","","These screens are part of the application and have no picture here.","",...n,"");return`${m.join(`
5
98
  `).trimEnd()}
6
- `}async function I(e,i,o){let s=k(e,o.page);try{if((await N(s)).isSymbolicLink()||!(await _(s,"utf8")).includes(E))throw Error(`Refusing to replace a hand-written page: ${o.page}`)}catch(c){if(c.code!=="ENOENT")throw c}let n=q(i,o);return await R(T(s),{recursive:!0}),await Bun.write(`${s}.tmp`,n),await P(`${s}.tmp`,s),{path:o.page,sha256:F(n)}}export{H as filmScreenshots,E as generatedScreensPage,q as renderScreensPage,G as validateScreenshotPublishing,I as writeScreensPage};
99
+ `}async function K(e,i,s){let o=E(e,s.page);try{if((await U(o)).isSymbolicLink()||!(await x(o,"utf8")).includes(F))throw Error(`Refusing to replace a hand-written page: ${s.page}`)}catch(m){if(m.code!=="ENOENT")throw m}let f=J(i,s);return await V(R(o),{recursive:!0}),await Bun.write(`${o}.tmp`,f),await S(`${o}.tmp`,o),{path:s.page,sha256:M(f)}}export{G as filmScreenshots,F as generatedScreensPage,J as renderScreensPage,q as validateScreenshotPublishing,K as writeScreensPage};
@@ -25,7 +25,7 @@ export declare interface ViewScreen {
25
25
  export declare interface ViewScreenOptions {
26
26
  root?: string
27
27
  directories?: string[]
28
- defaults?: Partial<Pick<ScreenshotPage, 'waitFor' | 'profiles' | 'masks' | 'prepare' | 'ready' | 'reason'>>
28
+ defaults?: Partial<Pick<ScreenshotPage, 'waitFor' | 'profiles' | 'viewports' | 'masks' | 'prepare' | 'ready' | 'reason'>>
29
29
  routes?: Record<string, ViewScreenRule>
30
30
  each?: (view: ViewScreen) => ViewScreenRule
31
31
  extra?: ScreenshotPage[]
@@ -34,6 +34,7 @@ export declare interface ScreenshotPage {
34
34
  model?: string
35
35
  sources?: string[]
36
36
  profiles?: string[]
37
+ viewports?: string[]
37
38
  waitFor: string
38
39
  expectedStatus?: number
39
40
  prepare?: (context: ScreenshotContext) => Promise<void>
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- import{createHash as Le}from"crypto";import{lstat as A,mkdir as K,mkdtemp as ae,readFile as P,rename as G,rm as I,rmdir as qe,stat as Je}from"fs/promises";import{tmpdir as We}from"os";import{dirname as le,isAbsolute as pe,join as g,relative as D,resolve as S}from"path";import{pathToFileURL as _e}from"url";function X(e){let i=`:is(${['input[type="password"]',...e].join(",")})`,c=`${i}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
- ${i}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
- ${c}, ${c}::selection {
2
+ import{createHash as _e}from"crypto";import{lstat as D,mkdir as K,mkdtemp as le,readFile as E,rename as G,rm as q,rmdir as Ie,stat as qe}from"fs/promises";import{tmpdir as ze}from"os";import{dirname as de,isAbsolute as pe,join as g,relative as B,resolve as y}from"path";import{pathToFileURL as Ke}from"url";function X(e){let o=`:is(${['input[type="password"]',...e].join(",")})`,a=`${o}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
+ ${o}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
+ ${a}, ${a}::selection {
5
5
  color: transparent !important;
6
6
  -webkit-text-fill-color: transparent !important;
7
7
  -webkit-text-stroke: 0 transparent !important;
@@ -9,28 +9,121 @@ ${c}, ${c}::selection {
9
9
  caret-color: transparent !important;
10
10
  forced-color-adjust: none !important;
11
11
  }
12
- ${c}::selection { background: transparent !important; }
13
- ${c}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
- ${c}::-webkit-search-cancel-button { visibility: hidden !important; }
15
- `}import{createHash as ue}from"crypto";import{readFile as he}from"fs/promises";import{existsSync as me}from"fs";import{isAbsolute as we,join as ge,relative as ye,resolve as Se}from"path";import{loadModelRegistry as be,modelFiles as Y}from"@stacksjs/orm/model-registry";function L(e){let i=Object.entries(e).map(([r,o])=>{let l=Object.entries(o.attributes??{}),u=o.belongsTo??[],x=(Array.isArray(u)?u:Object.values(u)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),v=o.traits?.useApi,b=o.traits?.useSeeder??o.traits?.seedable,y=(w,F)=>Boolean(F.hidden||F.encrypted||F.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),k=l.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(o.name??r),table:o.table,primaryKey:String(o.primaryKey??"id"),...v?.uri?{api:String(v.uri)}:{},parents:[...new Set([...x,...Array.isArray(b?.after)?b.after.map(String):[]])].sort(),seederCount:typeof b?.count==="number"?b.count:null,factoryFields:l.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:l.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:k,sensitiveFields:l.filter(([w,F])=>y(w,F)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...v?.routes?.includes("show")?["detail"]:[],...v?.middleware?.length?["permission-denied"]:[],...o.traits?.useSoftDeletes||o.traits?.softDeletable?["archived"]:[]])]}}).sort((r,o)=>r.name.localeCompare(o.name)),c=new Set(i.map((r)=>r.name)),t=new Map(i.map((r)=>[r.name,r])),a=[];for(;;){let r=[...t.values()].filter((o)=>o.parents.every((l)=>!c.has(l)||a.includes(l)));if(!r.length)break;for(let o of r)a.push(o.name),t.delete(o.name)}let f=new Set,d=new Map,h=new Map,m=[],n=new Set,s=0;function p(r){d.set(r,s),h.set(r,s++),m.push(r),n.add(r);for(let u of t.get(r)?.parents??[]){if(!t.has(u))continue;if(!d.has(u))p(u),h.set(r,Math.min(h.get(r),h.get(u)));else if(n.has(u))h.set(r,Math.min(h.get(r),d.get(u)))}if(h.get(r)!==d.get(r))return;let o=[],l;do l=m.pop(),n.delete(l),o.push(l);while(l!==r);if(o.length>1||t.get(r)?.parents.includes(r))for(let u of o)f.add(u)}for(let r of t.keys())if(!d.has(r))p(r);return{models:i,creationOrder:a,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(i.flatMap((r)=>r.parents).filter((r)=>!c.has(r)))].sort()}}async function q(e,i={}){if(i===!1)return L({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let c=Se(e,i.directory??"app/Models");if(we(i.directory??"")||ye(e,c).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=i.includeDefaults?ge(e,"storage/framework/defaults/app/Models"):void 0;if(!me(c)&&!t)return L({});let a=[],f=await be({userRoot:c,defaultsRoot:t,onImportError:(m)=>a.push(m)});if(a.length)throw Error(`Cannot inspect screenshot models: ${a.join(", ")}`);let d=L(f),h=[...Y(c),...t?Y(t):[]].sort();return d.sourceHash=ue("sha256").update(Buffer.concat(await Promise.all(h.map((m)=>he(m))))).digest("hex"),d}function J(e,i,c,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let a=i?t.models.filter((h)=>h.name===i):t.models.filter((h)=>h.api&&e.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),f=a.length===1?a[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let d=c[f.name];if(!d)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,m,n)=>{let s=m||n,p=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(p)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=d[p];if(r===void 0||r===""||typeof r!=="string"&&typeof r!=="number"||typeof r==="number"&&!Number.isFinite(r))throw Error(`Screenshot fixture ${f.name} has no ${s}`);return encodeURIComponent(String(r))})}import{createHash as ve}from"crypto";import{lstat as xe,mkdir as $e,mkdtemp as ke,readFile as Ee,rename as ee,rm as Pe}from"fs/promises";import{tmpdir as je}from"os";import{dirname as Oe,isAbsolute as Re,join as T,relative as Fe,resolve as te}from"path";var re="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",se=(e)=>ve("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),B=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1"),Z=(e)=>Math.ceil(e/2)*2;function oe(e,i,c,t){if(e){let a=e.secondsPerScreen??2;if(!Number.isFinite(a)||a<0.2||a>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let f of e.viewports??[])if(!t.some((d)=>d.name===f))throw Error(`Unknown film viewport: ${f}`)}if(i){let a=te(c,i.page);if(Re(i.page)||Fe(c,a).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function W(e,i,c,t){let a=[],f=t.secondsPerScreen??2,d=t.fps??12,h=await ke(T(je(),"stacks-screen-film-"));try{for(let m of c){if(t.viewports?.length&&!t.viewports.includes(m.name))continue;let n=i.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===m.name);if(!n.length)continue;let s=(y)=>`file '${T(e,y).replaceAll("'","'\\''")}'`,p=[...n.flatMap((y)=>[s(y.file),`duration ${f}`]),s(n.at(-1).file)].join(`
16
- `);await Bun.write(T(h,`${m.name}.txt`),`${p}
17
- `);let[r,o]=[Z(m.width),Z(m.height)],l=T(h,`${m.name}.mp4`),u;try{u=Bun.spawn([t.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-y","-f","concat","-safe","0","-i",T(h,`${m.name}.txt`),"-an","-vf",`scale=${r}:${o}:force_original_aspect_ratio=decrease,pad=${r}:${o}:(ow-iw)/2:(oh-ih)/2:color=white,format=yuv420p`,"-r",String(d),"-c:v","libx264","-preset","veryfast","-movflags","+faststart",l],{stdin:"ignore",stdout:"ignore",stderr:"pipe"})}catch{throw Error("FFmpeg is required to film the captured screens; install it or set film.ffmpeg")}let R=setTimeout(()=>u.kill(),600000),[x,v]=await Promise.all([u.exited,new Response(u.stderr).text()]);if(clearTimeout(R),x!==0)throw Error(`FFmpeg could not film the ${m.name} screens: ${v.trim().slice(0,400)||`exit ${x}`}`);let b=`film-${m.name}.mp4`;await ee(l,T(e,b)).catch(async()=>{await Bun.write(T(e,b),Bun.file(l))}),a.push({viewport:m.name,file:b,sha256:se(new Uint8Array(await Bun.file(T(e,b)).arrayBuffer())),screens:n.length,seconds:n.length*f})}return a}finally{await Pe(h,{recursive:!0,force:!0})}}function Me(e,i){let c=i.base.replace(/\/+$/,""),t=i.title??"Screens",a=e.results.filter((n)=>n.status==="captured"&&n.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",re,"",`# ${B(t)}`,"",`${new Set(a.map((n)=>n.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let n of e.films??[]){let s=a.find((p)=>p.viewport.name===n.viewport);f.push(`## Walkthrough video (${B(n.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${c}/${n.file}`)}"${s?` poster="${N(`${c}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${n.screens} screens in ${Math.round(n.seconds)} seconds. [Download the video](${c}/${n.file}).`,"")}let d=(n)=>n.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",h=new Map;for(let n of e.inventory)h.set(d(n.path),[...h.get(d(n.path))??[],n]);let m=[];for(let[n,s]of[...h].sort(([p],[r])=>p.localeCompare(r))){let p=[];for(let r of s){let o=a.filter((l)=>l.id===r.id);if(!o.length){let l=e.results.find((u)=>u.id===r.id);m.push(`- ${B(r.title)} (\`${r.path}\`): ${r.skip?B(r.skip):l?"the last capture failed.":"not captured yet."}`);continue}p.push(`### ${B(r.title)}`,"",B(o[0].description),"",...o[0].reason?[B(o[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let l of o)p.push("<figure>",` <img src="${N(`${c}/${l.file}`)}" alt="${N(`${l.title}, ${l.viewport.name}`)}" width="${l.viewport.width}" height="${l.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${l.viewport.width}px;height:auto">`,` <figcaption>${N(l.viewport.name)}, ${l.viewport.width} by ${l.viewport.height}${l.profile==="default"?"":`, signed in as ${N(l.profile)}`}</figcaption>`,"</figure>","")}if(p.length)f.push(`## ${B(n[0].toUpperCase()+n.slice(1).replace(/[-_]+/g," "))}`,"",...p)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
12
+ ${a}::selection { background: transparent !important; }
13
+ ${a}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
+ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
15
+ `}import{createHash as me}from"crypto";import{readFile as we}from"fs/promises";import{existsSync as ge}from"fs";import{isAbsolute as ye,join as be,relative as Se,resolve as ve}from"path";import{loadModelRegistry as ke,modelFiles as Y}from"@stacksjs/orm/model-registry";function H(e){let o=Object.entries(e).map(([s,n])=>{let f=Object.entries(n.attributes??{}),h=n.belongsTo??[],M=(Array.isArray(h)?h:Object.values(h)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),S=n.traits?.useApi,O=n.traits?.useSeeder??n.traits?.seedable,F=(w,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),v=f.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(n.name??s),table:n.table,primaryKey:String(n.primaryKey??"id"),...S?.uri?{api:String(S.uri)}:{},parents:[...new Set([...M,...Array.isArray(O?.after)?O.after.map(String):[]])].sort(),seederCount:typeof O?.count==="number"?O.count:null,factoryFields:f.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:f.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:v,sensitiveFields:f.filter(([w,R])=>F(w,R)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...S?.routes?.includes("show")?["detail"]:[],...S?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((s,n)=>s.name.localeCompare(n.name)),a=new Set(o.map((s)=>s.name)),t=new Map(o.map((s)=>[s.name,s])),l=[];for(;;){let s=[...t.values()].filter((n)=>n.parents.every((f)=>!a.has(f)||l.includes(f)));if(!s.length)break;for(let n of s)l.push(n.name),t.delete(n.name)}let d=new Set,p=new Map,u=new Map,m=[],i=new Set,r=0;function c(s){p.set(s,r),u.set(s,r++),m.push(s),i.add(s);for(let h of t.get(s)?.parents??[]){if(!t.has(h))continue;if(!p.has(h))c(h),u.set(s,Math.min(u.get(s),u.get(h)));else if(i.has(h))u.set(s,Math.min(u.get(s),p.get(h)))}if(u.get(s)!==p.get(s))return;let n=[],f;do f=m.pop(),i.delete(f),n.push(f);while(f!==s);if(n.length>1||t.get(s)?.parents.includes(s))for(let h of n)d.add(h)}for(let s of t.keys())if(!p.has(s))c(s);return{models:o,creationOrder:l,cycles:[...d].sort(),blocked:[...t.keys()].filter((s)=>!d.has(s)),externalParents:[...new Set(o.flatMap((s)=>s.parents).filter((s)=>!a.has(s)))].sort()}}async function L(e,o={}){if(o===!1)return H({});if(o.directory!==void 0&&!o.directory.trim())throw Error("Model directory must not be empty");let a=ve(e,o.directory??"app/Models");if(ye(o.directory??"")||Se(e,a).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=o.includeDefaults?be(e,"storage/framework/defaults/app/Models"):void 0;if(!ge(a)&&!t)return H({});let l=[],d=await ke({userRoot:a,defaultsRoot:t,onImportError:(m)=>l.push(m)});if(l.length)throw Error(`Cannot inspect screenshot models: ${l.join(", ")}`);let p=H(d),u=[...Y(a),...t?Y(t):[]].sort();return p.sourceHash=me("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>we(m))))).digest("hex"),p}function W(e,o,a,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let l=o?t.models.filter((u)=>u.name===o):t.models.filter((u)=>u.api&&e.replace(/^\//,"").startsWith(`${u.api.replace(/^\//,"")}/`)),d=l.length===1?l[0]:void 0;if(!d)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=a[d.name];if(!p)throw Error(`No screenshot fixture supplied for ${d.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,m,i)=>{let r=m||i,c=r==="id"?d.primaryKey:r;if(d.sensitiveFields.includes(c)||/token|secret|password/i.test(r))throw Error(`Refusing to publish a sensitive route parameter: ${r}`);let s=p[c];if(s===void 0||s===""||typeof s!=="string"&&typeof s!=="number"||typeof s==="number"&&!Number.isFinite(s))throw Error(`Screenshot fixture ${d.name} has no ${r}`);return encodeURIComponent(String(s))})}import{Mp4Muxer as xe}from"@ts-videos/mp4";import{BufferTarget as $e}from"ts-videos";function Z(e={}){let o=Bun.serve({port:0,hostname:"127.0.0.1",fetch(a){let t=e[new URL(a.url).pathname];if(t)return new Response(Bun.file(t),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${o.port}/`,stop:()=>{o.stop(!0)}}}var Ee=["6400","4d00","42e0"],Pe=(e)=>`(() => {
16
+ if (window.__stacksFilm) return true
17
+ const b64 = bytes => { let text = ''; for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(text) }
18
+ const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
19
+ film.start = async (width, height) => {
20
+ if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
21
+ film.width = width; film.height = height
22
+ const level = width * height > 2097152 ? '33' : '28'
23
+ for (const profile of ${JSON.stringify(Ee)}) {
24
+ const config = { codec: 'avc1.' + profile + level, width, height, bitrate: ${e.bitrate??0} || Math.max(1500000, Math.round(width * height * 3)), framerate: ${e.fps}, avc: { format: 'avc' } }
25
+ const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
26
+ if (!support || !support.supported) continue
27
+ film.canvas = new OffscreenCanvas(width, height)
28
+ film.context = film.canvas.getContext('2d')
29
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, width, height)
30
+ film.encoder = new VideoEncoder({
31
+ output(chunk, meta) {
32
+ const bytes = new Uint8Array(chunk.byteLength); chunk.copyTo(bytes)
33
+ const description = meta && meta.decoderConfig && meta.decoderConfig.description
34
+ if (description) film.description = b64(new Uint8Array(description.buffer || description, description.byteOffset || 0, description.byteLength))
35
+ film.chunks.push([chunk.type === 'key' ? 1 : 0, chunk.timestamp, b64(bytes)])
36
+ },
37
+ error(error) { film.error = String(error && error.message || error) },
38
+ })
39
+ film.encoder.configure(config)
40
+ return
41
+ }
42
+ throw new Error('This browser cannot encode H.264 video at ' + width + ' by ' + height)
43
+ }
44
+ film.add = async (picture, type, frames) => {
45
+ if (picture) {
46
+ const bitmap = await createImageBitmap(await (await fetch('data:' + type + ';base64,' + picture)).blob())
47
+ if (!film.encoder) await film.start(${e.width?Math.ceil(e.width/2)*2:"Math.ceil(bitmap.width / 2) * 2"}, ${e.height?Math.ceil(e.height/2)*2:"Math.ceil(bitmap.height / 2) * 2"})
48
+ const scale = Math.min(film.width / bitmap.width, film.height / bitmap.height, 1)
49
+ const [w, h] = [bitmap.width * scale, bitmap.height * scale]
50
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
51
+ film.context.drawImage(bitmap, (film.width - w) / 2, (film.height - h) / 2, w, h)
52
+ bitmap.close()
53
+ }
54
+ if (!film.encoder) throw new Error('A film starts with a picture')
55
+ for (let i = 0; i < frames; i++) {
56
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
57
+ // A key frame every two seconds keeps seeking quick without costing much.
58
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
59
+ frame.close(); film.frame++
60
+ }
61
+ if (film.encoder.encodeQueueSize > 30) await film.encoder.flush()
62
+ if (film.error) throw new Error(film.error)
63
+ }
64
+ film.open = async (url) => {
65
+ const video = film.video = document.createElement('video')
66
+ video.muted = true; video.playsInline = true; video.preload = 'auto'
67
+ await new Promise((resolve, reject) => {
68
+ video.addEventListener('loadeddata', resolve, { once: true })
69
+ video.addEventListener('error', () => reject(new Error('This browser cannot play the recording')), { once: true })
70
+ video.src = url
71
+ })
72
+ if (!video.videoWidth || !Number.isFinite(video.duration)) throw new Error('The recording has no picture')
73
+ await film.start(Math.ceil(video.videoWidth / 2) * 2, Math.ceil(video.videoHeight / 2) * 2)
74
+ return JSON.stringify({ seconds: video.duration, frames: Math.max(1, Math.round(video.duration * ${e.fps})) })
75
+ }
76
+ // One output frame per tick of this film's clock, each taken from the
77
+ // recording at that moment: a device's variable frame rate becomes steady.
78
+ film.copy = async (from, count, marks) => {
79
+ const video = film.video
80
+ for (let index = from; index < from + count; index++) {
81
+ const time = Math.min(index / ${e.fps}, Math.max(0, video.duration - 0.001))
82
+ if (Math.abs(video.currentTime - time) > 0.0005) {
83
+ await new Promise((resolve, reject) => {
84
+ video.addEventListener('seeked', resolve, { once: true })
85
+ video.addEventListener('error', () => reject(new Error('The recording could not be read')), { once: true })
86
+ video.currentTime = time
87
+ })
88
+ }
89
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
90
+ film.context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
91
+ for (const mark of marks) {
92
+ if (time < mark.start || time > mark.end) continue
93
+ film.context.globalAlpha = 0.9; film.context.strokeStyle = mark.color; film.context.lineWidth = 4
94
+ film.context.strokeRect(Math.round(mark.x - mark.size / 2) + 2, Math.round(mark.y - mark.size / 2) + 2, mark.size - 4, mark.size - 4)
95
+ film.context.globalAlpha = 1
96
+ }
97
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
98
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
99
+ frame.close(); film.frame++
100
+ }
101
+ await film.encoder.flush()
102
+ if (film.error) throw new Error(film.error)
103
+ }
104
+ film.drain = async (last) => {
105
+ if (last && film.encoder) { await film.encoder.flush(); film.encoder.close() }
106
+ if (film.error) throw new Error(film.error)
107
+ return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
108
+ }
109
+ return true
110
+ })()`,Me=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function ee(e,o){if(!Number.isInteger(o.fps)||o.fps<1||o.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(Pe(o));let a=[],t,l={width:0,height:0},d=0,p=async(u)=>{let m=JSON.parse(String(await e(`window.__stacksFilm.drain(${u})`)));if(l={width:m.width,height:m.height},m.description)t=new Uint8Array(Buffer.from(m.description,"base64"));for(let[i,r,c]of m.chunks)a.push([i,r,new Uint8Array(Buffer.from(c,"base64"))])};return{frames:()=>d,async add(u,m){if(!Number.isInteger(m)||m<1)return;let i=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(Me(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${i}, ${m})`),d+=m,d%(o.fps*20)<m)await p(!1)},async addVideo(u,m=[]){for(let r of m)if(![r.x,r.y,r.size,r.start,r.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(r.color))throw Error("Invalid film mark");let i=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let r=0;r<i.frames;r+=o.fps){let c=Math.min(o.fps,i.frames-r);await e(`window.__stacksFilm.copy(${r}, ${c}, ${JSON.stringify(m)})`),d+=c,await p(!1)}return i.seconds},async finish(){if(await p(!0),!a.length||!t)throw Error("The browser encoded no video");let u=new $e,m=new xe(u),i=m.addVideoTrack({codec:"h264",width:l.width,height:l.height,frameRate:o.fps,codecDescription:t});for(let[r,c,s]of a)await m.writePacket(i.id,{data:s,timestamp:c/1e6,duration:1/o.fps,isKeyframe:r===1});return await m.finalize(),u.buffer}}}import{createHash as Oe}from"crypto";import{lstat as Fe,mkdir as je,readFile as te,rename as re}from"fs/promises";import{dirname as Re,isAbsolute as Te,join as J,relative as Be,resolve as se}from"path";var ie="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",oe=(e)=>Oe("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),T=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function ne(e,o,a,t){if(e){let l=e.secondsPerScreen??2;if(!Number.isFinite(l)||l<0.2||l>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let d of e.viewports??[])if(!t.some((p)=>p.name===d))throw Error(`Unknown film viewport: ${d}`)}if(o){let l=se(a,o.page);if(Te(o.page)||Be(a,l).startsWith("..")||!o.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(o.base)||o.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function _(e,o,a,t,l=process.platform==="darwin"?"webkit":"chrome"){let d=[],p=t.secondsPerScreen??2,u=t.fps??12,m=Math.max(1,Math.round(p*u));if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before filming screens.");let i=Z();try{for(let r of a){if(t.viewports?.length&&!t.viewports.includes(r.name))continue;let c=o.filter((h)=>h.status==="captured"&&h.file&&h.viewport.name===r.name);if(!c.length)continue;let s=new Bun.WebView({width:320,height:240,backend:l==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),n;try{await s.navigate(i.url);let h=await ee((P)=>s.evaluate(P),{fps:u,width:r.width,height:r.height});for(let P of c)await h.add(new Uint8Array(await te(J(e,P.file))),m);n=await h.finish()}catch(h){throw Error(`The ${r.name} screens could not be filmed: ${h instanceof Error?h.message.slice(0,400):"the browser failed"}`)}finally{s.close()}let f=`film-${r.name}.mp4`;await Bun.write(J(e,`${f}.tmp`),n),await re(J(e,`${f}.tmp`),J(e,f)),d.push({viewport:r.name,file:f,sha256:oe(n),screens:c.length,seconds:c.length*m/u})}return d}finally{i.stop()}}function Ne(e,o){let a=o.base.replace(/\/+$/,""),t=o.title??"Screens",l=e.results.filter((i)=>i.status==="captured"&&i.file),d=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(o.description??"Every screen of the application, captured automatically from its views.")}`,"---","",ie,"",`# ${T(t)}`,"",`${new Set(l.map((i)=>i.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let i of e.films??[]){let r=l.find((c)=>c.viewport.name===i.viewport);d.push(`## Walkthrough video (${T(i.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${a}/${i.file}`)}"${r?` poster="${N(`${a}/${r.file}`)}"`:""} style="width:100%;max-width:${r&&r.viewport.width<600?r.viewport.width:1100}px;height:auto"></video>`,"",`${i.screens} screens in ${Math.round(i.seconds)} seconds. [Download the video](${a}/${i.file}).`,"")}let p=(i)=>i.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",u=new Map;for(let i of e.inventory)u.set(p(i.path),[...u.get(p(i.path))??[],i]);let m=[];for(let[i,r]of[...u].sort(([c],[s])=>c.localeCompare(s))){let c=[];for(let s of r){let n=l.filter((f)=>f.id===s.id);if(!n.length){let f=e.results.find((h)=>h.id===s.id);m.push(`- ${T(s.title)} (\`${s.path}\`): ${s.skip?T(s.skip):f?"the last capture failed.":"not captured yet."}`);continue}c.push(`### ${T(s.title)}`,"",T(n[0].description),"",...n[0].reason?[T(n[0].reason),""]:[],`Address: \`${s.path}\``,"");for(let f of n)c.push("<figure>",` <img src="${N(`${a}/${f.file}`)}" alt="${N(`${f.title}, ${f.viewport.name}`)}" width="${f.viewport.width}" height="${f.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${f.viewport.width}px;height:auto">`,` <figcaption>${N(f.viewport.name)}, ${f.viewport.width} by ${f.viewport.height}${f.profile==="default"?"":`, signed in as ${N(f.profile)}`}</figcaption>`,"</figure>","")}if(c.length)d.push(`## ${T(i[0].toUpperCase()+i.slice(1).replace(/[-_]+/g," "))}`,"",...c)}if(m.length)d.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${d.join(`
18
111
  `).trimEnd()}
19
- `}async function _(e,i,c){let t=te(e,c.page);try{if((await xe(t)).isSymbolicLink()||!(await Ee(t,"utf8")).includes(re))throw Error(`Refusing to replace a hand-written page: ${c.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let a=Me(i,c);return await $e(Oe(t),{recursive:!0}),await Bun.write(`${t}.tmp`,a),await ee(`${t}.tmp`,t),{path:c.page,sha256:se(a)}}import{createRouter as Te}from"@stacksjs/stx";import{readFileSync as Be}from"fs";import{relative as De,resolve as Ne}from"path";var ne=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Ce=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Ue(e){try{return Be(e,"utf8")}catch{return""}}function Ve(e,i){let c=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(c)return c;let t=i.split("/").filter(Boolean).map((a)=>a.startsWith("[")?`by ${ne(a.slice(1,-1).replace(/^\.\.\./,""))}`:ne(a));return t.length?Ce(t.join(" / ")):"Home"}function ie(e={}){let i=Ne(e.root??process.cwd()),c=[],t=new Set;for(let a of e.directories??["resources/views"])for(let f of Te(i,{pagesDir:a,emit:!1})){let d=f.pattern.replace(/\*(\w*)/g,(p,r)=>`[...${r||"path"}]`).replace(/:(\w+)/g,"[$1]"),h=d.split("/").filter(Boolean).map((p)=>p.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=h;for(let p=2;t.has(m);p++)m=`${h}-${p}`;t.add(m);let n=Ue(f.filePath),s=n.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];c.push({id:m,route:d,source:De(i,f.filePath).replaceAll("\\","/"),group:d.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:Ve(n,d),...s?{layout:s}:{},text:n})}return c.sort((a,f)=>a.route<f.route?-1:a.route>f.route?1:0)}function Ae(e={}){let i=[],c=new Set;for(let t of ie(e)){c.add(t.route);let a=[e.each?.(t),e.routes?.[t.route]],f={id:t.id,title:t.title,path:t.route,description:`The ${t.title} screen, served at ${t.route}.`,waitFor:"body",...e.defaults,sources:[t.source]};for(let d of a){if(d===void 0)continue;if(d===!1||typeof d==="string"){f.skip=d||"Left out of the screen documentation on purpose.";continue}Object.assign(f,d)}if(t.dynamic&&typeof f.path==="string"&&f.path===t.route&&!f.model&&!f.skip){if(e.strict)throw Error(`Dynamic view needs a concrete path or model: ${t.route} (${t.source})`);f.skip=`Needs a seeded example: give ${t.route} a concrete path, fixture resolver or model.`}if(typeof f.path==="function"&&!f.route)f.route=t.route;i.push(f)}for(let t of Object.keys(e.routes??{}))if(!c.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...i,...e.extra??[]]}import{spawnOwnedProcess as Ie}from"@stacksjs/cli/owned-process";var V="0.75.653";var xt=(e)=>e,O=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],H=(e)=>Le("sha256").update(e).digest("hex"),z=(e)=>/^[a-z0-9][a-z0-9._-]*$/i.test(e)&&!e.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e),ce=(e)=>{let i=new URL(e);return i.origin+i.pathname};async function fe(e,i=process.cwd()){let c=new URL(e.baseUrl);if(!["http:","https:"].includes(c.protocol)||c.username||c.password||c.search||c.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!e.outDir||!e.pages.length)throw Error("outDir and at least one page are required");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(e.backend&&!["webkit","chrome"].includes(e.backend))throw Error("backend must be webkit or chrome");if(e.requireHttpStatus!==void 0&&typeof e.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let t=Object.keys(e.profiles??{default:{}});if(!t.length||t.some((n)=>!z(n)))throw Error("Profile names must be safe filenames");let a=new Set,f=new Set;for(let n of e.pages){if(!z(n.id)||a.has(n.id))throw Error(`Duplicate or invalid screen id: ${n.id}`);if(a.add(n.id),n.expectedStatus!==void 0&&(!Number.isInteger(n.expectedStatus)||n.expectedStatus<100||n.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${n.id}`);if(!n.title.trim()||!n.description.trim()||!n.waitFor.trim())throw Error(`Screen ${n.id} needs title, description and waitFor`);if(typeof n.path!=="string"&&(typeof n.path!=="function"||!n.route))throw Error(`Screen ${n.id} needs a route pattern for its path resolver`);let s=new URL(typeof n.path==="string"?n.path:n.route,c);if(s.origin!==c.origin||s.username||s.password)throw Error(`Screen ${n.id} must stay on baseUrl's origin`);if(n.profiles?.some((p)=>!t.includes(p))||n.profiles?.length===0)throw Error(`Unknown or empty profiles for ${n.id}`);for(let p of n.sources??[]){let r=S(i,p);if(D(i,r).startsWith("..")||pe(p))throw Error(`Source must be inside the project: ${p}`);await P(r),f.add(D(i,r).replaceAll("\\","/"))}}let d=new Set;for(let n of e.viewports??O){if(!z(n.name)||d.has(n.name)||![n.width,n.height].every((s)=>Number.isInteger(s)&&s>=200&&s<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");d.add(n.name)}if(!d.size)throw Error("At least one viewport is required");for(let n of e.inputs??[])await P(S(i,n));oe(e.film===!0?{}:e.film,e.docs,i,e.viewports??O);let h=[],m=new Set;for(let n of e.coverage?.directories??[]){let s=S(i,n);if(D(i,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Je(s)).isDirectory())throw Error(`Missing coverage directory: ${n}`);let p=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){p++;let o=D(i,g(s,r)).replaceAll("\\","/");if(m.add(o),!f.has(o)&&!e.coverage?.exclude?.[o]?.trim())h.push(o)}if(!p)throw Error(`No .stx screens found in ${n}`)}for(let[n,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(n))throw Error(`Stale or unexplained coverage exclusion: ${n}`);if(h.length)throw Error(`Undocumented screens:
20
- ${h.sort().join(`
21
- `)}`)}async function Q(e){let i=(await import(_e(e).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function ze(e,i){let c=Date.now()+i;while(!await e()){if(Date.now()>=c)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function de(e,i){let c=e instanceof Error?e.message:"Screenshot capture failed";for(let t of i.redactEnv??[]){let a=process.env[t];if(a)c=c.replaceAll(a,"[redacted]")}return c.slice(0,1000)}async function Ke(e,i,c){let t=await Q(e),a=S(c.root),f=S(a,c.outDir??t.outDir),d=[],h=await q(a,t.models);try{let m={...t.fixtures,...await t.data?.prepare(h)},n=t.backend??(process.platform==="darwin"?"webkit":"chrome"),s=t.timeoutMs??30000;for(let p of t.viewports??O){if(c.viewports?.length&&!c.viewports.includes(p.name))continue;for(let r of t.pages){if(c.only?.length&&!c.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(i))continue;let o={id:r.id,profile:i,viewport:p,title:r.title,description:r.description,...r.reason?{reason:r.reason}:{},path:new URL(typeof r.path==="string"?r.path:r.route,t.baseUrl).pathname,status:"failed"};if(d.push(o),r.skip){o.status="skipped",o.error=r.skip,process.send?.({type:"screenshot-result",result:o});continue}let l="starting the browser",u,R;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");u=new Bun.WebView({width:p.width,height:p.height,backend:n==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:m,models:h,profile:i}):J(r.path,r.model,m,h),v=new URL(x,t.baseUrl);if(v.origin!==new URL(t.baseUrl).origin||v.username||v.password)throw Error("Resolved screenshot path must stay on the configured origin");let b={...r,path:x},y={view:u,baseUrl:t.baseUrl,profile:i,viewport:p,page:b};o.path=v.pathname,l="preparing the review profile",await t.profiles?.[i]?.prepare?.(y),l="opening the screen",await u.navigate(new URL(b.path,t.baseUrl).href),l="checking the document HTTP status";let k=Number(await u.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(k)&&k>=100&&k<=599)y.httpStatus=o.httpStatus=k;if(!y.httpStatus&&(t.requireHttpStatus||r.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(r.expectedStatus!==void 0?y.httpStatus!==r.expectedStatus:k>=400)throw Error(`The screen returned HTTP ${k}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);l="preparing the screen state",await r.prepare?.(y),l="waiting for screen readiness",await ze(async()=>Boolean(await u.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(y)),s);let w=String(await u.evaluate("location.href"));if(ce(w)!==ce(new URL(b.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(l="loading fonts and visible images",await u.evaluate(`(async () => {
112
+ `}async function I(e,o,a){let t=se(e,a.page);try{if((await Fe(t)).isSymbolicLink()||!(await te(t,"utf8")).includes(ie))throw Error(`Refusing to replace a hand-written page: ${a.page}`)}catch(d){if(d.code!=="ENOENT")throw d}let l=Ne(o,a);return await je(Re(t),{recursive:!0}),await Bun.write(`${t}.tmp`,l),await re(`${t}.tmp`,t),{path:a.page,sha256:oe(l)}}import{createRouter as Ue}from"@stacksjs/stx";import{readFileSync as Ce}from"fs";import{relative as Ae,resolve as De}from"path";var ae=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Ve=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function He(e){try{return Ce(e,"utf8")}catch{return""}}function Le(e,o){let a=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(a)return a;let t=o.split("/").filter(Boolean).map((l)=>l.startsWith("[")?`by ${ae(l.slice(1,-1).replace(/^\.\.\./,""))}`:ae(l));return t.length?Ve(t.join(" / ")):"Home"}function ce(e={}){let o=De(e.root??process.cwd()),a=[],t=new Set;for(let l of e.directories??["resources/views"])for(let d of Ue(o,{pagesDir:l,emit:!1})){let p=d.pattern.replace(/\*(\w*)/g,(c,s)=>`[...${s||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=p.split("/").filter(Boolean).map((c)=>c.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=u;for(let c=2;t.has(m);c++)m=`${u}-${c}`;t.add(m);let i=He(d.filePath),r=i.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];a.push({id:m,route:p,source:Ae(o,d.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...d.params],dynamic:d.isDynamic,title:Le(i,p),...r?{layout:r}:{},text:i})}return a.sort((l,d)=>l.route<d.route?-1:l.route>d.route?1:0)}function Je(e={}){let o=[],a=new Set;for(let t of ce(e)){a.add(t.route);let l=[e.each?.(t),e.routes?.[t.route]],d={id:t.id,title:t.title,path:t.route,description:`The ${t.title} screen, served at ${t.route}.`,waitFor:"body",...e.defaults,sources:[t.source]};for(let p of l){if(p===void 0)continue;if(p===!1||typeof p==="string"){d.skip=p||"Left out of the screen documentation on purpose.";continue}Object.assign(d,p)}if(t.dynamic&&typeof d.path==="string"&&d.path===t.route&&!d.model&&!d.skip){if(e.strict)throw Error(`Dynamic view needs a concrete path or model: ${t.route} (${t.source})`);d.skip=`Needs a seeded example: give ${t.route} a concrete path, fixture resolver or model.`}if(typeof d.path==="function"&&!d.route)d.route=t.route;o.push(d)}for(let t of Object.keys(e.routes??{}))if(!a.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...o,...e.extra??[]]}import{spawnOwnedProcess as Ge}from"@stacksjs/cli/owned-process";var A="0.75.657";var Ot=(e)=>e,j=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],V=(e)=>_e("sha256").update(e).digest("hex"),z=(e)=>/^[a-z0-9][a-z0-9._-]*$/i.test(e)&&!e.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e),fe=(e)=>{let o=new URL(e);return o.origin+o.pathname};async function he(e,o=process.cwd()){let a=new URL(e.baseUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!e.outDir||!e.pages.length)throw Error("outDir and at least one page are required");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(e.backend&&!["webkit","chrome"].includes(e.backend))throw Error("backend must be webkit or chrome");if(e.requireHttpStatus!==void 0&&typeof e.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let t=Object.keys(e.profiles??{default:{}});if(!t.length||t.some((i)=>!z(i)))throw Error("Profile names must be safe filenames");let l=new Set,d=new Set;for(let i of e.pages){if(!z(i.id)||l.has(i.id))throw Error(`Duplicate or invalid screen id: ${i.id}`);if(l.add(i.id),i.expectedStatus!==void 0&&(!Number.isInteger(i.expectedStatus)||i.expectedStatus<100||i.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${i.id}`);if(!i.title.trim()||!i.description.trim()||!i.waitFor.trim())throw Error(`Screen ${i.id} needs title, description and waitFor`);if(typeof i.path!=="string"&&(typeof i.path!=="function"||!i.route))throw Error(`Screen ${i.id} needs a route pattern for its path resolver`);let r=new URL(typeof i.path==="string"?i.path:i.route,a);if(r.origin!==a.origin||r.username||r.password)throw Error(`Screen ${i.id} must stay on baseUrl's origin`);if(i.profiles?.some((c)=>!t.includes(c))||i.profiles?.length===0)throw Error(`Unknown or empty profiles for ${i.id}`);for(let c of i.sources??[]){let s=y(o,c);if(B(o,s).startsWith("..")||pe(c))throw Error(`Source must be inside the project: ${c}`);await E(s),d.add(B(o,s).replaceAll("\\","/"))}}let p=new Set;for(let i of e.viewports??j){if(!z(i.name)||p.has(i.name)||![i.width,i.height].every((r)=>Number.isInteger(r)&&r>=200&&r<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");p.add(i.name)}if(!p.size)throw Error("At least one viewport is required");for(let i of e.pages)if(i.viewports!==void 0&&(!i.viewports.length||i.viewports.some((r)=>!p.has(r))))throw Error(`Unknown or empty viewports for ${i.id}`);for(let i of e.inputs??[])await E(y(o,i));ne(e.film===!0?{}:e.film,e.docs,o,e.viewports??j);let u=[],m=new Set;for(let i of e.coverage?.directories??[]){let r=y(o,i);if(B(o,r).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await qe(r)).isDirectory())throw Error(`Missing coverage directory: ${i}`);let c=0;for await(let s of new Bun.Glob("**/*.stx").scan({cwd:r,onlyFiles:!0})){c++;let n=B(o,g(r,s)).replaceAll("\\","/");if(m.add(n),!d.has(n)&&!e.coverage?.exclude?.[n]?.trim())u.push(n)}if(!c)throw Error(`No .stx screens found in ${i}`)}for(let[i,r]of Object.entries(e.coverage?.exclude??{}))if(!r.trim()||!m.has(i))throw Error(`Stale or unexplained coverage exclusion: ${i}`);if(u.length)throw Error(`Undocumented screens:
113
+ ${u.sort().join(`
114
+ `)}`)}async function Q(e){let o=(await import(Ke(e).href)).default;if(!o||typeof o!=="object")throw Error("Screenshot configuration must have a default export");return o}async function Qe(e,o){let a=Date.now()+o;while(!await e()){if(Date.now()>=a)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function ue(e,o){let a=e instanceof Error?e.message:"Screenshot capture failed";for(let t of o.redactEnv??[]){let l=process.env[t];if(l)a=a.replaceAll(l,"[redacted]")}return a.slice(0,1000)}async function Xe(e,o,a){let t=await Q(e),l=y(a.root),d=y(l,a.outDir??t.outDir),p=[],u=await L(l,t.models);try{let m={...t.fixtures,...await t.data?.prepare(u)},i=t.backend??(process.platform==="darwin"?"webkit":"chrome"),r=t.timeoutMs??30000;for(let c of t.viewports??j){if(a.viewports?.length&&!a.viewports.includes(c.name))continue;for(let s of t.pages){if(a.only?.length&&!a.only.includes(s.id))continue;if(!(s.profiles??Object.keys(t.profiles??{default:{}})).includes(o))continue;if(s.viewports&&!s.viewports.includes(c.name))continue;let n={id:s.id,profile:o,viewport:c,title:s.title,description:s.description,...s.reason?{reason:s.reason}:{},path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,status:"failed"};if(p.push(n),s.skip){n.status="skipped",n.error=s.skip,process.send?.({type:"screenshot-result",result:n});continue}let f="starting the browser",h,P;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");h=new Bun.WebView({width:c.width,height:c.height,backend:i==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let M=typeof s.path==="function"?await s.path({fixtures:m,models:u,profile:o}):W(s.path,s.model,m,u),S=new URL(M,t.baseUrl);if(S.origin!==new URL(t.baseUrl).origin||S.username||S.password)throw Error("Resolved screenshot path must stay on the configured origin");let O={...s,path:M},F={view:h,baseUrl:t.baseUrl,profile:o,viewport:c,page:O};n.path=S.pathname,f="preparing the review profile",await t.profiles?.[o]?.prepare?.(F),f="opening the screen",await h.navigate(new URL(O.path,t.baseUrl).href),f="checking the document HTTP status";let v=Number(await h.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(v)&&v>=100&&v<=599)F.httpStatus=n.httpStatus=v;if(!F.httpStatus&&(t.requireHttpStatus||s.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(s.expectedStatus!==void 0?F.httpStatus!==s.expectedStatus:v>=400)throw Error(`The screen returned HTTP ${v}${s.expectedStatus!==void 0?` instead of ${s.expectedStatus}`:"; check its route, access and fixture"}`);f="preparing the screen state",await s.prepare?.(F),f="waiting for screen readiness",await Qe(async()=>Boolean(await h.evaluate(`Boolean(document.querySelector(${JSON.stringify(s.waitFor)}))`))&&(!s.ready||await s.ready(F)),r);let w=String(await h.evaluate("location.href"));if(fe(w)!==fe(new URL(O.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(f="loading fonts and visible images",await h.evaluate(`(async () => {
22
115
  const style = document.createElement('style'); style.textContent = '*{animation:none!important;transition:none!important;scroll-behavior:auto!important;caret-color:transparent!important}'; document.head.append(style);
23
- for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
116
+ for (const selector of ${JSON.stringify(s.masks??[])}) document.querySelectorAll(selector);
24
117
  const maskSheet = new CSSStyleSheet();
25
- maskSheet.replaceSync(${JSON.stringify(X(r.masks??[]))});
118
+ maskSheet.replaceSync(${JSON.stringify(X(s.masks??[]))});
26
119
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
27
120
  await document.fonts.ready;
28
121
  for (const image of document.images) { const box=image.getBoundingClientRect(); if(box.bottom>0 && box.top<innerHeight && !image.complete) await new Promise(resolve=>{image.addEventListener('load',resolve,{once:true});image.addEventListener('error',resolve,{once:true})}); }
29
122
  await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
30
- })()`),await u.evaluate("[...document.images].some(image=>{const r=image.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight&&image.complete&&image.naturalWidth===0})"))throw Error("A visible image failed to load");l="saving the screenshot";let C=new Uint8Array(await(await u.screenshot()).arrayBuffer()),E=`${r.id}/${i}-${p.name}.png`,j=g(f,E);await K(le(j),{recursive:!0});let M=g(c.staging,`${r.id}-${i}-${p.name}.png`);await Bun.write(M,C),await G(M,j),o.file=E,o.sha256=H(C),o.status="captured"})(),new Promise((x,v)=>{R=setTimeout(()=>{u?.close(),v(Error("Screenshot deadline exceeded"))},s)})])}catch(x){o.error=`${l}: ${de(x,t)}`}finally{if(R)clearTimeout(R);u?.close(),process.send?.({type:"screenshot-result",result:o})}}}return d}finally{await t.data?.cleanup?.()}}async function $t(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let i=S(e.root??process.cwd()),c=S(i,e.config??"config/screenshots.ts"),t=await Q(c);await fe(t,i);for(let s of e.only??[])if(!t.pages.some((p)=>p.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??O).some((p)=>p.name===s))throw Error(`Unknown viewport: ${s}`);let a=S(i,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),d={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:V,models:await q(i,t.models),configHash:H(Buffer.concat([Buffer.from(V),await P(c),...await Promise.all(f.map((s)=>P(S(i,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return d;if(e.check){let s=JSON.parse(await P(g(a,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==V||s.configHash!==d.configHash||s.models?.sourceHash!==d.models.sourceHash||s.results.some((p)=>p.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let p of t.pages)for(let r of p.profiles??Object.keys(t.profiles??{default:{}}))for(let o of t.viewports??O){let l=s.results.find((u)=>u.id===p.id&&u.profile===r&&u.viewport.name===o.name);if(!l||!p.skip&&l.status!=="captured")throw Error(`Missing screenshot: ${p.id}/${r}-${o.name}`);if(l.file&&(D(a,S(a,l.file)).split(/[\\/]/)[0]===".."||pe(D(a,S(a,l.file)))||H(await P(g(a,l.file)))!==l.sha256))throw Error(`Screenshot bytes changed: ${p.id}`)}for(let p of s.films??[])if(D(a,S(a,p.file)).startsWith("..")||H(await P(g(a,p.file)))!==p.sha256)throw Error(`Screen film changed: ${p.file}`);if(t.film&&!s.films?.length)throw Error("The screen film is missing; capture again");if(t.docs&&(!s.docsPage||s.docsPage.path!==t.docs.page||H(await P(S(i,t.docs.page)))!==s.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return s}let h;try{let s=g(a,"manifest.json");if((await A(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(h=JSON.parse(await P(s,"utf8")),h.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((e.only?.length||e.viewports?.length)&&h.configHash!==d.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(s){if(s.code!=="ENOENT")throw s}let m=new Set(h?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let p=g(a,s.id);try{if((await A(p)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${s.id}`)}catch(r){if(r.code!=="ENOENT")throw r}for(let r of s.profiles??Object.keys(t.profiles??{default:{}}))for(let o of t.viewports??O){let l=`${s.id}/${r}-${o.name}.png`;try{if((await A(g(a,l))).isSymbolicLink()||!m.has(l))throw Error(`Refusing to overwrite an unowned screenshot: ${l}`)}catch(u){if(u.code!=="ENOENT")throw u}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await A(g(a,s))).isSymbolicLink()||!h)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(p){if(p.code!=="ENOENT")throw p}await K(a,{recursive:!0});let n=await ae(g(a,".stacks-screenshots-"));await Bun.write(g(n,"bunfig.toml"),`preload = []
31
- `);try{for(let o of Object.keys(t.profiles??{default:{}})){let l=g(n,`${o}.json`),u=t.pages.filter((E)=>(!e.only?.length||e.only.includes(E.id))&&(E.profiles??Object.keys(t.profiles??{default:{}})).includes(o)),R=u.length*(t.viewports??O).filter((E)=>!e.viewports?.length||e.viewports.includes(E.name)).length;if(!R)continue;let x=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!x)throw Error("An installed Bun is required for screenshot workers");let v=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,b=We(),y=process.platform!=="win32"&&Buffer.byteLength(b)>60?"/tmp":b,k=await ae(g(y,"stx-b-")),w={...process.env,TMPDIR:k,TMP:k,TEMP:k},F,C;try{let E=F=Ie([x,"--no-env-file",`--config=${g(n,"bunfig.toml")}`,v,"--worker",c,o,JSON.stringify({...e,root:i,staging:n}),l],{ownerRuntime:x,cwd:i,env:w,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(M)=>{let U=M;if(U?.type==="screenshot-result"&&U.result)e.onProgress?.(U.result)}});if((await Promise.race([E.exited,new Promise((M,U)=>{C=setTimeout(()=>{E.stop(),U(Error(`Screenshot worker timed out for ${o}`))},R*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${o}`);d.results.push(...JSON.parse(await P(l,"utf8")))}catch(E){for(let j of u)for(let M of t.viewports??O){if(e.viewports?.length&&!e.viewports.includes(M.name))continue;d.results.push({id:j.id,profile:o,viewport:M,title:j.title,description:j.description,path:new URL(typeof j.path==="string"?j.path:j.route,t.baseUrl).pathname,status:"failed",error:de(E,t)})}}finally{if(C)clearTimeout(C);await F?.stop(),await I(k,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let o=JSON.parse(await P(g(a,"manifest.json"),"utf8"));if(o.configHash===d.configHash&&o.models?.sourceHash===d.models.sourceHash){let l=new Set(d.results.map((u)=>`${u.id}/${u.profile}/${u.viewport.name}`));d.results.unshift(...o.results.filter((u)=>!l.has(`${u.id}/${u.profile}/${u.viewport.name}`)))}}catch{}for(let o of d.results){if(o.status!=="failed"||o.file)continue;let l=h?.results.find((u)=>u.id===o.id&&u.profile===o.profile&&u.viewport.name===o.viewport.name);if(l?.file)o.file=l.file,o.sha256=l.sha256}if(!e.only?.length&&!e.viewports?.length){let o=new Set(d.results.map((l)=>l.file).filter(Boolean));for(let l of m){if(!l||o.has(l)||D(a,S(a,l)).startsWith(".."))continue;await I(g(a,l),{force:!0}),await qe(le(g(a,l))).catch(()=>{})}}await K(a,{recursive:!0});let s;try{if(e.publish!==!1){if(t.film)d.films=await W(a,d.results,t.viewports??O,t.film===!0?{}:t.film);if(t.docs)d.docsPage=await _(i,d,t.docs)}}catch(o){s=o}await Bun.write(g(a,"manifest.json.tmp"),`${JSON.stringify(d,null,2)}
32
- `),await G(g(a,"manifest.json.tmp"),g(a,"manifest.json"));let p=(o)=>o.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
33
- `," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${V}. Review the images before publishing.`,""];for(let o of d.results)r.push(`## ${p(o.title)} (${o.profile}, ${o.viewport.name})`,"",p(o.description),"",...o.reason?[p(o.reason),""]:[],o.status==="captured"?`![${p(o.title)}](${o.file})`:`**${o.status}:** ${p(o.error??"No image")}`,"");if(await Bun.write(g(a,"gallery.md"),`${r.join(`
123
+ })()`),await h.evaluate("[...document.images].some(image=>{const r=image.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight&&image.complete&&image.naturalWidth===0})"))throw Error("A visible image failed to load");f="saving the screenshot";let U=new Uint8Array(await(await h.screenshot()).arrayBuffer()),k=`${s.id}/${o}-${c.name}.png`,b=g(d,k);await K(de(b),{recursive:!0});let x=g(a.staging,`${s.id}-${o}-${c.name}.png`);await Bun.write(x,U),await G(x,b),n.file=k,n.sha256=V(U),n.status="captured"})(),new Promise((M,S)=>{P=setTimeout(()=>{h?.close(),S(Error("Screenshot deadline exceeded"))},r)})])}catch(M){n.error=`${f}: ${ue(M,t)}`}finally{if(P)clearTimeout(P);h?.close(),process.send?.({type:"screenshot-result",result:n})}}}return p}finally{await t.data?.cleanup?.()}}async function Ft(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let o=y(e.root??process.cwd()),a=y(o,e.config??"config/screenshots.ts"),t=await Q(a);await he(t,o);for(let r of e.only??[])if(!t.pages.some((c)=>c.id===r))throw Error(`Unknown screen: ${r}`);for(let r of e.viewports??[])if(!(t.viewports??j).some((c)=>c.name===r))throw Error(`Unknown viewport: ${r}`);let l=y(o,e.outDir??t.outDir),d=[...new Set([...t.inputs??[],...t.pages.flatMap((r)=>r.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:A,models:await L(o,t.models),configHash:V(Buffer.concat([Buffer.from(A),await E(a),...await Promise.all(d.map((r)=>E(y(o,r))))])),inventory:t.pages.map((r)=>({id:r.id,title:r.title,path:new URL(typeof r.path==="string"?r.path:r.route,t.baseUrl).pathname,sources:r.sources??[],...r.skip?{skip:r.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return p;if(e.check){let r=JSON.parse(await E(g(l,"manifest.json"),"utf8"));if(r.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(r.generatorVersion!==A||r.configHash!==p.configHash||r.models?.sourceHash!==p.models.sourceHash||r.results.some((c)=>c.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let c of t.pages)for(let s of c.profiles??Object.keys(t.profiles??{default:{}}))for(let n of t.viewports??j){if(c.viewports&&!c.viewports.includes(n.name))continue;let f=r.results.find((h)=>h.id===c.id&&h.profile===s&&h.viewport.name===n.name);if(!f||!c.skip&&f.status!=="captured")throw Error(`Missing screenshot: ${c.id}/${s}-${n.name}`);if(f.file&&(B(l,y(l,f.file)).split(/[\\/]/)[0]===".."||pe(B(l,y(l,f.file)))||V(await E(g(l,f.file)))!==f.sha256))throw Error(`Screenshot bytes changed: ${c.id}`)}for(let c of r.films??[])if(B(l,y(l,c.file)).startsWith("..")||V(await E(g(l,c.file)))!==c.sha256)throw Error(`Screen film changed: ${c.file}`);if(t.film&&!r.films?.length)throw Error("The screen film is missing; capture again");if(t.docs&&(!r.docsPage||r.docsPage.path!==t.docs.page||V(await E(y(o,t.docs.page)))!==r.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return r}let u;try{let r=g(l,"manifest.json");if((await D(r)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(u=JSON.parse(await E(r,"utf8")),u.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((e.only?.length||e.viewports?.length)&&u.configHash!==p.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(r){if(r.code!=="ENOENT")throw r}let m=new Set(u?.results.map((r)=>r.file).filter(Boolean));for(let r of t.pages){let c=g(l,r.id);try{if((await D(c)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${r.id}`)}catch(s){if(s.code!=="ENOENT")throw s}for(let s of r.profiles??Object.keys(t.profiles??{default:{}}))for(let n of t.viewports??j){if(r.viewports&&!r.viewports.includes(n.name))continue;let f=`${r.id}/${s}-${n.name}.png`;try{if((await D(g(l,f))).isSymbolicLink()||!m.has(f))throw Error(`Refusing to overwrite an unowned screenshot: ${f}`)}catch(h){if(h.code!=="ENOENT")throw h}}}for(let r of["gallery.md","manifest.json.tmp"])try{if((await D(g(l,r))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${r}`)}catch(c){if(c.code!=="ENOENT")throw c}await K(l,{recursive:!0});let i=await le(g(l,".stacks-screenshots-"));await Bun.write(g(i,"bunfig.toml"),`preload = []
124
+ `);try{for(let n of Object.keys(t.profiles??{default:{}})){let f=g(i,`${n}.json`),h=t.pages.filter((k)=>(!e.only?.length||e.only.includes(k.id))&&(k.profiles??Object.keys(t.profiles??{default:{}})).includes(n)),P=h.reduce((k,b)=>k+(t.viewports??j).filter((x)=>(!e.viewports?.length||e.viewports.includes(x.name))&&(!b.viewports||b.viewports.includes(x.name))).length,0);if(!P)continue;let M=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!M)throw Error("An installed Bun is required for screenshot workers");let S=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",o):import.meta.path,O=ze(),F=process.platform!=="win32"&&Buffer.byteLength(O)>60?"/tmp":O,v=await le(g(F,"stx-b-")),w={...process.env,TMPDIR:v,TMP:v,TEMP:v},R,U;try{let k=R=Ge([M,"--no-env-file",`--config=${g(i,"bunfig.toml")}`,S,"--worker",a,n,JSON.stringify({...e,root:o,staging:i}),f],{ownerRuntime:M,cwd:o,env:w,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(x)=>{let C=x;if(C?.type==="screenshot-result"&&C.result)e.onProgress?.(C.result)}});if((await Promise.race([k.exited,new Promise((x,C)=>{U=setTimeout(()=>{k.stop(),C(Error(`Screenshot worker timed out for ${n}`))},P*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${n}`);p.results.push(...JSON.parse(await E(f,"utf8")))}catch(k){for(let b of h)for(let x of t.viewports??j){if(e.viewports?.length&&!e.viewports.includes(x.name)||b.viewports&&!b.viewports.includes(x.name))continue;p.results.push({id:b.id,profile:n,viewport:x,title:b.title,description:b.description,path:new URL(typeof b.path==="string"?b.path:b.route,t.baseUrl).pathname,status:"failed",error:ue(k,t)})}}finally{if(U)clearTimeout(U);await R?.stop(),await q(v,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let n=JSON.parse(await E(g(l,"manifest.json"),"utf8"));if(n.configHash===p.configHash&&n.models?.sourceHash===p.models.sourceHash){let f=new Set(p.results.map((h)=>`${h.id}/${h.profile}/${h.viewport.name}`));p.results.unshift(...n.results.filter((h)=>!f.has(`${h.id}/${h.profile}/${h.viewport.name}`)))}}catch{}for(let n of p.results){if(n.status!=="failed"||n.file)continue;let f=u?.results.find((h)=>h.id===n.id&&h.profile===n.profile&&h.viewport.name===n.viewport.name);if(f?.file)n.file=f.file,n.sha256=f.sha256}if(!e.only?.length&&!e.viewports?.length){let n=new Set(p.results.map((f)=>f.file).filter(Boolean));for(let f of m){if(!f||n.has(f)||B(l,y(l,f)).startsWith(".."))continue;await q(g(l,f),{force:!0}),await Ie(de(g(l,f))).catch(()=>{})}}await K(l,{recursive:!0});let r;try{if(e.publish!==!1){if(t.film)p.films=await _(l,p.results,t.viewports??j,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await I(o,p,t.docs)}}catch(n){r=n}await Bun.write(g(l,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
125
+ `),await G(g(l,"manifest.json.tmp"),g(l,"manifest.json"));let c=(n)=>n.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
126
+ `," "),s=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${A}. Review the images before publishing.`,""];for(let n of p.results)s.push(`## ${c(n.title)} (${n.profile}, ${n.viewport.name})`,"",c(n.description),"",...n.reason?[c(n.reason),""]:[],n.status==="captured"?`![${c(n.title)}](${n.file})`:`**${n.status}:** ${c(n.error??"No image")}`,"");if(await Bun.write(g(l,"gallery.md"),`${s.join(`
34
127
  `)}
35
- `),s)throw s;return d}finally{await I(n,{recursive:!0,force:!0})}}async function kt(e={}){let i=S(e.root??process.cwd()),c=await Q(S(i,e.config??"config/screenshots.ts"));await fe(c,i);let t=S(i,e.outDir??c.outDir),a=g(t,"manifest.json");if((await A(a)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await P(a,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(delete f.films,delete f.docsPage,c.film)f.films=await W(t,f.results,c.viewports??O,c.film===!0?{}:c.film);if(c.docs)f.docsPage=await _(i,f,c.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
36
- `),await G(g(t,"manifest.json.tmp"),a),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await Ke(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{$t as captureScreenshots,xt as defineScreenshotConfig,q as discoverScreenshotModels,ie as discoverViews,L as planScreenshotModels,kt as publishScreenshots,Ae as screensFromViews,J as screenshotFixturePath,fe as validateScreenshotConfig};
128
+ `),r)throw r;return p}finally{await q(i,{recursive:!0,force:!0})}}async function jt(e={}){let o=y(e.root??process.cwd()),a=await Q(y(o,e.config??"config/screenshots.ts"));await he(a,o);let t=y(o,e.outDir??a.outDir),l=g(t,"manifest.json");if((await D(l)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let d=JSON.parse(await E(l,"utf8"));if(d.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(delete d.films,delete d.docsPage,a.film)d.films=await _(t,d.results,a.viewports??j,a.film===!0?{}:a.film,a.backend);if(a.docs)d.docsPage=await I(o,d,a.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(d,null,2)}
129
+ `),await G(g(t,"manifest.json.tmp"),l),d}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await Xe(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{Ft as captureScreenshots,Ot as defineScreenshotConfig,L as discoverScreenshotModels,ce as discoverViews,H as planScreenshotModels,jt as publishScreenshots,Je as screensFromViews,W as screenshotFixturePath,he as validateScreenshotConfig};
package/dist/stories.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{createHash as tt,randomUUID as ot}from"crypto";import{createReadStream as nt}from"fs";import{copyFile as at,lstat as _,mkdir as T,open as ct,readFile as S,realpath as dt,rename as Y,rm as ft,writeFile as R}from"fs/promises";import{basename as lt,dirname as W,isAbsolute as et,join as a,relative as P,resolve as b,sep as ut}from"path";import{pathToFileURL as pt}from"url";var X="0.75.653";function xt(t){return t}function Et(t){return t}var C=`stacks-story-recordings-v1
2
+ import{createHash as tt,randomUUID as ot}from"crypto";import{createReadStream as nt}from"fs";import{copyFile as at,lstat as _,mkdir as T,open as ct,readFile as S,realpath as dt,rename as Y,rm as ft,writeFile as R}from"fs/promises";import{basename as lt,dirname as W,isAbsolute as et,join as a,relative as P,resolve as b,sep as ut}from"path";import{pathToFileURL as pt}from"url";var X="0.75.657";function xt(t){return t}function Et(t){return t}var C=`stacks-story-recordings-v1
3
3
  `,z="<!-- Generated by buddy docs:stories. -->",I=(t)=>tt("sha256").update(t).digest("hex"),Z=(t)=>typeof t==="string"&&/^[a-z0-9][a-z0-9-]{0,79}$/.test(t);function v(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replace(/[\r\n]/g," ").replace(/([\\`*_[\]#|])/g,"\\$1")}async function J(t){try{return await _(t),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function g(t,i=t){let n=b(t);while(!0){if(await J(n)){if((await _(n)).isSymbolicLink())throw Error(`Story output cannot traverse a symbolic link: ${n}`)}if(n===b(i))return;let e=W(n);if(e===n)return;n=e}}async function L(t,i){await g(i,t);let n=await _(i);if(!n.isFile()||n.size===0)throw Error(`Missing or empty story artifact: ${i}`);let e=tt("sha256"),c=0;for await(let u of nt(i))e.update(u),c+=u.length;return{path:P(t,i).split(ut).join("/"),sha256:e.digest("hex"),bytes:c}}function B(t,i){let n=b(t,i.path);if(!i.path||et(i.path)||P(t,n).startsWith(".."))throw Error("Story artifact escaped its output directory");return n}async function ht(t){if(!t||!Array.isArray(t.stories)||!t.stories.length)throw Error("Story configuration needs at least one story");let i=new Set,n=(e,c,u,r)=>{if(!Number.isInteger(e)||e<c||e>u)throw Error(`Invalid story ${r}`)};n(t.fps??12,1,60,"fps (1 to 60)"),n(t.holdMs??700,0,30000,"holdMs (0 to 30000)"),n(t.timeoutMs??120000,100,1800000,"timeoutMs (100 to 1800000)");for(let e of t.stories){if(!Z(e.id)||i.has(e.id)||!e.title?.trim())throw Error(`Invalid or duplicate story id/title: ${e.id}`);if(i.add(e.id),!["browser","ios","android"].includes(e.driver?.platform)||typeof e.driver.open!=="function")throw Error(`Invalid driver for story ${e.id}`);if(!Array.isArray(e.scenes)||!e.scenes.length)throw Error(`Story ${e.id} has no scenes`);let c=new Set;for(let u of e.scenes){if(!Z(u.id)||c.has(u.id)||!u.title?.trim()||typeof u.run!=="function")throw Error(`Invalid or duplicate scene in ${e.id}: ${u.id}`);c.add(u.id),n(u.holdMs??t.holdMs??700,0,30000,"scene holdMs"),n(u.timeoutMs??t.timeoutMs??120000,100,1800000,"scene timeoutMs")}}}function wt(t,i){let n=[z,`# ${v(t.title)}`,"",t.description?v(t.description):"","",`Platform: ${t.platform}. Result: **${t.status}**.`,""];if(t.video)n.push(`<video controls playsinline preload="metadata" src="${i}${t.video.path}" poster="${t.scenes.find((e)=>e.screenshot)?.screenshot?i+t.scenes.find((e)=>e.screenshot).screenshot.path:""}"></video>`,"",`[Download video](${i}${t.video.path})`,"");for(let e of t.scenes)if(n.push(`## ${v(e.title)}`,"",`Result: **${e.status}**.${e.startedMs===void 0?"":` Starts at ${(e.startedMs/1000).toFixed(1)}s.`}`,"",e.description?v(e.description):"",""),e.screenshot)n.push(`![${v(e.title)}](${i}${e.screenshot.path})`,"");else n.push("No screenshot was captured for this scene.","");return`${n.join(`
4
4
  `).trimEnd()}
5
5
  `}async function $t(t={}){if(t.list&&t.check)throw Error("Choose --list or --check");let i=await dt(b(t.root??process.cwd())),n=b(i,t.config??"config/stories.ts"),e=await S(n),c=(await import(`${pt(n).href}?story=${I(e)}`)).default;await ht(c);let u=[X,I(e),I(JSON.stringify(c,(s,o)=>typeof o==="function"?o.toString():o))];for(let s of[...c.inputs??[]].sort())u.push(`${s}:${I(await S(b(i,s)))}`);let r=b(i,t.outDir??c.outDir??"docs/stories"),l=c.publishDir===!1?void 0:b(i,c.publishDir??a(W(r),"public",lt(r)));if(l&&(l===r||!P(r,l).startsWith("..")||!P(l,r).startsWith("..")))throw Error("Published media must have a separate directory outside the story output");if(r===i||P(r,i)===""||!P(r,i).startsWith("..")&&!et(P(r,i)))throw Error("Story output must not contain the project root");let p={version:1,configHash:I(u.join(`
@@ -17,7 +17,6 @@ export declare interface BrowserStoryOptions {
17
17
  viewport?: LaunchOptions['viewport']
18
18
  chromePath?: string
19
19
  headless?: boolean
20
- ffmpeg?: string
21
20
  masks?: string[]
22
21
  cursor?: { color?: string, size?: number, moveMs?: number, clickMs?: number }
23
22
  beforeNavigate?: (cdp: Cdp) => Promise<void>
@@ -40,7 +39,6 @@ export declare interface NativeStoryOptions {
40
39
  input?: NativeStoryInput
41
40
  adb?: string
42
41
  xcrun?: string
43
- ffmpeg?: string
44
42
  tapFeedback?: boolean
45
43
  tapColor?: string
46
44
  tapMs?: number
@@ -1,7 +1,102 @@
1
1
  // @bun
2
- import{spawnOwnedProcess as U}from"@stacksjs/cli/owned-process";import{click as q,launch as J,settle as H,waitFor as L}from"@stacksjs/testing/browser";import{randomUUID as R}from"crypto";import{readFile as X,rm as D}from"fs/promises";import{dirname as F,join as j}from"path";function z(e){let r=`:is(${['input[type="password"]',...e].join(",")})`,i=`${r}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
- ${r}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
- ${i}, ${i}::selection {
2
+ import{spawnOwnedProcess as W}from"@stacksjs/cli/owned-process";import{click as te,launch as V,settle as re,waitFor as L}from"@stacksjs/testing/browser";import{randomUUID as J}from"crypto";import{readFile as ie,rm as D}from"fs/promises";import{dirname as j,join as q}from"path";import{Mp4Muxer as Y}from"@ts-videos/mp4";import{BufferTarget as G}from"ts-videos";function R(e={}){let t=Bun.serve({port:0,hostname:"127.0.0.1",fetch(o){let l=e[new URL(o.url).pathname];if(l)return new Response(Bun.file(l),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${t.port}/`,stop:()=>{t.stop(!0)}}}var Q=["6400","4d00","42e0"],Z=(e)=>`(() => {
3
+ if (window.__stacksFilm) return true
4
+ const b64 = bytes => { let text = ''; for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(text) }
5
+ const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
6
+ film.start = async (width, height) => {
7
+ if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
8
+ film.width = width; film.height = height
9
+ const level = width * height > 2097152 ? '33' : '28'
10
+ for (const profile of ${JSON.stringify(Q)}) {
11
+ const config = { codec: 'avc1.' + profile + level, width, height, bitrate: ${e.bitrate??0} || Math.max(1500000, Math.round(width * height * 3)), framerate: ${e.fps}, avc: { format: 'avc' } }
12
+ const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
13
+ if (!support || !support.supported) continue
14
+ film.canvas = new OffscreenCanvas(width, height)
15
+ film.context = film.canvas.getContext('2d')
16
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, width, height)
17
+ film.encoder = new VideoEncoder({
18
+ output(chunk, meta) {
19
+ const bytes = new Uint8Array(chunk.byteLength); chunk.copyTo(bytes)
20
+ const description = meta && meta.decoderConfig && meta.decoderConfig.description
21
+ if (description) film.description = b64(new Uint8Array(description.buffer || description, description.byteOffset || 0, description.byteLength))
22
+ film.chunks.push([chunk.type === 'key' ? 1 : 0, chunk.timestamp, b64(bytes)])
23
+ },
24
+ error(error) { film.error = String(error && error.message || error) },
25
+ })
26
+ film.encoder.configure(config)
27
+ return
28
+ }
29
+ throw new Error('This browser cannot encode H.264 video at ' + width + ' by ' + height)
30
+ }
31
+ film.add = async (picture, type, frames) => {
32
+ if (picture) {
33
+ const bitmap = await createImageBitmap(await (await fetch('data:' + type + ';base64,' + picture)).blob())
34
+ if (!film.encoder) await film.start(${e.width?Math.ceil(e.width/2)*2:"Math.ceil(bitmap.width / 2) * 2"}, ${e.height?Math.ceil(e.height/2)*2:"Math.ceil(bitmap.height / 2) * 2"})
35
+ const scale = Math.min(film.width / bitmap.width, film.height / bitmap.height, 1)
36
+ const [w, h] = [bitmap.width * scale, bitmap.height * scale]
37
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
38
+ film.context.drawImage(bitmap, (film.width - w) / 2, (film.height - h) / 2, w, h)
39
+ bitmap.close()
40
+ }
41
+ if (!film.encoder) throw new Error('A film starts with a picture')
42
+ for (let i = 0; i < frames; i++) {
43
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
44
+ // A key frame every two seconds keeps seeking quick without costing much.
45
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
46
+ frame.close(); film.frame++
47
+ }
48
+ if (film.encoder.encodeQueueSize > 30) await film.encoder.flush()
49
+ if (film.error) throw new Error(film.error)
50
+ }
51
+ film.open = async (url) => {
52
+ const video = film.video = document.createElement('video')
53
+ video.muted = true; video.playsInline = true; video.preload = 'auto'
54
+ await new Promise((resolve, reject) => {
55
+ video.addEventListener('loadeddata', resolve, { once: true })
56
+ video.addEventListener('error', () => reject(new Error('This browser cannot play the recording')), { once: true })
57
+ video.src = url
58
+ })
59
+ if (!video.videoWidth || !Number.isFinite(video.duration)) throw new Error('The recording has no picture')
60
+ await film.start(Math.ceil(video.videoWidth / 2) * 2, Math.ceil(video.videoHeight / 2) * 2)
61
+ return JSON.stringify({ seconds: video.duration, frames: Math.max(1, Math.round(video.duration * ${e.fps})) })
62
+ }
63
+ // One output frame per tick of this film's clock, each taken from the
64
+ // recording at that moment: a device's variable frame rate becomes steady.
65
+ film.copy = async (from, count, marks) => {
66
+ const video = film.video
67
+ for (let index = from; index < from + count; index++) {
68
+ const time = Math.min(index / ${e.fps}, Math.max(0, video.duration - 0.001))
69
+ if (Math.abs(video.currentTime - time) > 0.0005) {
70
+ await new Promise((resolve, reject) => {
71
+ video.addEventListener('seeked', resolve, { once: true })
72
+ video.addEventListener('error', () => reject(new Error('The recording could not be read')), { once: true })
73
+ video.currentTime = time
74
+ })
75
+ }
76
+ film.context.fillStyle = '#fff'; film.context.fillRect(0, 0, film.width, film.height)
77
+ film.context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
78
+ for (const mark of marks) {
79
+ if (time < mark.start || time > mark.end) continue
80
+ film.context.globalAlpha = 0.9; film.context.strokeStyle = mark.color; film.context.lineWidth = 4
81
+ film.context.strokeRect(Math.round(mark.x - mark.size / 2) + 2, Math.round(mark.y - mark.size / 2) + 2, mark.size - 4, mark.size - 4)
82
+ film.context.globalAlpha = 1
83
+ }
84
+ const frame = new VideoFrame(film.canvas, { timestamp: Math.round(film.frame * 1e6 / ${e.fps}), duration: Math.round(1e6 / ${e.fps}) })
85
+ film.encoder.encode(frame, { keyFrame: film.frame % ${Math.max(1,Math.round(e.fps*2))} === 0 })
86
+ frame.close(); film.frame++
87
+ }
88
+ await film.encoder.flush()
89
+ if (film.error) throw new Error(film.error)
90
+ }
91
+ film.drain = async (last) => {
92
+ if (last && film.encoder) { await film.encoder.flush(); film.encoder.close() }
93
+ if (film.error) throw new Error(film.error)
94
+ return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
+ }
96
+ return true
97
+ })()`,ee=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function z(e,t){if(!Number.isInteger(t.fps)||t.fps<1||t.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(Z(t));let o=[],l,w={width:0,height:0},m=0,c=async(r)=>{let i=JSON.parse(String(await e(`window.__stacksFilm.drain(${r})`)));if(w={width:i.width,height:i.height},i.description)l=new Uint8Array(Buffer.from(i.description,"base64"));for(let[u,s,f]of i.chunks)o.push([u,s,new Uint8Array(Buffer.from(f,"base64"))])};return{frames:()=>m,async add(r,i){if(!Number.isInteger(i)||i<1)return;let u=r?`${JSON.stringify(Buffer.from(r).toString("base64"))}, ${JSON.stringify(ee(r))}`:"null, null";if(await e(`window.__stacksFilm.add(${u}, ${i})`),m+=i,m%(t.fps*20)<i)await c(!1)},async addVideo(r,i=[]){for(let s of i)if(![s.x,s.y,s.size,s.start,s.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(s.color))throw Error("Invalid film mark");let u=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(r)})`)));for(let s=0;s<u.frames;s+=t.fps){let f=Math.min(t.fps,u.frames-s);await e(`window.__stacksFilm.copy(${s}, ${f}, ${JSON.stringify(i)})`),m+=f,await c(!1)}return u.seconds},async finish(){if(await c(!0),!o.length||!l)throw Error("The browser encoded no video");let r=new G,i=new Y(r),u=i.addVideoTrack({codec:"h264",width:w.width,height:w.height,frameRate:t.fps,codecDescription:l});for(let[s,f,p]of o)await i.writePacket(u.id,{data:p,timestamp:f/1e6,duration:1/t.fps,isKeyframe:s===1});return await i.finalize(),r.buffer}}}function _(e){let t=`:is(${['input[type="password"]',...e].join(",")})`,o=`${t}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
98
+ ${t}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
99
+ ${o}, ${o}::selection {
5
100
  color: transparent !important;
6
101
  -webkit-text-fill-color: transparent !important;
7
102
  -webkit-text-stroke: 0 transparent !important;
@@ -9,20 +104,20 @@ ${i}, ${i}::selection {
9
104
  caret-color: transparent !important;
10
105
  forced-color-adjust: none !important;
11
106
  }
12
- ${i}::selection { background: transparent !important; }
13
- ${i}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
- ${i}::-webkit-search-cancel-button { visibility: hidden !important; }
15
- `}function k(e,r,i,l){if(!Number.isFinite(e)||e<r||e>i)throw Error(`Invalid ${l}`)}function Y(e){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return r}async function f(e,r,i=30000){r?.throwIfAborted();let l=U(e),h=!1,u=()=>{l.stop().catch(()=>{})};r?.addEventListener("abort",u,{once:!0});let s=setTimeout(()=>{h=!0,u()},i);try{let[o,n]=await Promise.all([l.exited,new Response(l.stdout).bytes(),new Response(l.stderr).text()]);if(r?.throwIfAborted(),h)throw Error("Story tool timed out");if(o.code!==0)throw Error(`Story tool failed: ${e[0]}`);return n}finally{clearTimeout(s),r?.removeEventListener("abort",u),await l.stop()}}async function G(e,r="ffmpeg"){await f([r,"-hide_banner","-loglevel","error","-nostdin","-n",...e],void 0,180000)}function re(e){let r=Y(e.baseUrl),i={color:"#2563eb",size:18,moveMs:450,clickMs:400,...e.cursor};if(!/^#[0-9a-f]{6}$/i.test(i.color))throw Error("Cursor color must be a six-digit hex color");return k(i.size,6,80,"cursor size"),k(i.moveMs,0,5000,"cursor movement"),k(i.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:l,fps:h,signal:u}){let s=await J({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:o}=s,n,E=!1,g,w,m,y,T=new Map,C=o.on("Network.responseReceived",(v)=>{if(v.type==="Document")T.set(v.frameId,{status:v.response.status})}),S=()=>{E=!0,n?.stop().catch(()=>{}),s.close().catch(()=>{})};u.addEventListener("abort",S,{once:!0});try{u.throwIfAborted();let v=`stacks-story-${R()}`,p=z(e.masks??[]),x=`(() => {
107
+ ${o}::selection { background: transparent !important; }
108
+ ${o}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
109
+ ${o}::-webkit-search-cancel-button { visibility: hidden !important; }
110
+ `}function N(e,t,o,l){if(!Number.isFinite(e)||e<t||e>o)throw Error(`Invalid ${l}`)}function oe(e){let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return t}async function k(e,t,o=30000){t?.throwIfAborted();let l=W(e),w=!1,m=()=>{l.stop().catch(()=>{})};t?.addEventListener("abort",m,{once:!0});let c=setTimeout(()=>{w=!0,m()},o);try{let[r,i]=await Promise.all([l.exited,new Response(l.stdout).bytes(),new Response(l.stderr).text()]);if(t?.throwIfAborted(),w)throw Error("Story tool timed out");if(r.code!==0)throw Error(`Story tool failed: ${e[0]}`);return i}finally{clearTimeout(c),t?.removeEventListener("abort",m),await l.stop()}}function ye(e){let t=oe(e.baseUrl),o={color:"#2563eb",size:18,moveMs:450,clickMs:400,...e.cursor};if(!/^#[0-9a-f]{6}$/i.test(o.color))throw Error("Cursor color must be a six-digit hex color");return N(o.size,6,80,"cursor size"),N(o.moveMs,0,5000,"cursor movement"),N(o.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:l,fps:w,signal:m}){let c=await V({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:r}=c,i,u,s,f=!1,p,g,A,I,T=new Map,C=r.on("Network.responseReceived",(n)=>{if(n.type==="Document")T.set(n.frameId,{status:n.response.status})}),h,S=new Promise((n)=>{h=n}),P=async()=>{h(),u?.stop(),u=void 0;let n=i;i=void 0,await Promise.race([n?.close().catch(()=>{}),Bun.sleep(5000)])},d=()=>{f=!0,P(),c.close().catch(()=>{})};m.addEventListener("abort",d,{once:!0});try{m.throwIfAborted();let n=`stacks-story-${J()}`,v=_(e.masks??[]),E=`(() => {
16
111
  const start = () => {
17
112
  const maskSheet = new CSSStyleSheet();
18
- maskSheet.replaceSync(${JSON.stringify(p)});
113
+ maskSheet.replaceSync(${JSON.stringify(v)});
19
114
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
20
- const host = document.createElement('div'); host.id = ${JSON.stringify(v)};
115
+ const host = document.createElement('div'); host.id = ${JSON.stringify(n)};
21
116
  host.style.cssText='all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important;';
22
117
  const shadow=host.attachShadow({mode:'closed'}); const dot=document.createElement('div');
23
- dot.style.cssText=${JSON.stringify(`position:absolute;width:${i.size}px;height:${i.size}px;border:2px solid white;border-radius:50%;background:${i.color};box-shadow:0 1px 4px #0008;left:24px;top:24px;transform:translate(-50%,-50%);pointer-events:none;`)};
118
+ dot.style.cssText=${JSON.stringify(`position:absolute;width:${o.size}px;height:${o.size}px;border:2px solid white;border-radius:50%;background:${o.color};box-shadow:0 1px 4px #0008;left:24px;top:24px;transform:translate(-50%,-50%);pointer-events:none;`)};
24
119
  shadow.append(dot); document.documentElement.append(host);
25
120
  addEventListener('mousemove', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px'},true);
26
- addEventListener('pointerdown', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px';const pulse=document.createElement('div');pulse.style.cssText='position:absolute;left:'+event.clientX+'px;top:'+event.clientY+'px;width:12px;height:12px;border:4px solid ${i.color};border-radius:50%;transform:translate(-50%,-50%);';shadow.append(pulse);pulse.animate([{opacity:1,width:'12px',height:'12px'},{opacity:0,width:'70px',height:'70px'}],{duration:${i.clickMs}}).finished.then(()=>pulse.remove())},true);
121
+ addEventListener('pointerdown', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px';const pulse=document.createElement('div');pulse.style.cssText='position:absolute;left:'+event.clientX+'px;top:'+event.clientY+'px;width:12px;height:12px;border:4px solid ${o.color};border-radius:50%;transform:translate(-50%,-50%);';shadow.append(pulse);pulse.animate([{opacity:1,width:'12px',height:'12px'},{opacity:0,width:'70px',height:'70px'}],{duration:${o.clickMs}}).finished.then(()=>pulse.remove())},true);
27
122
  }; if(document.documentElement) start(); else new MutationObserver((_,observer)=>{if(document.documentElement){observer.disconnect();start()}}).observe(document,{childList:true});
28
- })()`;await o.send("Page.addScriptToEvaluateOnNewDocument",{source:x});let P={x:24,y:24},a={cdp:o,async goto(t,d={}){let M=new URL(t,r);if(M.origin!==r.origin||M.username||M.password)throw Error("Story navigation must stay on baseUrl origin");let N=d.expectedStatus??200;if(!Number.isInteger(N)||N<100||N>599)throw Error("Invalid expected document status");let I=await o.send("Page.navigate",{url:M.href});if(I.errorText||!await H(o,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(T.get(I.frameId)?.status!==N)throw Error("Unexpected story document HTTP status");if(new URL(await o.evaluate("location.href")).origin!==r.origin)throw Error("Story page redirected outside baseUrl origin")},async click(t){u.throwIfAborted();let d=typeof t==="string"?t:t.selector,M=typeof t==="string"?void 0:t.text,N=await L(async()=>o.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(d)})].filter(el=>${M===void 0?"true":`el.textContent.trim()===${JSON.stringify(M)}`});if(all.length!==1)return null;const el=all[0];el.scrollIntoView({block:'center',behavior:'instant'});const r=el.getBoundingClientRect();return r.width&&r.height?{x:r.x+r.width/2,y:r.y+r.height/2}:null})()`),12000),I=P,_=performance.now();do{u.throwIfAborted();let O=i.moveMs?Math.min(1,(performance.now()-_)/i.moveMs):1;if(P={x:I.x+(N.x-I.x)*O,y:I.y+(N.y-I.y)*O},await o.send("Input.dispatchMouseEvent",{type:"mouseMoved",...P}),O===1)break;await Bun.sleep(16)}while(!0);await q(o,t),await Bun.sleep(i.clickMs)},async type(t,d){await a.click(t),await o.send("Input.insertText",{text:d})},async expectText(t,d){await L(()=>o.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent.includes(${JSON.stringify(d)}) ?? false`),12000)}};if(await e.beforeNavigate?.(o),u.throwIfAborted(),await a.goto(r.href),e.prepare)await e.prepare(a);m=Buffer.from((await o.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),y=o.on("Page.screencastFrame",(t)=>{m=Buffer.from(t.data,"base64"),o.send("Page.screencastFrameAck",{sessionId:t.sessionId}).catch((d)=>{w=d})}),n=U([e.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-n","-f","image2pipe","-framerate",String(h),"-vcodec","mjpeg","-i","pipe:0","-an","-vf","pad=ceil(iw/2)*2:ceil(ih/2)*2","-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",l],{stdin:"pipe"}),await n.started;let c=new Response(n.stderr).text();new Response(n.stdout).arrayBuffer(),await o.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let b=performance.now();g=(async()=>{let t=0;while(!E){if(u.throwIfAborted(),w)throw w;let d=Math.floor((performance.now()-b)/1000*h)+1;if(d-t>h*10)throw Error("Story encoder cannot keep up with the recording");while(t<d)n.stdin.write(m),await n.stdin.flush(),t++;await Bun.sleep(Math.max(1,1000/h/2))}})().catch((t)=>{w=t});let A;return{context:a,screenshot:async()=>Buffer.from((await o.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>A??=(async()=>{E=!0;let t=setTimeout(()=>{w=Error("Story video finalization timed out"),n.stop().catch(()=>{})},30000);try{await g,await o.send("Page.stopScreencast"),y?.(),await n.stdin.end();let d=await n.exited;if(await c,w||d.code!==0)throw Error("Story video capture failed",{cause:w});if(e.failOnBrowserErrors!==!1&&o.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(t)}})(),async close(){E=!0,y?.(),C(),u.removeEventListener("abort",S);try{await n.stop(),await g}finally{await s.close()}}}}catch(v){E=!0,y?.(),C(),u.removeEventListener("abort",S);try{await n?.stop(),await g}finally{await s.close()}throw v}}}}function oe(e){let r=e.platform==="ios";if(r?!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(e.device):!/^emulator-\d+$/.test(e.device))throw Error("Native stories require an explicit simulator UUID or emulator serial");if(r&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let i=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(i))throw Error("Tap color must be a six-digit hex color");k(e.tapMs??450,100,5000,"tap feedback");let l=e.tapSize??72;return k(l,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:h,fps:u,signal:s}){let o=j(F(h),"native-raw.mp4"),n=e.adb??"adb",E=e.xcrun??"xcrun",g=`/sdcard/stacks-story-${R()}.mp4`,w,m,y,T=0,C=[],S=e.input??{async tap(p,x){await f([n,"-s",e.device,"shell","input","tap",String(Math.round(p)),String(Math.round(x))],s)},async swipe(p,x,P){await f([n,"-s",e.device,"shell","input","swipe",String(Math.round(p.x)),String(Math.round(p.y)),String(Math.round(x.x)),String(Math.round(x.y)),String(Math.round(P))],s)},async type(p){if(!/^[a-z0-9@._+ -]*$/i.test(p))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await f([n,"-s",e.device,"shell","input","text",p.replaceAll(" ","%s")],s)}},v=(p,x)=>{k(p,0,16384,"tap x"),k(x,0,16384,"tap y")};try{if(s.throwIfAborted(),r){let{recordIosSimulatorVideo:a}=await import("craft-native/testing");w=(await a({device:e.device,path:o,xcrun:E})).stop}else{if(new TextDecoder().decode(await f([n,"-s",e.device,"get-state"],s)).trim()!=="device")throw Error("Android emulator is unavailable");m=U([n,"-s",e.device,"shell",`screenrecord --time-limit 180 ${g} & recorder=$!; trap 'kill -2 "$recorder" 2>/dev/null; wait "$recorder"; exit' HUP INT TERM; echo STACKS_RECORDER:$recorder; wait "$recorder"; result=$?; trap - HUP INT TERM; exit "$result"`]),await m.started;let c=m.stdout.getReader(),b="",A=setTimeout(()=>{m.stop()},15000);try{while(!y){let t=await c.read();if(t.done)throw Error("Android recorder stopped before startup");b+=new TextDecoder().decode(t.value);let d=/STACKS_RECORDER:(\d+)/.exec(b);if(d)y=Number(d[1]);if(b.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(A)}(async()=>{while(!(await c.read()).done);})().catch(()=>{}),new Response(m.stderr).text();let B=async()=>{await f([n,"-s",e.device,"shell",`case "$(cat /proc/${y}/cmdline 2>/dev/null)" in *${g}*) kill -2 ${y};; *) exit 3;; esac`])};await f([n,"-s",e.device,"shell","kill","-0",String(y)],s),w=async()=>{await B();let t=setTimeout(()=>{m.stop()},15000);try{await m.exited}finally{clearTimeout(t)}await f([n,"-s",e.device,"pull",g,o])},await f([n,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${g} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${y} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],s,20000)}T=performance.now();let p={async tap(a,c){s.throwIfAborted(),v(a,c);let b={x:a,y:c,start:(performance.now()-T)/1000,end:0};C.push(b);try{await S.tap(a,c)}finally{b.end=(performance.now()-T)/1000+(e.tapMs??450)/1000}},async swipe(a,c,b){if(s.throwIfAborted(),v(a.x,a.y),v(c.x,c.y),k(b,1,1e4,"swipe duration"),!S.swipe)throw Error("Native driver does not support swipes");await S.swipe(a,c,b)},async type(a){if(s.throwIfAborted(),!S.type)throw Error("Native driver does not support typing");await S.type(a)}},x;return{context:p,async screenshot(){if(s.throwIfAborted(),!r)return f([n,"-s",e.device,"exec-out","screencap","-p"],s);let a=j(F(h),`screenshot-${R()}.png`);try{return await f([E,"simctl","io",e.device,"screenshot",a],s),await X(a)}finally{await D(a,{force:!0})}},finish:()=>x??=(async()=>{await w();let a=e.tapFeedback===!1?[]:C.map((c)=>`drawbox=x=${Math.round(c.x-l/2)}:y=${Math.round(c.y-l/2)}:w=${l}:h=${l}:color=0x${i.slice(1)}@0.9:t=4:enable='between(t,${c.start.toFixed(3)},${c.end.toFixed(3)})'`);await G(["-i",o,"-an","-vf",[...a,"pad=ceil(iw/2)*2:ceil(ih/2)*2"].join(","),"-r",String(u),"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",h],e.ffmpeg),await D(o)})(),async close(){try{if(!x)await w?.()}finally{if(await m?.stop(),!r)await f([n,"-s",e.device,"shell","rm","-f",g])}}}}catch(p){try{await w?.()}finally{await m?.stop()}throw p}}}}export{re as browserStory,oe as nativeStory};
123
+ })()`;await r.send("Page.addScriptToEvaluateOnNewDocument",{source:E});let O={x:24,y:24},M={cdp:r,async goto(a,b={}){let y=new URL(a,t);if(y.origin!==t.origin||y.username||y.password)throw Error("Story navigation must stay on baseUrl origin");let x=b.expectedStatus??200;if(!Number.isInteger(x)||x<100||x>599)throw Error("Invalid expected document status");let B=await r.send("Page.navigate",{url:y.href});if(B.errorText||!await re(r,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(T.get(B.frameId)?.status!==x)throw Error("Unexpected story document HTTP status");if(new URL(await r.evaluate("location.href")).origin!==t.origin)throw Error("Story page redirected outside baseUrl origin")},async click(a){m.throwIfAborted();let b=typeof a==="string"?a:a.selector,y=typeof a==="string"?void 0:a.text,x=await L(async()=>r.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(b)})].filter(el=>${y===void 0?"true":`el.textContent.trim()===${JSON.stringify(y)}`});if(all.length!==1)return null;const el=all[0];el.scrollIntoView({block:'center',behavior:'instant'});const r=el.getBoundingClientRect();return r.width&&r.height?{x:r.x+r.width/2,y:r.y+r.height/2}:null})()`),12000),B=O,K=performance.now();do{m.throwIfAborted();let U=o.moveMs?Math.min(1,(performance.now()-K)/o.moveMs):1;if(O={x:B.x+(x.x-B.x)*U,y:B.y+(x.y-B.y)*U},await r.send("Input.dispatchMouseEvent",{type:"mouseMoved",...O}),U===1)break;await Bun.sleep(16)}while(!0);await te(r,a),await Bun.sleep(o.clickMs)},async type(a,b){await M.click(a),await r.send("Input.insertText",{text:b})},async expectText(a,b){await L(()=>r.evaluate(`document.querySelector(${JSON.stringify(a)})?.textContent.includes(${JSON.stringify(b)}) ?? false`),12000)}};if(await e.beforeNavigate?.(r),m.throwIfAborted(),await M.goto(t.href),e.prepare)await e.prepare(M);A=Buffer.from((await r.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),I=r.on("Page.screencastFrame",(a)=>{A=Buffer.from(a.data,"base64"),r.send("Page.screencastFrameAck",{sessionId:a.sessionId}).catch((b)=>{g=b})}),u=R(),i=await V({viewport:{width:320,height:240},chromePath:e.chromePath,headless:e.headless});let F=i.cdp;await F.send("Page.navigate",{url:u.url}),await L(()=>F.evaluate('document.readyState === "complete"'),15000),s=await z((a)=>F.evaluate(a),{fps:w}),await r.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let H=performance.now();p=(async()=>{let a=0,b;while(!f){if(m.throwIfAborted(),g)throw g;let y=Math.floor((performance.now()-H)/1000*w)+1;if(y-a>w*10)throw Error("Story encoder cannot keep up with the recording");if(y>a){let x=A;await Promise.race([s.add(x===b?void 0:x,y-a),S]),b=x,a=y}await Bun.sleep(Math.max(1,1000/w/2))}})().catch((a)=>{g=a});let X;return{context:M,screenshot:async()=>Buffer.from((await r.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>X??=(async()=>{f=!0;let a=!1,b=setTimeout(()=>{a=!0,P()},60000);try{if(await p,await r.send("Page.stopScreencast"),I?.(),g)throw Error("Story video capture failed",{cause:g});let y;try{y=await Promise.race([s.finish(),S.then(()=>{throw Error("The encoder page closed")})])}catch(x){throw Error(a?"Story video finalization timed out":"Story video capture failed",{cause:x})}if(await Bun.write(l,y),e.failOnBrowserErrors!==!1&&r.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(b),await P()}})(),async close(){f=!0,I?.(),C(),m.removeEventListener("abort",d);try{await P(),await p}finally{await c.close()}}}}catch(n){f=!0,I?.(),C(),m.removeEventListener("abort",d);try{await P(),await p}finally{await c.close()}throw n}}}}function ve(e){let t=e.platform==="ios";if(t?!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(e.device):!/^emulator-\d+$/.test(e.device))throw Error("Native stories require an explicit simulator UUID or emulator serial");if(t&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let o=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(o))throw Error("Tap color must be a six-digit hex color");N(e.tapMs??450,100,5000,"tap feedback");let l=e.tapSize??72;return N(l,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:w,fps:m,signal:c}){let r=q(j(w),"native-raw.mp4"),i=e.adb??"adb",u=e.xcrun??"xcrun",s=`/sdcard/stacks-story-${J()}.mp4`,f,p,g,A=0,I=[],T=e.input??{async tap(h,S){await k([i,"-s",e.device,"shell","input","tap",String(Math.round(h)),String(Math.round(S))],c)},async swipe(h,S,P){await k([i,"-s",e.device,"shell","input","swipe",String(Math.round(h.x)),String(Math.round(h.y)),String(Math.round(S.x)),String(Math.round(S.y)),String(Math.round(P))],c)},async type(h){if(!/^[a-z0-9@._+ -]*$/i.test(h))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await k([i,"-s",e.device,"shell","input","text",h.replaceAll(" ","%s")],c)}},C=(h,S)=>{N(h,0,16384,"tap x"),N(S,0,16384,"tap y")};try{if(c.throwIfAborted(),t){let{recordIosSimulatorVideo:d}=await import("craft-native/testing");f=(await d({device:e.device,path:r,xcrun:u})).stop}else{if(new TextDecoder().decode(await k([i,"-s",e.device,"get-state"],c)).trim()!=="device")throw Error("Android emulator is unavailable");p=W([i,"-s",e.device,"shell",`screenrecord --time-limit 180 ${s} & recorder=$!; trap 'kill -2 "$recorder" 2>/dev/null; wait "$recorder"; exit' HUP INT TERM; echo STACKS_RECORDER:$recorder; wait "$recorder"; result=$?; trap - HUP INT TERM; exit "$result"`]),await p.started;let n=p.stdout.getReader(),v="",E=setTimeout(()=>{p.stop()},15000);try{while(!g){let M=await n.read();if(M.done)throw Error("Android recorder stopped before startup");v+=new TextDecoder().decode(M.value);let F=/STACKS_RECORDER:(\d+)/.exec(v);if(F)g=Number(F[1]);if(v.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(E)}(async()=>{while(!(await n.read()).done);})().catch(()=>{}),new Response(p.stderr).text();let O=async()=>{await k([i,"-s",e.device,"shell",`case "$(cat /proc/${g}/cmdline 2>/dev/null)" in *${s}*) kill -2 ${g};; *) exit 3;; esac`])};await k([i,"-s",e.device,"shell","kill","-0",String(g)],c),f=async()=>{await O();let M=setTimeout(()=>{p.stop()},15000);try{await p.exited}finally{clearTimeout(M)}await k([i,"-s",e.device,"pull",s,r])},await k([i,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${s} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${g} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],c,20000)}A=performance.now();let h={async tap(d,n){c.throwIfAborted(),C(d,n);let v={x:d,y:n,start:(performance.now()-A)/1000,end:0};I.push(v);try{await T.tap(d,n)}finally{v.end=(performance.now()-A)/1000+(e.tapMs??450)/1000}},async swipe(d,n,v){if(c.throwIfAborted(),C(d.x,d.y),C(n.x,n.y),N(v,1,1e4,"swipe duration"),!T.swipe)throw Error("Native driver does not support swipes");await T.swipe(d,n,v)},async type(d){if(c.throwIfAborted(),!T.type)throw Error("Native driver does not support typing");await T.type(d)}},S;return{context:h,async screenshot(){if(c.throwIfAborted(),!t)return k([i,"-s",e.device,"exec-out","screencap","-p"],c);let d=q(j(w),`screenshot-${J()}.png`);try{return await k([u,"simctl","io",e.device,"screenshot",d],c),await ie(d)}finally{await D(d,{force:!0})}},finish:()=>S??=(async()=>{if(await f(),typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before recording native stories.");let d=R({"/raw.mp4":r}),n=new Bun.WebView({width:320,height:240,backend:process.platform==="darwin"?"webkit":{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}});try{await n.navigate(d.url);let v=await z((E)=>n.evaluate(E),{fps:m});await v.addVideo("/raw.mp4",e.tapFeedback===!1?[]:I.map((E)=>({x:E.x,y:E.y,size:l,color:o,start:E.start,end:E.end}))),await Bun.write(w,await v.finish())}finally{n.close(),d.stop()}await D(r)})(),async close(){try{if(!S)await f?.()}finally{if(await p?.stop(),!t)await k([i,"-s",e.device,"shell","rm","-f",s])}}}}catch(h){try{await f?.()}finally{await p?.stop()}throw h}}}}export{ye as browserStory,ve as nativeStory};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/docs",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.653",
5
+ "version": "0.75.657",
6
6
  "description": "The Stacks way to document.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,17 +58,19 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@stacksjs/bunpress": "^0.2.25",
61
- "@stacksjs/cli": "0.75.653",
62
- "@stacksjs/config": "0.75.653",
63
- "@stacksjs/path": "0.75.653",
64
- "@stacksjs/orm": "0.75.653",
61
+ "@stacksjs/cli": "0.75.657",
62
+ "@stacksjs/config": "0.75.657",
63
+ "@stacksjs/path": "0.75.657",
64
+ "@stacksjs/orm": "0.75.657",
65
65
  "@stacksjs/stx": "^0.2.908",
66
- "@stacksjs/testing": "0.75.653",
67
- "craft-native": ">=0.0.499"
66
+ "@stacksjs/testing": "0.75.657",
67
+ "@ts-videos/mp4": "^0.1.2",
68
+ "craft-native": ">=0.0.499",
69
+ "ts-videos": "^0.1.2"
68
70
  },
69
71
  "devDependencies": {
70
- "@stacksjs/alias": "0.75.653",
71
- "@stacksjs/server": "0.75.653",
72
+ "@stacksjs/alias": "0.75.657",
73
+ "@stacksjs/server": "0.75.657",
72
74
  "better-dx": "^0.2.39"
73
75
  }
74
76
  }