@stacksjs/docs 0.75.634 → 0.75.636

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.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{createHash as se}from"crypto";import{lstat as N,mkdir as C,mkdtemp as oe,readFile as E,rename as W,rm as ne,stat as ie}from"fs/promises";import{dirname as ae,isAbsolute as I,join as y,relative as M,resolve as k}from"path";import{pathToFileURL as ce}from"url";import{createHash as z}from"crypto";import{readFile as G}from"fs/promises";import{existsSync as Q}from"fs";import{isAbsolute as X,join as Y,relative as Z,resolve as ee}from"path";import{loadModelRegistry as te,modelFiles as J}from"@stacksjs/orm/model-registry";function U(r){let i=Object.entries(r).map(([e,n])=>{let a=Object.entries(n.attributes??{}),u=n.belongsTo??[],x=(Array.isArray(u)?u:Object.values(u)).map((p)=>typeof p==="string"?p:p&&typeof p==="object"?String(p.model??p.name??""):"").filter(Boolean),S=n.traits?.useApi,v=n.traits?.useSeeder??n.traits?.seedable,g=(p,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(p)),w=a.filter(([,p])=>p.required&&!p.nullable&&typeof p.factory!=="function"&&!Object.hasOwn(p,"default")).map(([p])=>p);return{name:String(n.name??e),table:n.table,primaryKey:String(n.primaryKey??"id"),...S?.uri?{api:String(S.uri)}:{},parents:[...new Set([...x,...Array.isArray(v?.after)?v.after.map(String):[]])].sort(),seederCount:typeof v?.count==="number"?v.count:null,factoryFields:a.filter(([,p])=>typeof p.factory==="function").map(([p])=>p),defaultFields:a.filter(([,p])=>Object.hasOwn(p,"default")).map(([p])=>p),requiredWithoutFactory:w,sensitiveFields:a.filter(([p,R])=>g(p,R)).map(([p])=>p),suggestedStates:[...new Set(["empty","populated",...S?.routes?.includes("show")?["detail"]:[],...S?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((e,n)=>e.name.localeCompare(n.name)),l=new Set(i.map((e)=>e.name)),s=new Map(i.map((e)=>[e.name,e])),d=[];for(;;){let e=[...s.values()].filter((n)=>n.parents.every((a)=>!l.has(a)||d.includes(a)));if(!e.length)break;for(let n of e)d.push(n.name),s.delete(n.name)}let m=new Set,f=new Map,h=new Map,b=[],o=new Set,t=0;function c(e){f.set(e,t),h.set(e,t++),b.push(e),o.add(e);for(let u of s.get(e)?.parents??[]){if(!s.has(u))continue;if(!f.has(u))c(u),h.set(e,Math.min(h.get(e),h.get(u)));else if(o.has(u))h.set(e,Math.min(h.get(e),f.get(u)))}if(h.get(e)!==f.get(e))return;let n=[],a;do a=b.pop(),o.delete(a),n.push(a);while(a!==e);if(n.length>1||s.get(e)?.parents.includes(e))for(let u of n)m.add(u)}for(let e of s.keys())if(!f.has(e))c(e);return{models:i,creationOrder:d,cycles:[...m].sort(),blocked:[...s.keys()].filter((e)=>!m.has(e)),externalParents:[...new Set(i.flatMap((e)=>e.parents).filter((e)=>!l.has(e)))].sort()}}async function F(r,i={}){if(i===!1)return U({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let l=ee(r,i.directory??"app/Models");if(X(i.directory??"")||Z(r,l).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let s=i.includeDefaults?Y(r,"storage/framework/defaults/app/Models"):void 0;if(!Q(l)&&!s)return U({});let d=[],m=await te({userRoot:l,defaultsRoot:s,onImportError:(b)=>d.push(b)});if(d.length)throw Error(`Cannot inspect screenshot models: ${d.join(", ")}`);let f=U(m),h=[...J(l),...s?J(s):[]].sort();return f.sourceHash=z("sha256").update(Buffer.concat(await Promise.all(h.map((b)=>G(b))))).digest("hex"),f}function T(r,i,l,s){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(r))return r;let d=i?s.models.filter((h)=>h.name===i):s.models.filter((h)=>h.api&&r.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),m=d.length===1?d[0]:void 0;if(!m)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let f=l[m.name];if(!f)throw Error(`No screenshot fixture supplied for ${m.name}`);return r.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,b,o)=>{let t=b||o,c=t==="id"?m.primaryKey:t;if(m.sensitiveFields.includes(c)||/token|secret|password/i.test(t))throw Error(`Refusing to publish a sensitive route parameter: ${t}`);let e=f[c];if(e===void 0||e===""||typeof e!=="string"&&typeof e!=="number"||typeof e==="number"&&!Number.isFinite(e))throw Error(`Screenshot fixture ${m.name} has no ${t}`);return encodeURIComponent(String(e))})}import{spawnOwnedProcess as de}from"@stacksjs/cli/owned-process";var O="0.75.634";var Pe=(r)=>r,P=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],H=(r)=>se("sha256").update(r).digest("hex"),B=(r)=>/^[a-z0-9][a-z0-9._-]*$/i.test(r)&&!r.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r),V=(r)=>{let i=new URL(r);return i.origin+i.pathname};async function le(r,i=process.cwd()){let l=new URL(r.baseUrl);if(!["http:","https:"].includes(l.protocol)||l.username||l.password||l.search||l.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!r.outDir||!r.pages.length)throw Error("outDir and at least one page are required");if(r.timeoutMs!==void 0&&(!Number.isFinite(r.timeoutMs)||r.timeoutMs<100||r.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(r.backend&&!["webkit","chrome"].includes(r.backend))throw Error("backend must be webkit or chrome");if(r.requireHttpStatus!==void 0&&typeof r.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let s=Object.keys(r.profiles??{default:{}});if(!s.length||s.some((o)=>!B(o)))throw Error("Profile names must be safe filenames");let d=new Set,m=new Set;for(let o of r.pages){if(!B(o.id)||d.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(d.add(o.id),o.expectedStatus!==void 0&&(!Number.isInteger(o.expectedStatus)||o.expectedStatus<100||o.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${o.id}`);if(!o.title.trim()||!o.description.trim()||!o.waitFor.trim())throw Error(`Screen ${o.id} needs title, description and waitFor`);if(typeof o.path!=="string"&&(typeof o.path!=="function"||!o.route))throw Error(`Screen ${o.id} needs a route pattern for its path resolver`);let t=new URL(typeof o.path==="string"?o.path:o.route,l);if(t.origin!==l.origin||t.username||t.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((c)=>!s.includes(c))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let c of o.sources??[]){let e=k(i,c);if(M(i,e).startsWith("..")||I(c))throw Error(`Source must be inside the project: ${c}`);await E(e),m.add(M(i,e).replaceAll("\\","/"))}}let f=new Set;for(let o of r.viewports??P){if(!B(o.name)||f.has(o.name)||![o.width,o.height].every((t)=>Number.isInteger(t)&&t>=200&&t<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");f.add(o.name)}if(!f.size)throw Error("At least one viewport is required");for(let o of r.inputs??[])await E(k(i,o));let h=[],b=new Set;for(let o of r.coverage?.directories??[]){let t=k(i,o);if(M(i,t).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await ie(t)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let c=0;for await(let e of new Bun.Glob("**/*.stx").scan({cwd:t,onlyFiles:!0})){c++;let n=M(i,y(t,e)).replaceAll("\\","/");if(b.add(n),!m.has(n)&&!r.coverage?.exclude?.[n]?.trim())h.push(n)}if(!c)throw Error(`No .stx screens found in ${o}`)}for(let[o,t]of Object.entries(r.coverage?.exclude??{}))if(!t.trim()||!b.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(h.length)throw Error(`Undocumented screens:
2
+ import{createHash as se}from"crypto";import{lstat as N,mkdir as C,mkdtemp as oe,readFile as E,rename as W,rm as ne,stat as ie}from"fs/promises";import{dirname as ae,isAbsolute as I,join as y,relative as M,resolve as k}from"path";import{pathToFileURL as ce}from"url";import{createHash as z}from"crypto";import{readFile as G}from"fs/promises";import{existsSync as Q}from"fs";import{isAbsolute as X,join as Y,relative as Z,resolve as ee}from"path";import{loadModelRegistry as te,modelFiles as J}from"@stacksjs/orm/model-registry";function U(r){let i=Object.entries(r).map(([e,n])=>{let a=Object.entries(n.attributes??{}),u=n.belongsTo??[],x=(Array.isArray(u)?u:Object.values(u)).map((p)=>typeof p==="string"?p:p&&typeof p==="object"?String(p.model??p.name??""):"").filter(Boolean),S=n.traits?.useApi,v=n.traits?.useSeeder??n.traits?.seedable,g=(p,R)=>Boolean(R.hidden||R.encrypted||R.personal||/password|token|secret|api.?key|email|phone|address/i.test(p)),w=a.filter(([,p])=>p.required&&!p.nullable&&typeof p.factory!=="function"&&!Object.hasOwn(p,"default")).map(([p])=>p);return{name:String(n.name??e),table:n.table,primaryKey:String(n.primaryKey??"id"),...S?.uri?{api:String(S.uri)}:{},parents:[...new Set([...x,...Array.isArray(v?.after)?v.after.map(String):[]])].sort(),seederCount:typeof v?.count==="number"?v.count:null,factoryFields:a.filter(([,p])=>typeof p.factory==="function").map(([p])=>p),defaultFields:a.filter(([,p])=>Object.hasOwn(p,"default")).map(([p])=>p),requiredWithoutFactory:w,sensitiveFields:a.filter(([p,R])=>g(p,R)).map(([p])=>p),suggestedStates:[...new Set(["empty","populated",...S?.routes?.includes("show")?["detail"]:[],...S?.middleware?.length?["permission-denied"]:[],...n.traits?.useSoftDeletes||n.traits?.softDeletable?["archived"]:[]])]}}).sort((e,n)=>e.name.localeCompare(n.name)),l=new Set(i.map((e)=>e.name)),s=new Map(i.map((e)=>[e.name,e])),d=[];for(;;){let e=[...s.values()].filter((n)=>n.parents.every((a)=>!l.has(a)||d.includes(a)));if(!e.length)break;for(let n of e)d.push(n.name),s.delete(n.name)}let m=new Set,f=new Map,h=new Map,b=[],o=new Set,t=0;function c(e){f.set(e,t),h.set(e,t++),b.push(e),o.add(e);for(let u of s.get(e)?.parents??[]){if(!s.has(u))continue;if(!f.has(u))c(u),h.set(e,Math.min(h.get(e),h.get(u)));else if(o.has(u))h.set(e,Math.min(h.get(e),f.get(u)))}if(h.get(e)!==f.get(e))return;let n=[],a;do a=b.pop(),o.delete(a),n.push(a);while(a!==e);if(n.length>1||s.get(e)?.parents.includes(e))for(let u of n)m.add(u)}for(let e of s.keys())if(!f.has(e))c(e);return{models:i,creationOrder:d,cycles:[...m].sort(),blocked:[...s.keys()].filter((e)=>!m.has(e)),externalParents:[...new Set(i.flatMap((e)=>e.parents).filter((e)=>!l.has(e)))].sort()}}async function F(r,i={}){if(i===!1)return U({});if(i.directory!==void 0&&!i.directory.trim())throw Error("Model directory must not be empty");let l=ee(r,i.directory??"app/Models");if(X(i.directory??"")||Z(r,l).split(/[\\/]/)[0]==="..")throw Error("Model directory must be inside the project");let s=i.includeDefaults?Y(r,"storage/framework/defaults/app/Models"):void 0;if(!Q(l)&&!s)return U({});let d=[],m=await te({userRoot:l,defaultsRoot:s,onImportError:(b)=>d.push(b)});if(d.length)throw Error(`Cannot inspect screenshot models: ${d.join(", ")}`);let f=U(m),h=[...J(l),...s?J(s):[]].sort();return f.sourceHash=z("sha256").update(Buffer.concat(await Promise.all(h.map((b)=>G(b))))).digest("hex"),f}function T(r,i,l,s){if(!/\[[^\]]+\]|:[a-z][\w]*(?=\/|$|[?#])/i.test(r))return r;let d=i?s.models.filter((h)=>h.name===i):s.models.filter((h)=>h.api&&r.replace(/^\//,"").startsWith(`${h.api.replace(/^\//,"")}/`)),m=d.length===1?d[0]:void 0;if(!m)throw Error("A dynamic screenshot route needs an explicit model or an unambiguous model API URI");let f=l[m.name];if(!f)throw Error(`No screenshot fixture supplied for ${m.name}`);return r.replace(/\[([^\]]+)\]|:([a-z][\w]*)(?=\/|$|[?#])/gi,(h,b,o)=>{let t=b||o,c=t==="id"?m.primaryKey:t;if(m.sensitiveFields.includes(c)||/token|secret|password/i.test(t))throw Error(`Refusing to publish a sensitive route parameter: ${t}`);let e=f[c];if(e===void 0||e===""||typeof e!=="string"&&typeof e!=="number"||typeof e==="number"&&!Number.isFinite(e))throw Error(`Screenshot fixture ${m.name} has no ${t}`);return encodeURIComponent(String(e))})}import{spawnOwnedProcess as de}from"@stacksjs/cli/owned-process";var O="0.75.636";var Pe=(r)=>r,P=[{name:"desktop",width:1440,height:900},{name:"mobile",width:390,height:844}],H=(r)=>se("sha256").update(r).digest("hex"),B=(r)=>/^[a-z0-9][a-z0-9._-]*$/i.test(r)&&!r.endsWith(".")&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(r),V=(r)=>{let i=new URL(r);return i.origin+i.pathname};async function le(r,i=process.cwd()){let l=new URL(r.baseUrl);if(!["http:","https:"].includes(l.protocol)||l.username||l.password||l.search||l.hash)throw Error("baseUrl must be an http(s) URL without credentials, query or fragment");if(!r.outDir||!r.pages.length)throw Error("outDir and at least one page are required");if(r.timeoutMs!==void 0&&(!Number.isFinite(r.timeoutMs)||r.timeoutMs<100||r.timeoutMs>120000))throw Error("timeoutMs must be between 100 and 120000");if(r.backend&&!["webkit","chrome"].includes(r.backend))throw Error("backend must be webkit or chrome");if(r.requireHttpStatus!==void 0&&typeof r.requireHttpStatus!=="boolean")throw Error("requireHttpStatus must be a boolean");let s=Object.keys(r.profiles??{default:{}});if(!s.length||s.some((o)=>!B(o)))throw Error("Profile names must be safe filenames");let d=new Set,m=new Set;for(let o of r.pages){if(!B(o.id)||d.has(o.id))throw Error(`Duplicate or invalid screen id: ${o.id}`);if(d.add(o.id),o.expectedStatus!==void 0&&(!Number.isInteger(o.expectedStatus)||o.expectedStatus<100||o.expectedStatus>599))throw Error(`Invalid expected HTTP status for ${o.id}`);if(!o.title.trim()||!o.description.trim()||!o.waitFor.trim())throw Error(`Screen ${o.id} needs title, description and waitFor`);if(typeof o.path!=="string"&&(typeof o.path!=="function"||!o.route))throw Error(`Screen ${o.id} needs a route pattern for its path resolver`);let t=new URL(typeof o.path==="string"?o.path:o.route,l);if(t.origin!==l.origin||t.username||t.password)throw Error(`Screen ${o.id} must stay on baseUrl's origin`);if(o.profiles?.some((c)=>!s.includes(c))||o.profiles?.length===0)throw Error(`Unknown or empty profiles for ${o.id}`);for(let c of o.sources??[]){let e=k(i,c);if(M(i,e).startsWith("..")||I(c))throw Error(`Source must be inside the project: ${c}`);await E(e),m.add(M(i,e).replaceAll("\\","/"))}}let f=new Set;for(let o of r.viewports??P){if(!B(o.name)||f.has(o.name)||![o.width,o.height].every((t)=>Number.isInteger(t)&&t>=200&&t<=7680))throw Error("Viewports need unique safe names and integer dimensions from 200 to 7680");f.add(o.name)}if(!f.size)throw Error("At least one viewport is required");for(let o of r.inputs??[])await E(k(i,o));let h=[],b=new Set;for(let o of r.coverage?.directories??[]){let t=k(i,o);if(M(i,t).startsWith(".."))throw Error("Coverage directories must be inside the project");if(!(await ie(t)).isDirectory())throw Error(`Missing coverage directory: ${o}`);let c=0;for await(let e of new Bun.Glob("**/*.stx").scan({cwd:t,onlyFiles:!0})){c++;let n=M(i,y(t,e)).replaceAll("\\","/");if(b.add(n),!m.has(n)&&!r.coverage?.exclude?.[n]?.trim())h.push(n)}if(!c)throw Error(`No .stx screens found in ${o}`)}for(let[o,t]of Object.entries(r.coverage?.exclude??{}))if(!t.trim()||!b.has(o))throw Error(`Stale or unexplained coverage exclusion: ${o}`);if(h.length)throw Error(`Undocumented screens:
3
3
  ${h.sort().join(`
4
4
  `)}`)}async function _(r){let i=(await import(ce(r).href)).default;if(!i||typeof i!=="object")throw Error("Screenshot configuration must have a default export");return i}async function ue(r,i){let l=Date.now()+i;while(!await r()){if(Date.now()>=l)throw Error("The screen did not become ready before its deadline");await Bun.sleep(100)}}function K(r,i){let l=r instanceof Error?r.message:"Screenshot capture failed";for(let s of i.redactEnv??[]){let d=process.env[s];if(d)l=l.replaceAll(d,"[redacted]")}return l.slice(0,1000)}async function pe(r,i,l){let s=await _(r),d=k(l.root),m=k(d,l.outDir??s.outDir),f=[],h=await F(d,s.models);try{let b={...s.fixtures,...await s.data?.prepare(h)},o=s.backend??(process.platform==="darwin"?"webkit":"chrome"),t=s.timeoutMs??30000;for(let c of s.viewports??P){if(l.viewports?.length&&!l.viewports.includes(c.name))continue;for(let e of s.pages){if(l.only?.length&&!l.only.includes(e.id))continue;if(!(e.profiles??Object.keys(s.profiles??{default:{}})).includes(i))continue;let n={id:e.id,profile:i,viewport:c,title:e.title,description:e.description,...e.reason?{reason:e.reason}:{},path:new URL(typeof e.path==="string"?e.path:e.route,s.baseUrl).pathname,status:"failed"};if(f.push(n),e.skip){n.status="skipped",n.error=e.skip,process.send?.({type:"screenshot-result",result:n});continue}let a="starting the browser",u,j;try{if(typeof Bun.WebView!=="function")throw Error("This Bun has no WebView. Upgrade Bun before capturing screens.");u=new Bun.WebView({width:c.width,height:c.height,backend:o==="chrome"?{type:"chrome",url:!1,argv:process.env.CI?["--no-sandbox","--disable-dev-shm-usage"]:[]}:"webkit"}),await Promise.race([(async()=>{let x=typeof e.path==="function"?await e.path({fixtures:b,models:h,profile:i}):T(e.path,e.model,b,h),S=new URL(x,s.baseUrl);if(S.origin!==new URL(s.baseUrl).origin||S.username||S.password)throw Error("Resolved screenshot path must stay on the configured origin");let v={...e,path:x},g={view:u,baseUrl:s.baseUrl,profile:i,viewport:c,page:v};n.path=S.pathname,a="preparing the review profile",await s.profiles?.[i]?.prepare?.(g),a="opening the screen",await u.navigate(new URL(v.path,s.baseUrl).href),a="checking the document HTTP status";let w=Number(await u.evaluate("performance.getEntriesByType('navigation')[0]?.responseStatus || 0"));if(Number.isInteger(w)&&w>=100&&w<=599)g.httpStatus=n.httpStatus=w;if(!g.httpStatus&&(s.requireHttpStatus||e.expectedStatus!==void 0))throw Error("The browser did not expose a document HTTP status; choose the chrome backend for HTTP-verified captures");if(e.expectedStatus!==void 0?g.httpStatus!==e.expectedStatus:w>=400)throw Error(`The screen returned HTTP ${w}${e.expectedStatus!==void 0?` instead of ${e.expectedStatus}`:"; check its route, access and fixture"}`);a="preparing the screen state",await e.prepare?.(g),a="waiting for screen readiness",await ue(async()=>Boolean(await u.evaluate(`Boolean(document.querySelector(${JSON.stringify(e.waitFor)}))`))&&(!e.ready||await e.ready(g)),t);let p=String(await u.evaluate("location.href"));if(V(p)!==V(new URL(v.path,s.baseUrl).href))throw Error("The screen redirected to a different route; check its login and fixture");if(a="loading fonts and visible images",await u.evaluate(`(async () => {
5
5
  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);
@@ -0,0 +1,68 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { version } from '../package.json';
3
+ export declare function defineStoryConfig(config: StoryConfig): StoryConfig;
4
+ export declare function defineStory<Context>(story: Story<Context>): Story<Context>;
5
+ /** Record configured journeys, then atomically publish their docs and hashed evidence. */
6
+ export declare function recordStories(options?: RecordStoryOptions): Promise<StoryReport>;
7
+ export declare interface StorySession<Context = unknown> {
8
+ context: Context
9
+ screenshot: () => Promise<Uint8Array>
10
+ finish: () => Promise<void>
11
+ close: () => Promise<void>
12
+ }
13
+ export declare interface StoryDriver<Context = unknown> {
14
+ platform: StoryPlatform
15
+ fingerprint?: unknown
16
+ open: (options: { videoPath: string, fps: number, signal: AbortSignal }) => Promise<StorySession<Context>>
17
+ }
18
+ export declare interface StoryScene<Context = unknown> {
19
+ id: string
20
+ title: string
21
+ description?: string
22
+ run: (context: Context, signal: AbortSignal) => Promise<void> | void
23
+ holdMs?: number
24
+ timeoutMs?: number
25
+ }
26
+ export declare interface Story<Context = any> {
27
+ id: string
28
+ title: string
29
+ description?: string
30
+ driver: StoryDriver<Context>
31
+ scenes: StoryScene<Context>[]
32
+ }
33
+ export declare interface StoryConfig {
34
+ stories: Story[]
35
+ outDir?: string
36
+ publishDir?: string | false
37
+ title?: string
38
+ fps?: number
39
+ holdMs?: number
40
+ timeoutMs?: number
41
+ inputs?: string[]
42
+ }
43
+ export declare interface StoryArtifact { path: string, sha256: string, bytes: number }
44
+ export declare interface StorySceneResult { id: string, title: string, description?: string, status: 'passed' | 'failed' | 'not-run', startedMs?: number, endedMs?: number, screenshot?: StoryArtifact }
45
+ export declare interface StoryResult { id: string, title: string, description?: string, platform: StoryPlatform, status: 'passed' | 'failed' | 'not-run', scenes: StorySceneResult[], video?: StoryArtifact, page?: StoryArtifact }
46
+ export declare interface StoryReport {
47
+ version: 1
48
+ configHash: string
49
+ runId?: string
50
+ inventory: { id: string, title: string, platform: StoryPlatform, scenes: { id: string, title: string }[] }[]
51
+ results: StoryResult[]
52
+ index?: StoryArtifact
53
+ outDir: string
54
+ mediaDir?: string
55
+ published?: StoryArtifact[]
56
+ }
57
+ export declare interface RecordStoryOptions {
58
+ config?: string
59
+ root?: string
60
+ outDir?: string
61
+ only?: string[]
62
+ list?: boolean
63
+ check?: boolean
64
+ signal?: AbortSignal
65
+ onProgress?: (result: StoryResult) => void
66
+ onError?: (error: unknown, storyId: string) => void
67
+ }
68
+ export type StoryPlatform = 'browser' | 'ios' | 'android';
@@ -0,0 +1,9 @@
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.636";function xt(t){return t}function Et(t){return t}var C=`stacks-story-recordings-v1
3
+ `,z="<!-- Generated by buddy docs:stories. -->",I=(t)=>tt("sha256").update(t).digest("hex"),Z=(t)=>typeof t==="string"&&/^[a-z0-9][a-z0-9-]{0,79}$/.test(t);function v(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replace(/[\r\n]/g," ").replace(/([\\`*_[\]#|])/g,"\\$1")}async function J(t){try{return await _(t),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function g(t,i=t){let n=b(t);while(!0){if(await J(n)){if((await _(n)).isSymbolicLink())throw Error(`Story output cannot traverse a symbolic link: ${n}`)}if(n===b(i))return;let e=W(n);if(e===n)return;n=e}}async function L(t,i){await g(i,t);let n=await _(i);if(!n.isFile()||n.size===0)throw Error(`Missing or empty story artifact: ${i}`);let e=tt("sha256"),c=0;for await(let u of nt(i))e.update(u),c+=u.length;return{path:P(t,i).split(ut).join("/"),sha256:e.digest("hex"),bytes:c}}function B(t,i){let n=b(t,i.path);if(!i.path||et(i.path)||P(t,n).startsWith(".."))throw Error("Story artifact escaped its output directory");return n}async function ht(t){if(!t||!Array.isArray(t.stories)||!t.stories.length)throw Error("Story configuration needs at least one story");let i=new Set,n=(e,c,u,r)=>{if(!Number.isInteger(e)||e<c||e>u)throw Error(`Invalid story ${r}`)};n(t.fps??12,1,60,"fps (1 to 60)"),n(t.holdMs??700,0,30000,"holdMs (0 to 30000)"),n(t.timeoutMs??120000,100,1800000,"timeoutMs (100 to 1800000)");for(let e of t.stories){if(!Z(e.id)||i.has(e.id)||!e.title?.trim())throw Error(`Invalid or duplicate story id/title: ${e.id}`);if(i.add(e.id),!["browser","ios","android"].includes(e.driver?.platform)||typeof e.driver.open!=="function")throw Error(`Invalid driver for story ${e.id}`);if(!Array.isArray(e.scenes)||!e.scenes.length)throw Error(`Story ${e.id} has no scenes`);let c=new Set;for(let u of e.scenes){if(!Z(u.id)||c.has(u.id)||!u.title?.trim()||typeof u.run!=="function")throw Error(`Invalid or duplicate scene in ${e.id}: ${u.id}`);c.add(u.id),n(u.holdMs??t.holdMs??700,0,30000,"scene holdMs"),n(u.timeoutMs??t.timeoutMs??120000,100,1800000,"scene timeoutMs")}}}function wt(t,i){let n=[z,`# ${v(t.title)}`,"",t.description?v(t.description):"","",`Platform: ${t.platform}. Result: **${t.status}**.`,""];if(t.video)n.push(`<video controls playsinline preload="metadata" src="${i}${t.video.path}" poster="${t.scenes.find((e)=>e.screenshot)?.screenshot?i+t.scenes.find((e)=>e.screenshot).screenshot.path:""}"></video>`,"",`[Download video](${i}${t.video.path})`,"");for(let e of t.scenes)if(n.push(`## ${v(e.title)}`,"",`Result: **${e.status}**.${e.startedMs===void 0?"":` Starts at ${(e.startedMs/1000).toFixed(1)}s.`}`,"",e.description?v(e.description):"",""),e.screenshot)n.push(`![${v(e.title)}](${i}${e.screenshot.path})`,"");else n.push("No screenshot was captured for this scene.","");return`${n.join(`
4
+ `).trimEnd()}
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(`
6
+ `)),outDir:r,mediaDir:l,inventory:c.stories.map((s)=>({id:s.id,title:s.title,platform:s.driver.platform,scenes:s.scenes.map(({id:o,title:d})=>({id:o,title:d}))})),results:c.stories.map((s)=>({id:s.id,title:s.title,description:s.description,platform:s.driver.platform,status:"not-run",scenes:s.scenes.map((o)=>({id:o.id,title:o.title,description:o.description,status:"not-run"}))}))},G=new Set(t.only??c.stories.map((s)=>s.id));if(!G.size||[...G].some((s)=>!c.stories.some((o)=>o.id===s)))throw Error("Unknown or empty story selection");if(t.list)return p;if(await g(r),t.check){if(await g(a(r,".stacks-stories")),await S(a(r,".stacks-stories"),"utf8")!==C)throw Error("Unowned story output");let s=JSON.parse(await S(a(r,"manifest.json"),"utf8"));if(s.version!==1||s.configHash!==p.configHash||JSON.stringify(s.inventory)!==JSON.stringify(p.inventory))throw Error("Story recordings are stale");if(!s.index||s.results.length!==p.results.length||s.results.some((o,d)=>o.id!==p.results[d].id||o.status!=="passed"||!o.video||!o.page||o.scenes.length!==p.results[d].scenes.length||o.scenes.some((m,U)=>m.id!==p.results[d].scenes[U].id||m.status!=="passed"||!m.screenshot)))throw Error("Story recordings are incomplete or failed");for(let o of[s.index,...s.results.flatMap((d)=>[d.video,d.page,...d.scenes.map((m)=>m.screenshot)])]){let d=await L(r,B(r,o));if(d.sha256!==o.sha256||d.bytes!==o.bytes)throw Error(`Story artifact changed: ${o.path}`)}if(l){if(await g(l),await g(a(l,".stacks-stories")),await S(a(l,".stacks-stories"),"utf8")!==C||!s.published?.length)throw Error("Published story media is incomplete");let o=s.results.flatMap((d)=>[d.video,...d.scenes.map((m)=>m.screenshot)]);if(JSON.stringify(s.published)!==JSON.stringify(o))throw Error("Published story media inventory changed");for(let d of o)if((await L(l,B(l,d))).sha256!==d.sha256)throw Error(`Published story media changed: ${d.path}`)}return{...s,outDir:r}}if(await J(r)){if(await g(a(r,".stacks-stories")),!await J(a(r,".stacks-stories"))||await S(a(r,".stacks-stories"),"utf8")!==C)throw Error(`Refusing to overwrite an unowned story directory: ${r}`)}else await T(r,{recursive:!0}),await R(a(r,".stacks-stories"),C,{flag:"wx"});let V=await ct(a(r,".recording.lock"),"wx",384).catch(()=>{throw Error("Story output is locked by another recording; inspect .recording.lock before removing a stale lock")});await V.writeFile(`${process.pid}
7
+ `);let q=`${new Date().toISOString().replaceAll(/[:.]/g,"-")}-${ot()}`;p.runId=q;let D=a(r,"runs",q),h=new AbortController,k=()=>h.abort(t.signal?.reason??Error("Story recording interrupted"));if(process.once("SIGINT",k),process.once("SIGTERM",k),t.signal?.addEventListener("abort",k,{once:!0}),t.signal?.aborted)k();try{await g(D,r),await T(D,{recursive:!0});for(let[f,w]of c.stories.entries()){if(!G.has(w.id))continue;let y=p.results[f],N=a(D,w.id);await T(N);let A,H=performance.now();try{h.signal.throwIfAborted(),A=await w.driver.open({videoPath:a(N,"video.mp4"),fps:c.fps??12,signal:h.signal}),H=performance.now(),y.status="passed";for(let[x,F]of w.scenes.entries()){h.signal.throwIfAborted();let O=y.scenes[x];O.startedMs=Math.round(performance.now()-H),O.status="failed";let Q=!1,rt=setTimeout(()=>h.abort(Error("Story scene timed out")),F.timeoutMs??c.timeoutMs??120000);try{await new Promise((E,M)=>{let j=()=>M(h.signal.reason);if(h.signal.addEventListener("abort",j,{once:!0}),Promise.resolve().then(()=>F.run(A.context,h.signal)).then(E,M).finally(()=>h.signal.removeEventListener("abort",j)),h.signal.aborted)j()}),await new Promise((E,M)=>{let j=()=>{clearTimeout(st),M(h.signal.reason)},st=setTimeout(()=>{h.signal.removeEventListener("abort",j),E()},F.holdMs??c.holdMs??700);if(h.signal.addEventListener("abort",j,{once:!0}),h.signal.aborted)j()}),Q=!0}finally{clearTimeout(rt);let E=await A.screenshot();if(E.length<8||Buffer.from(E.subarray(0,8)).toString("hex")!=="89504e470d0a1a0a")throw Error("Driver did not produce a PNG screenshot");let M=a(N,`${F.id}.png`);await R(M,E,{flag:"wx"}),O.screenshot=await L(r,M),O.status=Q?"passed":"failed",O.endedMs=Math.round(performance.now()-H)}}}catch(x){y.status="failed",t.onError?.(x,w.id)}finally{if(A){try{await A.finish(),y.video=await L(r,a(N,"video.mp4"))}catch(x){y.status="failed",t.onError?.(x,w.id)}try{await A.close()}catch(x){y.status="failed",t.onError?.(x,w.id)}}}let K=a(N,"index.md");if(await R(K,wt(y,"../../../"),{flag:"wx"}),y.page=await L(r,K),t.onProgress?.(y),h.signal.aborted)break}if(l){if(await g(l),await J(l)){if(await g(a(l,".stacks-stories")),await S(a(l,".stacks-stories"),"utf8")!==C)throw Error("Refusing to overwrite unowned published story media")}else await T(l,{recursive:!0}),await R(a(l,".stacks-stories"),C,{flag:"wx"});p.published=p.results.flatMap((f)=>[f.video,...f.scenes.map((w)=>w.screenshot)].filter((w)=>Boolean(w)));for(let f of p.published){let w=B(l,f);await g(w,l),await T(W(w),{recursive:!0}),await at(B(r,f),w,1)}}let s=a(r,"index.md"),o=a(r,"manifest.json");for(let f of[s,o])if(await J(f)){if(await g(f),f===s&&!(await S(f,"utf8")).startsWith(z))throw Error("Refusing to replace a hand-written story index");if(f===o&&JSON.parse(await S(f,"utf8")).version!==1)throw Error("Refusing to replace an unknown story manifest")}let d=[z,`# ${v(c.title??"User stories")}`,"","Videos and screenshots from automated end-to-end journeys.","",...p.results.flatMap((f)=>[`- ${f.page?`[${v(f.title)}](${f.page.path})`:v(f.title)} (${f.platform}): **${f.status}**`,""])].join(`
8
+ `),m=a(D,"index.md.tmp");await R(m,d,{flag:"wx"}),p.index={path:"index.md",sha256:I(d),bytes:Buffer.byteLength(d)};let U=a(D,"manifest.json.tmp");return await R(U,`${JSON.stringify(p,null,2)}
9
+ `,{flag:"wx"}),await Y(m,s),await Y(U,o),p}finally{process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),t.signal?.removeEventListener("abort",k),await V.close(),await ft(a(r,".recording.lock"))}}export{Et as defineStory,xt as defineStoryConfig,$t as recordStories};
@@ -0,0 +1,47 @@
1
+ import { click } from '@stacksjs/testing/browser';
2
+ import type { Cdp, LaunchOptions } from '@stacksjs/testing/browser';
3
+ import type { StoryDriver } from './stories';
4
+ /** Chrome actions reuse the guarded testing click and dispatch real mouse movement. */
5
+ export declare function browserStory(options: BrowserStoryOptions): StoryDriver<BrowserStoryContext>;
6
+ /** Record the OS display while reusing a native test driver's actual input actions. */
7
+ export declare function nativeStory(options: NativeStoryOptions): StoryDriver<NativeStoryContext>;
8
+ export declare interface BrowserStoryContext {
9
+ cdp: Cdp
10
+ goto: (path: string, options?: { expectedStatus?: number }) => Promise<void>
11
+ click: (target: string | { selector: string, text?: string }) => Promise<void>
12
+ type: (selector: string, value: string) => Promise<void>
13
+ expectText: (selector: string, text: string) => Promise<void>
14
+ }
15
+ export declare interface BrowserStoryOptions {
16
+ baseUrl: string
17
+ viewport?: LaunchOptions['viewport']
18
+ chromePath?: string
19
+ headless?: boolean
20
+ ffmpeg?: string
21
+ masks?: string[]
22
+ cursor?: { color?: string, size?: number, moveMs?: number, clickMs?: number }
23
+ prepare?: (context: BrowserStoryContext) => Promise<void>
24
+ failOnBrowserErrors?: boolean
25
+ }
26
+ export declare interface NativeStoryInput {
27
+ tap: (x: number, y: number) => Promise<void>
28
+ swipe?: (from: { x: number, y: number }, to: { x: number, y: number }, durationMs: number) => Promise<void>
29
+ type?: (text: string) => Promise<void>
30
+ }
31
+ export declare interface NativeStoryContext {
32
+ tap: NativeStoryInput['tap']
33
+ swipe: NonNullable<NativeStoryInput['swipe']>
34
+ type: NonNullable<NativeStoryInput['type']>
35
+ }
36
+ export declare interface NativeStoryOptions {
37
+ platform: 'ios' | 'android'
38
+ device: string
39
+ input?: NativeStoryInput
40
+ adb?: string
41
+ xcrun?: string
42
+ ffmpeg?: string
43
+ tapFeedback?: boolean
44
+ tapColor?: string
45
+ tapMs?: number
46
+ tapSize?: number
47
+ }
@@ -0,0 +1,13 @@
1
+ // @bun
2
+ import{spawnOwnedProcess as U}from"@stacksjs/cli/owned-process";import{click as j,launch as q,settle as J,waitFor as z}from"@stacksjs/testing/browser";import{randomUUID as C}from"crypto";import{readFile as H,rm as L}from"fs/promises";import{dirname as D,join as F}from"path";function M(e,n,s,l){if(!Number.isFinite(e)||e<n||e>s)throw Error(`Invalid ${l}`)}function X(e){let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||n.username||n.password)throw Error("Story baseUrl must be HTTP(S), without credentials");return n}async function f(e,n,s=30000){n?.throwIfAborted();let l=U(e),h=!1,p=()=>{l.stop().catch(()=>{})};n?.addEventListener("abort",p,{once:!0});let a=setTimeout(()=>{h=!0,p()},s);try{let[o,r]=await Promise.all([l.exited,new Response(l.stdout).bytes(),new Response(l.stderr).text()]);if(n?.throwIfAborted(),h)throw Error("Story tool timed out");if(o.code!==0)throw Error(`Story tool failed: ${e[0]}`);return r}finally{clearTimeout(a),n?.removeEventListener("abort",p),await l.stop()}}async function Y(e,n="ffmpeg"){await f([n,"-hide_banner","-loglevel","error","-nostdin","-n",...e],void 0,180000)}function Z(e){let n=X(e.baseUrl),s={color:"#2563eb",size:18,moveMs:450,clickMs:400,...e.cursor};if(!/^#[0-9a-f]{6}$/i.test(s.color))throw Error("Cursor color must be a six-digit hex color");return M(s.size,6,80,"cursor size"),M(s.moveMs,0,5000,"cursor movement"),M(s.clickMs,100,5000,"click feedback"),{platform:"browser",fingerprint:e,async open({videoPath:l,fps:h,signal:p}){let a=await q({viewport:e.viewport,chromePath:e.chromePath,headless:e.headless}),{cdp:o}=a,r,E=!1,g,w,m,y,P=new Map,O=o.on("Network.responseReceived",(v)=>{if(v.type==="Document")P.set(v.frameId,{status:v.response.status})}),S=()=>{E=!0,r?.stop().catch(()=>{}),a.close().catch(()=>{})};p.addEventListener("abort",S,{once:!0});try{p.throwIfAborted();let v=`stacks-story-${C()}`,u=['input[type="password"]',...e.masks??[]],x=`(() => {
3
+ const start = () => {
4
+ const style = document.createElement('style'); style.textContent = ${JSON.stringify(`${u.join(",")} { opacity: 0 !important; }`)}; document.documentElement.append(style);
5
+ const host = document.createElement('div'); host.id = ${JSON.stringify(v)};
6
+ host.style.cssText='all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important;';
7
+ const shadow=host.attachShadow({mode:'closed'}); const dot=document.createElement('div');
8
+ dot.style.cssText=${JSON.stringify(`position:absolute;width:${s.size}px;height:${s.size}px;border:2px solid white;border-radius:50%;background:${s.color};box-shadow:0 1px 4px #0008;left:24px;top:24px;transform:translate(-50%,-50%);pointer-events:none;`)};
9
+ shadow.append(dot); document.documentElement.append(host);
10
+ addEventListener('mousemove', event => {dot.style.left=event.clientX+'px';dot.style.top=event.clientY+'px'},true);
11
+ 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 ${s.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:${s.clickMs}}).finished.then(()=>pulse.remove())},true);
12
+ }; if(document.documentElement) start(); else new MutationObserver((_,observer)=>{if(document.documentElement){observer.disconnect();start()}}).observe(document,{childList:true});
13
+ })()`;await o.send("Page.addScriptToEvaluateOnNewDocument",{source:x});let T={x:24,y:24},i={cdp:o,async goto(t,d={}){let k=new URL(t,n);if(k.origin!==n.origin||k.username||k.password)throw Error("Story navigation must stay on baseUrl origin");let I=d.expectedStatus??200;if(!Number.isInteger(I)||I<100||I>599)throw Error("Invalid expected document status");let N=await o.send("Page.navigate",{url:k.href});if(N.errorText||!await J(o,{quietMs:150,timeoutMs:15000}))throw Error("Story page did not settle");if(P.get(N.frameId)?.status!==I)throw Error("Unexpected story document HTTP status");if(new URL(await o.evaluate("location.href")).origin!==n.origin)throw Error("Story page redirected outside baseUrl origin")},async click(t){p.throwIfAborted();let d=typeof t==="string"?t:t.selector,k=typeof t==="string"?void 0:t.text,I=await z(async()=>o.evaluate(`(() => {const all=[...document.querySelectorAll(${JSON.stringify(d)})].filter(el=>${k===void 0?"true":`el.textContent.trim()===${JSON.stringify(k)}`});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),N=T,_=performance.now();do{p.throwIfAborted();let R=s.moveMs?Math.min(1,(performance.now()-_)/s.moveMs):1;if(T={x:N.x+(I.x-N.x)*R,y:N.y+(I.y-N.y)*R},await o.send("Input.dispatchMouseEvent",{type:"mouseMoved",...T}),R===1)break;await Bun.sleep(16)}while(!0);await j(o,t),await Bun.sleep(s.clickMs)},async type(t,d){await i.click(t),await o.send("Input.insertText",{text:d})},async expectText(t,d){await z(()=>o.evaluate(`document.querySelector(${JSON.stringify(t)})?.textContent.includes(${JSON.stringify(d)}) ?? false`),12000)}};if(await i.goto(n.href),e.prepare)await e.prepare(i);m=Buffer.from((await o.send("Page.captureScreenshot",{format:"jpeg",quality:85})).data,"base64"),y=o.on("Page.screencastFrame",(t)=>{m=Buffer.from(t.data,"base64"),o.send("Page.screencastFrameAck",{sessionId:t.sessionId}).catch((d)=>{w=d})}),r=U([e.ffmpeg??"ffmpeg","-hide_banner","-loglevel","error","-nostdin","-n","-f","image2pipe","-framerate",String(h),"-vcodec","mjpeg","-i","pipe:0","-an","-vf","pad=ceil(iw/2)*2:ceil(ih/2)*2","-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",l],{stdin:"pipe"}),await r.started;let c=new Response(r.stderr).text();new Response(r.stdout).arrayBuffer(),await o.send("Page.startScreencast",{format:"jpeg",quality:85,everyNthFrame:1});let b=performance.now();g=(async()=>{let t=0;while(!E){if(p.throwIfAborted(),w)throw w;let d=Math.floor((performance.now()-b)/1000*h)+1;if(d-t>h*10)throw Error("Story encoder cannot keep up with the recording");while(t<d)r.stdin.write(m),await r.stdin.flush(),t++;await Bun.sleep(Math.max(1,1000/h/2))}})().catch((t)=>{w=t});let A;return{context:i,screenshot:async()=>Buffer.from((await o.send("Page.captureScreenshot",{format:"png"})).data,"base64"),finish:()=>A??=(async()=>{E=!0;let t=setTimeout(()=>{w=Error("Story video finalization timed out"),r.stop().catch(()=>{})},30000);try{await g,await o.send("Page.stopScreencast"),y?.(),await r.stdin.end();let d=await r.exited;if(await c,w||d.code!==0)throw Error("Story video capture failed",{cause:w});if(e.failOnBrowserErrors!==!1&&o.errors.length)throw Error("Browser story produced console or network errors")}finally{clearTimeout(t)}})(),async close(){E=!0,y?.(),O(),p.removeEventListener("abort",S);try{await r.stop(),await g}finally{await a.close()}}}}catch(v){E=!0,y?.(),O(),p.removeEventListener("abort",S);try{await r?.stop(),await g}finally{await a.close()}throw v}}}}function ee(e){let n=e.platform==="ios";if(n?!/^[\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(n&&!e.input)throw Error("iOS stories require an XCTest/Appium input adapter");let s=e.tapColor??"#2563eb";if(!/^#[0-9a-f]{6}$/i.test(s))throw Error("Tap color must be a six-digit hex color");M(e.tapMs??450,100,5000,"tap feedback");let l=e.tapSize??72;return M(l,12,240,"tap indicator size"),{platform:e.platform,fingerprint:e,async open({videoPath:h,fps:p,signal:a}){let o=F(D(h),"native-raw.mp4"),r=e.adb??"adb",E=e.xcrun??"xcrun",g=`/sdcard/stacks-story-${C()}.mp4`,w,m,y,P=0,O=[],S=e.input??{async tap(u,x){await f([r,"-s",e.device,"shell","input","tap",String(Math.round(u)),String(Math.round(x))],a)},async swipe(u,x,T){await f([r,"-s",e.device,"shell","input","swipe",String(Math.round(u.x)),String(Math.round(u.y)),String(Math.round(x.x)),String(Math.round(x.y)),String(Math.round(T))],a)},async type(u){if(!/^[a-z0-9@._+ -]*$/i.test(u))throw Error("Use a native input adapter for Unicode or shell-sensitive text");await f([r,"-s",e.device,"shell","input","text",u.replaceAll(" ","%s")],a)}},v=(u,x)=>{M(u,0,16384,"tap x"),M(x,0,16384,"tap y")};try{if(a.throwIfAborted(),n){let{recordIosSimulatorVideo:i}=await import("craft-native/testing");w=(await i({device:e.device,path:o,xcrun:E})).stop}else{if(new TextDecoder().decode(await f([r,"-s",e.device,"get-state"],a)).trim()!=="device")throw Error("Android emulator is unavailable");m=U([r,"-s",e.device,"shell",`screenrecord --time-limit 180 ${g} & recorder=$!; trap 'kill -2 "$recorder" 2>/dev/null; wait "$recorder"; exit' HUP INT TERM; echo STACKS_RECORDER:$recorder; wait "$recorder"; result=$?; trap - HUP INT TERM; exit "$result"`]),await m.started;let c=m.stdout.getReader(),b="",A=setTimeout(()=>{m.stop()},15000);try{while(!y){let t=await c.read();if(t.done)throw Error("Android recorder stopped before startup");b+=new TextDecoder().decode(t.value);let d=/STACKS_RECORDER:(\d+)/.exec(b);if(d)y=Number(d[1]);if(b.length>4096)throw Error("Invalid Android recorder startup")}}finally{clearTimeout(A)}(async()=>{while(!(await c.read()).done);})().catch(()=>{}),new Response(m.stderr).text();let B=async()=>{await f([r,"-s",e.device,"shell",`case "$(cat /proc/${y}/cmdline 2>/dev/null)" in *${g}*) kill -2 ${y};; *) exit 3;; esac`])};await f([r,"-s",e.device,"shell","kill","-0",String(y)],a),w=async()=>{await B();let t=setTimeout(()=>{m.stop()},15000);try{await m.exited}finally{clearTimeout(t)}await f([r,"-s",e.device,"pull",g,o])},await f([r,"-s",e.device,"shell",`attempt=0; while [ "$attempt" -lt 300 ]; do size=$(stat -c %s ${g} 2>/dev/null); if [ "\${size:-0}" -gt 64 ]; then exit 0; fi; kill -0 ${y} 2>/dev/null || exit 1; attempt=$((attempt+1)); sleep 0.05; done; exit 2`],a,20000)}P=performance.now();let u={async tap(i,c){a.throwIfAborted(),v(i,c);let b={x:i,y:c,start:(performance.now()-P)/1000,end:0};O.push(b);try{await S.tap(i,c)}finally{b.end=(performance.now()-P)/1000+(e.tapMs??450)/1000}},async swipe(i,c,b){if(a.throwIfAborted(),v(i.x,i.y),v(c.x,c.y),M(b,1,1e4,"swipe duration"),!S.swipe)throw Error("Native driver does not support swipes");await S.swipe(i,c,b)},async type(i){if(a.throwIfAborted(),!S.type)throw Error("Native driver does not support typing");await S.type(i)}},x;return{context:u,async screenshot(){if(a.throwIfAborted(),!n)return f([r,"-s",e.device,"exec-out","screencap","-p"],a);let i=F(D(h),`screenshot-${C()}.png`);try{return await f([E,"simctl","io",e.device,"screenshot",i],a),await H(i)}finally{await L(i,{force:!0})}},finish:()=>x??=(async()=>{await w();let i=e.tapFeedback===!1?[]:O.map((c)=>`drawbox=x=${Math.round(c.x-l/2)}:y=${Math.round(c.y-l/2)}:w=${l}:h=${l}:color=0x${s.slice(1)}@0.9:t=4:enable='between(t,${c.start.toFixed(3)},${c.end.toFixed(3)})'`);await Y(["-i",o,"-an","-vf",[...i,"pad=ceil(iw/2)*2:ceil(ih/2)*2"].join(","),"-r",String(p),"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p","-movflags","+faststart",h],e.ffmpeg),await L(o)})(),async close(){try{if(!x)await w?.()}finally{if(await m?.stop(),!n)await f([r,"-s",e.device,"shell","rm","-f",g])}}}}catch(u){try{await w?.()}finally{await m?.stop()}throw u}}}}export{Z as browserStory,ee 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.634",
5
+ "version": "0.75.636",
6
6
  "description": "The Stacks way to document.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,15 +58,17 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@stacksjs/bunpress": "^0.2.25",
61
- "@stacksjs/cli": "0.75.634",
62
- "@stacksjs/config": "0.75.634",
63
- "@stacksjs/path": "0.75.634",
64
- "@stacksjs/orm": "0.75.634",
65
- "@stacksjs/stx": "^0.2.908"
61
+ "@stacksjs/cli": "0.75.636",
62
+ "@stacksjs/config": "0.75.636",
63
+ "@stacksjs/path": "0.75.636",
64
+ "@stacksjs/orm": "0.75.636",
65
+ "@stacksjs/stx": "^0.2.908",
66
+ "@stacksjs/testing": "0.75.636",
67
+ "craft-native": ">=0.0.499"
66
68
  },
67
69
  "devDependencies": {
68
- "@stacksjs/alias": "0.75.634",
69
- "@stacksjs/server": "0.75.634",
70
+ "@stacksjs/alias": "0.75.636",
71
+ "@stacksjs/server": "0.75.636",
70
72
  "better-dx": "^0.2.39"
71
73
  }
72
74
  }