@stacksjs/docs 0.75.672 → 0.75.674

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.
@@ -51,6 +51,7 @@ export declare interface ScreenshotConfig {
51
51
  backend?: 'webkit' | 'chrome'
52
52
  requireHttpStatus?: boolean
53
53
  timeoutMs?: number
54
+ retries?: number
54
55
  inputs?: string[]
55
56
  coverage?: { directories: string[], exclude?: Record<string, string> }
56
57
  redactEnv?: string[]
@@ -76,6 +77,7 @@ export declare interface ScreenshotResult {
76
77
  file?: string
77
78
  sha256?: string
78
79
  error?: string
80
+ attempts?: number
79
81
  }
80
82
  export declare interface ScreenshotReport {
81
83
  format: 1
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{createHash as Ke}from"crypto";import{lstat as U,mkdir as z,mkdtemp as fe,readFile as M,rename as K,rm as q,rmdir as Ge,stat as Qe}from"fs/promises";import{tmpdir as Xe}from"os";import{dirname as pe,isAbsolute as ue,join as g,relative as B,resolve as v}from"path";import{pathToFileURL as Ye}from"url";function X(e){let i=`:is(${['input[type="password"]',...e].join(",")})`,n=`${i}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
2
+ import{createHash as Ye}from"crypto";import{lstat as A,mkdir as z,mkdtemp as ue,readFile as P,rename as K,rm as I,rmdir as Ze,stat as et}from"fs/promises";import{tmpdir as tt}from"os";import{dirname as we,isAbsolute as ge,join as g,relative as T,resolve as x}from"path";import{pathToFileURL as rt}from"url";function ee(e){let i=`:is(${['input[type="password"]',...e].join(",")})`,n=`${i}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
3
3
  ${i}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
4
4
  ${n}, ${n}::selection {
5
5
  color: transparent !important;
@@ -12,7 +12,7 @@ ${n}, ${n}::selection {
12
12
  ${n}::selection { background: transparent !important; }
13
13
  ${n}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
14
14
  ${n}::-webkit-search-cancel-button { visibility: hidden !important; }
15
- `}import{join as ge}from"path";import{launch as ye}from"@stacksjs/testing/browser";function Y(e,i){let n=ge(e,"stx-b-");return i!=="win32"&&Buffer.byteLength(n)+6>60?"/tmp/stx-b-":n}function D(e){let i,n;return{async view(t,c){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:c,backend:e});if(!n){let f=await ye({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(),o=URL.parse(m.webSocketDebuggerUrl||"");if(o?.protocol!=="ws:"||o.host!==p||!o.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");n=o.href,i=f}catch(p){throw await f.close(),p}}return new Bun.WebView({width:t,height:c,backend:{type:"chrome",url:n}})},async close(){try{await i?.close()}finally{i=void 0,n=void 0}}}}import{createHash as be}from"crypto";import{readFile as ve}from"fs/promises";import{existsSync as Se}from"fs";import{isAbsolute as ke,join as xe,relative as $e,resolve as Ee}from"path";import{loadModelRegistry as Pe,modelFiles as Z}from"@stacksjs/orm/model-registry";function V(e){let i=Object.entries(e).map(([r,a])=>{let d=Object.entries(a.attributes??{}),h=a.belongsTo??[],x=(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=a.traits?.useApi,E=a.traits?.useSeeder??a.traits?.seedable,j=(w,S)=>Boolean(S.hidden||S.encrypted||S.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),O=d.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(a.name??r),table:a.table,primaryKey:String(a.primaryKey??"id"),...b?.uri?{api:String(b.uri)}:{},parents:[...new Set([...x,...Array.isArray(E?.after)?E.after.map(String):[]])].sort(),seederCount:typeof E?.count==="number"?E.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:O,sensitiveFields:d.filter(([w,S])=>j(w,S)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...b?.routes?.includes("show")?["detail"]:[],...b?.middleware?.length?["permission-denied"]:[],...a.traits?.useSoftDeletes||a.traits?.softDeletable?["archived"]:[]])]}}).sort((r,a)=>r.name.localeCompare(a.name)),n=new Set(i.map((r)=>r.name)),t=new Map(i.map((r)=>[r.name,r])),c=[];for(;;){let r=[...t.values()].filter((a)=>a.parents.every((d)=>!n.has(d)||c.includes(d)));if(!r.length)break;for(let a of r)c.push(a.name),t.delete(a.name)}let f=new Set,p=new Map,u=new Map,m=[],o=new Set,s=0;function l(r){p.set(r,s),u.set(r,s++),m.push(r),o.add(r);for(let h of t.get(r)?.parents??[]){if(!t.has(h))continue;if(!p.has(h))l(h),u.set(r,Math.min(u.get(r),u.get(h)));else if(o.has(h))u.set(r,Math.min(u.get(r),p.get(h)))}if(u.get(r)!==p.get(r))return;let a=[],d;do d=m.pop(),o.delete(d),a.push(d);while(d!==r);if(a.length>1||t.get(r)?.parents.includes(r))for(let h of a)f.add(h)}for(let r of t.keys())if(!p.has(r))l(r);return{models:i,creationOrder:c,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(i.flatMap((r)=>r.parents).filter((r)=>!n.has(r)))].sort()}}async function H(e,i={}){if(i===!1)return V({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let n=Ee(e,i.directory??"app/Models");if(ke(i.directory??"")||$e(e,n).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=i.includeDefaults?xe(e,"storage/framework/defaults/app/Models"):void 0;if(!Se(n)&&!t)return V({});let c=[],f=await Pe({userRoot:n,defaultsRoot:t,onImportError:(m)=>c.push(m)});if(c.length)throw Error(`Cannot inspect screenshot models: ${c.join(", ")}`);let p=V(f),u=[...Z(n),...t?Z(t):[]].sort();return p.sourceHash=be("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>ve(m))))).digest("hex"),p}function W(e,i,n,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let c=i?t.models.filter((u)=>u.name===i):t.models.filter((u)=>u.api&&e.replace(/^\//,"").startsWith(`${u.api.replace(/^\//,"")}/`)),f=c.length===1?c[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=n[f.name];if(!p)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,m,o)=>{let s=m||o,l=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(l)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=p[l];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 Me}from"@ts-videos/mp4";import{BufferTarget as Oe}from"ts-videos";function ee(e={}){let i=Bun.serve({port:0,hostname:"127.0.0.1",fetch(n){let t=e[new URL(n.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:${i.port}/`,stop:()=>{i.stop(!0)}}}var je=["6400","4d00","42e0"],Fe=(e)=>`(() => {
15
+ `}import{join as Se}from"path";import{launch as ke}from"@stacksjs/testing/browser";function te(e,i){let n=Se(e,"stx-b-");return i!=="win32"&&Buffer.byteLength(n)+6>60?"/tmp/stx-b-":n}function D(e){let i,n;return{async view(t,c){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:c,backend:e});if(!n){let f=await ke({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 h=await u.json(),o=URL.parse(h.webSocketDebuggerUrl||"");if(o?.protocol!=="ws:"||o.host!==p||!o.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");n=o.href,i=f}catch(p){throw await f.close(),p}}return new Bun.WebView({width:t,height:c,backend:{type:"chrome",url:n}})},async close(){try{await i?.close()}finally{i=void 0,n=void 0}}}}import{createHash as xe}from"crypto";import{readFile as $e}from"fs/promises";import{existsSync as Ee}from"fs";import{isAbsolute as Pe,join as Me,relative as Oe,resolve as je}from"path";import{loadModelRegistry as Fe,modelFiles as re}from"@stacksjs/orm/model-registry";function V(e){let i=Object.entries(e).map(([a,r])=>{let l=Object.entries(r.attributes??{}),m=r.belongsTo??[],k=(Array.isArray(m)?m:Object.values(m)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),y=r.traits?.useApi,E=r.traits?.useSeeder??r.traits?.seedable,F=(w,b)=>Boolean(b.hidden||b.encrypted||b.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),M=l.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(r.name??a),table:r.table,primaryKey:String(r.primaryKey??"id"),...y?.uri?{api:String(y.uri)}:{},parents:[...new Set([...k,...Array.isArray(E?.after)?E.after.map(String):[]])].sort(),seederCount:typeof E?.count==="number"?E.count:null,factoryFields:l.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:l.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:M,sensitiveFields:l.filter(([w,b])=>F(w,b)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...y?.routes?.includes("show")?["detail"]:[],...y?.middleware?.length?["permission-denied"]:[],...r.traits?.useSoftDeletes||r.traits?.softDeletable?["archived"]:[]])]}}).sort((a,r)=>a.name.localeCompare(r.name)),n=new Set(i.map((a)=>a.name)),t=new Map(i.map((a)=>[a.name,a])),c=[];for(;;){let a=[...t.values()].filter((r)=>r.parents.every((l)=>!n.has(l)||c.includes(l)));if(!a.length)break;for(let r of a)c.push(r.name),t.delete(r.name)}let f=new Set,p=new Map,u=new Map,h=[],o=new Set,s=0;function d(a){p.set(a,s),u.set(a,s++),h.push(a),o.add(a);for(let m of t.get(a)?.parents??[]){if(!t.has(m))continue;if(!p.has(m))d(m),u.set(a,Math.min(u.get(a),u.get(m)));else if(o.has(m))u.set(a,Math.min(u.get(a),p.get(m)))}if(u.get(a)!==p.get(a))return;let r=[],l;do l=h.pop(),o.delete(l),r.push(l);while(l!==a);if(r.length>1||t.get(a)?.parents.includes(a))for(let m of r)f.add(m)}for(let a of t.keys())if(!p.has(a))d(a);return{models:i,creationOrder:c,cycles:[...f].sort(),blocked:[...t.keys()].filter((a)=>!f.has(a)),externalParents:[...new Set(i.flatMap((a)=>a.parents).filter((a)=>!n.has(a)))].sort()}}async function L(e,i={}){if(i===!1)return V({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let n=je(e,i.directory??"app/Models");if(Pe(i.directory??"")||Oe(e,n).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=i.includeDefaults?Me(e,"storage/framework/defaults/app/Models"):void 0;if(!Ee(n)&&!t)return V({});let c=[],f=await Fe({userRoot:n,defaultsRoot:t,onImportError:(h)=>c.push(h)});if(c.length)throw Error(`Cannot inspect screenshot models: ${c.join(", ")}`);let p=V(f),u=[...re(n),...t?re(t):[]].sort();return p.sourceHash=xe("sha256").update(Buffer.concat(await Promise.all(u.map((h)=>$e(h))))).digest("hex"),p}function W(e,i,n,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let c=i?t.models.filter((u)=>u.name===i):t.models.filter((u)=>u.api&&e.replace(/^\//,"").startsWith(`${u.api.replace(/^\//,"")}/`)),f=c.length===1?c[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let p=n[f.name];if(!p)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(u,h,o)=>{let s=h||o,d=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(d)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let a=p[d];if(a===void 0||a===""||typeof a!=="string"&&typeof a!=="number"||typeof a==="number"&&!Number.isFinite(a))throw Error(`Screenshot fixture ${f.name} has no ${s}`);return encodeURIComponent(String(a))})}import{Mp4Muxer as Re}from"@ts-videos/mp4";import{BufferTarget as Te}from"ts-videos";function se(e={}){let i=Bun.serve({port:0,hostname:"127.0.0.1",fetch(n){let t=e[new URL(n.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:${i.port}/`,stop:()=>{i.stop(!0)}}}var Be=["6400","4d00","42e0"],Ne=(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 @@ ${n}::-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(je)}) {
23
+ for (const profile of ${JSON.stringify(Be)}) {
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,26 +107,26 @@ ${n}::-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
- })()`,Re=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function te(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(Fe(i));let n=[],t,c={width:0,height:0},f=0,p=async(u)=>{let m=JSON.parse(String(await e(`window.__stacksFilm.drain(${u})`)));if(c={width:m.width,height:m.height},m.description)t=new Uint8Array(Buffer.from(m.description,"base64"));for(let[o,s,l]of m.chunks)n.push([o,s,new Uint8Array(Buffer.from(l,"base64"))])};return{frames:()=>f,async add(u,m){if(!Number.isInteger(m)||m<1)return;let o=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(Re(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${o}, ${m})`),f+=m,f%(i.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 o=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let s=0;s<o.frames;s+=i.fps){let l=Math.min(i.fps,o.frames-s);await e(`window.__stacksFilm.copy(${s}, ${l}, ${JSON.stringify(m)})`),f+=l,await p(!1)}return o.seconds},async finish(){if(await p(!0),!n.length||!t)throw Error("The browser encoded no video");let u=new Oe,m=new Me(u),o=m.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:i.fps,codecDescription:t});for(let[s,l,r]of n)await m.writePacket(o.id,{data:r,timestamp:l/1e6,duration:1/i.fps,isKeyframe:s===1});return await m.finalize(),u.buffer}}}import{createHash as Te}from"crypto";import{lstat as Be,mkdir as Ne,readFile as re,rename as se}from"fs/promises";import{dirname as Ce,isAbsolute as Ue,join as L,relative as Ae,resolve as ie}from"path";var oe="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",ne=(e)=>Te("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,i,n,t){if(e){let c=e.secondsPerScreen??2;if(!Number.isFinite(c)||c<0.2||c>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(i){let c=ie(n,i.page);if(Ue(i.page)||Ae(n,c).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 J(e,i,n,t,c=process.platform==="darwin"?"webkit":"chrome"){let f=[],p=t.secondsPerScreen??2,u=t.fps??12,m=Math.max(1,Math.round(p*u)),o=D(c),s=ee();try{for(let l of n){if(t.viewports?.length&&!t.viewports.includes(l.name))continue;let r=i.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===l.name);if(!r.length)continue;let a,d;try{d=await o.view(320,240);let y=d;await y.navigate(s.url);let x=await te((b)=>y.evaluate(b),{fps:u,width:l.width,height:l.height});for(let b of r)await x.add(new Uint8Array(await re(L(e,b.file))),m);a=await x.finish()}catch(y){throw Error(`The ${l.name} screens could not be filmed: ${y instanceof Error?y.message.slice(0,400):"the browser failed"}`)}finally{d?.close()}let h=`film-${l.name}.mp4`;await Bun.write(L(e,`${h}.tmp`),a),await se(L(e,`${h}.tmp`),L(e,h)),f.push({viewport:l.name,file:h,sha256:ne(a),screens:r.length,seconds:r.length*m/u})}return f}finally{try{await o.close()}finally{s.stop()}}}function De(e,i){let n=i.base.replace(/\/+$/,""),t=i.title??"Screens",c=e.results.filter((o)=>o.status==="captured"&&o.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",oe,"",`# ${T(t)}`,"",`${new Set(c.map((o)=>o.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 o of e.films??[]){let s=c.find((l)=>l.viewport.name===o.viewport);f.push(`## Walkthrough video (${T(o.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${n}/${o.file}`)}"${s?` poster="${N(`${n}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${o.screens} screens in ${Math.round(o.seconds)} seconds. [Download the video](${n}/${o.file}).`,"")}let p=(o)=>o.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",u=new Map;for(let o of e.inventory)u.set(p(o.path),[...u.get(p(o.path))??[],o]);let m=[];for(let[o,s]of[...u].sort(([l],[r])=>l.localeCompare(r))){let l=[];for(let r of s){let a=c.filter((d)=>d.id===r.id);if(!a.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}l.push(`### ${T(r.title)}`,"",T(a[0].description),"",...a[0].reason?[T(a[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let d of a)l.push("<figure>",` <img src="${N(`${n}/${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(l.length)f.push(`## ${T(o[0].toUpperCase()+o.slice(1).replace(/[-_]+/g," "))}`,"",...l)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
110
+ })()`,Ce=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function ie(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(Ne(i));let n=[],t,c={width:0,height:0},f=0,p=async(u)=>{let h=JSON.parse(String(await e(`window.__stacksFilm.drain(${u})`)));if(c={width:h.width,height:h.height},h.description)t=new Uint8Array(Buffer.from(h.description,"base64"));for(let[o,s,d]of h.chunks)n.push([o,s,new Uint8Array(Buffer.from(d,"base64"))])};return{frames:()=>f,async add(u,h){if(!Number.isInteger(h)||h<1)return;let o=u?`${JSON.stringify(Buffer.from(u).toString("base64"))}, ${JSON.stringify(Ce(u))}`:"null, null";if(await e(`window.__stacksFilm.add(${o}, ${h})`),f+=h,f%(i.fps*20)<h)await p(!1)},async addVideo(u,h=[]){for(let s of h)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 o=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(u)})`)));for(let s=0;s<o.frames;s+=i.fps){let d=Math.min(i.fps,o.frames-s);await e(`window.__stacksFilm.copy(${s}, ${d}, ${JSON.stringify(h)})`),f+=d,await p(!1)}return o.seconds},async finish(){if(await p(!0),!n.length||!t)throw Error("The browser encoded no video");let u=new Te,h=new Re(u),o=h.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:i.fps,codecDescription:t});for(let[s,d,a]of n)await h.writePacket(o.id,{data:a,timestamp:d/1e6,duration:1/i.fps,isKeyframe:s===1});return await h.finalize(),u.buffer}}}import{createHash as Ae}from"crypto";import{lstat as Ue,mkdir as De,readFile as oe,rename as ne}from"fs/promises";import{dirname as Ve,isAbsolute as Le,join as H,relative as He,resolve as ae}from"path";var ce="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",le=(e)=>Ae("sha256").update(e).digest("hex"),B=(e)=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),R=(e)=>B(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function de(e,i,n,t){if(e){let c=e.secondsPerScreen??2;if(!Number.isFinite(c)||c<0.2||c>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(i){let c=ae(n,i.page);if(Le(i.page)||He(n,c).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 J(e,i,n,t,c=process.platform==="darwin"?"webkit":"chrome"){let f=[],p=t.secondsPerScreen??2,u=t.fps??12,h=Math.max(1,Math.round(p*u)),o=D(c),s=se();try{for(let d of n){if(t.viewports?.length&&!t.viewports.includes(d.name))continue;let a=i.filter((S)=>S.status==="captured"&&S.file&&S.viewport.name===d.name);if(!a.length)continue;let r,l;try{l=await o.view(320,240);let S=l;await S.navigate(s.url);let k=await ie((y)=>S.evaluate(y),{fps:u,width:d.width,height:d.height});for(let y of a)await k.add(new Uint8Array(await oe(H(e,y.file))),h);r=await k.finish()}catch(S){throw Error(`The ${d.name} screens could not be filmed: ${S instanceof Error?S.message.slice(0,400):"the browser failed"}`)}finally{l?.close()}let m=`film-${d.name}.mp4`;await Bun.write(H(e,`${m}.tmp`),r),await ne(H(e,`${m}.tmp`),H(e,m)),f.push({viewport:d.name,file:m,sha256:le(r),screens:a.length,seconds:a.length*h/u})}return f}finally{try{await o.close()}finally{s.stop()}}}function We(e,i){let n=i.base.replace(/\/+$/,""),t=i.title??"Screens",c=e.results.filter((o)=>o.status==="captured"&&o.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",ce,"",`# ${R(t)}`,"",`${new Set(c.map((o)=>o.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 o of e.films??[]){let s=c.find((d)=>d.viewport.name===o.viewport);f.push(`## Walkthrough video (${R(o.viewport)})`,"",`<video controls playsinline preload="none" src="${B(`${n}/${o.file}`)}"${s?` poster="${B(`${n}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${o.screens} screens in ${Math.round(o.seconds)} seconds. [Download the video](${n}/${o.file}).`,"")}let p=(o)=>o.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",u=new Map;for(let o of e.inventory)u.set(p(o.path),[...u.get(p(o.path))??[],o]);let h=[];for(let[o,s]of[...u].sort(([d],[a])=>d.localeCompare(a))){let d=[];for(let a of s){let r=c.filter((l)=>l.id===a.id);if(!r.length){let l=e.results.find((m)=>m.id===a.id);h.push(`- ${R(a.title)} (\`${a.path}\`): ${a.skip?R(a.skip):l?"the last capture failed.":"not captured yet."}`);continue}d.push(`### ${R(a.title)}`,"",R(r[0].description),"",...r[0].reason?[R(r[0].reason),""]:[],`Address: \`${a.path}\``,"");for(let l of r)d.push("<figure>",` <img src="${B(`${n}/${l.file}`)}" alt="${B(`${l.title}, ${l.viewport.name}`)}" width="${l.viewport.width}" height="${l.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${l.viewport.width}px;height:auto">`,` <figcaption>${B(l.viewport.name)}, ${l.viewport.width} by ${l.viewport.height}${l.profile==="default"?"":`, signed in as ${B(l.profile)}`}</figcaption>`,"</figure>","")}if(d.length)f.push(`## ${R(o[0].toUpperCase()+o.slice(1).replace(/[-_]+/g," "))}`,"",...d)}if(h.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...h,"");return`${f.join(`
111
111
  `).trimEnd()}
112
- `}async function _(e,i,n){let t=ie(e,n.page);try{if((await Be(t)).isSymbolicLink()||!(await re(t,"utf8")).includes(oe))throw Error(`Refusing to replace a hand-written page: ${n.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let c=De(i,n);return await Ne(Ce(t),{recursive:!0}),await Bun.write(`${t}.tmp`,c),await se(`${t}.tmp`,t),{path:n.page,sha256:ne(c)}}import{createRouter as Ve}from"@stacksjs/stx";import{readFileSync as He}from"fs";import{relative as Le,resolve as We}from"path";var ce=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Je=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function _e(e){try{return He(e,"utf8")}catch{return""}}function qe(e,i){let n=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(n)return n;let t=i.split("/").filter(Boolean).map((c)=>c.startsWith("[")?`by ${ce(c.slice(1,-1).replace(/^\.\.\./,""))}`:ce(c));return t.length?Je(t.join(" / ")):"Home"}function le(e={}){let i=We(e.root??process.cwd()),n=[],t=new Set;for(let c of e.directories??["resources/views"])for(let f of Ve(i,{pagesDir:c,emit:!1})){let p=f.pattern.replace(/\*(\w*)/g,(l,r)=>`[...${r||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=p.split("/").filter(Boolean).map((l)=>l.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=u;for(let l=2;t.has(m);l++)m=`${u}-${l}`;t.add(m);let o=_e(f.filePath),s=o.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];n.push({id:m,route:p,source:Le(i,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:qe(o,p),...s?{layout:s}:{},text:o})}return n.sort((c,f)=>c.route<f.route?-1:c.route>f.route?1:0)}function Ie(e={}){let i=[],n=new Set;for(let t of le(e)){n.add(t.route);let c=[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 c){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;i.push(f)}for(let t of Object.keys(e.routes??{}))if(!n.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...i,...e.extra??[]]}import{spawnOwnedProcess as Ze}from"@stacksjs/cli/owned-process";import{ChromeLaunchError as et}from"@stacksjs/testing/browser";var C="0.75.672";var Vt=(e)=>e,F=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],A=(e)=>Ke("sha256").update(e).digest("hex"),I=(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 i=new URL(e);return i.origin+i.pathname};async function he(e,i=process.cwd()){let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.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((o)=>!I(o)))throw Error("Profile names must be safe filenames");let c=new Set,f=new Set;for(let o of e.pages){if(!I(o.id)||c.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(c.add(o.id),o.expectedStatus!==void 0&&(!Number.isInteger(o.expectedStatus)||o.expectedStatus<100||o.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${o.id}`);if(!o.title.trim()||!o.description.trim()||!o.waitFor.trim())throw Error(`Screen ${o.id} needs title, description and waitFor`);if(typeof o.path!=="string"&&(typeof o.path!=="function"||!o.route))throw Error(`Screen ${o.id} needs a route pattern for its path resolver`);let s=new URL(typeof o.path==="string"?o.path:o.route,n);if(s.origin!==n.origin||s.username||s.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((l)=>!t.includes(l))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let l of o.sources??[]){let r=v(i,l);if(B(i,r).startsWith("..")||ue(l))throw Error(`Source must be inside the project: ${l}`);await M(r),f.add(B(i,r).replaceAll("\\","/"))}}let p=new Set;for(let o of e.viewports??F){if(!I(o.name)||p.has(o.name)||![o.width,o.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(o.name)}if(!p.size)throw Error("At least one viewport is required");for(let o of e.pages)if(o.viewports!==void 0&&(!o.viewports.length||o.viewports.some((s)=>!p.has(s))))throw Error(`Unknown or empty viewports for ${o.id}`);for(let o of e.inputs??[])await M(v(i,o));ae(e.film===!0?{}:e.film,e.docs,i,e.viewports??F);let u=[],m=new Set;for(let o of e.coverage?.directories??[]){let s=v(i,o);if(B(i,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Qe(s)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let l=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){l++;let a=B(i,g(s,r)).replaceAll("\\","/");if(m.add(a),!f.has(a)&&!e.coverage?.exclude?.[a]?.trim())u.push(a)}if(!l)throw Error(`No .stx screens found in ${o}`)}for(let[o,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(u.length)throw Error(`Undocumented screens:
112
+ `}async function _(e,i,n){let t=ae(e,n.page);try{if((await Ue(t)).isSymbolicLink()||!(await oe(t,"utf8")).includes(ce))throw Error(`Refusing to replace a hand-written page: ${n.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let c=We(i,n);return await De(Ve(t),{recursive:!0}),await Bun.write(`${t}.tmp`,c),await ne(`${t}.tmp`,t),{path:n.page,sha256:le(c)}}import{createRouter as Je}from"@stacksjs/stx";import{readFileSync as _e}from"fs";import{relative as Ie,resolve as qe}from"path";var fe=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),ze=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Ke(e){try{return _e(e,"utf8")}catch{return""}}function Ge(e,i){let n=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(n)return n;let t=i.split("/").filter(Boolean).map((c)=>c.startsWith("[")?`by ${fe(c.slice(1,-1).replace(/^\.\.\./,""))}`:fe(c));return t.length?ze(t.join(" / ")):"Home"}function pe(e={}){let i=qe(e.root??process.cwd()),n=[],t=new Set;for(let c of e.directories??["resources/views"])for(let f of Je(i,{pagesDir:c,emit:!1})){let p=f.pattern.replace(/\*(\w*)/g,(d,a)=>`[...${a||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=p.split("/").filter(Boolean).map((d)=>d.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",h=u;for(let d=2;t.has(h);d++)h=`${u}-${d}`;t.add(h);let o=Ke(f.filePath),s=o.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];n.push({id:h,route:p,source:Ie(i,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:Ge(o,p),...s?{layout:s}:{},text:o})}return n.sort((c,f)=>c.route<f.route?-1:c.route>f.route?1:0)}function Qe(e={}){let i=[],n=new Set;for(let t of pe(e)){n.add(t.route);let c=[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 c){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;i.push(f)}for(let t of Object.keys(e.routes??{}))if(!n.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...i,...e.extra??[]]}import{spawnOwnedProcess as st}from"@stacksjs/cli/owned-process";import{ChromeLaunchError as it}from"@stacksjs/testing/browser";var C="0.75.674";var Jt=(e)=>e,he="Screenshot deadline exceeded",j=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],U=(e)=>Ye("sha256").update(e).digest("hex"),q=(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),me=(e)=>{let i=new URL(e);return i.origin+i.pathname};async function ye(e,i=process.cwd()){let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.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.retries!==void 0&&(!Number.isInteger(e.retries)||e.retries<0||e.retries>3))throw Error("retries must be a whole number from 0 to 3");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((o)=>!q(o)))throw Error("Profile names must be safe filenames");let c=new Set,f=new Set;for(let o of e.pages){if(!q(o.id)||c.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(c.add(o.id),o.expectedStatus!==void 0&&(!Number.isInteger(o.expectedStatus)||o.expectedStatus<100||o.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${o.id}`);if(!o.title.trim()||!o.description.trim()||!o.waitFor.trim())throw Error(`Screen ${o.id} needs title, description and waitFor`);if(typeof o.path!=="string"&&(typeof o.path!=="function"||!o.route))throw Error(`Screen ${o.id} needs a route pattern for its path resolver`);let s=new URL(typeof o.path==="string"?o.path:o.route,n);if(s.origin!==n.origin||s.username||s.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((d)=>!t.includes(d))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let d of o.sources??[]){let a=x(i,d);if(T(i,a).startsWith("..")||ge(d))throw Error(`Source must be inside the project: ${d}`);await P(a),f.add(T(i,a).replaceAll("\\","/"))}}let p=new Set;for(let o of e.viewports??j){if(!q(o.name)||p.has(o.name)||![o.width,o.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(o.name)}if(!p.size)throw Error("At least one viewport is required");for(let o of e.pages)if(o.viewports!==void 0&&(!o.viewports.length||o.viewports.some((s)=>!p.has(s))))throw Error(`Unknown or empty viewports for ${o.id}`);for(let o of e.inputs??[])await P(x(i,o));de(e.film===!0?{}:e.film,e.docs,i,e.viewports??j);let u=[],h=new Set;for(let o of e.coverage?.directories??[]){let s=x(i,o);if(T(i,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await et(s)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let d=0;for await(let a of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){d++;let r=T(i,g(s,a)).replaceAll("\\","/");if(h.add(r),!f.has(r)&&!e.coverage?.exclude?.[r]?.trim())u.push(r)}if(!d)throw Error(`No .stx screens found in ${o}`)}for(let[o,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!h.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(u.length)throw Error(`Undocumented screens:
113
113
  ${u.sort().join(`
114
- `)}`)}async function G(e){let i=(await import(Ye(e).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function tt(e,i){let n=Date.now()+i;while(!await e()){if(Date.now()>=n)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function me(e,i){let n=e instanceof Error?e.message:"Screenshot capture failed";if(e instanceof et&&e.diagnostics.stderrTail.trim()){let t=e.diagnostics.stderrTail.trim(),c=t.split(`
114
+ `)}`)}async function G(e){let i=(await import(rt(e).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function ot(e,i){let n=Date.now()+i;while(!await e()){if(Date.now()>=n)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function be(e,i){let n=e instanceof Error?e.message:"Screenshot capture failed";if(e instanceof it&&e.diagnostics.stderrTail.trim()){let t=e.diagnostics.stderrTail.trim(),c=t.split(`
115
115
  `).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);n=`${n.split(`
116
116
  `,1)[0]}
117
- ${c}`}for(let t of i.redactEnv??[]){let c=process.env[t];if(c)n=n.replaceAll(c,"[redacted]")}return n.slice(0,1000)}async function rt(e,i,n){let t=await G(e),c=v(n.root),f=v(c,n.outDir??t.outDir),p=[],u=await H(c,t.models),m=D(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let o={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000;for(let l of t.viewports??F){if(n.viewports?.length&&!n.viewports.includes(l.name))continue;for(let r of t.pages){if(n.only?.length&&!n.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(i))continue;if(r.viewports&&!r.viewports.includes(l.name))continue;let a={id:r.id,profile:i,viewport:l,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(a),r.skip){a.status="skipped",a.error=r.skip,process.send?.({type:"screenshot-result",result:a});continue}let d="starting the browser",h,y;try{h=await m.view(l.width,l.height),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:o,models:u,profile:i}):W(r.path,r.model,o,u),b=new URL(x,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 E={...r,path:x},j={view:h,baseUrl:t.baseUrl,profile:i,viewport:l,page:E};a.path=b.pathname,d="preparing the review profile",await t.profiles?.[i]?.prepare?.(j),d="opening the screen",await h.navigate(new URL(E.path,t.baseUrl).href),d="checking the document HTTP status";let O=Number(await h.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(O)&&O>=100&&O<=599)j.httpStatus=a.httpStatus=O;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:O>=400)throw Error(`The screen returned HTTP ${O}${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 tt(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(E.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 () => {
117
+ ${c}`}for(let t of i.redactEnv??[]){let c=process.env[t];if(c)n=n.replaceAll(c,"[redacted]")}return n.slice(0,1000)}async function nt(e,i,n){let t=await G(e),c=x(n.root),f=x(c,n.outDir??t.outDir),p=[],u=await L(c,t.models),h=D(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let o={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000,d=t.retries??1;for(let a of t.viewports??j){if(n.viewports?.length&&!n.viewports.includes(a.name))continue;for(let r of t.pages){if(n.only?.length&&!n.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(i))continue;if(r.viewports&&!r.viewports.includes(a.name))continue;let l={id:r.id,profile:i,viewport:a,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(l),r.skip){l.status="skipped",l.error=r.skip,process.send?.({type:"screenshot-result",result:l});continue}let m=0;for(let S=0;;S++){m=S+1;let k="starting the browser",y,E;try{delete l.error,y=await h.view(a.width,a.height),await Promise.race([(async()=>{let F=typeof r.path==="function"?await r.path({fixtures:o,models:u,profile:i}):W(r.path,r.model,o,u),M=new URL(F,t.baseUrl);if(M.origin!==new URL(t.baseUrl).origin||M.username||M.password)throw Error("Resolved screenshot path must stay on the configured origin");let w={...r,path:F},b={view:y,baseUrl:t.baseUrl,profile:i,viewport:a,page:w};l.path=M.pathname,k="preparing the review profile",await t.profiles?.[i]?.prepare?.(b),k="opening the screen",await y.navigate(new URL(w.path,t.baseUrl).href),k="checking the document HTTP status";let v=Number(await y.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(v)&&v>=100&&v<=599)b.httpStatus=l.httpStatus=v;if(!b.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?b.httpStatus!==r.expectedStatus:v>=400)throw Error(`The screen returned HTTP ${v}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);k="preparing the screen state",await r.prepare?.(b),k="waiting for screen readiness",await ot(async()=>Boolean(await y.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(b)),s);let O=String(await y.evaluate("location.href"));if(me(O)!==me(new URL(w.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(k="loading fonts and visible images",await y.evaluate(`(async () => {
118
118
  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);
119
119
  for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
120
120
  const maskSheet = new CSSStyleSheet();
121
- maskSheet.replaceSync(${JSON.stringify(X(r.masks??[]))});
121
+ maskSheet.replaceSync(${JSON.stringify(ee(r.masks??[]))});
122
122
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
123
123
  await document.fonts.ready;
124
124
  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})}); }
125
125
  await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
126
- })()`),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 k=new Uint8Array(await(await h.screenshot()).arrayBuffer()),P=`${r.id}/${i}-${l.name}.png`,R=g(f,P);await z(pe(R),{recursive:!0});let Q=g(n.staging,`${r.id}-${i}-${l.name}.png`);await Bun.write(Q,k),await K(Q,R),a.file=P,a.sha256=A(k),a.status="captured"})(),new Promise((x,b)=>{y=setTimeout(()=>{h?.close(),b(Error("Screenshot deadline exceeded"))},s)})])}catch(x){a.error=`${d}: ${me(x,t)}`}finally{if(y)clearTimeout(y);h?.close(),process.send?.({type:"screenshot-result",result:a})}}}return p}finally{try{await m.close()}finally{await t.data?.cleanup?.()}}}async function Ht(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let i=v(e.root??process.cwd()),n=v(i,e.config??"config/screenshots.ts"),t=await G(n);await he(t,i);for(let s of e.only??[])if(!t.pages.some((l)=>l.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??F).some((l)=>l.name===s))throw Error(`Unknown viewport: ${s}`);let c=v(i,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:C,models:await H(i,t.models),configHash:A(Buffer.concat([Buffer.from(C),await M(n),...await Promise.all(f.map((s)=>M(v(i,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return p;if(e.check){let s=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==C||s.configHash!==p.configHash||s.models?.sourceHash!==p.models.sourceHash||s.results.some((l)=>l.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let l of t.pages)for(let r of l.profiles??Object.keys(t.profiles??{default:{}}))for(let a of t.viewports??F){if(l.viewports&&!l.viewports.includes(a.name))continue;let d=s.results.find((h)=>h.id===l.id&&h.profile===r&&h.viewport.name===a.name);if(!d||!l.skip&&d.status!=="captured")throw Error(`Missing screenshot: ${l.id}/${r}-${a.name}`);if(d.file&&(B(c,v(c,d.file)).split(/[\\/]/)[0]===".."||ue(B(c,v(c,d.file)))||A(await M(g(c,d.file)))!==d.sha256))throw Error(`Screenshot bytes changed: ${l.id}`)}for(let l of s.films??[])if(B(c,v(c,l.file)).startsWith("..")||A(await M(g(c,l.file)))!==l.sha256)throw Error(`Screen film changed: ${l.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||A(await M(v(i,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(c,"manifest.json");if((await U(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 l=g(c,s.id);try{if((await U(l)).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 a of t.viewports??F){if(s.viewports&&!s.viewports.includes(a.name))continue;let d=`${s.id}/${r}-${a.name}.png`;try{if((await U(g(c,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 U(g(c,s))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(l){if(l.code!=="ENOENT")throw l}await z(c,{recursive:!0});let o=await fe(g(c,".stacks-screenshots-"));await Bun.write(g(o,"bunfig.toml"),`preload = []
127
- `);try{for(let a of Object.keys(t.profiles??{default:{}})){let d=g(o,`${a}.json`),h=t.pages.filter((S)=>(!e.only?.length||e.only.includes(S.id))&&(S.profiles??Object.keys(t.profiles??{default:{}})).includes(a)),y=h.reduce((S,k)=>S+(t.viewports??F).filter((P)=>(!e.viewports?.length||e.viewports.includes(P.name))&&(!k.viewports||k.viewports.includes(P.name))).length,0);if(!y)continue;let x=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!x)throw Error("An installed Bun is required for screenshot workers");let b=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,E=await fe(Y(Xe(),process.platform)),j={...process.env,TMPDIR:E,TMP:E,TEMP:E},O,w;try{let S=O=Ze([x,"--no-env-file",`--config=${g(o,"bunfig.toml")}`,b,"--worker",n,a,JSON.stringify({...e,root:i,staging:o}),d],{ownerRuntime:x,cwd:i,env:j,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(P)=>{let R=P;if(R?.type==="screenshot-result"&&R.result)e.onProgress?.(R.result)}});if((await Promise.race([S.exited,new Promise((P,R)=>{w=setTimeout(()=>{S.stop(),R(Error(`Screenshot worker timed out for ${a}`))},y*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${a}`);p.results.push(...JSON.parse(await M(d,"utf8")))}catch(S){for(let k of h)for(let P of t.viewports??F){if(e.viewports?.length&&!e.viewports.includes(P.name)||k.viewports&&!k.viewports.includes(P.name))continue;p.results.push({id:k.id,profile:a,viewport:P,title:k.title,description:k.description,path:new URL(typeof k.path==="string"?k.path:k.route,t.baseUrl).pathname,status:"failed",error:me(S,t)})}}finally{if(w)clearTimeout(w);await O?.stop(),await q(E,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let a=JSON.parse(await M(g(c,"manifest.json"),"utf8"));if(a.configHash===p.configHash&&a.models?.sourceHash===p.models.sourceHash){let d=new Set(p.results.map((h)=>`${h.id}/${h.profile}/${h.viewport.name}`));p.results.unshift(...a.results.filter((h)=>!d.has(`${h.id}/${h.profile}/${h.viewport.name}`)))}}catch{}for(let a of p.results){if(a.status!=="failed"||a.file)continue;let d=u?.results.find((h)=>h.id===a.id&&h.profile===a.profile&&h.viewport.name===a.viewport.name);if(d?.file)a.file=d.file,a.sha256=d.sha256}if(!e.only?.length&&!e.viewports?.length){let a=new Set(p.results.map((d)=>d.file).filter(Boolean));for(let d of m){if(!d||a.has(d)||B(c,v(c,d)).startsWith(".."))continue;await q(g(c,d),{force:!0}),await Ge(pe(g(c,d))).catch(()=>{})}}await z(c,{recursive:!0});let s;try{if(e.publish!==!1&&we(p)){if(t.film)p.films=await J(c,p.results,t.viewports??F,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await _(i,p,t.docs)}}catch(a){s=a}await Bun.write(g(c,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
128
- `),await K(g(c,"manifest.json.tmp"),g(c,"manifest.json"));let l=(a)=>a.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
129
- `," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let a of p.results)r.push(`## ${l(a.title)} (${a.profile}, ${a.viewport.name})`,"",l(a.description),"",...a.reason?[l(a.reason),""]:[],a.status==="captured"?`![${l(a.title)}](${a.file})`:`**${a.status}:** ${l(a.error??"No image")}`,"");if(await Bun.write(g(c,"gallery.md"),`${r.join(`
126
+ })()`),await y.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");k="saving the screenshot";let Q=new Uint8Array(await(await y.screenshot()).arrayBuffer()),X=`${r.id}/${i}-${a.name}.png`,Y=g(f,X);await z(we(Y),{recursive:!0});let Z=g(n.staging,`${r.id}-${i}-${a.name}.png`);await Bun.write(Z,Q),await K(Z,Y),l.file=X,l.sha256=U(Q),l.status="captured"})(),new Promise((F,M)=>{E=setTimeout(()=>{y?.close(),M(Error(he))},s)})])}catch(F){l.error=`${k}: ${be(F,t)}`}finally{if(E)clearTimeout(E);y?.close()}if(l.status==="captured"||S>=d||!l.error?.endsWith(he))break;await Bun.sleep(2000)}if(l.status!=="captured"&&l.error)l.attempts=m;process.send?.({type:"screenshot-result",result:l})}}return p}finally{try{await h.close()}finally{await t.data?.cleanup?.()}}}async function _t(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let i=x(e.root??process.cwd()),n=x(i,e.config??"config/screenshots.ts"),t=await G(n);await ye(t,i);for(let s of e.only??[])if(!t.pages.some((d)=>d.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??j).some((d)=>d.name===s))throw Error(`Unknown viewport: ${s}`);let c=x(i,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),p={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:C,models:await L(i,t.models),configHash:U(Buffer.concat([Buffer.from(C),await P(n),...await Promise.all(f.map((s)=>P(x(i,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return p;if(e.check){let s=JSON.parse(await P(g(c,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==C||s.configHash!==p.configHash||s.models?.sourceHash!==p.models.sourceHash||s.results.some((d)=>d.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let d of t.pages)for(let a of d.profiles??Object.keys(t.profiles??{default:{}}))for(let r of t.viewports??j){if(d.viewports&&!d.viewports.includes(r.name))continue;let l=s.results.find((m)=>m.id===d.id&&m.profile===a&&m.viewport.name===r.name);if(!l||!d.skip&&l.status!=="captured")throw Error(`Missing screenshot: ${d.id}/${a}-${r.name}`);if(l.file&&(T(c,x(c,l.file)).split(/[\\/]/)[0]===".."||ge(T(c,x(c,l.file)))||U(await P(g(c,l.file)))!==l.sha256))throw Error(`Screenshot bytes changed: ${d.id}`)}for(let d of s.films??[])if(T(c,x(c,d.file)).startsWith("..")||U(await P(g(c,d.file)))!==d.sha256)throw Error(`Screen film changed: ${d.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||U(await P(x(i,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(c,"manifest.json");if((await A(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(u=JSON.parse(await P(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 h=new Set(u?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let d=g(c,s.id);try{if((await A(d)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${s.id}`)}catch(a){if(a.code!=="ENOENT")throw a}for(let a of s.profiles??Object.keys(t.profiles??{default:{}}))for(let r of t.viewports??j){if(s.viewports&&!s.viewports.includes(r.name))continue;let l=`${s.id}/${a}-${r.name}.png`;try{if((await A(g(c,l))).isSymbolicLink()||!h.has(l))throw Error(`Refusing to overwrite an unowned screenshot: ${l}`)}catch(m){if(m.code!=="ENOENT")throw m}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await A(g(c,s))).isSymbolicLink()||!u)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(d){if(d.code!=="ENOENT")throw d}await z(c,{recursive:!0});let o=await ue(g(c,".stacks-screenshots-"));await Bun.write(g(o,"bunfig.toml"),`preload = []
127
+ `);try{for(let r of Object.keys(t.profiles??{default:{}})){let l=g(o,`${r}.json`),m=t.pages.filter((b)=>(!e.only?.length||e.only.includes(b.id))&&(b.profiles??Object.keys(t.profiles??{default:{}})).includes(r)),S=m.reduce((b,v)=>b+(t.viewports??j).filter((O)=>(!e.viewports?.length||e.viewports.includes(O.name))&&(!v.viewports||v.viewports.includes(O.name))).length,0);if(!S)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 y=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,E=await ue(te(tt(),process.platform)),F={...process.env,TMPDIR:E,TMP:E,TEMP:E},M,w;try{let b=M=st([k,"--no-env-file",`--config=${g(o,"bunfig.toml")}`,y,"--worker",n,r,JSON.stringify({...e,root:i,staging:o}),l],{ownerRuntime:k,cwd:i,env:F,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(O)=>{let N=O;if(N?.type==="screenshot-result"&&N.result)e.onProgress?.(N.result)}});if((await Promise.race([b.exited,new Promise((O,N)=>{w=setTimeout(()=>{b.stop(),N(Error(`Screenshot worker timed out for ${r}`))},S*((t.timeoutMs??30000)+2000)*(1+(t.retries??1))+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${r}`);p.results.push(...JSON.parse(await P(l,"utf8")))}catch(b){for(let v of m)for(let O of t.viewports??j){if(e.viewports?.length&&!e.viewports.includes(O.name)||v.viewports&&!v.viewports.includes(O.name))continue;p.results.push({id:v.id,profile:r,viewport:O,title:v.title,description:v.description,path:new URL(typeof v.path==="string"?v.path:v.route,t.baseUrl).pathname,status:"failed",error:be(b,t)})}}finally{if(w)clearTimeout(w);await M?.stop(),await I(E,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let r=JSON.parse(await P(g(c,"manifest.json"),"utf8"));if(r.configHash===p.configHash&&r.models?.sourceHash===p.models.sourceHash){let l=new Set(p.results.map((m)=>`${m.id}/${m.profile}/${m.viewport.name}`));p.results.unshift(...r.results.filter((m)=>!l.has(`${m.id}/${m.profile}/${m.viewport.name}`)))}}catch{}for(let r of p.results){if(r.status!=="failed"||r.file)continue;let l=u?.results.find((m)=>m.id===r.id&&m.profile===r.profile&&m.viewport.name===r.viewport.name);if(l?.file)r.file=l.file,r.sha256=l.sha256}if(!e.only?.length&&!e.viewports?.length){let r=new Set(p.results.map((l)=>l.file).filter(Boolean));for(let l of h){if(!l||r.has(l)||T(c,x(c,l)).startsWith(".."))continue;await I(g(c,l),{force:!0}),await Ze(we(g(c,l))).catch(()=>{})}}await z(c,{recursive:!0});let s;try{if(e.publish!==!1&&ve(p)){if(t.film)p.films=await J(c,p.results,t.viewports??j,t.film===!0?{}:t.film,t.backend);if(t.docs)p.docsPage=await _(i,p,t.docs)}}catch(r){s=r}await Bun.write(g(c,"manifest.json.tmp"),`${JSON.stringify(p,null,2)}
128
+ `),await K(g(c,"manifest.json.tmp"),g(c,"manifest.json"));let d=(r)=>r.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
129
+ `," "),a=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let r of p.results)a.push(`## ${d(r.title)} (${r.profile}, ${r.viewport.name})`,"",d(r.description),"",...r.reason?[d(r.reason),""]:[],r.status==="captured"?`![${d(r.title)}](${r.file})`:`**${r.status}:** ${d(r.error??"No image")}`,"");if(await Bun.write(g(c,"gallery.md"),`${a.join(`
130
130
  `)}
131
- `),s)throw s;return p}finally{await q(o,{recursive:!0,force:!0})}}function we(e){let i=new Set(e.results.map((n)=>n.id));return e.inventory.every((n)=>i.has(n.id))}async function Lt(e={}){let i=v(e.root??process.cwd()),n=await G(v(i,e.config??"config/screenshots.ts"));await he(n,i);let t=v(i,e.outDir??n.outDir),c=g(t,"manifest.json");if((await U(c)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await M(c,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(!we(f))throw Error("This manifest pictures only part of the inventory; capture every screen before publishing its films and page");if(delete f.films,delete f.docsPage,n.film)f.films=await J(t,f.results,n.viewports??F,n.film===!0?{}:n.film,n.backend);if(n.docs)f.docsPage=await _(i,f,n.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
132
- `),await K(g(t,"manifest.json.tmp"),c),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await rt(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{Ht as captureScreenshots,Vt as defineScreenshotConfig,H as discoverScreenshotModels,le as discoverViews,V as planScreenshotModels,Lt as publishScreenshots,Ie as screensFromViews,W as screenshotFixturePath,he as validateScreenshotConfig};
131
+ `),s)throw s;return p}finally{await I(o,{recursive:!0,force:!0})}}function ve(e){let i=new Set(e.results.map((n)=>n.id));return e.inventory.every((n)=>i.has(n.id))}async function It(e={}){let i=x(e.root??process.cwd()),n=await G(x(i,e.config??"config/screenshots.ts"));await ye(n,i);let t=x(i,e.outDir??n.outDir),c=g(t,"manifest.json");if((await A(c)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await P(c,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(!ve(f))throw Error("This manifest pictures only part of the inventory; capture every screen before publishing its films and page");if(delete f.films,delete f.docsPage,n.film)f.films=await J(t,f.results,n.viewports??j,n.film===!0?{}:n.film,n.backend);if(n.docs)f.docsPage=await _(i,f,n.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
132
+ `),await K(g(t,"manifest.json.tmp"),c),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await nt(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{_t as captureScreenshots,Jt as defineScreenshotConfig,L as discoverScreenshotModels,pe as discoverViews,V as planScreenshotModels,It as publishScreenshots,Qe as screensFromViews,W as screenshotFixturePath,ye as validateScreenshotConfig};
package/dist/stories.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{createHash as nt,randomUUID as lt}from"crypto";import{createReadStream as ut}from"fs";import{copyFile as pt,lstat as Y,mkdir as _,open as ht,readFile as P,realpath as at,rename as Z,rm as st,writeFile as F}from"fs/promises";import{basename as ct,dirname as Q,isAbsolute as et,join as u,relative as T,resolve as A,sep as dt}from"path";import{pathToFileURL as wt}from"url";var rt="0.75.672";function $t(t){return t}function Mt(t){return t}var B=`stacks-story-recordings-v1
2
+ import{createHash as nt,randomUUID as lt}from"crypto";import{createReadStream as ut}from"fs";import{copyFile as pt,lstat as Y,mkdir as _,open as ht,readFile as P,realpath as at,rename as Z,rm as st,writeFile as F}from"fs/promises";import{basename as ct,dirname as Q,isAbsolute as et,join as u,relative as T,resolve as A,sep as dt}from"path";import{pathToFileURL as wt}from"url";var rt="0.75.674";function $t(t){return t}function Mt(t){return t}var B=`stacks-story-recordings-v1
3
3
  `,tt="<!-- Generated by buddy docs:stories. -->",L=(t)=>nt("sha256").update(t).digest("hex"),it=(t)=>typeof t==="string"&&/^[a-z0-9][a-z0-9-]{0,79}$/.test(t);function N(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replace(/[\r\n]/g," ").replace(/([\\`*_[\]#|])/g,"\\$1")}async function H(t){try{return await Y(t),!0}catch(s){if(s.code==="ENOENT")return!1;throw s}}async function x(t,s=t){let n=A(t);while(!0){if(await H(n)){if((await Y(n)).isSymbolicLink())throw Error(`Story output cannot traverse a symbolic link: ${n}`)}if(n===A(s))return;let e=Q(n);if(e===n)return;n=e}}async function q(t,s){await x(s,t);let n=await Y(s);if(!n.isFile()||n.size===0)throw Error(`Missing or empty story artifact: ${s}`);let e=nt("sha256"),f=0;for await(let m of ut(s))e.update(m),f+=m.length;return{path:T(t,s).split(dt).join("/"),sha256:e.digest("hex"),bytes:f}}function K(t,s){let n=A(t,s.path);if(!s.path||et(s.path)||T(t,n).startsWith(".."))throw Error("Story artifact escaped its output directory");return n}async function jt(t,s,n=process.cwd()){if(!t.length||!s.endsWith(".mp4"))throw Error("Expected story manifests and an MP4 destination");let e=await Promise.all(t.map(async(o)=>{let b=JSON.parse(await P(o,"utf8")),a=await at(b.mediaDir?A(n,b.mediaDir):Q(A(o)));return{report:b,root:a}})),{configHash:f,inventory:m}=e[0].report;if(!m.length||e.some(({report:o})=>o.version!==1||o.configHash!==f))throw Error("The recordings must share one Stacks story configuration");let{Mp4Demuxer:i,Mp4Muxer:d}=await import("@ts-videos/mp4"),{BufferSource:y,BufferTarget:W,parseMp4Chapters:X}=await import("ts-videos"),G=new W,D=new d(G),h=[],v,r=0;for(let o of m){let b=e.flatMap(({report:l,root:S})=>l.results.filter((U)=>U.id===o.id&&U.status==="passed").map((U)=>({root:S,result:U}))).at(-1),a=b?.result.video;if(!a||b.result.scenes.length!==o.scenes.length||o.scenes.some((l)=>!b.result.scenes.some((S)=>S.id===l.id&&S.status==="passed"&&S.screenshot)))throw Error(`Story ${o.id} has missing or failed recording evidence`);let w=K(b.root,a);if(await x(w,b.root),ct(w)!=="video.mp4"||!(await Y(w)).isFile())throw Error(`Unexpected video path for ${o.id}`);let g=await P(w);if(g.length!==a.bytes||L(g)!==a.sha256)throw Error(`The recording for ${o.id} no longer matches its manifest`);let M=new i(new y(g)),R=await M.getTracks(),C=R.find((l)=>l.type==="video");if(C?.codec!=="h264"||!C.codecDescription?.length||R.some((l)=>l.type==="audio"))throw Error(`Story ${o.id} needs a silent H.264 recording`);let{width:J,height:j,codecDescription:I,frameRate:O}=C;if(!v)v={id:D.addVideoTrack({codec:"h264",width:J,height:j,frameRate:O,codecDescription:I}).id,width:J,height:j,description:I};if(J!==v.width||j!==v.height||!Buffer.from(I).equals(v.description))throw Error(`Story ${o.id} has a different viewport or H.264 configuration`);let z=Math.round(r*1000);D.addChapter(o.title,z);let V,k=0;for await(let l of M.packets(C.id)){if(V===void 0&&!l.isKeyframe)throw Error(`Story ${o.id} has no opening keyframe`);V??=l.timestamp;let S=l.timestamp-V;if(!Number.isFinite(S)||S<0||!l.duration||!Number.isFinite(l.duration)||l.duration<=0)throw Error(`Story ${o.id} has invalid video timing`);await D.writePacket(v.id,{...l,timestamp:r+S}),k=Math.max(k,S+l.duration)}if(!k)throw Error(`Story ${o.id} has no video frames`);r+=k,h.push({title:o.title,start:z,end:Math.round(r*1000)})}await D.finalize();let p=G.buffer,E=X(p).chapters;if(E.length!==h.length||E.some((o,b)=>o.startTime!==h[b]?.start||o.title!==h[b]?.title))throw Error("The MP4 chapters did not match the story inventory");let c=A(s);return await F(c,p,{flag:"wx"}),{output:c,seconds:r,chapters:h}}function ot(t,s){let n=T(t,s);return n&&!n.startsWith("..")&&!et(n)?n.split(dt).join("/"):s}async function mt(t){if(!t||!Array.isArray(t.stories)||!t.stories.length)throw Error("Story configuration needs at least one story");let s=new Set,n=(e,f,m,i)=>{if(!Number.isInteger(e)||e<f||e>m)throw Error(`Invalid story ${i}`)};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(!it(e.id)||s.has(e.id)||!e.title?.trim())throw Error(`Invalid or duplicate story id/title: ${e.id}`);if(s.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 f=new Set;for(let m of e.scenes){if(!it(m.id)||f.has(m.id)||!m.title?.trim()||typeof m.run!=="function")throw Error(`Invalid or duplicate scene in ${e.id}: ${m.id}`);f.add(m.id),n(m.holdMs??t.holdMs??700,0,30000,"scene holdMs"),n(m.timeoutMs??t.timeoutMs??120000,100,1800000,"scene timeoutMs")}}}function gt(t,s){let n=[tt,`# ${N(t.title)}`,"",t.description?N(t.description):"","",`Platform: ${t.platform}. Result: **${t.status}**.`,""];if(t.video)n.push(`<video controls playsinline preload="metadata" src="${s}${t.video.path}" poster="${t.scenes.find((e)=>e.screenshot)?.screenshot?s+t.scenes.find((e)=>e.screenshot).screenshot.path:""}"></video>`,"",`[Download video](${s}${t.video.path})`,"");for(let e of t.scenes)if(n.push(`## ${N(e.title)}`,"",`Result: **${e.status}**.${e.startedMs===void 0?"":` Starts at ${(e.startedMs/1000).toFixed(1)}s.`}`,"",e.description?N(e.description):"",""),e.screenshot)n.push(`![${N(e.title)}](${s}${e.screenshot.path})`,"");else n.push("No screenshot was captured for this scene.","");return`${n.join(`
4
4
  `).trimEnd()}
5
5
  `}async function Pt(t={}){if(t.list&&t.check)throw Error("Choose --list or --check");let s=await at(A(t.root??process.cwd())),n=A(s,t.config??"config/stories.ts"),e=await P(n),f=(await import(`${wt(n).href}?story=${L(e)}`)).default;await mt(f);let m=[rt,L(e),L(JSON.stringify(f,(r,p)=>typeof p==="function"?p.toString():p))];for(let r of[...f.inputs??[]].sort())m.push(`${r}:${L(await P(A(s,r)))}`);let i=A(s,t.outDir??f.outDir??"docs/stories"),d=f.publishDir===!1?void 0:A(s,f.publishDir??u(Q(i),"public",ct(i)));if(d&&(d===i||!T(i,d).startsWith("..")||!T(d,i).startsWith("..")))throw Error("Published media must have a separate directory outside the story output");if(i===s||T(i,s)===""||!T(i,s).startsWith("..")&&!et(T(i,s)))throw Error("Story output must not contain the project root");let y={version:1,configHash:L(m.join(`
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.672",
5
+ "version": "0.75.674",
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.33",
61
- "@stacksjs/cli": "0.75.672",
62
- "@stacksjs/config": "0.75.672",
63
- "@stacksjs/path": "0.75.672",
64
- "@stacksjs/orm": "0.75.672",
65
- "@stacksjs/stx": "^0.2.930",
66
- "@stacksjs/testing": "0.75.672",
61
+ "@stacksjs/cli": "0.75.674",
62
+ "@stacksjs/config": "0.75.674",
63
+ "@stacksjs/path": "0.75.674",
64
+ "@stacksjs/orm": "0.75.674",
65
+ "@stacksjs/stx": "^0.2.931",
66
+ "@stacksjs/testing": "0.75.674",
67
67
  "@ts-videos/mp4": "^0.2.2",
68
68
  "craft-native": ">=0.0.499",
69
69
  "ts-videos": "^0.2.2"
70
70
  },
71
71
  "devDependencies": {
72
- "@stacksjs/alias": "0.75.672",
73
- "@stacksjs/server": "0.75.672",
72
+ "@stacksjs/alias": "0.75.674",
73
+ "@stacksjs/server": "0.75.674",
74
74
  "better-dx": "^0.2.39"
75
75
  }
76
76
  }