@stacksjs/docs 0.75.650 → 0.75.653
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/screenshot-publish.d.ts +22 -0
- package/dist/screenshot-publish.js +6 -0
- package/dist/screenshot-views.d.ts +35 -0
- package/dist/screenshot-views.js +2 -0
- package/dist/screenshots.d.ts +15 -0
- package/dist/screenshots.js +20 -15
- package/dist/stories.js +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -40,3 +40,5 @@ MIT license. Contributions follow the Stacks repository conventions.
|
|
|
40
40
|
## Automated UI documentation
|
|
41
41
|
|
|
42
42
|
`@stacksjs/docs/screenshots` exports `defineScreenshotConfig`, `validateScreenshotConfig` and `captureScreenshots`. Run a configured inventory with `buddy docs:screenshots`; use `--list` to verify template coverage and `--check` to validate saved captures. Each authentication profile owns a separate Bun WebView worker process. See the [screen documentation guide](https://stacksjs.com/docs/guide/screenshots) for readiness hooks, role setup, masks, artifacts and CI examples.
|
|
43
|
+
|
|
44
|
+
`screensFromViews()` derives that inventory from the application's stx views, so every route is captured without a hand-written list. Add `film` for a walkthrough MP4 per viewport and `docs` for a generated page showing every screen. See `docs/guide/automatic-screens.md`.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ScreenshotReport, ScreenshotResult, ScreenshotViewport } from './screenshots';
|
|
2
|
+
export declare function validateScreenshotPublishing(film: ScreenshotFilmOptions | false | undefined, docs: ScreenshotDocsOptions | undefined, root: string, viewports: ScreenshotViewport[]): void;
|
|
3
|
+
/** One MP4 per viewport: every captured screen in inventory order, held for a readable moment. */
|
|
4
|
+
export declare function filmScreenshots(output: string, results: ScreenshotResult[], viewports: ScreenshotViewport[], options: ScreenshotFilmOptions): Promise<ScreenshotFilm[]>;
|
|
5
|
+
/** The page readers open: the films, then every screen with its explanation and pictures. */
|
|
6
|
+
export declare function renderScreensPage(report: Pick<ScreenshotReport, 'results' | 'inventory' | 'generatorVersion'> & { films?: ScreenshotFilm[] }, options: ScreenshotDocsOptions): string;
|
|
7
|
+
export declare function writeScreensPage(root: string, report: Parameters<typeof renderScreensPage>[0], options: ScreenshotDocsOptions): Promise<ScreenshotDocsPage>;
|
|
8
|
+
export declare const generatedScreensPage: '<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->';
|
|
9
|
+
export declare interface ScreenshotFilmOptions {
|
|
10
|
+
secondsPerScreen?: number
|
|
11
|
+
fps?: number
|
|
12
|
+
viewports?: string[]
|
|
13
|
+
ffmpeg?: string
|
|
14
|
+
}
|
|
15
|
+
export declare interface ScreenshotDocsOptions {
|
|
16
|
+
page: string
|
|
17
|
+
base: string
|
|
18
|
+
title?: string
|
|
19
|
+
description?: string
|
|
20
|
+
}
|
|
21
|
+
export declare interface ScreenshotFilm { viewport: string, file: string, sha256: string, screens: number, seconds: number }
|
|
22
|
+
export declare interface ScreenshotDocsPage { path: string, sha256: string }
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{createHash as B}from"crypto";import{lstat as N,mkdir as R,mkdtemp as D,readFile as _,rename as P,rm as j}from"fs/promises";import{tmpdir as M}from"os";import{dirname as T,isAbsolute as V,join as m,relative as U,resolve as k}from"path";var E="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",F=(e)=>B("sha256").update(e).digest("hex"),u=(e)=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),g=(e)=>u(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1"),x=(e)=>Math.ceil(e/2)*2;function G(e,i,o,s){if(e){let n=e.secondsPerScreen??2;if(!Number.isFinite(n)||n<0.2||n>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let c of e.viewports??[])if(!s.some((v)=>v.name===c))throw Error(`Unknown film viewport: ${c}`)}if(i){let n=k(o,i.page);if(V(i.page)||U(o,n).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function H(e,i,o,s){let n=[],c=s.secondsPerScreen??2,v=s.fps??12,h=await D(m(M(),"stacks-screen-film-"));try{for(let a of o){if(s.viewports?.length&&!s.viewports.includes(a.name))continue;let t=i.filter((w)=>w.status==="captured"&&w.file&&w.viewport.name===a.name);if(!t.length)continue;let l=(w)=>`file '${m(e,w).replaceAll("'","'\\''")}'`,f=[...t.flatMap((w)=>[l(w.file),`duration ${c}`]),l(t.at(-1).file)].join(`
|
|
3
|
+
`);await Bun.write(m(h,`${a.name}.txt`),`${f}
|
|
4
|
+
`);let[p,d]=[x(a.width),x(a.height)],r=m(h,`${a.name}.mp4`),y;try{y=Bun.spawn([s.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-y","-f","concat","-safe","0","-i",m(h,`${a.name}.txt`),"-an","-vf",`scale=${p}:${d}:force_original_aspect_ratio=decrease,pad=${p}:${d}:(ow-iw)/2:(oh-ih)/2:color=white,format=yuv420p`,"-r",String(v),"-c:v","libx264","-preset","veryfast","-movflags","+faststart",r],{stdin:"ignore",stdout:"ignore",stderr:"pipe"})}catch{throw Error("FFmpeg is required to film the captured screens; install it or set film.ffmpeg")}let A=setTimeout(()=>y.kill(),600000),[b,O]=await Promise.all([y.exited,new Response(y.stderr).text()]);if(clearTimeout(A),b!==0)throw Error(`FFmpeg could not film the ${a.name} screens: ${O.trim().slice(0,400)||`exit ${b}`}`);let S=`film-${a.name}.mp4`;await P(r,m(e,S)).catch(async()=>{await Bun.write(m(e,S),Bun.file(r))}),n.push({viewport:a.name,file:S,sha256:F(new Uint8Array(await Bun.file(m(e,S)).arrayBuffer())),screens:t.length,seconds:t.length*c})}return n}finally{await j(h,{recursive:!0,force:!0})}}function q(e,i){let o=i.base.replace(/\/+$/,""),s=i.title??"Screens",n=e.results.filter((t)=>t.status==="captured"&&t.file),c=["---",`title: ${JSON.stringify(s)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",E,"",`# ${g(s)}`,"",`${new Set(n.map((t)=>t.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let t of e.films??[]){let l=n.find((f)=>f.viewport.name===t.viewport);c.push(`## Walkthrough video (${g(t.viewport)})`,"",`<video controls playsinline preload="none" src="${u(`${o}/${t.file}`)}"${l?` poster="${u(`${o}/${l.file}`)}"`:""} style="width:100%;max-width:${l&&l.viewport.width<600?l.viewport.width:1100}px;height:auto"></video>`,"",`${t.screens} screens in ${Math.round(t.seconds)} seconds. [Download the video](${o}/${t.file}).`,"")}let v=(t)=>t.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",h=new Map;for(let t of e.inventory)h.set(v(t.path),[...h.get(v(t.path))??[],t]);let a=[];for(let[t,l]of[...h].sort(([f],[p])=>f.localeCompare(p))){let f=[];for(let p of l){let d=n.filter((r)=>r.id===p.id);if(!d.length){let r=e.results.find((y)=>y.id===p.id);a.push(`- ${g(p.title)} (\`${p.path}\`): ${p.skip?g(p.skip):r?"the last capture failed.":"not captured yet."}`);continue}f.push(`### ${g(p.title)}`,"",g(d[0].description),"",...d[0].reason?[g(d[0].reason),""]:[],`Address: \`${p.path}\``,"");for(let r of d)f.push("<figure>",` <img src="${u(`${o}/${r.file}`)}" alt="${u(`${r.title}, ${r.viewport.name}`)}" width="${r.viewport.width}" height="${r.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${r.viewport.width}px;height:auto">`,` <figcaption>${u(r.viewport.name)}, ${r.viewport.width} by ${r.viewport.height}${r.profile==="default"?"":`, signed in as ${u(r.profile)}`}</figcaption>`,"</figure>","")}if(f.length)c.push(`## ${g(t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," "))}`,"",...f)}if(a.length)c.push("## Not pictured","","These screens are part of the application and have no picture here.","",...a,"");return`${c.join(`
|
|
5
|
+
`).trimEnd()}
|
|
6
|
+
`}async function I(e,i,o){let s=k(e,o.page);try{if((await N(s)).isSymbolicLink()||!(await _(s,"utf8")).includes(E))throw Error(`Refusing to replace a hand-written page: ${o.page}`)}catch(c){if(c.code!=="ENOENT")throw c}let n=q(i,o);return await R(T(s),{recursive:!0}),await Bun.write(`${s}.tmp`,n),await P(`${s}.tmp`,s),{path:o.page,sha256:F(n)}}export{H as filmScreenshots,E as generatedScreensPage,q as renderScreensPage,G as validateScreenshotPublishing,I as writeScreensPage};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ScreenshotPage } from './screenshots';
|
|
2
|
+
/** Every stx view under the given directories, in route order. Reads files only; opens no browser. */
|
|
3
|
+
export declare function discoverViews(options?: Pick<ViewScreenOptions, 'root' | 'directories'>): ViewScreen[];
|
|
4
|
+
/**
|
|
5
|
+
* Screenshot pages for every stx view.
|
|
6
|
+
*
|
|
7
|
+
* A static route is captured as it is. A dynamic route needs a concrete
|
|
8
|
+
* address: give its rule a `path` (a seeded example or a fixture resolver) or
|
|
9
|
+
* a `model`. Without one it stays in the inventory as an explained gap, so
|
|
10
|
+
* the report shows exactly which screens still lack a fixture.
|
|
11
|
+
*/
|
|
12
|
+
export declare function screensFromViews(options?: ViewScreenOptions): ScreenshotPage[];
|
|
13
|
+
/** One stx view, as the router serves it. */
|
|
14
|
+
export declare interface ViewScreen {
|
|
15
|
+
id: string
|
|
16
|
+
route: string
|
|
17
|
+
source: string
|
|
18
|
+
group: string
|
|
19
|
+
params: string[]
|
|
20
|
+
dynamic: boolean
|
|
21
|
+
title: string
|
|
22
|
+
layout?: string
|
|
23
|
+
text: string
|
|
24
|
+
}
|
|
25
|
+
export declare interface ViewScreenOptions {
|
|
26
|
+
root?: string
|
|
27
|
+
directories?: string[]
|
|
28
|
+
defaults?: Partial<Pick<ScreenshotPage, 'waitFor' | 'profiles' | 'masks' | 'prepare' | 'ready' | 'reason'>>
|
|
29
|
+
routes?: Record<string, ViewScreenRule>
|
|
30
|
+
each?: (view: ViewScreen) => ViewScreenRule
|
|
31
|
+
extra?: ScreenshotPage[]
|
|
32
|
+
strict?: boolean
|
|
33
|
+
}
|
|
34
|
+
/** What a rule may change about one discovered view. `false` or a string leaves it out, with that reason. */
|
|
35
|
+
export type ViewScreenRule = Partial<Omit<ScreenshotPage, 'sources'>> | string | false | undefined | void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{createRouter as d}from"@stacksjs/stx";import{readFileSync as h}from"fs";import{relative as m,resolve as w}from"path";var f=(t)=>t.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),y=(t)=>t?t[0].toUpperCase()+t.slice(1):t;function S(t){try{return h(t,"utf8")}catch{return""}}function x(t,n){let i=t.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(i)return i;let e=n.split("/").filter(Boolean).map((o)=>o.startsWith("[")?`by ${f(o.slice(1,-1).replace(/^\.\.\./,""))}`:f(o));return e.length?y(e.join(" / ")):"Home"}function P(t={}){let n=w(t.root??process.cwd()),i=[],e=new Set;for(let o of t.directories??["resources/views"])for(let r of d(n,{pagesDir:o,emit:!1})){let s=r.pattern.replace(/\*(\w*)/g,(c,g)=>`[...${g||"path"}]`).replace(/:(\w+)/g,"[$1]"),u=s.split("/").filter(Boolean).map((c)=>c.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",a=u;for(let c=2;e.has(a);c++)a=`${u}-${c}`;e.add(a);let l=S(r.filePath),p=l.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];i.push({id:a,route:s,source:m(n,r.filePath).replaceAll("\\","/"),group:s.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...r.params],dynamic:r.isDynamic,title:x(l,s),...p?{layout:p}:{},text:l})}return i.sort((o,r)=>o.route<r.route?-1:o.route>r.route?1:0)}function O(t={}){let n=[],i=new Set;for(let e of P(t)){i.add(e.route);let o=[t.each?.(e),t.routes?.[e.route]],r={id:e.id,title:e.title,path:e.route,description:`The ${e.title} screen, served at ${e.route}.`,waitFor:"body",...t.defaults,sources:[e.source]};for(let s of o){if(s===void 0)continue;if(s===!1||typeof s==="string"){r.skip=s||"Left out of the screen documentation on purpose.";continue}Object.assign(r,s)}if(e.dynamic&&typeof r.path==="string"&&r.path===e.route&&!r.model&&!r.skip){if(t.strict)throw Error(`Dynamic view needs a concrete path or model: ${e.route} (${e.source})`);r.skip=`Needs a seeded example: give ${e.route} a concrete path, fixture resolver or model.`}if(typeof r.path==="function"&&!r.route)r.route=e.route;n.push(r)}for(let e of Object.keys(t.routes??{}))if(!i.has(e))throw Error(`Screenshot rule for a view that does not exist: ${e}`);return[...n,...t.extra??[]]}export{P as discoverViews,O as screensFromViews};
|
package/dist/screenshots.d.ts
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { discoverScreenshotModels, screenshotFixturePath, type ScreenshotFixtures, type ScreenshotModelOptions, type ScreenshotModelPlan } from './screenshot-models';
|
|
2
|
+
import { type ScreenshotDocsOptions, type ScreenshotDocsPage, type ScreenshotFilm, type ScreenshotFilmOptions } from './screenshot-publish';
|
|
2
3
|
import { version as generatorVersion } from '../package.json';
|
|
3
4
|
export type { ScreenshotFixtures, ScreenshotModel, ScreenshotModelOptions, ScreenshotModelPlan } from './screenshot-models';
|
|
5
|
+
export type { ViewScreen, ViewScreenOptions, ViewScreenRule } from './screenshot-views';
|
|
6
|
+
export type { ScreenshotDocsOptions, ScreenshotDocsPage, ScreenshotFilm, ScreenshotFilmOptions } from './screenshot-publish';
|
|
4
7
|
export declare function validateScreenshotConfig(config: ScreenshotConfig, root?: ReturnType<typeof process.cwd>): Promise<void>;
|
|
5
8
|
/** Capture the explicit inventory; failures remain in the report and fail CI. */
|
|
6
9
|
export declare function captureScreenshots(options?: ScreenshotOptions): Promise<ScreenshotReport>;
|
|
10
|
+
/**
|
|
11
|
+
* Rebuild the films and the docs page from the saved manifest, without
|
|
12
|
+
* opening a browser. For a wrapper that captures in batches with
|
|
13
|
+
* `publish: false`, and for changing film or page settings after a capture.
|
|
14
|
+
*/
|
|
15
|
+
export declare function publishScreenshots(options?: Pick<ScreenshotOptions, 'config' | 'root' | 'outDir'>): Promise<ScreenshotReport>;
|
|
7
16
|
export declare const defineScreenshotConfig: (config: ScreenshotConfig) => ScreenshotConfig;
|
|
8
17
|
export declare interface ScreenshotViewport { name: string, width: number, height: number }
|
|
9
18
|
export declare interface ScreenshotContext {
|
|
@@ -50,6 +59,8 @@ export declare interface ScreenshotConfig {
|
|
|
50
59
|
prepare: (plan: ScreenshotModelPlan) => Promise<ScreenshotFixtures>
|
|
51
60
|
cleanup?: () => Promise<void>
|
|
52
61
|
}
|
|
62
|
+
film?: ScreenshotFilmOptions | boolean
|
|
63
|
+
docs?: ScreenshotDocsOptions
|
|
53
64
|
}
|
|
54
65
|
export declare interface ScreenshotResult {
|
|
55
66
|
id: string
|
|
@@ -75,6 +86,8 @@ export declare interface ScreenshotReport {
|
|
|
75
86
|
results: ScreenshotResult[]
|
|
76
87
|
models: ScreenshotModelPlan
|
|
77
88
|
inventory: Array<{ id: string, title: string, path: string, sources: string[], skip?: string }>
|
|
89
|
+
films?: ScreenshotFilm[]
|
|
90
|
+
docsPage?: ScreenshotDocsPage
|
|
78
91
|
}
|
|
79
92
|
export declare interface ScreenshotOptions {
|
|
80
93
|
config?: string
|
|
@@ -84,6 +97,8 @@ export declare interface ScreenshotOptions {
|
|
|
84
97
|
viewports?: string[]
|
|
85
98
|
list?: boolean
|
|
86
99
|
check?: boolean
|
|
100
|
+
publish?: boolean
|
|
87
101
|
onProgress?: (result: ScreenshotResult) => void
|
|
88
102
|
}
|
|
89
103
|
export { discoverScreenshotModels, planScreenshotModels, screenshotFixturePath } from './screenshot-models';
|
|
104
|
+
export { discoverViews, screensFromViews } from './screenshot-views';
|
package/dist/screenshots.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createHash as
|
|
3
|
-
${
|
|
4
|
-
${
|
|
2
|
+
import{createHash as Le}from"crypto";import{lstat as A,mkdir as K,mkdtemp as ae,readFile as P,rename as G,rm as I,rmdir as qe,stat as Je}from"fs/promises";import{tmpdir as We}from"os";import{dirname as le,isAbsolute as pe,join as g,relative as D,resolve as S}from"path";import{pathToFileURL as _e}from"url";function X(e){let i=`:is(${['input[type="password"]',...e].join(",")})`,c=`${i}:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))`;return`
|
|
3
|
+
${i}:not(:is(textarea,input:is(:not([type]),[type="text" i],[type="password" i],[type="email" i],[type="search" i],[type="tel" i],[type="url" i]))) { opacity: 0 !important; }
|
|
4
|
+
${c}, ${c}::selection {
|
|
5
5
|
color: transparent !important;
|
|
6
6
|
-webkit-text-fill-color: transparent !important;
|
|
7
7
|
-webkit-text-stroke: 0 transparent !important;
|
|
@@ -9,23 +9,28 @@ ${d}, ${d}::selection {
|
|
|
9
9
|
caret-color: transparent !important;
|
|
10
10
|
forced-color-adjust: none !important;
|
|
11
11
|
}
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
${
|
|
15
|
-
`}import{createHash as
|
|
12
|
+
${c}::selection { background: transparent !important; }
|
|
13
|
+
${c}::placeholder { color: GrayText !important; -webkit-text-fill-color: GrayText !important; }
|
|
14
|
+
${c}::-webkit-search-cancel-button { visibility: hidden !important; }
|
|
15
|
+
`}import{createHash as ue}from"crypto";import{readFile as he}from"fs/promises";import{existsSync as me}from"fs";import{isAbsolute as we,join as ge,relative as ye,resolve as Se}from"path";import{loadModelRegistry as be,modelFiles as Y}from"@stacksjs/orm/model-registry";function L(e){let i=Object.entries(e).map(([r,o])=>{let l=Object.entries(o.attributes??{}),u=o.belongsTo??[],x=(Array.isArray(u)?u:Object.values(u)).map((w)=>typeof w==="string"?w:w&&typeof w==="object"?String(w.model??w.name??""):"").filter(Boolean),v=o.traits?.useApi,b=o.traits?.useSeeder??o.traits?.seedable,y=(w,F)=>Boolean(F.hidden||F.encrypted||F.personal||/password|token|secret|api.?key|email|phone|address/i.test(w)),k=l.filter(([,w])=>w.required&&!w.nullable&&typeof w.factory!=="function"&&!Object.hasOwn(w,"default")).map(([w])=>w);return{name:String(o.name??r),table:o.table,primaryKey:String(o.primaryKey??"id"),...v?.uri?{api:String(v.uri)}:{},parents:[...new Set([...x,...Array.isArray(b?.after)?b.after.map(String):[]])].sort(),seederCount:typeof b?.count==="number"?b.count:null,factoryFields:l.filter(([,w])=>typeof w.factory==="function").map(([w])=>w),defaultFields:l.filter(([,w])=>Object.hasOwn(w,"default")).map(([w])=>w),requiredWithoutFactory:k,sensitiveFields:l.filter(([w,F])=>y(w,F)).map(([w])=>w),suggestedStates:[...new Set(["empty","populated",...v?.routes?.includes("show")?["detail"]:[],...v?.middleware?.length?["permission-denied"]:[],...o.traits?.useSoftDeletes||o.traits?.softDeletable?["archived"]:[]])]}}).sort((r,o)=>r.name.localeCompare(o.name)),c=new Set(i.map((r)=>r.name)),t=new Map(i.map((r)=>[r.name,r])),a=[];for(;;){let r=[...t.values()].filter((o)=>o.parents.every((l)=>!c.has(l)||a.includes(l)));if(!r.length)break;for(let o of r)a.push(o.name),t.delete(o.name)}let f=new Set,d=new Map,h=new Map,m=[],n=new Set,s=0;function p(r){d.set(r,s),h.set(r,s++),m.push(r),n.add(r);for(let u of t.get(r)?.parents??[]){if(!t.has(u))continue;if(!d.has(u))p(u),h.set(r,Math.min(h.get(r),h.get(u)));else if(n.has(u))h.set(r,Math.min(h.get(r),d.get(u)))}if(h.get(r)!==d.get(r))return;let o=[],l;do l=m.pop(),n.delete(l),o.push(l);while(l!==r);if(o.length>1||t.get(r)?.parents.includes(r))for(let u of o)f.add(u)}for(let r of t.keys())if(!d.has(r))p(r);return{models:i,creationOrder:a,cycles:[...f].sort(),blocked:[...t.keys()].filter((r)=>!f.has(r)),externalParents:[...new Set(i.flatMap((r)=>r.parents).filter((r)=>!c.has(r)))].sort()}}async function q(e,i={}){if(i===!1)return L({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let c=Se(e,i.directory??"app/Models");if(we(i.directory??"")||ye(e,c).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let t=i.includeDefaults?ge(e,"storage/framework/defaults/app/Models"):void 0;if(!me(c)&&!t)return L({});let a=[],f=await be({userRoot:c,defaultsRoot:t,onImportError:(m)=>a.push(m)});if(a.length)throw Error(`Cannot inspect screenshot models: ${a.join(", ")}`);let d=L(f),h=[...Y(c),...t?Y(t):[]].sort();return d.sourceHash=ue("sha256").update(Buffer.concat(await Promise.all(h.map((m)=>he(m))))).digest("hex"),d}function J(e,i,c,t){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(e))return e;let a=i?t.models.filter((h)=>h.name===i):t.models.filter((h)=>h.api&&e.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),f=a.length===1?a[0]:void 0;if(!f)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let d=c[f.name];if(!d)throw Error(`No screenshot fixture supplied for ${f.name}`);return e.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,m,n)=>{let s=m||n,p=s==="id"?f.primaryKey:s;if(f.sensitiveFields.includes(p)||/token|secret|password/i.test(s))throw Error(`Refusing to publish a sensitive route parameter: ${s}`);let r=d[p];if(r===void 0||r===""||typeof r!=="string"&&typeof r!=="number"||typeof r==="number"&&!Number.isFinite(r))throw Error(`Screenshot fixture ${f.name} has no ${s}`);return encodeURIComponent(String(r))})}import{createHash as ve}from"crypto";import{lstat as xe,mkdir as $e,mkdtemp as ke,readFile as Ee,rename as ee,rm as Pe}from"fs/promises";import{tmpdir as je}from"os";import{dirname as Oe,isAbsolute as Re,join as T,relative as Fe,resolve as te}from"path";var re="<!-- Generated by buddy docs:screenshots. Edit config/screenshots.ts instead. -->",se=(e)=>ve("sha256").update(e).digest("hex"),N=(e)=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),B=(e)=>N(e).replace(/[\r\n]+/g," ").replace(/([\\`*_[\]#|])/g,"\\$1"),Z=(e)=>Math.ceil(e/2)*2;function oe(e,i,c,t){if(e){let a=e.secondsPerScreen??2;if(!Number.isFinite(a)||a<0.2||a>30)throw Error("film.secondsPerScreen must be between 0.2 and 30");if(!Number.isInteger(e.fps??12)||(e.fps??12)<1||(e.fps??12)>60)throw Error("film.fps must be an integer from 1 to 60");for(let f of e.viewports??[])if(!t.some((d)=>d.name===f))throw Error(`Unknown film viewport: ${f}`)}if(i){let a=te(c,i.page);if(Re(i.page)||Fe(c,a).startsWith("..")||!i.page.endsWith(".md"))throw Error("docs.page must be a Markdown file inside the project");if(!/^\/[\w./-]*$/.test(i.base)||i.base.includes(".."))throw Error("docs.base must be a site path such as /screens")}}async function W(e,i,c,t){let a=[],f=t.secondsPerScreen??2,d=t.fps??12,h=await ke(T(je(),"stacks-screen-film-"));try{for(let m of c){if(t.viewports?.length&&!t.viewports.includes(m.name))continue;let n=i.filter((y)=>y.status==="captured"&&y.file&&y.viewport.name===m.name);if(!n.length)continue;let s=(y)=>`file '${T(e,y).replaceAll("'","'\\''")}'`,p=[...n.flatMap((y)=>[s(y.file),`duration ${f}`]),s(n.at(-1).file)].join(`
|
|
16
|
+
`);await Bun.write(T(h,`${m.name}.txt`),`${p}
|
|
17
|
+
`);let[r,o]=[Z(m.width),Z(m.height)],l=T(h,`${m.name}.mp4`),u;try{u=Bun.spawn([t.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-y","-f","concat","-safe","0","-i",T(h,`${m.name}.txt`),"-an","-vf",`scale=${r}:${o}:force_original_aspect_ratio=decrease,pad=${r}:${o}:(ow-iw)/2:(oh-ih)/2:color=white,format=yuv420p`,"-r",String(d),"-c:v","libx264","-preset","veryfast","-movflags","+faststart",l],{stdin:"ignore",stdout:"ignore",stderr:"pipe"})}catch{throw Error("FFmpeg is required to film the captured screens; install it or set film.ffmpeg")}let R=setTimeout(()=>u.kill(),600000),[x,v]=await Promise.all([u.exited,new Response(u.stderr).text()]);if(clearTimeout(R),x!==0)throw Error(`FFmpeg could not film the ${m.name} screens: ${v.trim().slice(0,400)||`exit ${x}`}`);let b=`film-${m.name}.mp4`;await ee(l,T(e,b)).catch(async()=>{await Bun.write(T(e,b),Bun.file(l))}),a.push({viewport:m.name,file:b,sha256:se(new Uint8Array(await Bun.file(T(e,b)).arrayBuffer())),screens:n.length,seconds:n.length*f})}return a}finally{await Pe(h,{recursive:!0,force:!0})}}function Me(e,i){let c=i.base.replace(/\/+$/,""),t=i.title??"Screens",a=e.results.filter((n)=>n.status==="captured"&&n.file),f=["---",`title: ${JSON.stringify(t)}`,`description: ${JSON.stringify(i.description??"Every screen of the application, captured automatically from its views.")}`,"---","",re,"",`# ${B(t)}`,"",`${new Set(a.map((n)=>n.id)).size} of ${e.inventory.length} screens, captured automatically from the application's views with @stacksjs/docs ${e.generatorVersion}. A new view appears here after the next capture.`,""];for(let n of e.films??[]){let s=a.find((p)=>p.viewport.name===n.viewport);f.push(`## Walkthrough video (${B(n.viewport)})`,"",`<video controls playsinline preload="none" src="${N(`${c}/${n.file}`)}"${s?` poster="${N(`${c}/${s.file}`)}"`:""} style="width:100%;max-width:${s&&s.viewport.width<600?s.viewport.width:1100}px;height:auto"></video>`,"",`${n.screens} screens in ${Math.round(n.seconds)} seconds. [Download the video](${c}/${n.file}).`,"")}let d=(n)=>n.split("/").filter(Boolean)[0]?.replace(/^[[:].*/,"profiles")??"home",h=new Map;for(let n of e.inventory)h.set(d(n.path),[...h.get(d(n.path))??[],n]);let m=[];for(let[n,s]of[...h].sort(([p],[r])=>p.localeCompare(r))){let p=[];for(let r of s){let o=a.filter((l)=>l.id===r.id);if(!o.length){let l=e.results.find((u)=>u.id===r.id);m.push(`- ${B(r.title)} (\`${r.path}\`): ${r.skip?B(r.skip):l?"the last capture failed.":"not captured yet."}`);continue}p.push(`### ${B(r.title)}`,"",B(o[0].description),"",...o[0].reason?[B(o[0].reason),""]:[],`Address: \`${r.path}\``,"");for(let l of o)p.push("<figure>",` <img src="${N(`${c}/${l.file}`)}" alt="${N(`${l.title}, ${l.viewport.name}`)}" width="${l.viewport.width}" height="${l.viewport.height}" loading="lazy" style="display:block;width:100%;max-width:${l.viewport.width}px;height:auto">`,` <figcaption>${N(l.viewport.name)}, ${l.viewport.width} by ${l.viewport.height}${l.profile==="default"?"":`, signed in as ${N(l.profile)}`}</figcaption>`,"</figure>","")}if(p.length)f.push(`## ${B(n[0].toUpperCase()+n.slice(1).replace(/[-_]+/g," "))}`,"",...p)}if(m.length)f.push("## Not pictured","","These screens are part of the application and have no picture here.","",...m,"");return`${f.join(`
|
|
18
|
+
`).trimEnd()}
|
|
19
|
+
`}async function _(e,i,c){let t=te(e,c.page);try{if((await xe(t)).isSymbolicLink()||!(await Ee(t,"utf8")).includes(re))throw Error(`Refusing to replace a hand-written page: ${c.page}`)}catch(f){if(f.code!=="ENOENT")throw f}let a=Me(i,c);return await $e(Oe(t),{recursive:!0}),await Bun.write(`${t}.tmp`,a),await ee(`${t}.tmp`,t),{path:c.page,sha256:se(a)}}import{createRouter as Te}from"@stacksjs/stx";import{readFileSync as Be}from"fs";import{relative as De,resolve as Ne}from"path";var ne=(e)=>e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),Ce=(e)=>e?e[0].toUpperCase()+e.slice(1):e;function Ue(e){try{return Be(e,"utf8")}catch{return""}}function Ve(e,i){let c=e.match(/<title>([^<{@]+)<\/title>/i)?.[1]?.trim();if(c)return c;let t=i.split("/").filter(Boolean).map((a)=>a.startsWith("[")?`by ${ne(a.slice(1,-1).replace(/^\.\.\./,""))}`:ne(a));return t.length?Ce(t.join(" / ")):"Home"}function ie(e={}){let i=Ne(e.root??process.cwd()),c=[],t=new Set;for(let a of e.directories??["resources/views"])for(let f of Te(i,{pagesDir:a,emit:!1})){let d=f.pattern.replace(/\*(\w*)/g,(p,r)=>`[...${r||"path"}]`).replace(/:(\w+)/g,"[$1]"),h=d.split("/").filter(Boolean).map((p)=>p.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")).filter(Boolean).join("-").toLowerCase()||"index",m=h;for(let p=2;t.has(m);p++)m=`${h}-${p}`;t.add(m);let n=Ue(f.filePath),s=n.match(/@(?:extends|layout)\(\s*['"]([^'"]+)['"]/)?.[1];c.push({id:m,route:d,source:De(i,f.filePath).replaceAll("\\","/"),group:d.split("/").filter(Boolean)[0]?.replace(/^\[.*\]$/,"profile")??"home",params:[...f.params],dynamic:f.isDynamic,title:Ve(n,d),...s?{layout:s}:{},text:n})}return c.sort((a,f)=>a.route<f.route?-1:a.route>f.route?1:0)}function Ae(e={}){let i=[],c=new Set;for(let t of ie(e)){c.add(t.route);let a=[e.each?.(t),e.routes?.[t.route]],f={id:t.id,title:t.title,path:t.route,description:`The ${t.title} screen, served at ${t.route}.`,waitFor:"body",...e.defaults,sources:[t.source]};for(let d of a){if(d===void 0)continue;if(d===!1||typeof d==="string"){f.skip=d||"Left out of the screen documentation on purpose.";continue}Object.assign(f,d)}if(t.dynamic&&typeof f.path==="string"&&f.path===t.route&&!f.model&&!f.skip){if(e.strict)throw Error(`Dynamic view needs a concrete path or model: ${t.route} (${t.source})`);f.skip=`Needs a seeded example: give ${t.route} a concrete path, fixture resolver or model.`}if(typeof f.path==="function"&&!f.route)f.route=t.route;i.push(f)}for(let t of Object.keys(e.routes??{}))if(!c.has(t))throw Error(`Screenshot rule for a view that does not exist: ${t}`);return[...i,...e.extra??[]]}import{spawnOwnedProcess as Ie}from"@stacksjs/cli/owned-process";var V="0.75.653";var xt=(e)=>e,O=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],H=(e)=>Le("sha256").update(e).digest("hex"),z=(e)=>/^[a-z0-9][a-z0-9._-]*$/i.test(e)&&!e.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(e),ce=(e)=>{let i=new URL(e);return i.origin+i.pathname};async function fe(e,i=process.cwd()){let c=new URL(e.baseUrl);if(!["http:","https:"].includes(c.protocol)||c.username||c.password||c.search||c.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!e.outDir||!e.pages.length)throw Error("outDir and at least one page are required");if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<100||e.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(e.backend&&!["webkit","chrome"].includes(e.backend))throw Error("backend must be webkit or chrome");if(e.requireHttpStatus!==void 0&&typeof e.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let t=Object.keys(e.profiles??{default:{}});if(!t.length||t.some((n)=>!z(n)))throw Error("Profile names must be safe filenames");let a=new Set,f=new Set;for(let n of e.pages){if(!z(n.id)||a.has(n.id))throw Error(`Duplicate or invalid screen id: ${n.id}`);if(a.add(n.id),n.expectedStatus!==void 0&&(!Number.isInteger(n.expectedStatus)||n.expectedStatus<100||n.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${n.id}`);if(!n.title.trim()||!n.description.trim()||!n.waitFor.trim())throw Error(`Screen ${n.id} needs title, description and waitFor`);if(typeof n.path!=="string"&&(typeof n.path!=="function"||!n.route))throw Error(`Screen ${n.id} needs a route pattern for its path resolver`);let s=new URL(typeof n.path==="string"?n.path:n.route,c);if(s.origin!==c.origin||s.username||s.password)throw Error(`Screen ${n.id} must stay on baseUrl's origin`);if(n.profiles?.some((p)=>!t.includes(p))||n.profiles?.length===0)throw Error(`Unknown or empty profiles for ${n.id}`);for(let p of n.sources??[]){let r=S(i,p);if(D(i,r).startsWith("..")||pe(p))throw Error(`Source must be inside the project: ${p}`);await P(r),f.add(D(i,r).replaceAll("\\","/"))}}let d=new Set;for(let n of e.viewports??O){if(!z(n.name)||d.has(n.name)||![n.width,n.height].every((s)=>Number.isInteger(s)&&s>=200&&s<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");d.add(n.name)}if(!d.size)throw Error("At least one viewport is required");for(let n of e.inputs??[])await P(S(i,n));oe(e.film===!0?{}:e.film,e.docs,i,e.viewports??O);let h=[],m=new Set;for(let n of e.coverage?.directories??[]){let s=S(i,n);if(D(i,s).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await Je(s)).isDirectory())throw Error(`Missing coverage directory: ${n}`);let p=0;for await(let r of new Bun.Glob("**/*.stx").scan({cwd:s,onlyFiles:!0})){p++;let o=D(i,g(s,r)).replaceAll("\\","/");if(m.add(o),!f.has(o)&&!e.coverage?.exclude?.[o]?.trim())h.push(o)}if(!p)throw Error(`No .stx screens found in ${n}`)}for(let[n,s]of Object.entries(e.coverage?.exclude??{}))if(!s.trim()||!m.has(n))throw Error(`Stale or unexplained coverage exclusion: ${n}`);if(h.length)throw Error(`Undocumented screens:
|
|
16
20
|
${h.sort().join(`
|
|
17
|
-
`)}`)}async function
|
|
21
|
+
`)}`)}async function Q(e){let i=(await import(_e(e).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function ze(e,i){let c=Date.now()+i;while(!await e()){if(Date.now()>=c)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function de(e,i){let c=e instanceof Error?e.message:"Screenshot capture failed";for(let t of i.redactEnv??[]){let a=process.env[t];if(a)c=c.replaceAll(a,"[redacted]")}return c.slice(0,1000)}async function Ke(e,i,c){let t=await Q(e),a=S(c.root),f=S(a,c.outDir??t.outDir),d=[],h=await q(a,t.models);try{let m={...t.fixtures,...await t.data?.prepare(h)},n=t.backend??(process.platform==="darwin"?"webkit":"chrome"),s=t.timeoutMs??30000;for(let p of t.viewports??O){if(c.viewports?.length&&!c.viewports.includes(p.name))continue;for(let r of t.pages){if(c.only?.length&&!c.only.includes(r.id))continue;if(!(r.profiles??Object.keys(t.profiles??{default:{}})).includes(i))continue;let o={id:r.id,profile:i,viewport:p,title:r.title,description:r.description,...r.reason?{reason:r.reason}:{},path:new URL(typeof r.path==="string"?r.path:r.route,t.baseUrl).pathname,status:"failed"};if(d.push(o),r.skip){o.status="skipped",o.error=r.skip,process.send?.({type:"screenshot-result",result:o});continue}let l="starting the browser",u,R;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");u=new Bun.WebView({width:p.width,height:p.height,backend:n==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let x=typeof r.path==="function"?await r.path({fixtures:m,models:h,profile:i}):J(r.path,r.model,m,h),v=new URL(x,t.baseUrl);if(v.origin!==new URL(t.baseUrl).origin||v.username||v.password)throw Error("Resolved screenshot path must stay on the configured origin");let b={...r,path:x},y={view:u,baseUrl:t.baseUrl,profile:i,viewport:p,page:b};o.path=v.pathname,l="preparing the review profile",await t.profiles?.[i]?.prepare?.(y),l="opening the screen",await u.navigate(new URL(b.path,t.baseUrl).href),l="checking the document HTTP status";let k=Number(await u.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(k)&&k>=100&&k<=599)y.httpStatus=o.httpStatus=k;if(!y.httpStatus&&(t.requireHttpStatus||r.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(r.expectedStatus!==void 0?y.httpStatus!==r.expectedStatus:k>=400)throw Error(`The screen returned HTTP ${k}${r.expectedStatus!==void 0?` instead of ${r.expectedStatus}`:"; check its route, access and fixture"}`);l="preparing the screen state",await r.prepare?.(y),l="waiting for screen readiness",await ze(async()=>Boolean(await u.evaluate(`Boolean(document.querySelector(${JSON.stringify(r.waitFor)}))`))&&(!r.ready||await r.ready(y)),s);let w=String(await u.evaluate("location.href"));if(ce(w)!==ce(new URL(b.path,t.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(l="loading fonts and visible images",await u.evaluate(`(async () => {
|
|
18
22
|
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);
|
|
19
|
-
for (const selector of ${JSON.stringify(
|
|
23
|
+
for (const selector of ${JSON.stringify(r.masks??[])}) document.querySelectorAll(selector);
|
|
20
24
|
const maskSheet = new CSSStyleSheet();
|
|
21
|
-
maskSheet.replaceSync(${JSON.stringify(
|
|
25
|
+
maskSheet.replaceSync(${JSON.stringify(X(r.masks??[]))});
|
|
22
26
|
document.adoptedStyleSheets = [...document.adoptedStyleSheets, maskSheet];
|
|
23
27
|
await document.fonts.ready;
|
|
24
28
|
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})}); }
|
|
25
29
|
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
|
|
26
|
-
})()`),await
|
|
27
|
-
`);try{for(let
|
|
28
|
-
`),await
|
|
29
|
-
`," "),
|
|
30
|
+
})()`),await u.evaluate("[...document.images].some(image=>{const r=image.getBoundingClientRect();return r.bottom>0&&r.top<innerHeight&&image.complete&&image.naturalWidth===0})"))throw Error("A visible image failed to load");l="saving the screenshot";let C=new Uint8Array(await(await u.screenshot()).arrayBuffer()),E=`${r.id}/${i}-${p.name}.png`,j=g(f,E);await K(le(j),{recursive:!0});let M=g(c.staging,`${r.id}-${i}-${p.name}.png`);await Bun.write(M,C),await G(M,j),o.file=E,o.sha256=H(C),o.status="captured"})(),new Promise((x,v)=>{R=setTimeout(()=>{u?.close(),v(Error("Screenshot deadline exceeded"))},s)})])}catch(x){o.error=`${l}: ${de(x,t)}`}finally{if(R)clearTimeout(R);u?.close(),process.send?.({type:"screenshot-result",result:o})}}}return d}finally{await t.data?.cleanup?.()}}async function $t(e={}){if(e.list&&e.check)throw Error("Choose list or check, not both");let i=S(e.root??process.cwd()),c=S(i,e.config??"config/screenshots.ts"),t=await Q(c);await fe(t,i);for(let s of e.only??[])if(!t.pages.some((p)=>p.id===s))throw Error(`Unknown screen: ${s}`);for(let s of e.viewports??[])if(!(t.viewports??O).some((p)=>p.name===s))throw Error(`Unknown viewport: ${s}`);let a=S(i,e.outDir??t.outDir),f=[...new Set([...t.inputs??[],...t.pages.flatMap((s)=>s.sources??[])])].sort(),d={format:1,generator:"@stacksjs/docs/screenshots",generatorVersion:V,models:await q(i,t.models),configHash:H(Buffer.concat([Buffer.from(V),await P(c),...await Promise.all(f.map((s)=>P(S(i,s))))])),inventory:t.pages.map((s)=>({id:s.id,title:s.title,path:new URL(typeof s.path==="string"?s.path:s.route,t.baseUrl).pathname,sources:s.sources??[],...s.skip?{skip:s.skip}:{}})),backend:t.backend??(process.platform==="darwin"?"webkit":"chrome"),bun:Bun.version,results:[]};if(e.list)return d;if(e.check){let s=JSON.parse(await P(g(a,"manifest.json"),"utf8"));if(s.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(s.generatorVersion!==V||s.configHash!==d.configHash||s.models?.sourceHash!==d.models.sourceHash||s.results.some((p)=>p.status==="failed"))throw Error("Screenshot SDK or inventory changed, or the previous capture failed; capture again");for(let p of t.pages)for(let r of p.profiles??Object.keys(t.profiles??{default:{}}))for(let o of t.viewports??O){let l=s.results.find((u)=>u.id===p.id&&u.profile===r&&u.viewport.name===o.name);if(!l||!p.skip&&l.status!=="captured")throw Error(`Missing screenshot: ${p.id}/${r}-${o.name}`);if(l.file&&(D(a,S(a,l.file)).split(/[\\/]/)[0]===".."||pe(D(a,S(a,l.file)))||H(await P(g(a,l.file)))!==l.sha256))throw Error(`Screenshot bytes changed: ${p.id}`)}for(let p of s.films??[])if(D(a,S(a,p.file)).startsWith("..")||H(await P(g(a,p.file)))!==p.sha256)throw Error(`Screen film changed: ${p.file}`);if(t.film&&!s.films?.length)throw Error("The screen film is missing; capture again");if(t.docs&&(!s.docsPage||s.docsPage.path!==t.docs.page||H(await P(S(i,t.docs.page)))!==s.docsPage.sha256))throw Error("The screens documentation page is missing or changed; capture again");return s}let h;try{let s=g(a,"manifest.json");if((await A(s)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");if(h=JSON.parse(await P(s,"utf8")),h.generator!=="@stacksjs/docs/screenshots")throw Error("Refusing to overwrite an unowned manifest");if((e.only?.length||e.viewports?.length)&&h.configHash!==d.configHash)throw Error("Capture inputs or SDK changed; use a fresh output directory or run a complete capture before updating individual screens")}catch(s){if(s.code!=="ENOENT")throw s}let m=new Set(h?.results.map((s)=>s.file).filter(Boolean));for(let s of t.pages){let p=g(a,s.id);try{if((await A(p)).isSymbolicLink())throw Error(`Screenshot directory is a symlink: ${s.id}`)}catch(r){if(r.code!=="ENOENT")throw r}for(let r of s.profiles??Object.keys(t.profiles??{default:{}}))for(let o of t.viewports??O){let l=`${s.id}/${r}-${o.name}.png`;try{if((await A(g(a,l))).isSymbolicLink()||!m.has(l))throw Error(`Refusing to overwrite an unowned screenshot: ${l}`)}catch(u){if(u.code!=="ENOENT")throw u}}}for(let s of["gallery.md","manifest.json.tmp"])try{if((await A(g(a,s))).isSymbolicLink()||!h)throw Error(`Refusing to overwrite an unowned screenshot artifact: ${s}`)}catch(p){if(p.code!=="ENOENT")throw p}await K(a,{recursive:!0});let n=await ae(g(a,".stacks-screenshots-"));await Bun.write(g(n,"bunfig.toml"),`preload = []
|
|
31
|
+
`);try{for(let o of Object.keys(t.profiles??{default:{}})){let l=g(n,`${o}.json`),u=t.pages.filter((E)=>(!e.only?.length||e.only.includes(E.id))&&(E.profiles??Object.keys(t.profiles??{default:{}})).includes(o)),R=u.length*(t.viewports??O).filter((E)=>!e.viewports?.length||e.viewports.includes(E.name)).length;if(!R)continue;let x=import.meta.path.startsWith("/$bunfs/")?Bun.which("bun"):process.execPath;if(!x)throw Error("An installed Bun is required for screenshot workers");let v=import.meta.path.startsWith("/$bunfs/")?Bun.resolveSync("@stacksjs/docs/screenshots",i):import.meta.path,b=We(),y=process.platform!=="win32"&&Buffer.byteLength(b)>60?"/tmp":b,k=await ae(g(y,"stx-b-")),w={...process.env,TMPDIR:k,TMP:k,TEMP:k},F,C;try{let E=F=Ie([x,"--no-env-file",`--config=${g(n,"bunfig.toml")}`,v,"--worker",c,o,JSON.stringify({...e,root:i,staging:n}),l],{ownerRuntime:x,cwd:i,env:w,stdin:"ignore",stdout:"ignore",stderr:"ignore",ipc:(M)=>{let U=M;if(U?.type==="screenshot-result"&&U.result)e.onProgress?.(U.result)}});if((await Promise.race([E.exited,new Promise((M,U)=>{C=setTimeout(()=>{E.stop(),U(Error(`Screenshot worker timed out for ${o}`))},R*((t.timeoutMs??30000)+2000)+30000)})])).code!==0)throw Error(`Screenshot worker failed for ${o}`);d.results.push(...JSON.parse(await P(l,"utf8")))}catch(E){for(let j of u)for(let M of t.viewports??O){if(e.viewports?.length&&!e.viewports.includes(M.name))continue;d.results.push({id:j.id,profile:o,viewport:M,title:j.title,description:j.description,path:new URL(typeof j.path==="string"?j.path:j.route,t.baseUrl).pathname,status:"failed",error:de(E,t)})}}finally{if(C)clearTimeout(C);await F?.stop(),await I(k,{recursive:!0,force:!0})}}if(e.only?.length||e.viewports?.length)try{let o=JSON.parse(await P(g(a,"manifest.json"),"utf8"));if(o.configHash===d.configHash&&o.models?.sourceHash===d.models.sourceHash){let l=new Set(d.results.map((u)=>`${u.id}/${u.profile}/${u.viewport.name}`));d.results.unshift(...o.results.filter((u)=>!l.has(`${u.id}/${u.profile}/${u.viewport.name}`)))}}catch{}for(let o of d.results){if(o.status!=="failed"||o.file)continue;let l=h?.results.find((u)=>u.id===o.id&&u.profile===o.profile&&u.viewport.name===o.viewport.name);if(l?.file)o.file=l.file,o.sha256=l.sha256}if(!e.only?.length&&!e.viewports?.length){let o=new Set(d.results.map((l)=>l.file).filter(Boolean));for(let l of m){if(!l||o.has(l)||D(a,S(a,l)).startsWith(".."))continue;await I(g(a,l),{force:!0}),await qe(le(g(a,l))).catch(()=>{})}}await K(a,{recursive:!0});let s;try{if(e.publish!==!1){if(t.film)d.films=await W(a,d.results,t.viewports??O,t.film===!0?{}:t.film);if(t.docs)d.docsPage=await _(i,d,t.docs)}}catch(o){s=o}await Bun.write(g(a,"manifest.json.tmp"),`${JSON.stringify(d,null,2)}
|
|
32
|
+
`),await G(g(a,"manifest.json.tmp"),g(a,"manifest.json"));let p=(o)=>o.replace(/[\\`*_[\]<>]/g,"\\$&").replaceAll(`
|
|
33
|
+
`," "),r=["# Screen captures","",`Generated from the explicit screen inventory with @stacksjs/docs ${V}. Review the images before publishing.`,""];for(let o of d.results)r.push(`## ${p(o.title)} (${o.profile}, ${o.viewport.name})`,"",p(o.description),"",...o.reason?[p(o.reason),""]:[],o.status==="captured"?``:`**${o.status}:** ${p(o.error??"No image")}`,"");if(await Bun.write(g(a,"gallery.md"),`${r.join(`
|
|
30
34
|
`)}
|
|
31
|
-
`),
|
|
35
|
+
`),s)throw s;return d}finally{await I(n,{recursive:!0,force:!0})}}async function kt(e={}){let i=S(e.root??process.cwd()),c=await Q(S(i,e.config??"config/screenshots.ts"));await fe(c,i);let t=S(i,e.outDir??c.outDir),a=g(t,"manifest.json");if((await A(a)).isSymbolicLink())throw Error("Screenshot manifest must not be a symlink");let f=JSON.parse(await P(a,"utf8"));if(f.generator!=="@stacksjs/docs/screenshots")throw Error("This is not a Stacks screenshot manifest");if(delete f.films,delete f.docsPage,c.film)f.films=await W(t,f.results,c.viewports??O,c.film===!0?{}:c.film);if(c.docs)f.docsPage=await _(i,f,c.docs);return await Bun.write(g(t,"manifest.json.tmp"),`${JSON.stringify(f,null,2)}
|
|
36
|
+
`),await G(g(t,"manifest.json.tmp"),a),f}if(import.meta.main&&process.argv[2]==="--worker")try{let e=await Ke(process.argv[3],process.argv[4],JSON.parse(process.argv[5]));await Bun.write(process.argv[6],JSON.stringify(e))}catch{process.exitCode=1}export{$t as captureScreenshots,xt as defineScreenshotConfig,q as discoverScreenshotModels,ie as discoverViews,L as planScreenshotModels,kt as publishScreenshots,Ae as screensFromViews,J as screenshotFixturePath,fe as validateScreenshotConfig};
|
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.653";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/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.653",
|
|
6
6
|
"description": "The Stacks way to document.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,17 +58,17 @@
|
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@stacksjs/bunpress": "^0.2.25",
|
|
61
|
-
"@stacksjs/cli": "0.75.
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
63
|
-
"@stacksjs/path": "0.75.
|
|
64
|
-
"@stacksjs/orm": "0.75.
|
|
61
|
+
"@stacksjs/cli": "0.75.653",
|
|
62
|
+
"@stacksjs/config": "0.75.653",
|
|
63
|
+
"@stacksjs/path": "0.75.653",
|
|
64
|
+
"@stacksjs/orm": "0.75.653",
|
|
65
65
|
"@stacksjs/stx": "^0.2.908",
|
|
66
|
-
"@stacksjs/testing": "0.75.
|
|
66
|
+
"@stacksjs/testing": "0.75.653",
|
|
67
67
|
"craft-native": ">=0.0.499"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
-
"@stacksjs/alias": "0.75.
|
|
71
|
-
"@stacksjs/server": "0.75.
|
|
70
|
+
"@stacksjs/alias": "0.75.653",
|
|
71
|
+
"@stacksjs/server": "0.75.653",
|
|
72
72
|
"better-dx": "^0.2.39"
|
|
73
73
|
}
|
|
74
74
|
}
|