@stacksjs/docs 0.75.657 → 0.75.660

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.
@@ -0,0 +1,5 @@
1
+ /** Open WebViews inside the same isolated browser launcher that runs browser tests. */
2
+ export declare function captureBrowser(backend: 'webkit' | 'chrome'): {
3
+ view: (width: number, height: number) => Promise<Bun.WebView>;
4
+ close: () => Promise<void>
5
+ };
@@ -1,5 +1,5 @@
1
1
  // @bun
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)=>`(() => {
2
+ import{Mp4Muxer as O}from"@ts-videos/mp4";import{BufferTarget as T}from"ts-videos";function x(e={}){let r=Bun.serve({port:0,hostname:"127.0.0.1",fetch(s){let n=e[new URL(s.url).pathname];if(n)return new Response(Bun.file(n),{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:${r.port}/`,stop:()=>{r.stop(!0)}}}var N=["6400","4d00","42e0"],U=(e)=>`(() => {
3
3
  if (window.__stacksFilm) return true
4
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
5
  const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
@@ -7,7 +7,7 @@ import{Mp4Muxer as A}from"@ts-videos/mp4";import{BufferTarget as O}from"ts-video
7
7
  if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
8
8
  film.width = width; film.height = height
9
9
  const level = width * height > 2097152 ? '33' : '28'
10
- for (const profile of ${JSON.stringify(P)}) {
10
+ for (const profile of ${JSON.stringify(N)}) {
11
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
12
  const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
13
13
  if (!support || !support.supported) continue
@@ -94,6 +94,6 @@ import{Mp4Muxer as A}from"@ts-videos/mp4";import{BufferTarget as O}from"ts-video
94
94
  return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
95
  }
96
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(`
97
+ })()`,V=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function S(e,r){if(!Number.isInteger(r.fps)||r.fps<1||r.fps>60)throw Error("Film frames per second must be an integer from 1 to 60");await e(U(r));let s=[],n,l={width:0,height:0},c=0,h=async(f)=>{let i=JSON.parse(String(await e(`window.__stacksFilm.drain(${f})`)));if(l={width:i.width,height:i.height},i.description)n=new Uint8Array(Buffer.from(i.description,"base64"));for(let[t,o,a]of i.chunks)s.push([t,o,new Uint8Array(Buffer.from(a,"base64"))])};return{frames:()=>c,async add(f,i){if(!Number.isInteger(i)||i<1)return;let t=f?`${JSON.stringify(Buffer.from(f).toString("base64"))}, ${JSON.stringify(V(f))}`:"null, null";if(await e(`window.__stacksFilm.add(${t}, ${i})`),c+=i,c%(r.fps*20)<i)await h(!1)},async addVideo(f,i=[]){for(let o of i)if(![o.x,o.y,o.size,o.start,o.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(o.color))throw Error("Invalid film mark");let t=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(f)})`)));for(let o=0;o<t.frames;o+=r.fps){let a=Math.min(r.fps,t.frames-o);await e(`window.__stacksFilm.copy(${o}, ${a}, ${JSON.stringify(i)})`),c+=a,await h(!1)}return t.seconds},async finish(){if(await h(!0),!s.length||!n)throw Error("The browser encoded no video");let f=new T,i=new O(f),t=i.addVideoTrack({codec:"h264",width:l.width,height:l.height,frameRate:r.fps,codecDescription:n});for(let[o,a,m]of s)await i.writePacket(t.id,{data:m,timestamp:a/1e6,duration:1/r.fps,isKeyframe:o===1});return await i.finalize(),f.buffer}}}import{launch as C}from"@stacksjs/testing/browser";function E(e){let r,s;return{async view(n,l){if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");if(e==="webkit")return new Bun.WebView({width:n,height:l,backend:e});if(!s){let c=await C({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let h=`127.0.0.1:${c.port}`,f=await fetch(`http://${h}/json/version`,{signal:AbortSignal.timeout(5000)});if(!f.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${f.status})`);let i=await f.json(),t=URL.parse(i.webSocketDebuggerUrl||"");if(t?.protocol!=="ws:"||t.host!==h||!t.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");s=t.href,r=c}catch(h){throw await c.close(),h}}return new Bun.WebView({width:n,height:l,backend:{type:"chrome",url:s}})},async close(){try{await r?.close()}finally{r=void 0,s=void 0}}}}import{createHash as R}from"crypto";import{lstat as _,mkdir as W,readFile as F,rename as M}from"fs/promises";import{dirname as D,isAbsolute as J,join as v,relative as L,resolve as P}from"path";var A="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",B=(e)=>R("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 ee(e,r,s,n){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 c of e.viewports??[])if(!n.some((h)=>h.name===c))throw Error(`Unknown film viewport: ${c}`)}if(r){let l=P(s,r.page);if(J(r.page)||L(s,l).startsWith("..")||!r.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(r.base)||r.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function te(e,r,s,n,l=process.platform==="darwin"?"webkit":"chrome"){let c=[],h=n.secondsPerScreen??2,f=n.fps??12,i=Math.max(1,Math.round(h*f)),t=E(l),o=x();try{for(let a of s){if(n.viewports?.length&&!n.viewports.includes(a.name))continue;let m=r.filter((u)=>u.status==="captured"&&u.file&&u.viewport.name===a.name);if(!m.length)continue;let p,d;try{d=await t.view(320,240);let u=d;await u.navigate(o.url);let k=await S((y)=>u.evaluate(y),{fps:f,width:a.width,height:a.height});for(let y of m)await k.add(new Uint8Array(await F(v(e,y.file))),i);p=await k.finish()}catch(u){throw Error(`The ${a.name} screens could not be filmed: ${u instanceof Error?u.message.slice(0,400):"the browser failed"}`)}finally{d?.close()}let b=`film-${a.name}.mp4`;await Bun.write(v(e,`${b}.tmp`),p),await M(v(e,`${b}.tmp`),v(e,b)),c.push({viewport:a.name,file:b,sha256:B(p),screens:m.length,seconds:m.length*i/f})}return c}finally{try{await t.close()}finally{o.stop()}}}function j(e,r){let s=r.base.replace(/\/+$/,""),n=r.title??"Screens",l=e.results.filter((t)=>t.status==="captured"&&t.file),c=["---",`title: ${JSON.stringify(n)}`,`description: ${JSON.stringify(r.description??"Every screen of the application, captured automatically from its views.")}`,"---","",A,"",`# ${w(n)}`,"",`${new Set(l.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 o=l.find((a)=>a.viewport.name===t.viewport);c.push(`## Walkthrough video (${w(t.viewport)})`,"",`<video controls playsinline preload="none" src="${g(`${s}/${t.file}`)}"${o?` poster="${g(`${s}/${o.file}`)}"`:""} style="width:100%;max-width:${o&&o.viewport.width<600?o.viewport.width:1100}px;height:auto"></video>`,"",`${t.screens} screens in ${Math.round(t.seconds)} seconds. [Download the video](${s}/${t.file}).`,"")}let h=(t)=>t.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",f=new Map;for(let t of e.inventory)f.set(h(t.path),[...f.get(h(t.path))??[],t]);let i=[];for(let[t,o]of[...f].sort(([a],[m])=>a.localeCompare(m))){let a=[];for(let m of o){let p=l.filter((d)=>d.id===m.id);if(!p.length){let d=e.results.find((b)=>b.id===m.id);i.push(`- ${w(m.title)} (\`${m.path}\`): ${m.skip?w(m.skip):d?"the last capture failed.":"not captured yet."}`);continue}a.push(`### ${w(m.title)}`,"",w(p[0].description),"",...p[0].reason?[w(p[0].reason),""]:[],`Address: \`${m.path}\``,"");for(let d of p)a.push("<figure>",` <img src="${g(`${s}/${d.file}`)}" alt="${g(`${d.title}, ${d.viewport.name}`)}" width="${d.viewport.width}" height="${d.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${d.viewport.width}px;height:auto">`,` <figcaption>${g(d.viewport.name)}, ${d.viewport.width} by ${d.viewport.height}${d.profile==="default"?"":`, signed in as ${g(d.profile)}`}</figcaption>`,"</figure>","")}if(a.length)c.push(`## ${w(t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," "))}`,"",...a)}if(i.length)c.push("## Not pictured","","These screens are part of the application and have no picture here.","",...i,"");return`${c.join(`
98
98
  `).trimEnd()}
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};
99
+ `}async function re(e,r,s){let n=P(e,s.page);try{if((await _(n)).isSymbolicLink()||!(await F(n,"utf8")).includes(A))throw Error(`Refusing to replace a hand-written page: ${s.page}`)}catch(c){if(c.code!=="ENOENT")throw c}let l=j(r,s);return await W(D(n),{recursive:!0}),await Bun.write(`${n}.tmp`,l),await M(`${n}.tmp`,n),{path:s.page,sha256:B(l)}}export{te as filmScreenshots,A as generatedScreensPage,j as renderScreensPage,ee as validateScreenshotPublishing,re as writeScreensPage};
@@ -1,5 +1,5 @@
1
1
  // @bun
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`
2
+ import{createHash as Ie}from"crypto";import{lstat as D,mkdir as G,mkdtemp as fe,readFile as M,rename as Q,rm as z,rmdir as ze,stat as Ke}from"fs/promises";import{tmpdir as Ge}from"os";import{dirname as pe,isAbsolute as ue,join as g,relative as B,resolve as S}from"path";import{pathToFileURL as Qe}from"url";function Y(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
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
4
  ${a}, ${a}::selection {
5
5
  color: transparent !important;
@@ -12,7 +12,7 @@ ${a}, ${a}::selection {
12
12
  ${a}::selection { background: transparent !important; }
13
13
  ${a}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
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)=>`(() => {
15
+ `}import{launch as we}from"@stacksjs/testing/browser";function H(e){let o,a;return{async view(t,l){if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");if(e==="webkit")return new Bun.WebView({width:t,height:l,backend:e});if(!a){let f=await we({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let p=`127.0.0.1:${f.port}`,u=await fetch(`http://${p}/json/version`,{signal:AbortSignal.timeout(5000)});if(!u.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${u.status})`);let m=await u.json(),i=URL.parse(m.webSocketDebuggerUrl||"");if(i?.protocol!=="ws:"||i.host!==p||!i.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");a=i.href,o=f}catch(p){throw await f.close(),p}}return new Bun.WebView({width:t,height:l,backend:{type:"chrome",url:a}})},async close(){try{await o?.close()}finally{o=void 0,a=void 0}}}}import{createHash as ge}from"crypto";import{readFile as ye}from"fs/promises";import{existsSync as be}from"fs";import{isAbsolute as Se,join as ve,relative as ke,resolve as xe}from"path";import{loadModelRegistry as $e,modelFiles as Z}from"@stacksjs/orm/model-registry";function L(e){let o=Object.entries(e).map(([r,n])=>{let d=Object.entries(n.attributes??{}),h=n.belongsTo??[],k=(Array.isArray(h)?h:Object.values(h)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),b=n.traits?.useApi,O=n.traits?.useSeeder??n.traits?.seedable,j=(w,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),x=d.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(n.name??r),table:n.table,primaryKey:String(n.primaryKey??"id"),...b?.uri?{api:String(b.uri)}:{},parents:[...new Set([...k,...Array.isArray(O?.after)?O.after.map(String):[]])].sort(),seederCount:typeof O?.count==="number"?O.count:null,factoryFields:d.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:d.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:x,sensitiveFields:d.filter(([w,R])=>j(w,R)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...b?.routes?.includes("show")?["detail"]:[],...b?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((r,n)=>r.name.localeCompare(n.name)),a=new Set(o.map((r)=>r.name)),t=new Map(o.map((r)=>[r.name,r])),l=[];for(;;){let r=[...t.values()].filter((n)=>n.parents.every((d)=>!a.has(d)||l.includes(d)));if(!r.length)break;for(let n of r)l.push(n.name),t.delete(n.name)}let f=new Set,p=new Map,u=new Map,m=[],i=new Set,s=0;function c(r){p.set(r,s),u.set(r,s++),m.push(r),i.add(r);for(let h of t.get(r)?.parents??[]){if(!t.has(h))continue;if(!p.has(h))c(h),u.set(r,Math.min(u.get(r),u.get(h)));else if(i.has(h))u.set(r,Math.min(u.get(r),p.get(h)))}if(u.get(r)!==p.get(r))return;let n=[],d;do d=m.pop(),i.delete(d),n.push(d);while(d!==r);if(n.length>1||t.get(r)?.parents.includes(r))for(let h of n)f.add(h)}for(let r of t.keys())if(!p.has(r))c(r);return{models:o,creationOrder:l,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(o.flatMap((r)=>r.parents).filter((r)=>!a.has(r)))].sort()}}async function J(e,o={}){if(o===!1)return L({});if(o.directory!==void 0&&!o.directory.trim())throw Error("Model directory must not be empty");let a=xe(e,o.directory??"app/Models");if(Se(o.directory??"")||ke(e,a).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=o.includeDefaults?ve(e,"storage/framework/defaults/app/Models"):void 0;if(!be(a)&&!t)return L({});let l=[],f=await $e({userRoot:a,defaultsRoot:t,onImportError:(m)=>l.push(m)});if(l.length)throw Error(`Cannot inspect screenshot models: ${l.join(", ")}`);let p=L(f),u=[...Z(a),...t?Z(t):[]].sort();return p.sourceHash=ge("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>ye(m))))).digest("hex"),p}function _(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(/^\//,"")}/`)),f=l.length===1?l[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=a[f.name];if(!p)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,m,i)=>{let s=m||i,c=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(c)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=p[c];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{Mp4Muxer as Ee}from"@ts-videos/mp4";import{BufferTarget as Pe}from"ts-videos";function ee(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 Me=["6400","4d00","42e0"],Oe=(e)=>`(() => {
16
16
  if (window.__stacksFilm) return true
17
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
18
  const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
@@ -20,7 +20,7 @@ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
20
20
  if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
21
21
  film.width = width; film.height = height
22
22
  const level = width * height > 2097152 ? '33' : '28'
23
- for (const profile of ${JSON.stringify(Ee)}) {
23
+ for (const profile of ${JSON.stringify(Me)}) {
24
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
25
  const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
26
26
  if (!support || !support.supported) continue
@@ -107,23 +107,23 @@ ${a}::-webkit-search-cancel-button { visibility: hidden !important; }
107
107
  return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
108
108
  }
109
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(`
110
+ })()`,je=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function te(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(Oe(o));let a=[],t,l={width:0,height:0},f=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,s,c]of m.chunks)a.push([i,s,new Uint8Array(Buffer.from(c,"base64"))])};return{frames:()=>f,async add(u,m){if(!Number.isInteger(m)||m<1)return;let i=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(je(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${i}, ${m})`),f+=m,f%(o.fps*20)<m)await p(!1)},async addVideo(u,m=[]){for(let s of m)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 i=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let s=0;s<i.frames;s+=o.fps){let c=Math.min(o.fps,i.frames-s);await e(`window.__stacksFilm.copy(${s}, ${c}, ${JSON.stringify(m)})`),f+=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 Pe,m=new Ee(u),i=m.addVideoTrack({codec:"h264",width:l.width,height:l.height,frameRate:o.fps,codecDescription:t});for(let[s,c,r]of a)await m.writePacket(i.id,{data:r,timestamp:c/1e6,duration:1/o.fps,isKeyframe:s===1});return await m.finalize(),u.buffer}}}import{createHash as Fe}from"crypto";import{lstat as Re,mkdir as Te,readFile as re,rename as se}from"fs/promises";import{dirname as Be,isAbsolute as Ne,join as W,relative as Ce,resolve as ie}from"path";var oe="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",ne=(e)=>Fe("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 ae(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 f of e.viewports??[])if(!t.some((p)=>p.name===f))throw Error(`Unknown film viewport: ${f}`)}if(o){let l=ie(a,o.page);if(Ne(o.page)||Ce(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 q(e,o,a,t,l=process.platform==="darwin"?"webkit":"chrome"){let f=[],p=t.secondsPerScreen??2,u=t.fps??12,m=Math.max(1,Math.round(p*u)),i=H(l),s=ee();try{for(let c of a){if(t.viewports?.length&&!t.viewports.includes(c.name))continue;let r=o.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===c.name);if(!r.length)continue;let n,d;try{d=await i.view(320,240);let y=d;await y.navigate(s.url);let k=await te((b)=>y.evaluate(b),{fps:u,width:c.width,height:c.height});for(let b of r)await k.add(new Uint8Array(await re(W(e,b.file))),m);n=await k.finish()}catch(y){throw Error(`The ${c.name} screens could not be filmed: ${y instanceof Error?y.message.slice(0,400):"the browser failed"}`)}finally{d?.close()}let h=`film-${c.name}.mp4`;await Bun.write(W(e,`${h}.tmp`),n),await se(W(e,`${h}.tmp`),W(e,h)),f.push({viewport:c.name,file:h,sha256:ne(n),screens:r.length,seconds:r.length*m/u})}return f}finally{try{await i.close()}finally{s.stop()}}}function Ue(e,o){let a=o.base.replace(/\/+$/,""),t=o.title??"Screens",l=e.results.filter((i)=>i.status==="captured"&&i.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(o.description??"Every screen of the application, captured automatically from its views.")}`,"---","",oe,"",`# ${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 s=l.find((c)=>c.viewport.name===i.viewport);f.push(`## Walkthrough video (${T(i.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${a}/${i.file}`)}"${s?` poster="${N(`${a}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.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,s]of[...u].sort(([c],[r])=>c.localeCompare(r))){let c=[];for(let r of s){let n=l.filter((d)=>d.id===r.id);if(!n.length){let d=e.results.find((h)=>h.id===r.id);m.push(`- ${T(r.title)} (\`${r.path}\`): ${r.skip?T(r.skip):d?"the last capture failed.":"not captured yet."}`);continue}c.push(`### ${T(r.title)}`,"",T(n[0].description),"",...n[0].reason?[T(n[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let d of n)c.push("<figure>",` <img src="${N(`${a}/${d.file}`)}" alt="${N(`${d.title}, ${d.viewport.name}`)}" width="${d.viewport.width}" height="${d.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${d.viewport.width}px;height:auto">`,` <figcaption>${N(d.viewport.name)}, ${d.viewport.width} by ${d.viewport.height}${d.profile==="default"?"":`, signed in as ${N(d.profile)}`}</figcaption>`,"</figure>","")}if(c.length)f.push(`## ${T(i[0].toUpperCase()+i.slice(1).replace(/[-_]+/g," "))}`,"",...c)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
111
111
  `).trimEnd()}
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:
112
+ `}async function I(e,o,a){let t=ie(e,a.page);try{if((await Re(t)).isSymbolicLink()||!(await re(t,"utf8")).includes(oe))throw Error(`Refusing to replace a hand-written page: ${a.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let l=Ue(o,a);return await Te(Be(t),{recursive:!0}),await Bun.write(`${t}.tmp`,l),await se(`${t}.tmp`,t),{path:a.page,sha256:ne(l)}}import{createRouter as Ae}from"@stacksjs/stx";import{readFileSync as De}from"fs";import{relative as Ve,resolve as He}from"path";var ce=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Le=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Je(e){try{return De(e,"utf8")}catch{return""}}function We(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 ${ce(l.slice(1,-1).replace(/^\.\.\./,""))}`:ce(l));return t.length?Le(t.join(" / ")):"Home"}function le(e={}){let o=He(e.root??process.cwd()),a=[],t=new Set;for(let l of e.directories??["resources/views"])for(let f of Ae(o,{pagesDir:l,emit:!1})){let p=f.pattern.replace(/\*(\w*)/g,(c,r)=>`[...${r||"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=Je(f.filePath),s=i.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];a.push({id:m,route:p,source:Ve(o,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:We(i,p),...s?{layout:s}:{},text:i})}return a.sort((l,f)=>l.route<f.route?-1:l.route>f.route?1:0)}function _e(e={}){let o=[],a=new Set;for(let t of le(e)){a.add(t.route);let l=[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 p of l){if(p===void 0)continue;if(p===!1||typeof p==="string"){f.skip=p||"Left out of the screen documentation on purpose.";continue}Object.assign(f,p)}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;o.push(f)}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 Xe}from"@stacksjs/cli/owned-process";var A="0.75.660";var Nt=(e)=>e,F=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],V=(e)=>Ie("sha256").update(e).digest("hex"),K=(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),de=(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)=>!K(i)))throw Error("Profile names must be safe filenames");let l=new Set,f=new Set;for(let i of e.pages){if(!K(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 s=new URL(typeof i.path==="string"?i.path:i.route,a);if(s.origin!==a.origin||s.username||s.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 r=S(o,c);if(B(o,r).startsWith("..")||ue(c))throw Error(`Source must be inside the project: ${c}`);await M(r),f.add(B(o,r).replaceAll("\\","/"))}}let p=new Set;for(let i of e.viewports??F){if(!K(i.name)||p.has(i.name)||![i.width,i.height].every((s)=>Number.isInteger(s)&&s>=200&&s<=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((s)=>!p.has(s))))throw Error(`Unknown or empty viewports for ${i.id}`);for(let i of e.inputs??[])await M(S(o,i));ae(e.film===!0?{}:e.film,e.docs,o,e.viewports??F);let u=[],m=new Set;for(let i of e.coverage?.directories??[]){let s=S(o,i);if(B(o,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Ke(s)).isDirectory())throw Error(`Missing coverage directory: ${i}`);let c=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){c++;let n=B(o,g(s,r)).replaceAll("\\","/");if(m.add(n),!f.has(n)&&!e.coverage?.exclude?.[n]?.trim())u.push(n)}if(!c)throw Error(`No .stx screens found in ${i}`)}for(let[i,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(i))throw Error(`Stale or unexplained coverage exclusion: ${i}`);if(u.length)throw Error(`Undocumented screens:
113
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 () => {
114
+ `)}`)}async function X(e){let o=(await import(Qe(e).href)).default;if(!o||typeof o!=="object")throw Error("Screenshot configuration must have a default export");return o}async function Ye(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 me(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 Ze(e,o,a){let t=await X(e),l=S(a.root),f=S(l,a.outDir??t.outDir),p=[],u=await J(l,t.models),m=H(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let i={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000;for(let c of t.viewports??F){if(a.viewports?.length&&!a.viewports.includes(c.name))continue;for(let r of t.pages){if(a.only?.length&&!a.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(o))continue;if(r.viewports&&!r.viewports.includes(c.name))continue;let n={id:r.id,profile:o,viewport:c,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(p.push(n),r.skip){n.status="skipped",n.error=r.skip,process.send?.({type:"screenshot-result",result:n});continue}let d="starting the browser",h,y;try{h=await m.view(c.width,c.height),await Promise.race([(async()=>{let k=typeof r.path==="function"?await r.path({fixtures:i,models:u,profile:o}):_(r.path,r.model,i,u),b=new URL(k,t.baseUrl);if(b.origin!==new URL(t.baseUrl).origin||b.username||b.password)throw Error("Resolved screenshot path must stay on the configured origin");let O={...r,path:k},j={view:h,baseUrl:t.baseUrl,profile:o,viewport:c,page:O};n.path=b.pathname,d="preparing the review profile",await t.profiles?.[o]?.prepare?.(j),d="opening the screen",await h.navigate(new URL(O.path,t.baseUrl).href),d="checking the document HTTP status";let x=Number(await h.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(x)&&x>=100&&x<=599)j.httpStatus=n.httpStatus=x;if(!j.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?j.httpStatus!==r.expectedStatus:x>=400)throw Error(`The screen returned HTTP ${x}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);d="preparing the screen state",await r.prepare?.(j),d="waiting for screen readiness",await Ye(async()=>Boolean(await h.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(j)),s);let w=String(await h.evaluate("location.href"));if(de(w)!==de(new URL(O.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(d="loading fonts and visible images",await h.evaluate(`(async () => {
115
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);
116
- for (const selector of ${JSON.stringify(s.masks??[])}) document.querySelectorAll(selector);
116
+ for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
117
117
  const maskSheet = new CSSStyleSheet();
118
- maskSheet.replaceSync(${JSON.stringify(X(s.masks??[]))});
118
+ maskSheet.replaceSync(${JSON.stringify(Y(r.masks??[]))});
119
119
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
120
120
  await document.fonts.ready;
121
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})}); }
122
122
  await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
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(`
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");d="saving the screenshot";let C=new Uint8Array(await(await h.screenshot()).arrayBuffer()),E=`${r.id}/${o}-${c.name}.png`,v=g(f,E);await G(pe(v),{recursive:!0});let P=g(a.staging,`${r.id}-${o}-${c.name}.png`);await Bun.write(P,C),await Q(P,v),n.file=E,n.sha256=V(C),n.status="captured"})(),new Promise((k,b)=>{y=setTimeout(()=>{h?.close(),b(Error("Screenshot deadline exceeded"))},s)})])}catch(k){n.error=`${d}: ${me(k,t)}`}finally{if(y)clearTimeout(y);h?.close(),process.send?.({type:"screenshot-result",result:n})}}}return p}finally{try{await m.close()}finally{await t.data?.cleanup?.()}}}async function Ct(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let o=S(e.root??process.cwd()),a=S(o,e.config??"config/screenshots.ts"),t=await X(a);await he(t,o);for(let s of e.only??[])if(!t.pages.some((c)=>c.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??F).some((c)=>c.name===s))throw Error(`Unknown viewport: ${s}`);let l=S(o,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:A,models:await J(o,t.models),configHash:V(Buffer.concat([Buffer.from(A),await M(a),...await Promise.all(f.map((s)=>M(S(o,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 p;if(e.check){let s=JSON.parse(await M(g(l,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==A||s.configHash!==p.configHash||s.models?.sourceHash!==p.models.sourceHash||s.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 r of c.profiles??Object.keys(t.profiles??{default:{}}))for(let n of t.viewports??F){if(c.viewports&&!c.viewports.includes(n.name))continue;let d=s.results.find((h)=>h.id===c.id&&h.profile===r&&h.viewport.name===n.name);if(!d||!c.skip&&d.status!=="captured")throw Error(`Missing screenshot: ${c.id}/${r}-${n.name}`);if(d.file&&(B(l,S(l,d.file)).split(/[\\/]/)[0]===".."||ue(B(l,S(l,d.file)))||V(await M(g(l,d.file)))!==d.sha256))throw Error(`Screenshot bytes changed: ${c.id}`)}for(let c of s.films??[])if(B(l,S(l,c.file)).startsWith("..")||V(await M(g(l,c.file)))!==c.sha256)throw Error(`Screen film changed: ${c.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||V(await M(S(o,t.docs.page)))!==s.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return s}let u;try{let s=g(l,"manifest.json");if((await D(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(u=JSON.parse(await M(s,"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(s){if(s.code!=="ENOENT")throw s}let m=new Set(u?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let c=g(l,s.id);try{if((await D(c)).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 n of t.viewports??F){if(s.viewports&&!s.viewports.includes(n.name))continue;let d=`${s.id}/${r}-${n.name}.png`;try{if((await D(g(l,d))).isSymbolicLink()||!m.has(d))throw Error(`Refusing to overwrite an unowned screenshot: ${d}`)}catch(h){if(h.code!=="ENOENT")throw h}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await D(g(l,s))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(c){if(c.code!=="ENOENT")throw c}await G(l,{recursive:!0});let i=await fe(g(l,".stacks-screenshots-"));await Bun.write(g(i,"bunfig.toml"),`preload = []
124
+ `);try{for(let n of Object.keys(t.profiles??{default:{}})){let d=g(i,`${n}.json`),h=t.pages.filter((E)=>(!e.only?.length||e.only.includes(E.id))&&(E.profiles??Object.keys(t.profiles??{default:{}})).includes(n)),y=h.reduce((E,v)=>E+(t.viewports??F).filter((P)=>(!e.viewports?.length||e.viewports.includes(P.name))&&(!v.viewports||v.viewports.includes(P.name))).length,0);if(!y)continue;let k=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!k)throw Error("An installed Bun is required for screenshot workers");let b=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",o):import.meta.path,O=Ge(),j=process.platform!=="win32"&&Buffer.byteLength(O)>60?"/tmp":O,x=await fe(g(j,"stx-b-")),w={...process.env,TMPDIR:x,TMP:x,TEMP:x},R,C;try{let E=R=Xe([k,"--no-env-file",`--config=${g(i,"bunfig.toml")}`,b,"--worker",a,n,JSON.stringify({...e,root:o,staging:i}),d],{ownerRuntime:k,cwd:o,env:w,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(P)=>{let U=P;if(U?.type==="screenshot-result"&&U.result)e.onProgress?.(U.result)}});if((await Promise.race([E.exited,new Promise((P,U)=>{C=setTimeout(()=>{E.stop(),U(Error(`Screenshot worker timed out for ${n}`))},y*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${n}`);p.results.push(...JSON.parse(await M(d,"utf8")))}catch(E){for(let v of h)for(let P of t.viewports??F){if(e.viewports?.length&&!e.viewports.includes(P.name)||v.viewports&&!v.viewports.includes(P.name))continue;p.results.push({id:v.id,profile:n,viewport:P,title:v.title,description:v.description,path:new URL(typeof v.path==="string"?v.path:v.route,t.baseUrl).pathname,status:"failed",error:me(E,t)})}}finally{if(C)clearTimeout(C);await R?.stop(),await z(x,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let n=JSON.parse(await M(g(l,"manifest.json"),"utf8"));if(n.configHash===p.configHash&&n.models?.sourceHash===p.models.sourceHash){let d=new Set(p.results.map((h)=>`${h.id}/${h.profile}/${h.viewport.name}`));p.results.unshift(...n.results.filter((h)=>!d.has(`${h.id}/${h.profile}/${h.viewport.name}`)))}}catch{}for(let n of p.results){if(n.status!=="failed"||n.file)continue;let d=u?.results.find((h)=>h.id===n.id&&h.profile===n.profile&&h.viewport.name===n.viewport.name);if(d?.file)n.file=d.file,n.sha256=d.sha256}if(!e.only?.length&&!e.viewports?.length){let n=new Set(p.results.map((d)=>d.file).filter(Boolean));for(let d of m){if(!d||n.has(d)||B(l,S(l,d)).startsWith(".."))continue;await z(g(l,d),{force:!0}),await ze(pe(g(l,d))).catch(()=>{})}}await G(l,{recursive:!0});let s;try{if(e.publish!==!1){if(t.film)p.films=await q(l,p.results,t.viewports??F,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await I(o,p,t.docs)}}catch(n){s=n}await Bun.write(g(l,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
125
+ `),await Q(g(l,"manifest.json.tmp"),g(l,"manifest.json"));let c=(n)=>n.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
126
+ `," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${A}. Review the images before publishing.`,""];for(let n of p.results)r.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"),`${r.join(`
127
127
  `)}
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};
128
+ `),s)throw s;return p}finally{await z(i,{recursive:!0,force:!0})}}async function Ut(e={}){let o=S(e.root??process.cwd()),a=await X(S(o,e.config??"config/screenshots.ts"));await he(a,o);let t=S(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 f=JSON.parse(await M(l,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(delete f.films,delete f.docsPage,a.film)f.films=await q(t,f.results,a.viewports??F,a.film===!0?{}:a.film,a.backend);if(a.docs)f.docsPage=await I(o,f,a.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
129
+ `),await Q(g(t,"manifest.json.tmp"),l),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await Ze(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{Ct as captureScreenshots,Nt as defineScreenshotConfig,J as discoverScreenshotModels,le as discoverViews,L as planScreenshotModels,Ut as publishScreenshots,_e as screensFromViews,_ 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.657";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.660";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(`
@@ -1,5 +1,5 @@
1
1
  // @bun
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)=>`(() => {
2
+ import{spawnOwnedProcess as q}from"@stacksjs/cli/owned-process";import{click as ie,launch as J,settle as oe,waitFor as L}from"@stacksjs/testing/browser";import{randomUUID as _}from"crypto";import{readFile as ne,rm as j}from"fs/promises";import{dirname as W,join as H}from"path";import{Mp4Muxer as G}from"@ts-videos/mp4";import{BufferTarget as Q}from"ts-videos";function R(e={}){let t=Bun.serve({port:0,hostname:"127.0.0.1",fetch(o){let m=e[new URL(o.url).pathname];if(m)return new Response(Bun.file(m),{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 Z=["6400","4d00","42e0"],ee=(e)=>`(() => {
3
3
  if (window.__stacksFilm) return true
4
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
5
  const film = window.__stacksFilm = { chunks: [], description: null, error: null, frame: 0, encoder: null, canvas: null, context: null, width: 0, height: 0 }
@@ -7,7 +7,7 @@ import{spawnOwnedProcess as W}from"@stacksjs/cli/owned-process";import{click as
7
7
  if (typeof VideoEncoder !== 'function') throw new Error('This browser has no WebCodecs video encoder')
8
8
  film.width = width; film.height = height
9
9
  const level = width * height > 2097152 ? '33' : '28'
10
- for (const profile of ${JSON.stringify(Q)}) {
10
+ for (const profile of ${JSON.stringify(Z)}) {
11
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
12
  const support = await VideoEncoder.isConfigSupported(config).catch(() => null)
13
13
  if (!support || !support.supported) continue
@@ -94,7 +94,7 @@ import{spawnOwnedProcess as W}from"@stacksjs/cli/owned-process";import{click as
94
94
  return JSON.stringify({ width: film.width, height: film.height, description: film.description, chunks: film.chunks.splice(0) })
95
95
  }
96
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`
97
+ })()`,te=(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(ee(t));let o=[],m,f={width:0,height:0},d=0,n=async(r)=>{let i=JSON.parse(String(await e(`window.__stacksFilm.drain(${r})`)));if(f={width:i.width,height:i.height},i.description)m=new Uint8Array(Buffer.from(i.description,"base64"));for(let[u,c,p]of i.chunks)o.push([u,c,new Uint8Array(Buffer.from(p,"base64"))])};return{frames:()=>d,async add(r,i){if(!Number.isInteger(i)||i<1)return;let u=r?`${JSON.stringify(Buffer.from(r).toString("base64"))}, ${JSON.stringify(te(r))}`:"null, null";if(await e(`window.__stacksFilm.add(${u}, ${i})`),d+=i,d%(t.fps*20)<i)await n(!1)},async addVideo(r,i=[]){for(let c of i)if(![c.x,c.y,c.size,c.start,c.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(c.color))throw Error("Invalid film mark");let u=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(r)})`)));for(let c=0;c<u.frames;c+=t.fps){let p=Math.min(t.fps,u.frames-c);await e(`window.__stacksFilm.copy(${c}, ${p}, ${JSON.stringify(i)})`),d+=p,await n(!1)}return u.seconds},async finish(){if(await n(!0),!o.length||!m)throw Error("The browser encoded no video");let r=new Q,i=new G(r),u=i.addVideoTrack({codec:"h264",width:f.width,height:f.height,frameRate:t.fps,codecDescription:m});for(let[c,p,w]of o)await i.writePacket(u.id,{data:w,timestamp:p/1e6,duration:1/t.fps,isKeyframe:c===1});return await i.finalize(),r.buffer}}}import{launch as re}from"@stacksjs/testing/browser";function V(e){let t,o;return{async view(m,f){if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");if(e==="webkit")return new Bun.WebView({width:m,height:f,backend:e});if(!o){let d=await re({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let n=`127.0.0.1:${d.port}`,r=await fetch(`http://${n}/json/version`,{signal:AbortSignal.timeout(5000)});if(!r.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${r.status})`);let i=await r.json(),u=URL.parse(i.webSocketDebuggerUrl||"");if(u?.protocol!=="ws:"||u.host!==n||!u.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");o=u.href,t=d}catch(n){throw await d.close(),n}}return new Bun.WebView({width:m,height:f,backend:{type:"chrome",url:o}})},async close(){try{await t?.close()}finally{t=void 0,o=void 0}}}}function D(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
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
99
  ${o}, ${o}::selection {
100
100
  color: transparent !important;
@@ -107,12 +107,12 @@ ${o}, ${o}::selection {
107
107
  ${o}::selection { background: transparent !important; }
108
108
  ${o}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
109
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=`(() => {
110
+ `}function N(e,t,o,m){if(!Number.isFinite(e)||e<t||e>o)throw Error(`Invalid ${m}`)}function ae(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 E(e,t,o=30000){t?.throwIfAborted();let m=q(e),f=!1,d=()=>{m.stop().catch(()=>{})};t?.addEventListener("abort",d,{once:!0});let n=setTimeout(()=>{f=!0,d()},o);try{let[r,i]=await Promise.all([m.exited,new Response(m.stdout).bytes(),new Response(m.stderr).text()]);if(t?.throwIfAborted(),f)throw Error("Story tool timed out");if(r.code!==0)throw Error(`Story tool failed: ${e[0]}`);return i}finally{clearTimeout(n),t?.removeEventListener("abort",d),await m.stop()}}function Se(e){let t=ae(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:m,fps:f,signal:d}){let n=await J({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:r}=n,i,u,c,p=!1,w,x,A,B,M=new Map,I=r.on("Network.responseReceived",(s)=>{if(s.type==="Document")M.set(s.frameId,{status:s.response.status})}),h,k=new Promise((s)=>{h=s}),T=async()=>{h(),u?.stop(),u=void 0;let s=i;i=void 0,await Promise.race([s?.close().catch(()=>{}),Bun.sleep(5000)])},l=()=>{p=!0,T(),n.close().catch(()=>{})};d.addEventListener("abort",l,{once:!0});try{d.throwIfAborted();let s=`stacks-story-${_()}`,v=D(e.masks??[]),O=`(() => {
111
111
  const start = () => {
112
112
  const maskSheet = new CSSStyleSheet();
113
113
  maskSheet.replaceSync(${JSON.stringify(v)});
114
114
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
115
- const host = document.createElement('div'); host.id = ${JSON.stringify(n)};
115
+ const host = document.createElement('div'); host.id = ${JSON.stringify(s)};
116
116
  host.style.cssText='all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important;';
117
117
  const shadow=host.attachShadow({mode:'closed'}); const dot=document.createElement('div');
118
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;`)};
@@ -120,4 +120,4 @@ ${o}::-webkit-search-cancel-button { visibility: hidden !important; }
120
120
  addEventListener('mousemove', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px'},true);
121
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);
122
122
  }; if(document.documentElement) start(); else new MutationObserver((_,observer)=>{if(document.documentElement){observer.disconnect();start()}}).observe(document,{childList:true});
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};
123
+ })()`;await r.send("Page.addScriptToEvaluateOnNewDocument",{source:O});let P={x:24,y:24},y={cdp:r,async goto(a,g={}){let b=new URL(a,t);if(b.origin!==t.origin||b.username||b.password)throw Error("Story navigation must stay on baseUrl origin");let S=g.expectedStatus??200;if(!Number.isInteger(S)||S<100||S>599)throw Error("Invalid expected document status");let C=await r.send("Page.navigate",{url:b.href});if(C.errorText||!await oe(r,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(M.get(C.frameId)?.status!==S)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){d.throwIfAborted();let g=typeof a==="string"?a:a.selector,b=typeof a==="string"?void 0:a.text,S=await L(async()=>r.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(g)})].filter(el=>${b===void 0?"true":`el.textContent.trim()===${JSON.stringify(b)}`});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),C=P,Y=performance.now();do{d.throwIfAborted();let U=o.moveMs?Math.min(1,(performance.now()-Y)/o.moveMs):1;if(P={x:C.x+(S.x-C.x)*U,y:C.y+(S.y-C.y)*U},await r.send("Input.dispatchMouseEvent",{type:"mouseMoved",...P}),U===1)break;await Bun.sleep(16)}while(!0);await ie(r,a),await Bun.sleep(o.clickMs)},async type(a,g){await y.click(a),await r.send("Input.insertText",{text:g})},async expectText(a,g){await L(()=>r.evaluate(`document.querySelector(${JSON.stringify(a)})?.textContent.includes(${JSON.stringify(g)}) ?? false`),12000)}};if(await e.beforeNavigate?.(r),d.throwIfAborted(),await y.goto(t.href),e.prepare)await e.prepare(y);A=Buffer.from((await r.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),B=r.on("Page.screencastFrame",(a)=>{A=Buffer.from(a.data,"base64"),r.send("Page.screencastFrameAck",{sessionId:a.sessionId}).catch((g)=>{x=g})}),u=R(),i=await J({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),c=await z((a)=>F.evaluate(a),{fps:f}),await r.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let X=performance.now();w=(async()=>{let a=0,g;while(!p){if(d.throwIfAborted(),x)throw x;let b=Math.floor((performance.now()-X)/1000*f)+1;if(b-a>f*10)throw Error("Story encoder cannot keep up with the recording");if(b>a){let S=A;await Promise.race([c.add(S===g?void 0:S,b-a),k]),g=S,a=b}await Bun.sleep(Math.max(1,1000/f/2))}})().catch((a)=>{x=a});let K;return{context:y,screenshot:async()=>Buffer.from((await r.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>K??=(async()=>{p=!0;let a=!1,g=setTimeout(()=>{a=!0,T()},60000);try{if(await w,await r.send("Page.stopScreencast"),B?.(),x)throw Error("Story video capture failed",{cause:x});let b;try{b=await Promise.race([c.finish(),k.then(()=>{throw Error("The encoder page closed")})])}catch(S){throw Error(a?"Story video finalization timed out":"Story video capture failed",{cause:S})}if(await Bun.write(m,b),e.failOnBrowserErrors!==!1&&r.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(g),await T()}})(),async close(){p=!0,B?.(),I(),d.removeEventListener("abort",l);try{await T(),await w}finally{await n.close()}}}}catch(s){p=!0,B?.(),I(),d.removeEventListener("abort",l);try{await T(),await w}finally{await n.close()}throw s}}}}function ke(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 m=e.tapSize??72;return N(m,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:f,fps:d,signal:n}){let r=H(W(f),"native-raw.mp4"),i=e.adb??"adb",u=e.xcrun??"xcrun",c=`/sdcard/stacks-story-${_()}.mp4`,p,w,x,A=0,B=[],M=e.input??{async tap(h,k){await E([i,"-s",e.device,"shell","input","tap",String(Math.round(h)),String(Math.round(k))],n)},async swipe(h,k,T){await E([i,"-s",e.device,"shell","input","swipe",String(Math.round(h.x)),String(Math.round(h.y)),String(Math.round(k.x)),String(Math.round(k.y)),String(Math.round(T))],n)},async type(h){if(!/^[a-z0-9@._+ -]*$/i.test(h))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await E([i,"-s",e.device,"shell","input","text",h.replaceAll(" ","%s")],n)}},I=(h,k)=>{N(h,0,16384,"tap x"),N(k,0,16384,"tap y")};try{if(n.throwIfAborted(),t){let{recordIosSimulatorVideo:l}=await import("craft-native/testing");p=(await l({device:e.device,path:r,xcrun:u})).stop}else{if(new TextDecoder().decode(await E([i,"-s",e.device,"get-state"],n)).trim()!=="device")throw Error("Android emulator is unavailable");w=q([i,"-s",e.device,"shell",`screenrecord --time-limit 180 ${c} & 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 w.started;let s=w.stdout.getReader(),v="",O=setTimeout(()=>{w.stop()},15000);try{while(!x){let y=await s.read();if(y.done)throw Error("Android recorder stopped before startup");v+=new TextDecoder().decode(y.value);let F=/STACKS_RECORDER:(\d+)/.exec(v);if(F)x=Number(F[1]);if(v.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(O)}(async()=>{while(!(await s.read()).done);})().catch(()=>{}),new Response(w.stderr).text();let P=async()=>{await E([i,"-s",e.device,"shell",`case "$(cat /proc/${x}/cmdline 2>/dev/null)" in *${c}*) kill -2 ${x};; *) exit 3;; esac`])};await E([i,"-s",e.device,"shell","kill","-0",String(x)],n),p=async()=>{await P();let y=setTimeout(()=>{w.stop()},15000);try{await w.exited}finally{clearTimeout(y)}await E([i,"-s",e.device,"pull",c,r])},await E([i,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${c} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${x} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],n,20000)}A=performance.now();let h={async tap(l,s){n.throwIfAborted(),I(l,s);let v={x:l,y:s,start:(performance.now()-A)/1000,end:0};B.push(v);try{await M.tap(l,s)}finally{v.end=(performance.now()-A)/1000+(e.tapMs??450)/1000}},async swipe(l,s,v){if(n.throwIfAborted(),I(l.x,l.y),I(s.x,s.y),N(v,1,1e4,"swipe duration"),!M.swipe)throw Error("Native driver does not support swipes");await M.swipe(l,s,v)},async type(l){if(n.throwIfAborted(),!M.type)throw Error("Native driver does not support typing");await M.type(l)}},k;return{context:h,async screenshot(){if(n.throwIfAborted(),!t)return E([i,"-s",e.device,"exec-out","screencap","-p"],n);let l=H(W(f),`screenshot-${_()}.png`);try{return await E([u,"simctl","io",e.device,"screenshot",l],n),await ne(l)}finally{await j(l,{force:!0})}},finish:()=>k??=(async()=>{await p();let l=V(process.platform==="darwin"?"webkit":"chrome"),s=R({"/raw.mp4":r}),v;try{v=await l.view(320,240);let O=v;await O.navigate(s.url);let P=await z((y)=>O.evaluate(y),{fps:d});await P.addVideo("/raw.mp4",e.tapFeedback===!1?[]:B.map((y)=>({x:y.x,y:y.y,size:m,color:o,start:y.start,end:y.end}))),await Bun.write(f,await P.finish())}finally{s.stop();try{v?.close()}finally{await l.close()}}await j(r)})(),async close(){try{if(!k)await p?.()}finally{if(await w?.stop(),!t)await E([i,"-s",e.device,"shell","rm","-f",c])}}}}catch(h){try{await p?.()}finally{await w?.stop()}throw h}}}}export{Se as browserStory,ke 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.657",
5
+ "version": "0.75.660",
6
6
  "description": "The Stacks way to document.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,19 +58,19 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@stacksjs/bunpress": "^0.2.25",
61
- "@stacksjs/cli": "0.75.657",
62
- "@stacksjs/config": "0.75.657",
63
- "@stacksjs/path": "0.75.657",
64
- "@stacksjs/orm": "0.75.657",
61
+ "@stacksjs/cli": "0.75.660",
62
+ "@stacksjs/config": "0.75.660",
63
+ "@stacksjs/path": "0.75.660",
64
+ "@stacksjs/orm": "0.75.660",
65
65
  "@stacksjs/stx": "^0.2.908",
66
- "@stacksjs/testing": "0.75.657",
66
+ "@stacksjs/testing": "0.75.660",
67
67
  "@ts-videos/mp4": "^0.1.2",
68
68
  "craft-native": ">=0.0.499",
69
69
  "ts-videos": "^0.1.2"
70
70
  },
71
71
  "devDependencies": {
72
- "@stacksjs/alias": "0.75.657",
73
- "@stacksjs/server": "0.75.657",
72
+ "@stacksjs/alias": "0.75.660",
73
+ "@stacksjs/server": "0.75.660",
74
74
  "better-dx": "^0.2.39"
75
75
  }
76
76
  }