@stacksjs/docs 0.75.660 → 0.75.663
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capture-browser.d.ts +2 -0
- package/dist/screenshot-publish.js +3 -3
- package/dist/screenshots.js +16 -13
- package/dist/stories.js +1 -1
- package/dist/story-drivers.d.ts +1 -0
- package/dist/story-drivers.js +7 -7
- package/package.json +10 -10
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Leave room in a Unix socket path for Chromium's temporary directory and socket name. */
|
|
2
|
+
export declare function captureWorkerTempTemplate(root: string, platform: NodeJS.Platform): string;
|
|
1
3
|
/** Open WebViews inside the same isolated browser launcher that runs browser tests. */
|
|
2
4
|
export declare function captureBrowser(backend: 'webkit' | 'chrome'): {
|
|
3
5
|
view: (width: number, height: number) => Promise<Bun.WebView>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
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(
|
|
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(i){let o=e[new URL(i.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:${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 }
|
|
@@ -94,6 +94,6 @@ import{Mp4Muxer as O}from"@ts-videos/mp4";import{BufferTarget as T}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
|
-
})()`,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
|
|
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 i=[],o,l={width:0,height:0},c=0,h=async(f)=>{let n=JSON.parse(String(await e(`window.__stacksFilm.drain(${f})`)));if(l={width:n.width,height:n.height},n.description)o=new Uint8Array(Buffer.from(n.description,"base64"));for(let[t,s,a]of n.chunks)i.push([t,s,new Uint8Array(Buffer.from(a,"base64"))])};return{frames:()=>c,async add(f,n){if(!Number.isInteger(n)||n<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}, ${n})`),c+=n,c%(r.fps*20)<n)await h(!1)},async addVideo(f,n=[]){for(let s of n)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 t=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(f)})`)));for(let s=0;s<t.frames;s+=r.fps){let a=Math.min(r.fps,t.frames-s);await e(`window.__stacksFilm.copy(${s}, ${a}, ${JSON.stringify(n)})`),c+=a,await h(!1)}return t.seconds},async finish(){if(await h(!0),!i.length||!o)throw Error("The browser encoded no video");let f=new T,n=new O(f),t=n.addVideoTrack({codec:"h264",width:l.width,height:l.height,frameRate:r.fps,codecDescription:o});for(let[s,a,d]of i)await n.writePacket(t.id,{data:d,timestamp:a/1e6,duration:1/r.fps,isKeyframe:s===1});return await n.finalize(),f.buffer}}}import{join as C}from"path";import{launch as R}from"@stacksjs/testing/browser";function Q(e,r){let i=C(e,"stx-b-");return r!=="win32"&&Buffer.byteLength(i)+6>60?"/tmp/stx-b-":i}function E(e){let r,i;return{async view(o,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:o,height:l,backend:e});if(!i){let c=await R({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 n=await f.json(),t=URL.parse(n.webSocketDebuggerUrl||"");if(t?.protocol!=="ws:"||t.host!==h||!t.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");i=t.href,r=c}catch(h){throw await c.close(),h}}return new Bun.WebView({width:o,height:l,backend:{type:"chrome",url:i}})},async close(){try{await r?.close()}finally{r=void 0,i=void 0}}}}import{createHash as _}from"crypto";import{lstat as W,mkdir as J,readFile as F,rename as M}from"fs/promises";import{dirname as L,isAbsolute as j,join as v,relative as D,resolve as P}from"path";var A="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",B=(e)=>_("sha256").update(e).digest("hex"),g=(e)=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),w=(e)=>g(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function ie(e,r,i,o){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(!o.some((h)=>h.name===c))throw Error(`Unknown film viewport: ${c}`)}if(r){let l=P(i,r.page);if(j(r.page)||D(i,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 ne(e,r,i,o,l=process.platform==="darwin"?"webkit":"chrome"){let c=[],h=o.secondsPerScreen??2,f=o.fps??12,n=Math.max(1,Math.round(h*f)),t=E(l),s=x();try{for(let a of i){if(o.viewports?.length&&!o.viewports.includes(a.name))continue;let d=r.filter((u)=>u.status==="captured"&&u.file&&u.viewport.name===a.name);if(!d.length)continue;let p,m;try{m=await t.view(320,240);let u=m;await u.navigate(s.url);let k=await S((y)=>u.evaluate(y),{fps:f,width:a.width,height:a.height});for(let y of d)await k.add(new Uint8Array(await F(v(e,y.file))),n);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{m?.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:d.length,seconds:d.length*n/f})}return c}finally{try{await t.close()}finally{s.stop()}}}function z(e,r){let i=r.base.replace(/\/+$/,""),o=r.title??"Screens",l=e.results.filter((t)=>t.status==="captured"&&t.file),c=["---",`title: ${JSON.stringify(o)}`,`description: ${JSON.stringify(r.description??"Every screen of the application, captured automatically from its views.")}`,"---","",A,"",`# ${w(o)}`,"",`${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 s=l.find((a)=>a.viewport.name===t.viewport);c.push(`## Walkthrough video (${w(t.viewport)})`,"",`<video controls playsinline preload="none" src="${g(`${i}/${t.file}`)}"${s?` poster="${g(`${i}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${t.screens} screens in ${Math.round(t.seconds)} seconds. [Download the video](${i}/${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 n=[];for(let[t,s]of[...f].sort(([a],[d])=>a.localeCompare(d))){let a=[];for(let d of s){let p=l.filter((m)=>m.id===d.id);if(!p.length){let m=e.results.find((b)=>b.id===d.id);n.push(`- ${w(d.title)} (\`${d.path}\`): ${d.skip?w(d.skip):m?"the last capture failed.":"not captured yet."}`);continue}a.push(`### ${w(d.title)}`,"",w(p[0].description),"",...p[0].reason?[w(p[0].reason),""]:[],`Address: \`${d.path}\``,"");for(let m of p)a.push("<figure>",` <img src="${g(`${i}/${m.file}`)}" alt="${g(`${m.title}, ${m.viewport.name}`)}" width="${m.viewport.width}" height="${m.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${m.viewport.width}px;height:auto">`,` <figcaption>${g(m.viewport.name)}, ${m.viewport.width} by ${m.viewport.height}${m.profile==="default"?"":`, signed in as ${g(m.profile)}`}</figcaption>`,"</figure>","")}if(a.length)c.push(`## ${w(t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," "))}`,"",...a)}if(n.length)c.push("## Not pictured","","These screens are part of the application and have no picture here.","",...n,"");return`${c.join(`
|
|
98
98
|
`).trimEnd()}
|
|
99
|
-
`}async function
|
|
99
|
+
`}async function oe(e,r,i){let o=P(e,i.page);try{if((await W(o)).isSymbolicLink()||!(await F(o,"utf8")).includes(A))throw Error(`Refusing to replace a hand-written page: ${i.page}`)}catch(c){if(c.code!=="ENOENT")throw c}let l=z(r,i);return await J(L(o),{recursive:!0}),await Bun.write(`${o}.tmp`,l),await M(`${o}.tmp`,o),{path:i.page,sha256:B(l)}}export{ne as filmScreenshots,A as generatedScreensPage,z as renderScreensPage,ie as validateScreenshotPublishing,oe as writeScreensPage};
|
package/dist/screenshots.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createHash as
|
|
2
|
+
import{createHash as ze}from"crypto";import{lstat as U,mkdir as z,mkdtemp as fe,readFile as M,rename as K,rm as q,rmdir as Ke,stat as Ge}from"fs/promises";import{tmpdir as Qe}from"os";import{dirname as pe,isAbsolute as ue,join as g,relative as B,resolve as S}from"path";import{pathToFileURL as Xe}from"url";function X(e){let o=`:is(${['input[type="password"]',...e].join(",")})`,a=`${o}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
|
|
3
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{
|
|
15
|
+
`}import{join as we}from"path";import{launch as ge}from"@stacksjs/testing/browser";function Y(e,o){let a=we(e,"stx-b-");return o!=="win32"&&Buffer.byteLength(a)+6>60?"/tmp/stx-b-":a}function D(e){let o,a;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(!a){let f=await ge({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:c,backend:{type:"chrome",url:a}})},async close(){try{await o?.close()}finally{o=void 0,a=void 0}}}}import{createHash as ye}from"crypto";import{readFile as be}from"fs/promises";import{existsSync as Se}from"fs";import{isAbsolute as ve,join as ke,relative as xe,resolve as $e}from"path";import{loadModelRegistry as Ee,modelFiles as Z}from"@stacksjs/orm/model-registry";function V(e){let o=Object.entries(e).map(([r,n])=>{let d=Object.entries(n.attributes??{}),h=n.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=n.traits?.useApi,E=n.traits?.useSeeder??n.traits?.seedable,j=(w,v)=>Boolean(v.hidden||v.encrypted||v.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(n.name??r),table:n.table,primaryKey:String(n.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,v])=>j(w,v)).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])),c=[];for(;;){let r=[...t.values()].filter((n)=>n.parents.every((d)=>!a.has(d)||c.includes(d)));if(!r.length)break;for(let n of r)c.push(n.name),t.delete(n.name)}let f=new Set,p=new Map,u=new Map,m=[],i=new Set,s=0;function l(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))l(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))l(r);return{models:o,creationOrder:c,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 H(e,o={}){if(o===!1)return V({});if(o.directory!==void 0&&!o.directory.trim())throw Error("Model directory must not be empty");let a=$e(e,o.directory??"app/Models");if(ve(o.directory??"")||xe(e,a).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=o.includeDefaults?ke(e,"storage/framework/defaults/app/Models"):void 0;if(!Se(a)&&!t)return V({});let c=[],f=await Ee({userRoot:a,defaultsRoot:t,onImportError:(m)=>c.push(m)});if(c.length)throw Error(`Cannot inspect screenshot models: ${c.join(", ")}`);let p=V(f),u=[...Z(a),...t?Z(t):[]].sort();return p.sourceHash=ye("sha256").update(Buffer.concat(await Promise.all(u.map((m)=>be(m))))).digest("hex"),p}function W(e,o,a,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let c=o?t.models.filter((u)=>u.name===o):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=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,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 Pe}from"@ts-videos/mp4";import{BufferTarget as Me}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 Oe=["6400","4d00","42e0"],je=(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(
|
|
23
|
+
for (const profile of ${JSON.stringify(Oe)}) {
|
|
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,26 @@ ${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
|
-
})()`,
|
|
110
|
+
})()`,Fe=(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(je(o));let a=[],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[i,s,l]of m.chunks)a.push([i,s,new Uint8Array(Buffer.from(l,"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(Fe(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 l=Math.min(o.fps,i.frames-s);await e(`window.__stacksFilm.copy(${s}, ${l}, ${JSON.stringify(m)})`),f+=l,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 Me,m=new Pe(u),i=m.addVideoTrack({codec:"h264",width:c.width,height:c.height,frameRate:o.fps,codecDescription:t});for(let[s,l,r]of a)await m.writePacket(i.id,{data:r,timestamp:l/1e6,duration:1/o.fps,isKeyframe:s===1});return await m.finalize(),u.buffer}}}import{createHash as Re}from"crypto";import{lstat as Te,mkdir as Be,readFile as re,rename as se}from"fs/promises";import{dirname as Ne,isAbsolute as Ce,join as L,relative as Ue,resolve as ie}from"path";var oe="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",ne=(e)=>Re("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),T=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1");function ae(e,o,a,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(o){let c=ie(a,o.page);if(Ce(o.page)||Ue(a,c).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 J(e,o,a,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)),i=D(c),s=ee();try{for(let l of a){if(t.viewports?.length&&!t.viewports.includes(l.name))continue;let r=o.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===l.name);if(!r.length)continue;let n,d;try{d=await i.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);n=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`),n),await se(L(e,`${h}.tmp`),L(e,h)),f.push({viewport:l.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 Ae(e,o){let a=o.base.replace(/\/+$/,""),t=o.title??"Screens",c=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(c.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=c.find((l)=>l.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(([l],[r])=>l.localeCompare(r))){let l=[];for(let r of s){let n=c.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}l.push(`### ${T(r.title)}`,"",T(n[0].description),"",...n[0].reason?[T(n[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let d of n)l.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(l.length)f.push(`## ${T(i[0].toUpperCase()+i.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(`
|
|
111
111
|
`).trimEnd()}
|
|
112
|
-
`}async function
|
|
112
|
+
`}async function _(e,o,a){let t=ie(e,a.page);try{if((await Te(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 c=Ae(o,a);return await Be(Ne(t),{recursive:!0}),await Bun.write(`${t}.tmp`,c),await se(`${t}.tmp`,t),{path:a.page,sha256:ne(c)}}import{createRouter as De}from"@stacksjs/stx";import{readFileSync as Ve}from"fs";import{relative as He,resolve as Le}from"path";var ce=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),We=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Je(e){try{return Ve(e,"utf8")}catch{return""}}function _e(e,o){let a=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(a)return a;let t=o.split("/").filter(Boolean).map((c)=>c.startsWith("[")?`by ${ce(c.slice(1,-1).replace(/^\.\.\./,""))}`:ce(c));return t.length?We(t.join(" / ")):"Home"}function le(e={}){let o=Le(e.root??process.cwd()),a=[],t=new Set;for(let c of e.directories??["resources/views"])for(let f of De(o,{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 i=Je(f.filePath),s=i.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];a.push({id:m,route:p,source:He(o,f.filePath).replaceAll("\\","/"),group:p.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:_e(i,p),...s?{layout:s}:{},text:i})}return a.sort((c,f)=>c.route<f.route?-1:c.route>f.route?1:0)}function qe(e={}){let o=[],a=new Set;for(let t of le(e)){a.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;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 Ye}from"@stacksjs/cli/owned-process";import{ChromeLaunchError as Ze}from"@stacksjs/testing/browser";var C="0.75.663";var Dt=(e)=>e,F=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],A=(e)=>ze("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 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)=>!I(i)))throw Error("Profile names must be safe filenames");let c=new Set,f=new Set;for(let i of e.pages){if(!I(i.id)||c.has(i.id))throw Error(`Duplicate or invalid screen id: ${i.id}`);if(c.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((l)=>!t.includes(l))||i.profiles?.length===0)throw Error(`Unknown or empty profiles for ${i.id}`);for(let l of i.sources??[]){let r=S(o,l);if(B(o,r).startsWith("..")||ue(l))throw Error(`Source must be inside the project: ${l}`);await M(r),f.add(B(o,r).replaceAll("\\","/"))}}let p=new Set;for(let i of e.viewports??F){if(!I(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 Ge(s)).isDirectory())throw Error(`Missing coverage directory: ${i}`);let l=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){l++;let n=B(o,g(s,r)).replaceAll("\\","/");if(m.add(n),!f.has(n)&&!e.coverage?.exclude?.[n]?.trim())u.push(n)}if(!l)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
|
|
114
|
+
`)}`)}async function G(e){let o=(await import(Xe(e).href)).default;if(!o||typeof o!=="object")throw Error("Screenshot configuration must have a default export");return o}async function et(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";if(e instanceof Ze&&e.diagnostics.stderrTail.trim()){let t=e.diagnostics.stderrTail.trim(),c=t.split(`
|
|
115
|
+
`).filter((f)=>/FATAL|Check failed/.test(f)).at(-1)??t.slice(-750);a=`${a.split(`
|
|
116
|
+
`,1)[0]}
|
|
117
|
+
${c}`}for(let t of o.redactEnv??[]){let c=process.env[t];if(c)a=a.replaceAll(c,"[redacted]")}return a.slice(0,1000)}async function tt(e,o,a){let t=await G(e),c=S(a.root),f=S(c,a.outDir??t.outDir),p=[],u=await H(c,t.models),m=D(t.backend??(process.platform==="darwin"?"webkit":"chrome"));try{let i={...t.fixtures,...await t.data?.prepare(u)},s=t.timeoutMs??30000;for(let l of t.viewports??F){if(a.viewports?.length&&!a.viewports.includes(l.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(l.name))continue;let n={id:r.id,profile:o,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(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(l.width,l.height),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:i,models:u,profile:o}):W(r.path,r.model,i,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:o,viewport:l,page:E};n.path=b.pathname,d="preparing the review profile",await t.profiles?.[o]?.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=n.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 et(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 () => {
|
|
115
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);
|
|
116
119
|
for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
|
|
117
120
|
const maskSheet = new CSSStyleSheet();
|
|
118
|
-
maskSheet.replaceSync(${JSON.stringify(
|
|
121
|
+
maskSheet.replaceSync(${JSON.stringify(X(r.masks??[]))});
|
|
119
122
|
document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
|
|
120
123
|
await document.fonts.ready;
|
|
121
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})}); }
|
|
122
125
|
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");d="saving the screenshot";let
|
|
124
|
-
`);try{for(let n of Object.keys(t.profiles??{default:{}})){let d=g(i,`${n}.json`),h=t.pages.filter((
|
|
125
|
-
`),await
|
|
126
|
-
`," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${
|
|
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}/${o}-${l.name}.png`,R=g(f,P);await z(pe(R),{recursive:!0});let Q=g(a.staging,`${r.id}-${o}-${l.name}.png`);await Bun.write(Q,k),await K(Q,R),n.file=P,n.sha256=A(k),n.status="captured"})(),new Promise((x,b)=>{y=setTimeout(()=>{h?.close(),b(Error("Screenshot deadline exceeded"))},s)})])}catch(x){n.error=`${d}: ${me(x,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 Vt(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 G(a);await he(t,o);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=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:C,models:await H(o,t.models),configHash:A(Buffer.concat([Buffer.from(C),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(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 n of t.viewports??F){if(l.viewports&&!l.viewports.includes(n.name))continue;let d=s.results.find((h)=>h.id===l.id&&h.profile===r&&h.viewport.name===n.name);if(!d||!l.skip&&d.status!=="captured")throw Error(`Missing screenshot: ${l.id}/${r}-${n.name}`);if(d.file&&(B(c,S(c,d.file)).split(/[\\/]/)[0]===".."||ue(B(c,S(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,S(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(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(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 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 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 i=await fe(g(c,".stacks-screenshots-"));await Bun.write(g(i,"bunfig.toml"),`preload = []
|
|
127
|
+
`);try{for(let n of Object.keys(t.profiles??{default:{}})){let d=g(i,`${n}.json`),h=t.pages.filter((v)=>(!e.only?.length||e.only.includes(v.id))&&(v.profiles??Object.keys(t.profiles??{default:{}})).includes(n)),y=h.reduce((v,k)=>v+(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",o):import.meta.path,E=await fe(Y(Qe(),process.platform)),j={...process.env,TMPDIR:E,TMP:E,TEMP:E},O,w;try{let v=O=Ye([x,"--no-env-file",`--config=${g(i,"bunfig.toml")}`,b,"--worker",a,n,JSON.stringify({...e,root:o,staging:i}),d],{ownerRuntime:x,cwd:o,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([v.exited,new Promise((P,R)=>{w=setTimeout(()=>{v.stop(),R(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(v){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:n,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(v,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 n=JSON.parse(await M(g(c,"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(c,S(c,d)).startsWith(".."))continue;await q(g(c,d),{force:!0}),await Ke(pe(g(c,d))).catch(()=>{})}}await z(c,{recursive:!0});let s;try{if(e.publish!==!1){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 _(o,p,t.docs)}}catch(n){s=n}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=(n)=>n.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
|
|
129
|
+
`," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${C}. Review the images before publishing.`,""];for(let n of p.results)r.push(`## ${l(n.title)} (${n.profile}, ${n.viewport.name})`,"",l(n.description),"",...n.reason?[l(n.reason),""]:[],n.status==="captured"?``:`**${n.status}:** ${l(n.error??"No image")}`,"");if(await Bun.write(g(c,"gallery.md"),`${r.join(`
|
|
127
130
|
`)}
|
|
128
|
-
`),s)throw s;return p}finally{await
|
|
129
|
-
`),await
|
|
131
|
+
`),s)throw s;return p}finally{await q(i,{recursive:!0,force:!0})}}async function Ht(e={}){let o=S(e.root??process.cwd()),a=await G(S(o,e.config??"config/screenshots.ts"));await he(a,o);let t=S(o,e.outDir??a.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(delete f.films,delete f.docsPage,a.film)f.films=await J(t,f.results,a.viewports??F,a.film===!0?{}:a.film,a.backend);if(a.docs)f.docsPage=await _(o,f,a.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 tt(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{Vt as captureScreenshots,Dt as defineScreenshotConfig,H as discoverScreenshotModels,le as discoverViews,V as planScreenshotModels,Ht as publishScreenshots,qe as screensFromViews,W as screenshotFixturePath,he as validateScreenshotConfig};
|
package/dist/stories.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createHash as tt,randomUUID as ot}from"crypto";import{createReadStream as nt}from"fs";import{copyFile as at,lstat as _,mkdir as T,open as ct,readFile as S,realpath as dt,rename as Y,rm as ft,writeFile as R}from"fs/promises";import{basename as lt,dirname as W,isAbsolute as et,join as a,relative as P,resolve as b,sep as ut}from"path";import{pathToFileURL as pt}from"url";var X="0.75.
|
|
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.663";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("&","&").replaceAll("<","<").replaceAll(">",">").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(``,"");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(`
|
package/dist/story-drivers.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export declare interface BrowserStoryOptions {
|
|
|
17
17
|
viewport?: LaunchOptions['viewport']
|
|
18
18
|
chromePath?: string
|
|
19
19
|
headless?: boolean
|
|
20
|
+
ffmpeg?: string
|
|
20
21
|
masks?: string[]
|
|
21
22
|
cursor?: { color?: string, size?: number, moveMs?: number, clickMs?: number }
|
|
22
23
|
beforeNavigate?: (cdp: Cdp) => Promise<void>
|
package/dist/story-drivers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{spawnOwnedProcess as
|
|
2
|
+
import{spawnOwnedProcess as D}from"@stacksjs/cli/owned-process";import{click as oe,launch as W,settle as ne,waitFor as _}from"@stacksjs/testing/browser";import{randomUUID as V}from"crypto";import{readFile as ae,rm as H}from"fs/promises";import{dirname as q,join as X}from"path";import{Mp4Muxer as G}from"@ts-videos/mp4";import{BufferTarget as Q}from"ts-videos";function z(e={}){let r=Bun.serve({port:0,hostname:"127.0.0.1",fetch(o){let a=e[new URL(o.url).pathname];if(a)return new Response(Bun.file(a),{headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});return new Response('<!doctype html><meta charset="utf-8"><title>Film</title>',{headers:{"Content-Type":"text/html"}})}});return{url:`http://127.0.0.1:${r.port}/`,stop:()=>{r.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 }
|
|
@@ -94,8 +94,8 @@ import{spawnOwnedProcess as q}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
|
-
})()`,te=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function
|
|
98
|
-
${
|
|
97
|
+
})()`,te=(e)=>e[0]===137&&e[1]===80?"image/png":"image/jpeg";async function L(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(ee(r));let o=[],a,u={width:0,height:0},c=0,n=async(t)=>{let i=JSON.parse(String(await e(`window.__stacksFilm.drain(${t})`)));if(u={width:i.width,height:i.height},i.description)a=new Uint8Array(Buffer.from(i.description,"base64"));for(let[d,l,p]of i.chunks)o.push([d,l,new Uint8Array(Buffer.from(p,"base64"))])};return{frames:()=>c,async add(t,i){if(!Number.isInteger(i)||i<1)return;let d=t?`${JSON.stringify(Buffer.from(t).toString("base64"))}, ${JSON.stringify(te(t))}`:"null, null";if(await e(`window.__stacksFilm.add(${d}, ${i})`),c+=i,c%(r.fps*20)<i)await n(!1)},async addVideo(t,i=[]){for(let l of i)if(![l.x,l.y,l.size,l.start,l.end].every(Number.isFinite)||!/^#[0-9a-f]{6}$/i.test(l.color))throw Error("Invalid film mark");let d=JSON.parse(String(await e(`window.__stacksFilm.open(${JSON.stringify(t)})`)));for(let l=0;l<d.frames;l+=r.fps){let p=Math.min(r.fps,d.frames-l);await e(`window.__stacksFilm.copy(${l}, ${p}, ${JSON.stringify(i)})`),c+=p,await n(!1)}return d.seconds},async finish(){if(await n(!0),!o.length||!a)throw Error("The browser encoded no video");let t=new Q,i=new G(t),d=i.addVideoTrack({codec:"h264",width:u.width,height:u.height,frameRate:r.fps,codecDescription:a});for(let[l,p,h]of o)await i.writePacket(d.id,{data:h,timestamp:p/1e6,duration:1/r.fps,isKeyframe:l===1});return await i.finalize(),t.buffer}}}import{join as re}from"path";import{launch as ie}from"@stacksjs/testing/browser";function we(e,r){let o=re(e,"stx-b-");return r!=="win32"&&Buffer.byteLength(o)+6>60?"/tmp/stx-b-":o}function J(e){let r,o;return{async view(a,u){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:a,height:u,backend:e});if(!o){let c=await ie({shared:!1,quietLiveReload:!1,chromePath:process.env.BUN_CHROME_PATH||void 0});try{let n=`127.0.0.1:${c.port}`,t=await fetch(`http://${n}/json/version`,{signal:AbortSignal.timeout(5000)});if(!t.ok)throw Error(`Could not read Chrome\u2019s DevTools endpoint (HTTP ${t.status})`);let i=await t.json(),d=URL.parse(i.webSocketDebuggerUrl||"");if(d?.protocol!=="ws:"||d.host!==n||!d.pathname.startsWith("/devtools/browser/"))throw Error("Chrome did not return its own loopback DevTools endpoint");o=d.href,r=c}catch(n){throw await c.close(),n}}return new Bun.WebView({width:a,height:u,backend:{type:"chrome",url:o}})},async close(){try{await r?.close()}finally{r=void 0,o=void 0}}}}function j(e){let r=`:is(${['input[type="password"]',...e].join(",")})`,o=`${r}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
|
|
98
|
+
${r}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
|
|
99
99
|
${o}, ${o}::selection {
|
|
100
100
|
color: transparent !important;
|
|
101
101
|
-webkit-text-fill-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
|
|
110
|
+
`}function A(e,r,o,a){if(!Number.isFinite(e)||e<r||e>o)throw Error(`Invalid ${a}`)}function se(e){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||r.username||r.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return r}async function M(e,r,o=30000){r?.throwIfAborted();let a=D(e),u=!1,c=()=>{a.stop().catch(()=>{})};r?.addEventListener("abort",c,{once:!0});let n=setTimeout(()=>{u=!0,c()},o);try{let[t,i]=await Promise.all([a.exited,new Response(a.stdout).bytes(),new Response(a.stderr).text()]);if(r?.throwIfAborted(),u)throw Error("Story tool timed out");if(t.code!==0)throw Error(`Story tool failed: ${e[0]}`);return i}finally{clearTimeout(n),r?.removeEventListener("abort",c),await a.stop()}}async function ce(e,r,o){let a=D([e,"-hide_banner","-loglevel","error","-nostdin","-n","-threads","2","-f","image2pipe","-framerate",String(r),"-vcodec","mjpeg","-i","pipe:0","-an","-filter_threads","1","-vf","pad=ceil(iw/2)*2:ceil(ih/2)*2","-c:v","libx264","-threads","2","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",o],{stdin:"pipe"}),u=new Response(a.stderr).text(),c=new Response(a.stdout).arrayBuffer();try{await a.started;let n=a.stdin;if(!n)throw Error("Story encoder has no input stream");return{async add(t,i){for(let d=0;d<i;d++)n.write(t),await n.flush()},async finish(){await n.end();let[t,i]=await Promise.all([a.exited,u,c]);if(t.code!==0)throw Error(`Story encoder failed: ${i.trim()||t.signal||t.code}`)},async close(){await a.stop()}}}catch(n){throw await a.stop(),n}}function Me(e){let r=se(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 A(o.size,6,80,"cursor size"),A(o.moveMs,0,5000,"cursor movement"),A(o.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:a,fps:u,signal:c}){let n=await W({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:t}=n,i,d,l,p,h=!1,E,T,C,P,F=new Map,v=t.on("Network.responseReceived",(f)=>{if(f.type==="Document")F.set(f.frameId,{status:f.response.status})}),k,O=new Promise((f)=>{k=f}),m=async()=>{k(),d?.stop(),d=void 0;let f=i,N=p;i=void 0,p=void 0,await Promise.allSettled([Promise.race([f?.close(),Bun.sleep(5000)]),N?.close()])},w=()=>{h=!0,m(),n.close().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{c.throwIfAborted();let f=`stacks-story-${V()}`,N=j(e.masks??[]),I=`(() => {
|
|
111
111
|
const start = () => {
|
|
112
112
|
const maskSheet = new CSSStyleSheet();
|
|
113
|
-
maskSheet.replaceSync(${JSON.stringify(
|
|
113
|
+
maskSheet.replaceSync(${JSON.stringify(N)});
|
|
114
114
|
document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
|
|
115
|
-
const host = document.createElement('div'); host.id = ${JSON.stringify(
|
|
115
|
+
const host = document.createElement('div'); host.id = ${JSON.stringify(f)};
|
|
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
|
|
123
|
+
})()`;await t.send("Page.addScriptToEvaluateOnNewDocument",{source:I});let b={x:24,y:24},B={cdp:t,async goto(s,y={}){let g=new URL(s,r);if(g.origin!==r.origin||g.username||g.password)throw Error("Story navigation must stay on baseUrl origin");let x=y.expectedStatus??200;if(!Number.isInteger(x)||x<100||x>599)throw Error("Invalid expected document status");let S=await t.send("Page.navigate",{url:g.href});if(S.errorText||!await ne(t,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(F.get(S.frameId)?.status!==x)throw Error("Unexpected story document HTTP status");if(new URL(await t.evaluate("location.href")).origin!==r.origin)throw Error("Story page redirected outside baseUrl origin")},async click(s){c.throwIfAborted();let y=typeof s==="string"?s:s.selector,g=typeof s==="string"?void 0:s.text,x=await _(async()=>t.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(y)})].filter(el=>${g===void 0?"true":`el.textContent.trim()===${JSON.stringify(g)}`});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),S=b,R=performance.now();do{c.throwIfAborted();let U=o.moveMs?Math.min(1,(performance.now()-R)/o.moveMs):1;if(b={x:S.x+(x.x-S.x)*U,y:S.y+(x.y-S.y)*U},await t.send("Input.dispatchMouseEvent",{type:"mouseMoved",...b}),U===1)break;await Bun.sleep(16)}while(!0);await oe(t,s),await Bun.sleep(o.clickMs)},async type(s,y){await B.click(s),await t.send("Input.insertText",{text:y})},async expectText(s,y){await _(()=>t.evaluate(`document.querySelector(${JSON.stringify(s)})?.textContent.includes(${JSON.stringify(y)}) ?? false`),12000)}};if(await e.beforeNavigate?.(t),c.throwIfAborted(),await B.goto(r.href),e.prepare)await e.prepare(B);if(C=Buffer.from((await t.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),P=t.on("Page.screencastFrame",(s)=>{C=Buffer.from(s.data,"base64"),t.send("Page.screencastFrameAck",{sessionId:s.sessionId}).catch((y)=>{T=y})}),e.ffmpeg)p=await ce(e.ffmpeg,u,a);else{d=z(),i=await W({viewport:{width:320,height:240},chromePath:e.chromePath,headless:e.headless});let s=i.cdp;await s.send("Page.navigate",{url:d.url}),await _(()=>s.evaluate('document.readyState === "complete"'),15000),l=await L((y)=>s.evaluate(y),{fps:u})}c.throwIfAborted(),await t.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let K=performance.now();E=(async()=>{let s=0,y;while(!h){if(c.throwIfAborted(),T)throw T;let g=Math.floor((performance.now()-K)/1000*u)+1;if(g-s>u*10)throw Error("Story encoder cannot keep up with the recording");if(g>s){let x=C,S=g-s,R=p?p.add(x,S):l.add(x===y?void 0:x,S);await Promise.race([R,O]),y=x,s=g}await Bun.sleep(Math.max(1,1000/u/2))}})().catch((s)=>{T=s});let Y;return{context:B,screenshot:async()=>Buffer.from((await t.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>Y??=(async()=>{h=!0;let s=p,y=!1,g=setTimeout(()=>{y=!0,m()},60000);try{if(await E,await t.send("Page.stopScreencast"),P?.(),T)throw Error("Story video capture failed",{cause:T});let x=s?s.finish():l.finish().then((S)=>Bun.write(a,S));try{await Promise.race([x,O.then(()=>{throw Error("The story encoder closed")})])}catch(S){throw Error(y?"Story video finalization timed out":"Story video capture failed",{cause:S})}if(e.failOnBrowserErrors!==!1&&t.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(g),await m()}})(),async close(){h=!0,P?.(),v(),c.removeEventListener("abort",w);try{await m(),await E}finally{await n.close()}}}}catch(f){h=!0,P?.(),v(),c.removeEventListener("abort",w);try{await m(),await E}finally{await n.close()}throw f}}}}function Te(e){let r=e.platform==="ios";if(r?!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(e.device):!/^emulator-\d+$/.test(e.device))throw Error("Native stories require an explicit simulator UUID or emulator serial");if(r&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let o=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(o))throw Error("Tap color must be a six-digit hex color");A(e.tapMs??450,100,5000,"tap feedback");let a=e.tapSize??72;return A(a,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:u,fps:c,signal:n}){let t=X(q(u),"native-raw.mp4"),i=e.adb??"adb",d=e.xcrun??"xcrun",l=`/sdcard/stacks-story-${V()}.mp4`,p,h,E,T=0,C=[],P=e.input??{async tap(v,k){await M([i,"-s",e.device,"shell","input","tap",String(Math.round(v)),String(Math.round(k))],n)},async swipe(v,k,O){await M([i,"-s",e.device,"shell","input","swipe",String(Math.round(v.x)),String(Math.round(v.y)),String(Math.round(k.x)),String(Math.round(k.y)),String(Math.round(O))],n)},async type(v){if(!/^[a-z0-9@._+ -]*$/i.test(v))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await M([i,"-s",e.device,"shell","input","text",v.replaceAll(" ","%s")],n)}},F=(v,k)=>{A(v,0,16384,"tap x"),A(k,0,16384,"tap y")};try{if(n.throwIfAborted(),r){let{recordIosSimulatorVideo:m}=await import("craft-native/testing");p=(await m({device:e.device,path:t,xcrun:d})).stop}else{if(new TextDecoder().decode(await M([i,"-s",e.device,"get-state"],n)).trim()!=="device")throw Error("Android emulator is unavailable");h=D([i,"-s",e.device,"shell",`screenrecord --time-limit 180 ${l} & 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 h.started;let w=h.stdout.getReader(),f="",N=setTimeout(()=>{h.stop()},15000);try{while(!E){let b=await w.read();if(b.done)throw Error("Android recorder stopped before startup");f+=new TextDecoder().decode(b.value);let B=/STACKS_RECORDER:(\d+)/.exec(f);if(B)E=Number(B[1]);if(f.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(N)}(async()=>{while(!(await w.read()).done);})().catch(()=>{}),new Response(h.stderr).text();let I=async()=>{await M([i,"-s",e.device,"shell",`case "$(cat /proc/${E}/cmdline 2>/dev/null)" in *${l}*) kill -2 ${E};; *) exit 3;; esac`])};await M([i,"-s",e.device,"shell","kill","-0",String(E)],n),p=async()=>{await I();let b=setTimeout(()=>{h.stop()},15000);try{await h.exited}finally{clearTimeout(b)}await M([i,"-s",e.device,"pull",l,t])},await M([i,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${l} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${E} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],n,20000)}T=performance.now();let v={async tap(m,w){n.throwIfAborted(),F(m,w);let f={x:m,y:w,start:(performance.now()-T)/1000,end:0};C.push(f);try{await P.tap(m,w)}finally{f.end=(performance.now()-T)/1000+(e.tapMs??450)/1000}},async swipe(m,w,f){if(n.throwIfAborted(),F(m.x,m.y),F(w.x,w.y),A(f,1,1e4,"swipe duration"),!P.swipe)throw Error("Native driver does not support swipes");await P.swipe(m,w,f)},async type(m){if(n.throwIfAborted(),!P.type)throw Error("Native driver does not support typing");await P.type(m)}},k;return{context:v,async screenshot(){if(n.throwIfAborted(),!r)return M([i,"-s",e.device,"exec-out","screencap","-p"],n);let m=X(q(u),`screenshot-${V()}.png`);try{return await M([d,"simctl","io",e.device,"screenshot",m],n),await ae(m)}finally{await H(m,{force:!0})}},finish:()=>k??=(async()=>{await p();let m=J(process.platform==="darwin"?"webkit":"chrome"),w=z({"/raw.mp4":t}),f;try{f=await m.view(320,240);let N=f;await N.navigate(w.url);let I=await L((b)=>N.evaluate(b),{fps:c});await I.addVideo("/raw.mp4",e.tapFeedback===!1?[]:C.map((b)=>({x:b.x,y:b.y,size:a,color:o,start:b.start,end:b.end}))),await Bun.write(u,await I.finish())}finally{w.stop();try{f?.close()}finally{await m.close()}}await H(t)})(),async close(){try{if(!k)await p?.()}finally{if(await h?.stop(),!r)await M([i,"-s",e.device,"shell","rm","-f",l])}}}}catch(v){try{await p?.()}finally{await h?.stop()}throw v}}}}export{Me as browserStory,Te 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.
|
|
5
|
+
"version": "0.75.663",
|
|
6
6
|
"description": "The Stacks way to document.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -57,20 +57,20 @@
|
|
|
57
57
|
"prepublishOnly": "bun run build"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@stacksjs/bunpress": "^0.2.
|
|
61
|
-
"@stacksjs/cli": "0.75.
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
63
|
-
"@stacksjs/path": "0.75.
|
|
64
|
-
"@stacksjs/orm": "0.75.
|
|
65
|
-
"@stacksjs/stx": "^0.2.
|
|
66
|
-
"@stacksjs/testing": "0.75.
|
|
60
|
+
"@stacksjs/bunpress": "^0.2.32",
|
|
61
|
+
"@stacksjs/cli": "0.75.663",
|
|
62
|
+
"@stacksjs/config": "0.75.663",
|
|
63
|
+
"@stacksjs/path": "0.75.663",
|
|
64
|
+
"@stacksjs/orm": "0.75.663",
|
|
65
|
+
"@stacksjs/stx": "^0.2.927",
|
|
66
|
+
"@stacksjs/testing": "0.75.663",
|
|
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.
|
|
73
|
-
"@stacksjs/server": "0.75.
|
|
72
|
+
"@stacksjs/alias": "0.75.663",
|
|
73
|
+
"@stacksjs/server": "0.75.663",
|
|
74
74
|
"better-dx": "^0.2.39"
|
|
75
75
|
}
|
|
76
76
|
}
|