cueframe 0.3.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cueframe.js CHANGED
@@ -1,36 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import{A as E,B as w,C as v,D as Fe,a as N,b as Z,c as C,d as p,e as j,f as g,g as T,h as I,i as Ie,j as Re,k,l as fe,m as Te,n as Oe,o as F,p as L,q as Pe,r as Q,s as q,t as Y,u as Ae,v as ge,w as m,x as y,y as A,z as l}from"./chunk-4FMFWW74.js";import"./chunk-3QSA3EBY.js";import{Command as _r}from"commander";import{existsSync as Ue,mkdirSync as Gt,readFileSync as Kt,writeFileSync as Ht,readdirSync as Vt,statSync as Zt}from"fs";import{homedir as Qt}from"os";import{dirname as Me,join as X}from"path";import{fileURLToPath as Yt}from"url";import{agents as Xt,detectGlobalAgents as De,upsertServer as eo}from"add-mcp";var ee="cueframe";function to(){let t=Me(Yt(import.meta.url));for(let e=0;e<8;e++){let o=X(t,"skills");if(Ue(o)&&Zt(o).isDirectory())return o;let r=Me(t);if(r===t)break;t=r}return null}function oo(t,e){let o=`> Installed ${e} by \`cueframe install\`. Skills and tools change often \u2014
2
+ import{A as J,B as R,C as Ot,a as Z,b as St,c as W,d as Ct,e as jt,f as Tt,g as $t,h as Ve,i as Be,j as oe,k as Se,l as Rt,m as Me,n as p,o as _,p as U,q as m,r as Ce,s as qe,t as T,u as O,v as P,w as h,x as $,y as x,z as A}from"./chunk-QKQNZIRI.js";import{a as qr}from"./chunk-3QSA3EBY.js";import{Command as Ss}from"commander";import{existsSync as ut,mkdirSync as Jr,readFileSync as Gr,writeFileSync as Hr,readdirSync as Kr,statSync as Yr}from"fs";import{homedir as Xr}from"os";import{dirname as At,join as Je}from"path";import{fileURLToPath as Qr}from"url";import{agents as en,detectGlobalAgents as It,upsertServer as tn}from"add-mcp";var Ge="cueframe";function rn(){let t=At(Qr(import.meta.url));for(let e=0;e<8;e++){let r=Je(t,"skills");if(ut(r)&&Yr(r).isDirectory())return r;let n=At(t);if(n===t)break;t=n}return null}function nn(t,e){let r=`> Installed ${e} by \`npx -y cueframe install\`. Skills and tools change often \u2014
3
3
  > if that date is more than a week old, run \`npx -y cueframe install\` to refresh.
4
- `,r=t.match(/^---\n[\s\S]*?\n---\n/);return r?`${r[0]}
5
- ${o}${t.slice(r[0].length)}`:`${o}
6
- ${t}`}function ro(t){let e=to();e||(g(t,"install",new Error("Bundled skills/ directory not found"),m.UserError),l(m.UserError));let o=new Date().toISOString().slice(0,10),r=[];for(let n of Vt(e)){let i=X(e,n,"SKILL.md");if(!Ue(i))continue;let s=X(Qt(),".claude","skills",n);Gt(s,{recursive:!0});let a=X(s,"SKILL.md");Ht(a,oo(Kt(i,"utf8"),o),"utf8"),r.push(a)}return r}function no(t){return(Xt[t]?.supportedTransports??[]).includes("http")}async function io(t){return(await De()).map(o=>{if(!no(o))return{agent:o,wired:!1,error:"speaks stdio only \u2014 CueFrame\u2019s MCP server is remote HTTP"};try{let r=eo(o,ee,{type:"http",url:t});return{agent:o,wired:r.success,path:r.path,error:r.error}}catch(r){return{agent:o,wired:!1,error:r instanceof Error?r.message:String(r)}}})}async function Ne(t){let e=`${N(t.target)}/v1/mcp`;if(t.dryRun){let n=await De();j(t,{ok:!0,dryRun:!0,mcpUrl:e,wouldWire:n,serverName:ee},()=>{console.log(`Would wire MCP server "${ee}" \u2192 ${e} into:`),n.length===0&&console.log(" (no agents detected on this machine)");for(let i of n)console.log(` \u2192 ${i}`);console.log("Would install the CueFrame agent skills into ~/.claude/skills"),console.log("Dry run \u2014 nothing was written.")});return}let o=ro(t),r=await io(e);o.length===0&&r.length===0&&(g(t,"install",new Error("No agents detected and no skills found \u2014 nothing to install"),m.UserError),l(m.UserError)),j(t,{ok:!0,mcpUrl:e,agents:r,skills:o},()=>{if(console.log(`\u2713 CueFrame MCP server (${e})`),r.length===0)console.log(" No agents detected on this machine. Add it manually:"),console.log(` claude mcp add --transport http ${ee} ${e}`),console.log(` \u2026or add the MCP server ${e} as a custom connector.`);else for(let n of r)console.log(n.wired?` \u2192 wired ${n.agent}`:` \u2717 ${n.agent}: ${n.error??"failed"}`);console.log(`\u2713 Installed ${o.length} CueFrame skill(s) into ~/.claude/skills`),console.log(""),console.log("Next: ask your agent to make a video \u2014 it opens a browser to authorize on"),console.log("first call. No API key needed. (Prefer the CLI? Run `cueframe login`.)"),console.log("Restart your agent session to load the MCP server and skills.")})}import{existsSync as he,mkdirSync as so,readFileSync as We,writeFileSync as ye}from"fs";import{join as we}from"path";var Le="cueframe.json",ao="cueframe/components",te=".cueframe/";function co(t,e){let o=we(t,".gitignore");if(he(o)){let r=We(o,"utf8"),n=r.split(`
7
- `).map(i=>i.trim());if(n.includes(te)||n.includes(".cueframe"))return!1;if(!e){let i=r.endsWith(`
8
- `)||r.length===0?"":`
9
- `;ye(o,`${r}${i}
4
+ `,n=t.match(/^---\n[\s\S]*?\n---\n/);return n?`${n[0]}
5
+ ${r}${t.slice(n[0].length)}`:`${r}
6
+ ${t}`}function on(t){let e=rn();e||(x(t,"install",new Error("Bundled skills/ directory not found"),p.UserError),m(p.UserError));let r=new Date().toISOString().slice(0,10),n=[],o=[];for(let s of Kr(e)){let i=Je(e,s,"SKILL.md");if(!ut(i))continue;let a=Je(Xr(),".claude","skills",s),u=Je(a,"SKILL.md");if(ut(u)&&!t.force){o.push(u);continue}Jr(a,{recursive:!0}),Hr(u,nn(Gr(i,"utf8"),r),"utf8"),n.push(u)}return{installed:n,skipped:o}}function sn(t){return(en[t]?.supportedTransports??[]).includes("http")}async function an(t){return(await It()).map(r=>{if(!sn(r))return{agent:r,wired:!1,error:"speaks stdio only \u2014 CueFrame\u2019s MCP server is remote HTTP"};try{let n=tn(r,Ge,{type:"http",url:t});return{agent:r,wired:n.success,path:n.path,error:n.error}}catch(n){return{agent:r,wired:!1,error:n instanceof Error?n.message:String(n)}}})}async function Pt(t){let e=`${Ce(t.target)}/v1/mcp`;if(t.dryRun){let s=await It();$(t,{ok:!0,dryRun:!0,mcpUrl:e,wouldWire:s,serverName:Ge},()=>{console.log(`Would wire MCP server "${Ge}" \u2192 ${e} into:`),s.length===0&&console.log(" (no agents detected on this machine)");for(let i of s)console.log(` \u2192 ${i}`);console.log("Would install the CueFrame agent skills into ~/.claude/skills"),console.log("Dry run \u2014 nothing was written.")});return}let r=await an(e),{installed:n,skipped:o}=on(t);n.length===0&&o.length===0&&r.length===0&&(x(t,"install",new Error("No agents detected and no skills found \u2014 nothing to install"),p.UserError),m(p.UserError)),$(t,{ok:!0,mcpUrl:e,agents:r,skills:n,skipped:o},()=>{if(console.log(`\u2713 CueFrame MCP server (${e})`),r.length===0)console.log(" No agents detected on this machine. Add it manually:"),console.log(` claude mcp add --transport http ${Ge} ${e}`),console.log(` \u2026or add the MCP server ${e} as a custom connector.`);else for(let s of r)console.log(s.wired?` \u2192 wired ${s.agent}`:` \u2717 ${s.agent}: ${s.error??"failed"}`);console.log(`\u2713 Installed ${n.length} CueFrame skill(s) into ~/.claude/skills`),o.length>0&&console.log(` ${o.length} skipped (already present \u2014 rerun with --force)`),r.some(s=>s.wired&&s.agent==="claude-code")||(console.log(" Note: only Claude Code reads that directory. Your other agents get the"),console.log(" same verbs as MCP tools from the server above \u2014 nothing else to install.")),console.log(""),console.log("Next: ask your agent to make a video \u2014 it opens a browser to authorize on"),console.log("first call. No API key needed."),console.log("Restart your agent session to load the MCP server and skills."),console.log(""),console.log("This installed no `cueframe` binary \u2014 npx leaves nothing on your PATH."),console.log("Prefer the terminal? Every command runs as `npx -y cueframe \u2026`:"),console.log(" npx -y cueframe login")})}import{existsSync as lt,mkdirSync as cn,readFileSync as Mt,writeFileSync as mt}from"fs";import{join as ft}from"path";var Nt="cueframe.json",dn="cueframe/components",He=".cueframe/";function un(t,e){let r=ft(t,".gitignore");if(lt(r)){let n=Mt(r,"utf8"),o=n.split(`
7
+ `).map(s=>s.trim());if(o.includes(He)||o.includes(".cueframe"))return!1;if(!e){let s=n.endsWith(`
8
+ `)||n.length===0?"":`
9
+ `;mt(r,`${n}${s}
10
10
  # CueFrame derived render cache (regenerated; never authored)
11
- ${te}
12
- `)}return!0}return e||ye(o,`# CueFrame derived render cache (regenerated; never authored)
13
- ${te}
14
- `),!0}function ze(t){let e=process.cwd(),o=t.dryRun??!1;p(t,"init_prepare",{cwd:e,dryRun:o});let r=we(e,Le),n=he(r),i=ao;if(n)try{let u=JSON.parse(We(r,"utf8"));typeof u.componentsDir=="string"&&u.componentsDir.length>0&&(i=u.componentsDir)}catch{}else o||ye(r,`${JSON.stringify({componentsDir:i},null,2)}
15
- `);let s=we(e,i),a=he(s);!a&&!o&&so(s,{recursive:!0});let f=co(e,o);j(t,{ok:!0,dryRun:o,root:e,manifest:{path:r,created:!n},componentsDir:i,componentsDirCreated:!a,gitignoreUpdated:f},()=>{console.log(`\u2713 ${o?"Would initialize":"Initialized"} CueFrame workspace at ${e}`),console.log(` ${n?"kept":"created"} ${Le} (componentsDir: ${i})`),console.log(` ${a?"exists":"created"} ${i}/`),f&&console.log(` gitignored ${te}`),console.log("Next: cueframe eject <primitive> or cueframe new component <name>")})}import{existsSync as je,mkdirSync as vo,readFileSync as re,readdirSync as Ge,statSync as jo,writeFileSync as Be}from"fs";import{dirname as Ee,join as B}from"path";import{fileURLToPath as Eo}from"url";import S from"typescript";import O from"typescript";var mo="@cueframe/primitives";function lo(t){if(!t.startsWith("."))return t;let e=t.split("/"),o=e.indexOf("lib");return o===-1||!e.slice(0,o).every(r=>r==="."||r==="..")?t:`${mo}/${e.slice(o).join("/")}`}function be(t,e){let o=O.createSourceFile(e,t,O.ScriptTarget.Latest,!1,e.endsWith(".tsx")?O.ScriptKind.TSX:O.ScriptKind.TS),r=[],n=s=>{let a;if(O.isImportDeclaration(s)||O.isExportDeclaration(s)?a=s.moduleSpecifier:O.isCallExpression(s)&&s.expression.kind===O.SyntaxKind.ImportKeyword&&(a=s.arguments[0]),a&&O.isStringLiteral(a)){let f=lo(a.text);f!==a.text&&r.push({start:a.getStart(o)+1,end:a.getEnd()-1,text:f})}O.forEachChild(s,n)};if(n(o),r.length===0)return t;r.sort((s,a)=>a.start-s.start);let i=t;for(let s of r)i=i.slice(0,s.start)+s.text+i.slice(s.end);return i}import{existsSync as oe,readFileSync as uo,readdirSync as po,statSync as fo}from"fs";import{dirname as go,join as W,parse as ho}from"path";var yo="cueframe/components";var wo="cueframe.json",bo=ge.object({componentsDir:ge.string().min(1).default(yo)}).passthrough();function U(t){let e=t,o=ho(e).root;for(;;){let r=W(e,wo);if(oe(r)){let n=uo(r,"utf8"),i=bo.parse(JSON.parse(n));return{root:e,manifest:i}}if(e===o)return null;e=go(e)}}function Je(t){return W(t.root,t.manifest.componentsDir)}function z(t,e){return W(Je(t),e)}function qe(t){let e=Je(t);return oe(e)?po(e).filter(o=>{let r=W(e,o);return fo(r).isDirectory()?oe(W(r,"index.tsx"))&&oe(W(r,"config.ts")):!1}).sort():[]}var ve="@cueframe/primitives",xo="cueframe.json";function So(){let t=Ee(Eo(import.meta.url));for(;;){let e=B(t,"packages","execution","primitives","src");if(je(e))return e;let o=Ee(t);if(o===t)return null;t=o}}function Ke(t){let e=[];for(let o of Ge(t)){if(o==="node_modules"||o==="dist"||o==="__tests__")continue;let r=B(t,o);jo(r).isDirectory()?e.push(...Ke(r)):o==="config.ts"&&e.push(r)}return e}function Co(t){let e=t;for(;S.isAsExpression(e)||S.isParenthesizedExpression(e)||typeof S.isSatisfiesExpression=="function"&&S.isSatisfiesExpression(e);)e=e.expression;return e}function $o(t,e){let o=S.createSourceFile(e,t,S.ScriptTarget.Latest,!0,S.ScriptKind.TS),r;for(let i of o.statements)if(S.isVariableStatement(i)){for(let s of i.declarationList.declarations)if(S.isIdentifier(s.name)&&s.name.text==="config"&&s.initializer){let a=Co(s.initializer);S.isObjectLiteralExpression(a)&&(r=a)}if(r)break}let n={sf:o};if(!r)return n;for(let i of r.properties){if(!S.isPropertyAssignment(i)||!(S.isIdentifier(i.name)||S.isStringLiteral(i.name)))continue;let s=i.name.text;s==="id"&&S.isStringLiteralLike(i.initializer)?n.id=i.initializer.text:s==="version"&&S.isStringLiteralLike(i.initializer)?n.version=i.initializer.text:s==="component"&&S.isIdentifier(i.initializer)&&(n.componentName=i.initializer.text)}return n}function He(t,e){let o=t.importClause;if(!o||o.isTypeOnly)return!1;if(o.name&&o.name.text===e)return!0;let r=o.namedBindings;return r&&S.isNamedImports(r)?r.elements.some(n=>!n.isTypeOnly&&n.name.text===e):!1}function ko(t,e){for(let o of t.statements)if(S.isImportDeclaration(o)&&S.isStringLiteral(o.moduleSpecifier)&&He(o,e))return o.moduleSpecifier.text}function _o(t,e,o){let r=S.createSourceFile(e,t,S.ScriptTarget.Latest,!1,S.ScriptKind.TS);for(let n of r.statements){if(!S.isImportDeclaration(n)||!S.isStringLiteral(n.moduleSpecifier)||!He(n,o))continue;let i=n.moduleSpecifier.getStart(r)+1,s=n.moduleSpecifier.getEnd()-1;return t.slice(0,i)+"./index"+t.slice(s)}return t}function D(t,e){g(t,"eject",new Error(e),m.UserError),l(m.UserError)}function Ve(t,e){E(t,"primitive",e);let o=t,r=e.dryRun??!1,n=e.force??!1;p(e,"eject_prepare",{primitive:o,dryRun:r,force:n});let i=U(process.cwd());i||D(e,"No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first to scaffold one.");let s=So();s||D(e,"Built-in primitive source not found \u2014 `cueframe eject` reads in-tree source and must run inside the CueFrame monorepo checkout.");let a,f;for(let P of Ke(s)){let R=$o(re(P,"utf8"),P);if(R.id===o){a=P,f=R;break}}(!a||!f)&&D(e,`Unknown primitive id "${o}". No built-in primitive declares config.id === "${o}".`),f.componentName||D(e,`Primitive "${o}" config has no \`component:\` identifier to eject.`);let u=f.componentName,c=f.version??"0.0.0",d=ko(f.sf,u);d||D(e,`Could not find the import that provides component "${u}" in ${a}.`);let h=Ee(a),x=d.replace(/^\.\//,""),b;for(let P of[".tsx",".ts"]){let R=B(h,x+P);if(je(R)){b=R;break}}b||D(e,`Component source for "${o}" not found on disk (resolved "${d}" beside ${a}).`);let _=re(b,"utf8"),J=be(_,"index.tsx"),H=`/** Owned eject of '${o}'. Adapts the ({durationInFrames, params}) mount contract to the primitive's props. */
16
- export default function ${u}Owned({ params }: { durationInFrames: number; params: Record<string, unknown> }) {
17
- return <${u} {...(params as Record<string, never>)} />;
18
- }
19
- `,ue=`${J.replace(/\s*$/,"")}
20
-
21
- ${H}`,V=re(a,"utf8"),Wt=be(V,"_config.ts"),zt=_o(Wt,"_config.ts",u),Jt=`import component from './index';
22
- import { config as base } from './_config';
23
-
24
- export const config = { ...base, component };
25
- export default config;
26
- `,M=z(i,o),ke=je(M);ke&&Ge(M).length>0&&!n&&D(e,`Component dir ${M} already exists and is non-empty. Pass --force to overwrite (this replaces local customizations).`);let pe={"index.tsx":ue,"_config.ts":zt,"config.ts":Jt};if(!r){vo(M,{recursive:!0});for(let[qt,Bt]of Object.entries(pe))Be(B(M,qt),Bt);let P=B(i.root,xo),R=JSON.parse(re(P,"utf8")),_e=R.components??{};_e[o]={ejectedFrom:ve,primitiveVersion:c},R.components=_e,Be(P,`${JSON.stringify(R,null,2)}
27
- `)}j(e,{ok:!0,dryRun:r,primitive:o,component:u,version:c,from:ve,dir:M,files:Object.keys(pe),overwritten:ke&&n},()=>{console.log(`\u2713 ${r?"Would eject":"Ejected"} ${o} (${u}) into ${M}`);for(let R of Object.keys(pe))console.log(` ${r?"would write":"wrote"} ${R}`);r||console.log(` stamped cueframe.json components.${o} (${ve}@${c})`),console.log("Edit the source, then render it on CueFrame.")})}import{existsSync as Io,mkdirSync as Ro,readFileSync as To,readdirSync as Oo,writeFileSync as Ze}from"fs";import{join as Qe}from"path";var Po="cueframe.json";function Ao(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}function Fo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}function xe(t,e){g(t,"new_component",new Error(e),m.UserError),l(m.UserError)}function Mo(t,e){return`import React from 'react';
11
+ ${He}
12
+ `)}return!0}return e||mt(r,`# CueFrame derived render cache (regenerated; never authored)
13
+ ${He}
14
+ `),!0}function Ut(t){let e=process.cwd(),r=t.dryRun??!1;h(t,"init_prepare",{cwd:e,dryRun:r});let n=ft(e,Nt),o=lt(n),s=dn;if(o)try{let d=JSON.parse(Mt(n,"utf8"));typeof d.componentsDir=="string"&&d.componentsDir.length>0&&(s=d.componentsDir)}catch{}else r||mt(n,`${JSON.stringify({componentsDir:s},null,2)}
15
+ `);let i=ft(e,s),a=lt(i);!a&&!r&&cn(i,{recursive:!0});let u=un(e,r);$(t,{ok:!0,dryRun:r,root:e,manifest:{path:n,created:!o},componentsDir:s,componentsDirCreated:!a,gitignoreUpdated:u},()=>{console.log(`\u2713 ${r?"Would initialize":"Initialized"} CueFrame workspace at ${e}`),console.log(` ${o?"kept":"created"} ${Nt} (componentsDir: ${s})`),console.log(` ${a?"exists":"created"} ${s}/`),u&&console.log(` gitignored ${He}`),console.log("Next: cueframe eject <primitive> or cueframe new component <name>")})}import{existsSync as Ro,mkdirSync as Oo,readFileSync as Ao,readdirSync as Io,writeFileSync as Yt}from"fs";import{join as Xt}from"path";import{existsSync as tt,readFileSync as ko,readdirSync as bo,statSync as Eo}from"fs";import{dirname as So,join as Ne,parse as Co}from"path";var Le={};qr(Le,{BRAND:()=>Mn,DIRTY:()=>de,EMPTY_PATH:()=>pn,INVALID:()=>w,NEVER:()=>wo,OK:()=>F,ParseStatus:()=>M,Schema:()=>E,ZodAny:()=>ae,ZodArray:()=>re,ZodBigInt:()=>le,ZodBoolean:()=>me,ZodBranded:()=>Fe,ZodCatch:()=>be,ZodDate:()=>fe,ZodDefault:()=>ke,ZodDiscriminatedUnion:()=>Xe,ZodEffects:()=>q,ZodEnum:()=>xe,ZodError:()=>L,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>et,ZodIntersection:()=>ye,ZodIssueCode:()=>f,ZodLazy:()=>ve,ZodLiteral:()=>_e,ZodMap:()=>Ae,ZodNaN:()=>Pe,ZodNativeEnum:()=>we,ZodNever:()=>G,ZodNull:()=>ge,ZodNullable:()=>Y,ZodNumber:()=>ue,ZodObject:()=>z,ZodOptional:()=>V,ZodParsedType:()=>y,ZodPipeline:()=>De,ZodPromise:()=>ce,ZodReadonly:()=>Ee,ZodRecord:()=>Qe,ZodSchema:()=>E,ZodSet:()=>Ie,ZodString:()=>ie,ZodSymbol:()=>Re,ZodTransformer:()=>q,ZodTuple:()=>K,ZodType:()=>E,ZodUndefined:()=>pe,ZodUnion:()=>he,ZodUnknown:()=>te,ZodVoid:()=>Oe,addIssueToContext:()=>g,any:()=>Bn,array:()=>Hn,bigint:()=>Ln,boolean:()=>Gt,coerce:()=>xo,custom:()=>Bt,date:()=>zn,datetimeRegex:()=>Wt,defaultErrorMap:()=>Q,discriminatedUnion:()=>Qn,effect:()=>mo,enum:()=>co,function:()=>so,getErrorMap:()=>je,getParsedType:()=>H,instanceof:()=>Fn,intersection:()=>eo,isAborted:()=>Ke,isAsync:()=>Te,isDirty:()=>Ye,isValid:()=>se,late:()=>Un,lazy:()=>io,literal:()=>ao,makeIssue:()=>Ue,map:()=>no,nan:()=>Dn,nativeEnum:()=>uo,never:()=>Jn,null:()=>Vn,nullable:()=>po,number:()=>Jt,object:()=>Kn,objectUtil:()=>pt,oboolean:()=>_o,onumber:()=>vo,optional:()=>fo,ostring:()=>yo,pipeline:()=>ho,preprocess:()=>go,promise:()=>lo,quotelessJson:()=>ln,record:()=>ro,set:()=>oo,setErrorMap:()=>fn,strictObject:()=>Yn,string:()=>qt,symbol:()=>Zn,transformer:()=>mo,tuple:()=>to,undefined:()=>Wn,union:()=>Xn,unknown:()=>qn,util:()=>j,void:()=>Gn});var j;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(j||(j={}));var pt;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(pt||(pt={}));var y=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),H=t=>{switch(typeof t){case"undefined":return y.undefined;case"string":return y.string;case"number":return Number.isNaN(t)?y.nan:y.number;case"boolean":return y.boolean;case"function":return y.function;case"bigint":return y.bigint;case"symbol":return y.symbol;case"object":return Array.isArray(t)?y.array:t===null?y.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?y.promise:typeof Map<"u"&&t instanceof Map?y.map:typeof Set<"u"&&t instanceof Set?y.set:typeof Date<"u"&&t instanceof Date?y.date:y.object;default:return y.unknown}};var f=j.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ln=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),L=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,u=0;for(;u<i.path.length;){let d=i.path[u];u===i.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(i))):a[d]=a[d]||{_errors:[]},a=a[d],u++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};L.create=t=>new L(t);var mn=(t,e)=>{let r;switch(t.code){case f.invalid_type:t.received===y.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case f.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,j.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:r=`Unrecognized key(s) in object: ${j.joinValues(t.keys,", ")}`;break;case f.invalid_union:r="Invalid input";break;case f.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${j.joinValues(t.options)}`;break;case f.invalid_enum_value:r=`Invalid enum value. Expected ${j.joinValues(t.options)}, received '${t.received}'`;break;case f.invalid_arguments:r="Invalid function arguments";break;case f.invalid_return_type:r="Invalid function return type";break;case f.invalid_date:r="Invalid date";break;case f.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:j.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case f.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case f.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case f.custom:r="Invalid input";break;case f.invalid_intersection_types:r="Intersection results could not be merged";break;case f.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case f.not_finite:r="Number must be finite";break;default:r=e.defaultError,j.assertNever(t)}return{message:r}},Q=mn;var Ft=Q;function fn(t){Ft=t}function je(){return Ft}var Ue=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",u=n.filter(d=>!!d).slice().reverse();for(let d of u)a=d(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},pn=[];function g(t,e){let r=je(),n=Ue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Q?void 0:Q].filter(o=>!!o)});t.common.issues.push(n)}var M=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return w;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return w;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),de=t=>({status:"dirty",value:t}),F=t=>({status:"valid",value:t}),Ke=t=>t.status==="aborted",Ye=t=>t.status==="dirty",se=t=>t.status==="valid",Te=t=>typeof Promise<"u"&&t instanceof Promise;var v;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var B=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dt=(t,e)=>{if(se(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new L(t.common.issues);return this._error=r,this._error}}};function b(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:u}=t;return i.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:u??r??a.defaultError}},description:o}}var E=class{get description(){return this._def.description}_getType(e){return H(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:H(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:H(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Te(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Dt(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return se(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>se(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:H(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Te(o)?o:Promise.resolve(o));return Dt(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:f.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new q({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return V.create(this,this._def)}nullable(){return Y.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this)}promise(){return ce.create(this,this._def)}or(e){return he.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new q({...b(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ke({...b(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new Fe({typeName:k.ZodBranded,type:this,...b(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new be({...b(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},gn=/^c[^\s-]{8,}$/i,hn=/^[0-9a-z]+$/,yn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,vn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_n=/^[a-z0-9_-]{21}$/i,xn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,kn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gt,En=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Sn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Cn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,jn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Tn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$n=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Rn=new RegExp(`^${zt}$`);function Zt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function On(t){return new RegExp(`^${Zt(t)}$`)}function Wt(t){let e=`${zt}T${Zt(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function An(t,e){return!!((e==="v4"||!e)&&En.test(t)||(e==="v6"||!e)&&Cn.test(t))}function In(t,e){if(!xn.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Pn(t,e){return!!((e==="v4"||!e)&&Sn.test(t)||(e==="v6"||!e)&&jn.test(t))}var ie=class t extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==y.string){let s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:y.string,received:s.parsedType}),w}let n=new M,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:f.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:f.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:f.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&g(o,{code:f.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")kn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")gt||(gt=new RegExp(bn,"u")),gt.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")vn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")_n.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")gn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")hn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")yn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:f.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:f.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:f.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Wt(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Rn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?On(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:f.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?wn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:f.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?An(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:f.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?In(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"jwt",code:f.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Pn(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cidr",code:f.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Tn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:f.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?$n.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64url",code:f.invalid_string,message:s.message}),n.dirty()):j.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...v.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...v.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...v.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...v.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...v.errToObj(r)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ie.create=t=>new ie({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...b(t)});function Nn(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var ue=class t extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==y.number){let s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:y.number,received:s.parsedType}),w}let n,o=new M;for(let s of this._def.checks)s.kind==="int"?j.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Nn(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:f.not_finite,message:s.message}),o.dirty()):j.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,v.toString(r))}gt(e,r){return this.setLimit("min",e,!1,v.toString(r))}lte(e,r){return this.setLimit("max",e,!0,v.toString(r))}lt(e,r){return this.setLimit("max",e,!1,v.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:v.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&j.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ue.create=t=>new ue({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...b(t)});var le=class t extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==y.bigint)return this._getInvalidInput(e);let n,o=new M;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:f.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):j.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return g(r,{code:f.invalid_type,expected:y.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,v.toString(r))}gt(e,r){return this.setLimit("min",e,!1,v.toString(r))}lte(e,r){return this.setLimit("max",e,!0,v.toString(r))}lt(e,r){return this.setLimit("max",e,!1,v.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:v.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};le.create=t=>new le({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...b(t)});var me=class extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==y.boolean){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.boolean,received:n.parsedType}),w}return F(e.data)}};me.create=t=>new me({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...b(t)});var fe=class t extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==y.date){let s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_type,expected:y.date,received:s.parsedType}),w}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return g(s,{code:f.invalid_date}),w}let n=new M,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:f.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:f.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):j.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};fe.create=t=>new fe({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...b(t)});var Re=class extends E{_parse(e){if(this._getType(e)!==y.symbol){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.symbol,received:n.parsedType}),w}return F(e.data)}};Re.create=t=>new Re({typeName:k.ZodSymbol,...b(t)});var pe=class extends E{_parse(e){if(this._getType(e)!==y.undefined){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.undefined,received:n.parsedType}),w}return F(e.data)}};pe.create=t=>new pe({typeName:k.ZodUndefined,...b(t)});var ge=class extends E{_parse(e){if(this._getType(e)!==y.null){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.null,received:n.parsedType}),w}return F(e.data)}};ge.create=t=>new ge({typeName:k.ZodNull,...b(t)});var ae=class extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};ae.create=t=>new ae({typeName:k.ZodAny,...b(t)});var te=class extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};te.create=t=>new te({typeName:k.ZodUnknown,...b(t)});var G=class extends E{_parse(e){let r=this._getOrReturnCtx(e);return g(r,{code:f.invalid_type,expected:y.never,received:r.parsedType}),w}};G.create=t=>new G({typeName:k.ZodNever,...b(t)});var Oe=class extends E{_parse(e){if(this._getType(e)!==y.undefined){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.void,received:n.parsedType}),w}return F(e.data)}};Oe.create=t=>new Oe({typeName:k.ZodVoid,...b(t)});var re=class t extends E{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==y.array)return g(r,{code:f.invalid_type,expected:y.array,received:r.parsedType}),w;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(g(r,{code:i?f.too_big:f.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(g(r,{code:f.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(g(r,{code:f.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new B(r,i,r.path,a)))).then(i=>M.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new B(r,i,r.path,a)));return M.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:v.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:v.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:v.toString(r)}})}nonempty(e){return this.min(1,e)}};re.create=(t,e)=>new re({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...b(e)});function $e(t){if(t instanceof z){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=V.create($e(n))}return new z({...t._def,shape:()=>e})}else return t instanceof re?new re({...t._def,type:$e(t.element)}):t instanceof V?V.create($e(t.unwrap())):t instanceof Y?Y.create($e(t.unwrap())):t instanceof K?K.create(t.items.map(e=>$e(e))):t}var z=class t extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=j.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==y.object){let d=this._getOrReturnCtx(e);return g(d,{code:f.invalid_type,expected:y.object,received:d.parsedType}),w}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof G&&this._def.unknownKeys==="strip"))for(let d in o.data)i.includes(d)||a.push(d);let u=[];for(let d of i){let c=s[d],l=o.data[d];u.push({key:{status:"valid",value:d},value:c._parse(new B(o,l,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof G){let d=this._def.unknownKeys;if(d==="passthrough")for(let c of a)u.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(d==="strict")a.length>0&&(g(o,{code:f.unrecognized_keys,keys:a}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let c of a){let l=o.data[c];u.push({key:{status:"valid",value:c},value:d._parse(new B(o,l,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let d=[];for(let c of u){let l=await c.key,S=await c.value;d.push({key:l,value:S,alwaysSet:c.alwaysSet})}return d}).then(d=>M.mergeObjectSync(n,d)):M.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:v.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of j.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of j.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return $e(this)}partial(e){let r={};for(let n of j.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of j.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof V;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Vt(j.objectKeys(this.shape))}};z.create=(t,e)=>new z({shape:()=>t,unknownKeys:"strip",catchall:G.create(),typeName:k.ZodObject,...b(e)});z.strictCreate=(t,e)=>new z({shape:()=>t,unknownKeys:"strict",catchall:G.create(),typeName:k.ZodObject,...b(e)});z.lazycreate=(t,e)=>new z({shape:t,unknownKeys:"strip",catchall:G.create(),typeName:k.ZodObject,...b(e)});var he=class extends E{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new L(a.ctx.common.issues));return g(r,{code:f.invalid_union,unionErrors:i}),w}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let u of n){let d={...r,common:{...r.common,issues:[]},parent:null},c=u._parseSync({data:r.data,path:r.path,parent:d});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(u=>new L(u));return g(r,{code:f.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}};he.create=(t,e)=>new he({options:t,typeName:k.ZodUnion,...b(e)});var ee=t=>t instanceof ve?ee(t.schema):t instanceof q?ee(t.innerType()):t instanceof _e?[t.value]:t instanceof xe?t.options:t instanceof we?j.objectValues(t.enum):t instanceof ke?ee(t._def.innerType):t instanceof pe?[void 0]:t instanceof ge?[null]:t instanceof V?[void 0,...ee(t.unwrap())]:t instanceof Y?[null,...ee(t.unwrap())]:t instanceof Fe||t instanceof Ee?ee(t.unwrap()):t instanceof be?ee(t._def.innerType):[],Xe=class t extends E{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.object)return g(r,{code:f.invalid_type,expected:y.object,received:r.parsedType}),w;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(g(r,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=ee(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...b(n)})}};function ht(t,e){let r=H(t),n=H(e);if(t===e)return{valid:!0,data:t};if(r===y.object&&n===y.object){let o=j.objectKeys(e),s=j.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let u=ht(t[a],e[a]);if(!u.valid)return{valid:!1};i[a]=u.data}return{valid:!0,data:i}}else if(r===y.array&&n===y.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],u=ht(i,a);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===y.date&&n===y.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ye=class extends E{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ke(s)||Ke(i))return w;let a=ht(s.value,i.value);return a.valid?((Ye(s)||Ye(i))&&r.dirty(),{status:r.value,value:a.data}):(g(n,{code:f.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ye.create=(t,e,r)=>new ye({left:t,right:e,typeName:k.ZodIntersection,...b(r)});var K=class t extends E{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.array)return g(n,{code:f.invalid_type,expected:y.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return g(n,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new B(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>M.mergeArray(r,i)):M.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};K.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K({items:t,typeName:k.ZodTuple,rest:null,...b(e)})};var Qe=class t extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.object)return g(n,{code:f.invalid_type,expected:y.object,received:n.parsedType}),w;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new B(n,a,n.path,a)),value:i._parse(new B(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?M.mergeObjectAsync(r,o):M.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof E?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...b(n)}):new t({keyType:ie.create(),valueType:e,typeName:k.ZodRecord,...b(r)})}},Ae=class extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.map)return g(n,{code:f.invalid_type,expected:y.map,received:n.parsedType}),w;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,u],d)=>({key:o._parse(new B(n,a,n.path,[d,"key"])),value:s._parse(new B(n,u,n.path,[d,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of i){let d=await u.key,c=await u.value;if(d.status==="aborted"||c.status==="aborted")return w;(d.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(d.value,c.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let u of i){let d=u.key,c=u.value;if(d.status==="aborted"||c.status==="aborted")return w;(d.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(d.value,c.value)}return{status:r.value,value:a}}}};Ae.create=(t,e,r)=>new Ae({valueType:e,keyType:t,typeName:k.ZodMap,...b(r)});var Ie=class t extends E{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.set)return g(n,{code:f.invalid_type,expected:y.set,received:n.parsedType}),w;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:f.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:f.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(u){let d=new Set;for(let c of u){if(c.status==="aborted")return w;c.status==="dirty"&&r.dirty(),d.add(c.value)}return{status:r.value,value:d}}let a=[...n.data.values()].map((u,d)=>s._parse(new B(n,u,n.path,d)));return n.common.async?Promise.all(a).then(u=>i(u)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:v.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:v.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ie.create=(t,e)=>new Ie({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...b(e)});var et=class t extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.function)return g(r,{code:f.invalid_type,expected:y.function,received:r.parsedType}),w;function n(a,u){return Ue({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,je(),Q].filter(d=>!!d),issueData:{code:f.invalid_arguments,argumentsError:u}})}function o(a,u){return Ue({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,je(),Q].filter(d=>!!d),issueData:{code:f.invalid_return_type,returnTypeError:u}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ce){let a=this;return F(async function(...u){let d=new L([]),c=await a._def.args.parseAsync(u,s).catch(I=>{throw d.addIssue(n(u,I)),d}),l=await Reflect.apply(i,this,c);return await a._def.returns._def.type.parseAsync(l,s).catch(I=>{throw d.addIssue(o(l,I)),d})})}else{let a=this;return F(function(...u){let d=a._def.args.safeParse(u,s);if(!d.success)throw new L([n(u,d.error)]);let c=Reflect.apply(i,this,d.data),l=a._def.returns.safeParse(c,s);if(!l.success)throw new L([o(c,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:K.create(e).rest(te.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||K.create([]).rest(te.create()),returns:r||te.create(),typeName:k.ZodFunction,...b(n)})}},ve=class extends E{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ve.create=(t,e)=>new ve({getter:t,typeName:k.ZodLazy,...b(e)});var _e=class extends E{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return g(r,{received:r.data,code:f.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};_e.create=(t,e)=>new _e({value:t,typeName:k.ZodLiteral,...b(e)});function Vt(t,e){return new xe({values:t,typeName:k.ZodEnum,...b(e)})}var xe=class t extends E{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{expected:j.joinValues(n),received:r.parsedType,code:f.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return g(r,{received:r.data,code:f.invalid_enum_value,options:n}),w}return F(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};xe.create=Vt;var we=class extends E{_parse(e){let r=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==y.string&&n.parsedType!==y.number){let o=j.objectValues(r);return g(n,{expected:j.joinValues(o),received:n.parsedType,code:f.invalid_type}),w}if(this._cache||(this._cache=new Set(j.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=j.objectValues(r);return g(n,{received:n.data,code:f.invalid_enum_value,options:o}),w}return F(e.data)}get enum(){return this._def.values}};we.create=(t,e)=>new we({values:t,typeName:k.ZodNativeEnum,...b(e)});var ce=class extends E{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.promise&&r.common.async===!1)return g(r,{code:f.invalid_type,expected:y.promise,received:r.parsedType}),w;let n=r.parsedType===y.promise?r.data:Promise.resolve(r.data);return F(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ce.create=(t,e)=>new ce({type:t,typeName:k.ZodPromise,...b(e)});var q=class extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return w;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?w:u.status==="dirty"?de(u.value):r.value==="dirty"?de(u.value):u});{if(r.value==="aborted")return w;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?de(a.value):r.value==="dirty"?de(a.value):a}}if(o.type==="refinement"){let i=a=>{let u=o.refinement(a,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!se(i))return w;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>se(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):w);j.assertNever(o)}};q.create=(t,e,r)=>new q({schema:t,typeName:k.ZodEffects,effect:e,...b(r)});q.createWithPreprocess=(t,e,r)=>new q({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...b(r)});var V=class extends E{_parse(e){return this._getType(e)===y.undefined?F(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(t,e)=>new V({innerType:t,typeName:k.ZodOptional,...b(e)});var Y=class extends E{_parse(e){return this._getType(e)===y.null?F(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Y.create=(t,e)=>new Y({innerType:t,typeName:k.ZodNullable,...b(e)});var ke=class extends E{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ke.create=(t,e)=>new ke({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var be=class extends E{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Te(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new L(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};be.create=(t,e)=>new be({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var Pe=class extends E{_parse(e){if(this._getType(e)!==y.nan){let n=this._getOrReturnCtx(e);return g(n,{code:f.invalid_type,expected:y.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};Pe.create=t=>new Pe({typeName:k.ZodNaN,...b(t)});var Mn=Symbol("zod_brand"),Fe=class extends E{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},De=class t extends E{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),de(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:k.ZodPipeline})}},Ee=class extends E{_parse(e){let r=this._def.innerType._parse(e),n=o=>(se(o)&&(o.value=Object.freeze(o.value)),o);return Te(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ee.create=(t,e)=>new Ee({innerType:t,typeName:k.ZodReadonly,...b(e)});function Lt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Bt(t,e={},r){return t?ae.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Lt(e,n),u=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:u})}});if(!s){let i=Lt(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ae.create()}var Un={object:z.lazycreate},k;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(k||(k={}));var Fn=(t,e={message:`Input not instance of ${t.name}`})=>Bt(r=>r instanceof t,e),qt=ie.create,Jt=ue.create,Dn=Pe.create,Ln=le.create,Gt=me.create,zn=fe.create,Zn=Re.create,Wn=pe.create,Vn=ge.create,Bn=ae.create,qn=te.create,Jn=G.create,Gn=Oe.create,Hn=re.create,Kn=z.create,Yn=z.strictCreate,Xn=he.create,Qn=Xe.create,eo=ye.create,to=K.create,ro=Qe.create,no=Ae.create,oo=Ie.create,so=et.create,io=ve.create,ao=_e.create,co=xe.create,uo=we.create,lo=ce.create,mo=q.create,fo=V.create,po=Y.create,go=q.createWithPreprocess,ho=De.create,yo=()=>qt().optional(),vo=()=>Jt().optional(),_o=()=>Gt().optional(),xo={string:(t=>ie.create({...t,coerce:!0})),number:(t=>ue.create({...t,coerce:!0})),boolean:(t=>me.create({...t,coerce:!0})),bigint:(t=>le.create({...t,coerce:!0})),date:(t=>fe.create({...t,coerce:!0}))};var wo=w;var jo="cueframe/components";var To="cueframe.json",$o=Le.object({componentsDir:Le.string().min(1).default(jo)}).passthrough();function ze(t){let e=t,r=Co(e).root;for(;;){let n=Ne(e,To);if(tt(n)){let o=ko(n,"utf8"),s=$o.parse(JSON.parse(o));return{root:e,manifest:s}}if(e===r)return null;e=So(e)}}function Ht(t){return Ne(t.root,t.manifest.componentsDir)}function rt(t,e){return Ne(Ht(t),e)}function Kt(t){let e=Ht(t);return tt(e)?bo(e).filter(r=>{let n=Ne(e,r);return Eo(n).isDirectory()?tt(Ne(n,"index.tsx"))&&tt(Ne(n,"config.ts")):!1}).sort():[]}var Po="cueframe.json";function No(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function Mo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function yt(t,e){x(t,"new_component",new Error(e),p.UserError),m(p.UserError)}function Uo(t,e){return`import React from 'react';
28
16
 
29
17
  /** Custom CueFrame component. Mounted as ({ durationInFrames, params }). Edit me. */
30
18
  export default function ${e}({ params }: { durationInFrames: number; params: Record<string, unknown> }) {
31
19
  return <div style={{ width: '100%', height: '100%', display: 'grid', placeItems: 'center' }}>{String((params as { text?: unknown }).text ?? '${t}')}</div>;
32
20
  }
33
- `}function Uo(t,e){return`import { z } from 'zod';
21
+ `}function Fo(t,e){return`import { z } from 'zod';
34
22
  import component from './index';
35
23
 
36
24
  const paramsSchema = z.object({}).passthrough();
@@ -45,40 +33,29 @@ export const config = {
45
33
  paramsSchema,
46
34
  };
47
35
  export default config;
48
- `}function Ye(t,e){E(t,"name",e);let o=e.dryRun??!1,r=e.force??!1,n=Ao(t);n||xe(e,`name "${t}" has no alphanumeric characters to form a component identifier.`);let i=Fo(t);p(e,"new_component_prepare",{name:t,dryRun:o,force:r});let s=U(process.cwd());s||xe(e,"No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first to scaffold one.");let a=z(s,t),f=Io(a);f&&Oo(a).length>0&&!r&&xe(e,`Component dir ${a} already exists and is non-empty. Pass --force to overwrite (this replaces local source).`);let u={"index.tsx":Mo(t,n),"config.ts":Uo(t,i)};if(!o){Ro(a,{recursive:!0});for(let[x,b]of Object.entries(u))Ze(Qe(a,x),b);let c=Qe(s.root,Po),d=JSON.parse(To(c,"utf8")),h=d.components??{};h[t]={custom:!0},d.components=h,Ze(c,`${JSON.stringify(d,null,2)}
49
- `)}j(e,{ok:!0,dryRun:o,name:t,component:n,dir:a,files:Object.keys(u),overwritten:f&&r},()=>{console.log(`\u2713 ${o?"Would scaffold":"Scaffolded"} custom component ${t} (${n}) into ${a}`);for(let d of Object.keys(u))console.log(` ${o?"would write":"wrote"} ${d}`);o||console.log(` stamped cueframe.json components.${t} (custom)`),console.log("Edit index.tsx, then `cueframe push "+t+"` to publish it to CueFrame.")})}import{existsSync as ne,readFileSync as ie}from"fs";import{join as se}from"path";import $ from"typescript";var Do="cueframe.json",No=["effects","transitions","text","layouts"];function Lo(t){return No.includes(t??"")?t:"layouts"}function Wo(t){let e=t;for(;$.isAsExpression(e)||$.isParenthesizedExpression(e)||typeof $.isSatisfiesExpression=="function"&&$.isSatisfiesExpression(e);)e=e.expression;return e}function zo(t,e){for(let o of t.statements)if($.isImportDeclaration(o)&&$.isStringLiteral(o.moduleSpecifier)&&o.moduleSpecifier.text===e)return!0;return!1}function Xe(t,e){let o=$.createSourceFile(e,t,$.ScriptTarget.Latest,!0,$.ScriptKind.TS),r;for(let i of o.statements)if($.isVariableStatement(i)){for(let s of i.declarationList.declarations)if($.isIdentifier(s.name)&&s.name.text==="config"&&s.initializer){let a=Wo(s.initializer);$.isObjectLiteralExpression(a)&&(r=a)}if(r)break}let n={};if(!r)return n;for(let i of r.properties){if(!$.isPropertyAssignment(i)||!($.isIdentifier(i.name)||$.isStringLiteral(i.name)))continue;let s=i.name.text;$.isStringLiteralLike(i.initializer)&&(s==="name"?n.name=i.initializer.text:s==="category"?n.category=i.initializer.text:s==="version"&&(n.version=i.initializer.text))}return n}function Jo(t){let e=se(t,"config.ts");if(!ne(e))return{};let o=ie(e,"utf8"),r=$.createSourceFile("config.ts",o,$.ScriptTarget.Latest,!0,$.ScriptKind.TS),n=se(t,"_config.ts");return zo(r,"./_config")&&ne(n)?Xe(ie(n,"utf8"),"_config.ts"):Xe(o,"config.ts")}function qo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Bo(t,e){let o=se(t.root,Do);if(ne(o))try{let n=JSON.parse(ie(o,"utf8")).components?.[e]?.ejectedFrom;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}async function et(t,e,o){let r=z(t,e),n=se(r,"index.tsx");if(!ne(n))throw Object.assign(new Error(`Component "${e}" has no index.tsx at ${r}. Scaffold it first (cueframe eject / new component).`),{code:"no_component_source"});let i=ie(n,"utf8"),s=Jo(r),a=s.name??qo(e),f=Lo(s.category),u=Bo(t,e),c=`Custom component "${e}" pushed from the local CueFrame workspace.`,d={type:"object",properties:{}};p(o,"push_component",{id:e,name:a,category:f,version:s.version,ejectedFrom:u});let h=!1;try{await Y.getComponent(e),h=!0}catch(x){if(x instanceof I&&x.status===404)h=!1;else throw x}return h?(await Y.updateComponent(e,{tsxSource:i,name:a,description:c,category:f,propSchema:d,origin:"repo-owned",...u?{ejectedFrom:u}:{}}),p(o,"pushed",{id:e,action:"updated"}),{id:e,action:"updated",name:a,category:f}):(await Y.createComponent({componentId:e,tsxSource:i,name:a,description:c,category:f,propSchema:d,origin:"repo-owned",...u?{ejectedFrom:u}:{}}),p(o,"pushed",{id:e,action:"created"}),{id:e,action:"created",name:a,category:f})}async function tt(t,e){t||(g(e,"push",new Error("Pass a component id (cueframe push <id>), or use `cueframe sync` to push all."),m.UserError),l(m.UserError)),E(t,"id",e),w(e.target);let o=U(process.cwd());o||(g(e,"push",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),m.UserError),l(m.UserError)),p(e,"push_prepare",{id:t,target:e.target});try{let r=await et(o,t,e);j(e,{ok:!0,target:e.target,...r},()=>{console.log(`\u2713 ${r.action} component ${r.id} (${r.name}) on CueFrame`)})}catch(r){let n=r.code==="no_component_source"?m.UserError:y(r);g(e,"push",r,n),e.json||console.error(`Push failed: ${v(r)}`),l(n)}}async function ot(t){w(t.target);let e=U(process.cwd());e||(g(t,"sync",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),m.UserError),l(m.UserError));let o=qe(e);p(t,"sync_prepare",{target:t.target,count:o.length,ids:o});let r=[],n=[];for(let i of o)try{r.push(await et(e,i,t))}catch(s){let a=s.code==="no_component_source"?m.UserError:y(s);g(t,"sync",s,a),n.push({id:i,error:s})}j(t,{ok:n.length===0,target:t.target,pushed:r,failed:n.map(i=>({id:i.id,error:v(i.error)}))},()=>{if(r.length===0&&n.length===0){console.log("No components to sync. Scaffold one with `cueframe eject` or `cueframe new component`.");return}for(let i of r)console.log(`\u2713 ${i.action} ${i.id} (${i.name})`);for(let i of n)console.error(`\u2716 ${i.id}: ${v(i.error)}`);console.log(`Synced ${r.length}/${o.length} component(s) to CueFrame.`)}),n.length>0&&l(y(n[0].error))}var ae=["media","sessions","projects","renders","webhooks"],rt={readonly:Object.fromEntries(ae.map(t=>[t,["read"]])),editall:Object.fromEntries(ae.map(t=>[t,["read","write"]]))};function Go(t){if(t.preset){let e=rt[t.preset];return e||(console.error(`Unknown --preset "${t.preset}". Valid: ${Object.keys(rt).join(", ")}.`),l(m.UserError)),e}if(t.scope)return Ko(t.scope);console.error("Provide --scope or --preset (e.g. --preset readonly | editall)."),l(m.UserError)}function Ko(t){let e={};for(let o of t.split(",").map(r=>r.trim()).filter(Boolean)){let[r,n]=o.split(":");(!r||!n)&&(console.error(`Invalid --scope "${o}". Use resource:rw (e.g. renders:rw,media:r).`),l(m.UserError)),ae.includes(r)||(console.error(`--scope "${o}": unknown resource "${r}". Valid: ${ae.join(", ")}.`),l(m.UserError));let i=[];/r/i.test(n)&&i.push("read"),/w/i.test(n)&&i.push("write"),i.length===0&&(console.error(`--scope "${o}": actions must include r and/or w.`),l(m.UserError)),e[r]=i}return Object.keys(e).length===0&&(console.error("--scope is required, e.g. --scope media:rw,projects:rw,renders:rw"),l(m.UserError)),e}async function nt(t){w("dev");let e=Go(t),o={name:t.name,permissions:e};if(t.expires){let r=Number(t.expires);(!Number.isFinite(r)||r<=0)&&(console.error("--expires must be a positive number of days."),l(m.UserError)),o.expiresIn=Math.round(r*86400)}try{let r=await fe("/v1/api-keys",{method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json"}});j(t,{ok:!0,id:r.id,prefix:r.prefix,start:r.start,key:r.key},()=>{let n=Object.entries(e).map(([i,s])=>`${i}:${s.map(a=>a[0]).join("")}`).join(" ");console.log(`\u2713 API key "${t.name}" created \u2014 scopes: ${n}`),console.log(`
50
- ${r.key}
51
- `),console.log(" Shown ONCE \u2014 store it now (paste it into your integration; not saved here).")})}catch(r){g(t,"keys_create",r,m.ApiClientError),l(m.ApiClientError)}}async function it(t){w("dev");let e=await k("/api/auth/api-key/list",{method:"GET"});e.status>=400&&(g(t,"keys_list",new Error(`list failed (${e.status})`),m.ApiClientError),l(m.ApiClientError));let o=Array.isArray(e.body)?e.body:[];j(t,{ok:!0,keys:o},()=>{if(o.length===0){console.log("No API keys.");return}for(let r of o)console.log(` ${r.id} ${r.name??"(unnamed)"} ${r.start??""}\u2026`)})}async function st(t,e){w("dev");let o=await k("/api/auth/api-key/delete",{method:"POST",body:JSON.stringify({keyId:t}),headers:{"content-type":"application/json"}});o.status>=400&&(g(e,"keys_revoke",new Error(`revoke failed (${o.status})`),m.ApiClientError),l(m.ApiClientError)),j(e,{ok:!0,revoked:t},()=>console.log(`\u2713 Revoked ${t}`))}async function at(t){w(t.target),p(t,"list_prepare",{target:t.target});try{let e=await L.listProjects(),o=t.limit,r=typeof o=="number"&&Number.isFinite(o)&&o>0?e.data.slice(0,o):e.data;if(p(t,"list_complete",{count:r.length,total:e.data.length,truncated:r.length<e.data.length,projects:r}),!t.json){if(e.data.length===0){console.log("No projects found.");return}for(let n of r){let i=new Date(n.createdAt).toLocaleDateString();console.log(` ${n.id} ${n.name} (${i})`)}r.length<e.data.length&&console.log(` \u2026 ${e.data.length-r.length} more (raise --limit to see all)`)}}catch(e){g(t,"list",e,y(e)),t.json||console.error(`Failed to list projects: ${v(e)}`),l(y(e))}}import{readFile as Ho,stat as Vo}from"fs/promises";import{existsSync as Zo}from"fs";import{basename as Qo,extname as Yo}from"path";var Xo=4e3;function er(t){switch(Yo(t).toLowerCase()){case".mp4":return"video/mp4";case".mov":return"video/quicktime";case".webm":return"video/webm";case".mkv":return"video/x-matroska";case".wav":return"audio/wav";case".mp3":return"audio/mpeg";case".m4a":return"audio/mp4";case".aac":return"audio/aac";default:return"video/mp4"}}var ct=["vo","music","sfx","ambience"];async function dt(t,e){Zo(t)||(g(e,"preflight",new Error(`File not found: ${t}`),m.UserError),e.json||console.error(`File not found: ${t}`),l(m.UserError));let o=Qo(t),r=(await Vo(t)).size,n=er(o);if(e.audioRole&&!ct.includes(e.audioRole)){let b=new Error(`--audio-role must be one of ${ct.join("|")} (got "${e.audioRole}")`);g(e,"preflight",b,m.UserError),e.json||console.error(b.message),l(m.UserError)}let i=e.audioRole;if(e.dryRun){p(e,"upload_dry_run",{file:o,sizeBytes:r,contentType:n,target:e.target,analyzeAfter:!!e.analyze,wouldCall:"POST /v1/media \u2192 presigned PUT \u2192 POST /v1/media/:id/finalize \u2192 poll processing"}),e.json||console.log(`[dry-run] Would upload ${o} (${(r/1024/1024).toFixed(1)} MB, ${n}) to ${e.target}.`);return}w(e.target),p(e,"upload_prepare",{file:o,sizeBytes:r,contentType:n,target:e.target});let s=C("Preparing upload\u2026",e.json),a,f;try{let b=await F.createMediaUpload({filename:o,contentType:n,size:r});a=b.id,f=b.uploadUrl,s.succeed("Ready"),p(e,"upload_ready",{mediaItemId:a})}catch(b){s.fail(`Failed: ${v(b)}`),g(e,"upload_prepare",b,y(b)),l(y(b))}let u=Date.now(),c=C(`Uploading ${o} (${(r/1024/1024).toFixed(1)} MB)\u2026`,e.json);try{let b=await Ho(t),_=await fetch(f,{method:"PUT",headers:{"Content-Type":n},body:b});if(!_.ok)throw new Error(`presigned PUT failed: ${_.status} ${_.statusText}`);await F.finalizeMedia(a,i?{audioRole:i}:{}),c.succeed(`Uploaded: ${o}`),p(e,"upload_complete",{mediaItemId:a,bytesUploaded:r,...i?{audioRole:i}:{},durationMs:Date.now()-u})}catch(b){c.fail(`Upload failed: ${v(b)}`),g(e,"upload",b,m.NetworkError),l(m.NetworkError)}let d=C("Processing (transcription)\u2026",e.json),h=Date.now(),x=null;for(;;){await new Promise(b=>setTimeout(b,Xo));try{let b=await F.getMedia(a),_=b?.processingStatus?.phase??"unknown",J=b?.processingStatus?.percent??null,H=Math.round((Date.now()-h)/1e3),ue=J!=null?` \xB7 ${Math.round(J*100)}%`:"";if(d.text=`Processing\u2026 ${_}${ue} (${H}s)`,p(e,"process_progress",{phase:_,percent:J,elapsedSec:H}),_==="complete"||_==="completed"){d.succeed(`Ready: ${a}`),x=b,p(e,"process_complete",{mediaItemId:a,durationMs:Date.now()-h,item:b});break}if(_==="error"){let V=b?.processingStatus?.error??"unknown error";d.fail(`Processing failed: ${V}`),g(e,"process",new Error(V),m.ApiServerError),l(m.ApiServerError)}}catch{}}if(e.analyze){T(`
52
- Media item ID: ${a}`,e);let{analyzeCommand:b}=await import("./analyze-4EZTZEAG.js");await b(a,{target:e.target,wait:!0,json:e.json});return}e.json||j(e,{mediaItemId:a,item:x},()=>{console.log(`
36
+ `}function Qt(t,e){R(t,"name",e);let r=e.dryRun??!1,n=e.force??!1,o=No(t);o||yt(e,`name "${t}" has no alphanumeric characters to form a component identifier.`);let s=Mo(t);h(e,"new_component_prepare",{name:t,dryRun:r,force:n});let i=ze(process.cwd());i||yt(e,"No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first to scaffold one.");let a=rt(i,t),u=Ro(a);u&&Io(a).length>0&&!n&&yt(e,`Component dir ${a} already exists and is non-empty. Pass --force to overwrite (this replaces local source).`);let d={"index.tsx":Uo(t,o),"config.ts":Fo(t,s)};if(!r){Oo(a,{recursive:!0});for(let[I,ne]of Object.entries(d))Yt(Xt(a,I),ne);let c=Xt(i.root,Po),l=JSON.parse(Ao(c,"utf8")),S=l.components??{};S[t]={custom:!0},l.components=S,Yt(c,`${JSON.stringify(l,null,2)}
37
+ `)}$(e,{ok:!0,dryRun:r,name:t,component:o,dir:a,files:Object.keys(d),overwritten:u&&n},()=>{console.log(`\u2713 ${r?"Would scaffold":"Scaffolded"} custom component ${t} (${o}) into ${a}`);for(let l of Object.keys(d))console.log(` ${r?"would write":"wrote"} ${l}`);r||console.log(` stamped cueframe.json components.${t} (custom)`),console.log("Edit index.tsx, then `cueframe push "+t+"` to publish it to CueFrame.")})}import{existsSync as ot,readFileSync as st}from"fs";import{join as it}from"path";import N from"typescript";var Do="cueframe.json",Lo=["effects","transitions","text","layouts"];function zo(t){return Lo.includes(t??"")?t:"layouts"}function Zo(t){let e=t;for(;N.isAsExpression(e)||N.isParenthesizedExpression(e)||typeof N.isSatisfiesExpression=="function"&&N.isSatisfiesExpression(e);)e=e.expression;return e}function Wo(t,e){for(let r of t.statements)if(N.isImportDeclaration(r)&&N.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===e)return!0;return!1}function er(t,e){let r=N.createSourceFile(e,t,N.ScriptTarget.Latest,!0,N.ScriptKind.TS),n;for(let s of r.statements)if(N.isVariableStatement(s)){for(let i of s.declarationList.declarations)if(N.isIdentifier(i.name)&&i.name.text==="config"&&i.initializer){let a=Zo(i.initializer);N.isObjectLiteralExpression(a)&&(n=a)}if(n)break}let o={};if(!n)return o;for(let s of n.properties){if(!N.isPropertyAssignment(s)||!(N.isIdentifier(s.name)||N.isStringLiteral(s.name)))continue;let i=s.name.text;N.isStringLiteralLike(s.initializer)&&(i==="name"?o.name=s.initializer.text:i==="category"?o.category=s.initializer.text:i==="version"&&(o.version=s.initializer.text))}return o}function Vo(t){let e=it(t,"config.ts");if(!ot(e))return{};let r=st(e,"utf8"),n=N.createSourceFile("config.ts",r,N.ScriptTarget.Latest,!0,N.ScriptKind.TS),o=it(t,"_config.ts");return Wo(n,"./_config")&&ot(o)?er(st(o,"utf8"),"_config.ts"):er(r,"config.ts")}function Bo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function qo(t,e){let r=it(t.root,Do);if(ot(r))try{let o=JSON.parse(st(r,"utf8")).components?.[e]?.ejectedFrom;return typeof o=="string"&&o.length>0?o:void 0}catch{return}}var nt="none \u2014 params are unvalidated server-side";async function tr(t,e,r){let n=rt(t,e),o=it(n,"index.tsx");if(!ot(o))throw Object.assign(new Error(`Component "${e}" has no index.tsx at ${n}. Scaffold it first (cueframe eject / new component).`),{code:"no_component_source"});let s=st(o,"utf8"),i=Vo(n),a=i.name??Bo(e),u=zo(i.category),d=qo(t,e),c=`Custom component "${e}" pushed from the local CueFrame workspace.`,l={type:"object",properties:{}};h(r,"push_component",{id:e,name:a,category:u,version:i.version,ejectedFrom:d,propSchema:nt});let S=!1;try{await Ve.getComponent(e),S=!0}catch(I){if(I instanceof Z&&I.status===404)S=!1;else throw I}return S?(await Ve.updateComponent(e,{tsxSource:s,name:a,description:c,category:u,propSchema:l,origin:"repo-owned",...d?{ejectedFrom:d}:{}}),h(r,"pushed",{id:e,action:"updated"}),{id:e,action:"updated",name:a,category:u,propSchema:nt}):(await Ve.createComponent({componentId:e,tsxSource:s,name:a,description:c,category:u,propSchema:l,origin:"repo-owned",...d?{ejectedFrom:d}:{}}),h(r,"pushed",{id:e,action:"created"}),{id:e,action:"created",name:a,category:u,propSchema:nt})}async function rr(t,e){t||(x(e,"push",new Error("Pass a component id (cueframe push <id>), or use `cueframe sync` to push all."),p.UserError),m(p.UserError)),R(t,"id",e),T(e.target);let r=ze(process.cwd());r||(x(e,"push",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),p.UserError),m(p.UserError)),h(e,"push_prepare",{id:t,target:e.target});try{let n=await tr(r,t,e);$(e,{ok:!0,target:e.target,...n},()=>{console.log(`\u2713 ${n.action} component ${n.id} (${n.name}) on CueFrame`),console.log(` propSchema: ${n.propSchema}`)})}catch(n){let o=n.code==="no_component_source"?p.UserError:_(n);x(e,"push",n,o),m(o)}}async function nr(t){T(t.target);let e=ze(process.cwd());e||(x(t,"sync",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),p.UserError),m(p.UserError));let r=Kt(e);h(t,"sync_prepare",{target:t.target,count:r.length,ids:r});let n=[],o=[];for(let s of r)try{n.push(await tr(e,s,t))}catch(i){let a=i.code==="no_component_source"?p.UserError:_(i);A(t,"sync",i,a),o.push({id:s,error:i})}$(t,{ok:o.length===0,target:t.target,pushed:n,failed:o.map(s=>({id:s.id,error:O(s.error)}))},()=>{if(n.length===0&&o.length===0){console.log("No components to sync. Scaffold one with `cueframe eject` or `cueframe new component`.");return}for(let s of n)console.log(`\u2713 ${s.action} ${s.id} (${s.name})`);n.length>0&&console.log(` propSchema: ${nt}`);for(let s of o)console.error(`\u2716 ${s.id}: ${O(s.error)}`);console.log(`Synced ${n.length}/${r.length} component(s) to CueFrame.`)}),o.length>0&&m(_(o[0].error))}var at=["media","sessions","projects","renders","webhooks"],or={readonly:Object.fromEntries(at.map(t=>[t,["read"]])),editall:Object.fromEntries(at.map(t=>[t,["read","write"]]))};function Jo(t){if(t.preset){let e=or[t.preset];return e||(console.error(`Unknown --preset "${t.preset}". Valid: ${Object.keys(or).join(", ")}.`),m(p.UserError)),e}if(t.scope)return Go(t.scope);console.error("Provide --scope or --preset (e.g. --preset readonly | editall)."),m(p.UserError)}function Go(t){let e={};for(let r of t.split(",").map(n=>n.trim()).filter(Boolean)){let[n,o]=r.split(":");(!n||!o)&&(console.error(`Invalid --scope "${r}". Use resource:rw (e.g. renders:rw,media:r).`),m(p.UserError)),at.includes(n)||(console.error(`--scope "${r}": unknown resource "${n}". Valid: ${at.join(", ")}.`),m(p.UserError));let s=[];/r/i.test(o)&&s.push("read"),/w/i.test(o)&&s.push("write"),s.length===0&&(console.error(`--scope "${r}": actions must include r and/or w.`),m(p.UserError)),e[n]=s}return Object.keys(e).length===0&&(console.error("--scope is required, e.g. --scope media:rw,projects:rw,renders:rw"),m(p.UserError)),e}async function sr(t){T(t.target);let e=Jo(t),r={name:t.name,permissions:e};if(t.expires){let n=Number(t.expires);(!Number.isFinite(n)||n<=0)&&(console.error("--expires must be a positive number of days."),m(p.UserError)),r.expiresIn=Math.round(n*86400)}try{let n=await Ct("/v1/api-keys",{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json"}});$(t,{ok:!0,id:n.id,prefix:n.prefix,start:n.start,key:n.key},()=>{let o=Object.entries(e).map(([s,i])=>`${s}:${i.map(a=>a[0]).join("")}`).join(" ");console.log(`\u2713 API key "${t.name}" created \u2014 scopes: ${o}`),console.log(`
38
+ ${n.key}
39
+ `),console.log(" Shown ONCE \u2014 store it now (paste it into your integration; not saved here).")})}catch(n){x(t,"keys_create",n,_(n)),m(_(n))}}async function ir(t){T(t.target);let e;try{e=await W("/api/auth/api-key/list",{method:"GET"})}catch(n){x(t,"keys_list",n,_(n)),m(_(n))}e.status>=400&&(x(t,"keys_list",new Error(`list failed (${e.status})`),U(e.status)),m(U(e.status)));let r=Array.isArray(e.body)?e.body:[];$(t,{ok:!0,keys:r},()=>{if(r.length===0){console.log("No API keys.");return}for(let n of r)console.log(` ${n.id} ${n.name??"(unnamed)"} ${n.start??""}\u2026`)})}async function ar(t,e){T(e.target);let r;try{r=await W("/api/auth/api-key/delete",{method:"POST",body:JSON.stringify({keyId:t}),headers:{"content-type":"application/json"}})}catch(n){x(e,"keys_revoke",n,_(n)),m(_(n))}r.status>=400&&(x(e,"keys_revoke",new Error(`revoke failed (${r.status})`),U(r.status)),m(U(r.status))),$(e,{ok:!0,revoked:t},()=>console.log(`\u2713 Revoked ${t}`))}async function cr(t){T(t.target),h(t,"list_prepare",{target:t.target});try{let e=await Se.listProjects(),r=t.limit,n=typeof r=="number"&&Number.isFinite(r)&&r>0?e.data.slice(0,r):e.data;if(h(t,"list_complete",{count:n.length,total:e.data.length,truncated:n.length<e.data.length,projects:n}),!t.json){if(e.data.length===0){console.log("No projects found.");return}for(let o of n){let s=new Date(o.createdAt).toLocaleDateString();console.log(` ${o.id} ${o.name} (${s})`)}n.length<e.data.length&&console.log(` \u2026 ${e.data.length-n.length} more (raise --limit to see all)`)}}catch(e){x(t,"list",e,_(e)),m(_(e))}}import{readFile as Ho,stat as Ko}from"fs/promises";import{existsSync as Yo}from"fs";import{basename as Xo,extname as Qo}from"path";var es=4e3,dr=1800*1e3,ur=5,lr={".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".wav":"audio/wav",".mp3":"audio/mpeg",".m4a":"audio/mp4",".aac":"audio/aac",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml"};function ts(t,e){let r=Qo(t).toLowerCase(),n=lr[r];if(!n){let o=new Error(`Unsupported file extension "${r||"(none)"}" for ${t}. Supported: ${Object.keys(lr).join(", ")}.`);x(e,"preflight",o,p.UserError),m(p.UserError)}return n}var mr=["vo","music","sfx","ambience"];async function fr(t,e){Yo(t)||(x(e,"preflight",new Error(`File not found: ${t}`),p.UserError),m(p.UserError));let r=Xo(t),n=(await Ko(t)).size,o=ts(r,e);if(e.audioRole&&!mr.includes(e.audioRole)){let C=new Error(`--audio-role must be one of ${mr.join("|")} (got "${e.audioRole}")`);x(e,"preflight",C,p.UserError),m(p.UserError)}let s=e.audioRole;if(e.dryRun){h(e,"upload_dry_run",{file:r,sizeBytes:n,contentType:o,target:e.target,analyzeAfter:!!e.analyze,wouldCall:"POST /v1/media \u2192 presigned PUT \u2192 POST /v1/media/:id/finalize \u2192 poll processing"}),e.json||console.log(`[dry-run] Would upload ${r} (${(n/1024/1024).toFixed(1)} MB, ${o}) to ${e.target}.`);return}T(e.target),h(e,"upload_prepare",{file:r,sizeBytes:n,contentType:o,target:e.target});let i=P("Preparing upload\u2026",e.json),a,u;try{let C=await oe.createMediaUpload({filename:r,contentType:o,size:n});a=C.id,u=C.uploadUrl,i.succeed("Ready"),h(e,"upload_ready",{mediaItemId:a})}catch(C){i.fail(`Failed: ${O(C)}`),A(e,"upload_prepare",C,_(C)),m(_(C))}let d=Date.now(),c=P(`Uploading ${r} (${(n/1024/1024).toFixed(1)} MB)\u2026`,e.json);try{let C=await Ho(t),X=await fetch(u,{method:"PUT",headers:{"Content-Type":o},body:C});if(!X.ok)throw new Error(`presigned PUT failed: ${X.status} ${X.statusText}`);await oe.finalizeMedia(a,s?{audioRole:s}:{}),c.succeed(`Uploaded: ${r}`),h(e,"upload_complete",{mediaItemId:a,bytesUploaded:n,...s?{audioRole:s}:{},durationMs:Date.now()-d})}catch(C){c.fail(`Upload failed: ${O(C)}`),A(e,"upload",C,p.NetworkError),m(p.NetworkError)}let l=P("Processing (transcription)\u2026",e.json),S=Date.now(),I=null,ne=0;for(;;){if(await new Promise(C=>setTimeout(C,es)),Date.now()-S>dr){let C=`Processing did not complete within ${Math.round(dr/6e4)}m. Media item ID: ${a}.`;l.fail(C),A(e,"process",new Error(C),p.ApiServerError),m(p.ApiServerError)}try{let C=await oe.getMedia(a);ne=0;let X=C?.processingStatus?.phase??"unknown",dt=C?.processingStatus?.percent??null,bt=Math.round((Date.now()-S)/1e3),Br=dt!=null?` \xB7 ${Math.round(dt*100)}%`:"";if(l.text=`Processing\u2026 ${X}${Br} (${bt}s)`,h(e,"process_progress",{phase:X,percent:dt,elapsedSec:bt}),X==="complete"||X==="completed"){l.succeed(`Ready: ${a}`),I=C,h(e,"process_complete",{mediaItemId:a,durationMs:Date.now()-S,item:C});break}if(X==="error"){let Et=C?.processingStatus?.error??"unknown error";l.fail(`Processing failed: ${Et}`),A(e,"process",new Error(Et),p.ApiServerError),m(p.ApiServerError)}}catch(C){C instanceof Z&&[401,403,404].includes(C.status)&&(l.fail(`Processing check failed: ${O(C)}`),A(e,"process",C,_(C)),m(_(C))),ne++,ne>=ur&&(l.fail(`Processing check failed: ${O(C)}`),A(e,"process",new Error(`Processing status unreadable after ${ur} consecutive failures: ${O(C)}`),_(C)),m(_(C)))}}if(e.analyze){J(`
40
+ Media item ID: ${a}`,e);let{analyzeCommand:C}=await import("./analyze-4EGOBMRV.js");await C(a,{target:e.target,wait:!0,json:e.json});return}e.json||$(e,{mediaItemId:a,item:I},()=>{console.log(`
53
41
  Media item ID: ${a}`),console.log(`
54
- Run \`cueframe analyze ${a} --target ${e.target}\` to generate clip suggestions.`)})}function Se(t){let e=Math.floor(t/60),o=Math.floor(t%60);return`${e}:${String(o).padStart(2,"0")}`}async function mt(t,e){t!==void 0&&E(t,"mediaItemId",e),w(e.target),p(e,"clips_prepare",{target:e.target,mode:t?"suggestions":"media-list",...t?{mediaItemId:t}:{}});try{if(!t){let r=await F.listMedia();if(p(e,"clips_complete",{mode:"media-list",count:r.data.length,media:r.data}),!e.json){if(r.data.length===0){console.log("No media items found. Import a video first.");return}console.log("Media items (pass the ID to `cueframe clips <id>`):"),console.log("");for(let n of r.data){let i=n.duration?`${Se(n.duration)} `:"",s=n.processingStatus?.phase??"unknown",a=s==="complete"?"":` [${s}]`;console.log(` ${n.id} ${n.name} ${i}${a}`)}}return}let o=await Ae.listMediaSuggestions(t);if(p(e,"clips_complete",{mode:"suggestions",mediaItemId:t,count:o.suggestions.length,suggestions:o.suggestions}),!e.json){if(o.suggestions.length===0){console.log("No clip suggestions found for this media item."),console.log("If analysis is still running, try again shortly. Otherwise the video may not have suitable clips.");return}console.log(`${o.suggestions.length} clip suggestion${o.suggestions.length!==1?"s":""}:`),console.log("");for(let r of o.suggestions){let n=`${Se(r.trim.start)} \u2192 ${Se(r.trim.end)}`,i=(r.trim.end-r.trim.start).toFixed(1);console.log(` ${r.id}`),console.log(` ${r.title}`),console.log(` ${n} (${i}s) ${r.format} score: ${r.score}`),r.reason&&console.log(` ${r.reason}`),console.log("")}}}catch(o){g(e,"clips",o,y(o)),e.json||console.error(`Failed: ${v(o)}`),l(y(o))}}import{readFileSync as tr}from"fs";async function lt(t,e){E(t,"projectId",e),w(e.target),p(e,"composition_get_prepare",{projectId:t});let o=await G(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_get");o.status>=400&&(K(o,e,"composition_get"),l(A(o.status)));let r=o.headers.etag,n=r&&ft(r);p(e,"composition_get_complete",{projectId:t,etag:n,status:o.status}),j(e,{etag:n,composition:o.body},()=>{n&&console.log(`# ETag: ${n}`),console.log(JSON.stringify(o.body,null,2))})}async function ut(t,e){E(t,"projectId",e),e.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),l(m.UserError)),w(e.target);let o=await Ce(t,e),r=await gt(e.body);p(e,"composition_put_prepare",{projectId:t,ifMatch:o});let n=new Headers({"content-type":"application/json","if-match":o}),i=await G(`/v1/projects/${t}/composition`,{method:"PUT",headers:n,body:r},e,"composition_put");i.status>=400&&(K(i,e,"composition_put"),l(A(i.status)));let s=i.headers.etag;p(e,"composition_put_complete",{projectId:t,etag:s,status:i.status,response:i.body}),j(e,{etag:s,response:i.body},()=>{console.log(`Composition saved (ETag: ${s??"unknown"}).`),i.body&&typeof i.body=="object"&&console.log(JSON.stringify(i.body,null,2))})}async function ce(t,e){E(t,"projectId",e),e.suggestionId||(console.error("--suggestion <suggestionId> is required"),l(m.UserError)),w(e.target);let o=await Ce(t,e),r;if(e.format)try{r=JSON.parse(e.format)}catch{console.error(`--format must be JSON, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`),l(m.UserError)}let n=JSON.stringify({suggestionId:e.suggestionId,...r?{format:r}:{}});p(e,"composition_from_suggestion_prepare",{projectId:t,suggestionId:e.suggestionId,ifMatch:o});let i,s=o,a=0,f=3;for(;;){a++;let c=new Headers({"content-type":"application/json","if-match":s});if(i=await G(`/v1/projects/${t}/composition/from-suggestion`,{method:"POST",headers:c,body:n},e,"composition_from_suggestion"),!(i.status===409&&typeof i.body=="object"&&i.body!==null&&i.body.code==="stale_etag"))break;if(a>f){p(e,"composition_from_suggestion_etag_retries_exhausted",{projectId:t,attempts:f});break}p(e,"composition_from_suggestion_etag_retry",{projectId:t,attempt:a,reason:"stale_etag"}),s=await Ce(t,e)}i.status>=400&&(K(i,e,"composition_from_suggestion"),l(A(i.status)));let u=i.headers.etag;p(e,"composition_from_suggestion_complete",{projectId:t,suggestionId:e.suggestionId,etag:u,status:i.status,response:i.body,attempts:a}),j(e,{etag:u,response:i.body},()=>{console.log(`Composition built from suggestion ${e.suggestionId} (ETag: ${u??"unknown"}).`),i.body&&typeof i.body=="object"&&console.log(JSON.stringify(i.body,null,2))})}async function pt(t){t.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),l(m.UserError)),w(t.target);let e=await gt(t.body);p(t,"composition_validate_prepare",{});let o=new Headers({"content-type":"application/json"}),r=await G("/v1/composition/validate",{method:"POST",headers:o,body:e},t,"composition_validate");r.status>=400&&(K(r,t,"composition_validate"),l(A(r.status))),p(t,"composition_validate_complete",{status:r.status}),j(t,{valid:!0},()=>{console.log("\u2713 Composition is valid.")})}function ft(t){return t.replace(/^W\//,"").replace(/-gzip(?=("?)$)/,"")}async function Ce(t,e){if(e.force)return"*";if(e.ifMatch)return e.ifMatch;let o=await G(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_etag_fetch");if(o.status===404)return T("No existing composition; treating as create (If-Match: *).",e),"*";o.status>=400&&(K(o,e,"composition_etag_fetch"),l(A(o.status)));let r=o.headers.etag;return r||(g(e,"composition_etag_fetch",new Error("Server returned no ETag on composition GET; cannot safely thread If-Match. Pass --force to overwrite anyway."),m.ApiServerError),l(m.ApiServerError)),ft(r)}async function gt(t){if(t.startsWith("@")){let e=t.slice(1);if(e==="-"){let o=[];for await(let r of process.stdin)o.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(o).toString("utf-8")}return tr(e,"utf-8")}return t}async function G(t,e,o,r){try{return await k(t,e)}catch(n){g(o,r,n,m.NetworkError),l(m.NetworkError)}}function K(t,e,o){let r=t.body?.error,n=r?.code??"unknown",i=r?.message??t.statusText,s=or(n,t.status,r?.details),a=A(t.status);e.json?g(e,o,Object.assign(new Error(i),{code:n,status:t.status,details:r?.details,advice:s}),a):(process.stderr.write(`\u2716 ${o}: ${i} (${n}, ${t.status})
55
- `),s&&process.stderr.write(` \u2192 ${s}
56
- `))}function or(t,e,o){let r=new I(e,{code:t,message:"",details:o&&typeof o=="object"?o:void 0}),n=Te(r);return n||(e===404?"Project or composition not found. Run `cueframe list` to confirm the project ID; the composition may not yet exist.":null)}import{readFile as ti}from"fs/promises";async function de(t,e){let o=e.map(s=>s==null?"null":String(s)).join(":"),r=`${t}:${o}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}var ht=1500,rr=1800*1e3;async function*nr(t,e,o){let r=Re();if(!r?.baseUrl)throw new Error("cueframe: createClient({baseUrl}) must be called before iterComposeEvents.");let n=r.baseUrl.replace(/\/$/,"")+`/v1/projects/${encodeURIComponent(t)}/compose/jobs/${encodeURIComponent(e)}/stream`,i=new Headers({accept:"text/event-stream",...r.headers??{}});r.apiKey&&!i.has("authorization")&&i.set("authorization",`Bearer ${r.apiKey}`);let a=await(r.fetch??fetch)(n,{method:"GET",headers:i,signal:o});if(!a.ok){let d;try{d=(await a.json()).error??{code:"unknown",message:a.statusText}}catch{d={code:"unknown",message:a.statusText}}throw new I(a.status,d,a.headers.get("x-request-id")??void 0)}if(!a.body)throw new Error("SSE response has no body");let f=a.body.getReader(),u=new TextDecoder("utf-8"),c="";try{for(;;){let{value:d,done:h}=await f.read();if(h)break;c+=u.decode(d,{stream:!0});let x=c.indexOf(`
57
-
58
- `);for(;x!==-1;){let b=c.slice(0,x);c=c.slice(x+2);let _=ir(b);_&&(yield _),x=c.indexOf(`
59
-
60
- `)}}}finally{try{f.releaseLock()}catch{}}}function ir(t){if(!t.trim())return null;let e=null,o=[];for(let n of t.split(`
61
- `)){if(!n||n.startsWith(":"))continue;let i=n.indexOf(":");if(i===-1)continue;let s=n.slice(0,i),a=n.slice(i+1).replace(/^ /,"");s==="event"?e=a:s==="data"&&o.push(a)}if(!e||o.length===0||e!=="compose_event")return null;let r;try{r=JSON.parse(o.join(`
62
- `))}catch{return null}return{event:e,data:r}}async function sr(t,e,o={}){let r=Date.now()+(o.timeoutMs??rr);for(;Date.now()<r;){let n=null;try{for await(let i of nr(t,e)){if(o.onTypedEvent?.(i.data),i.data.event==="checkpoint_reached"){let s=i.data.data;n={kind:"checkpoint",...s.checkpointId?{checkpointId:s.checkpointId}:{},stage:String(s.stage??""),version:Number(s.version??0),...s.artifactSummary?{artifactSummary:s.artifactSummary}:{}};break}if(i.data.event==="job_completed"){let s=i.data.data;n={kind:"complete",compositionId:s.compositionId??null,etag:s.etag??null};break}if(i.data.event==="job_failed"){let a=i.data.data.reason??"compose_failed";a==="cancelled"||a.startsWith("cancelled")?n={kind:"cancelled",reason:a}:n={kind:"error",message:a};break}}}catch(i){if(i instanceof I)throw i;await new Promise(s=>setTimeout(s,ht));continue}if(n)return n;await new Promise(i=>setTimeout(i,ht))}return{kind:"error",message:`Timed out waiting for compose to reach terminal state. ComposeJob: ${e}, Project: ${t}.`}}async function yt(t,e){E(t,"suggestionId",e),E(e.project,"projectId",e),w(e.target),p(e,"compose_prepare",{suggestionId:t,projectId:e.project,target:e.target});let o=e.idempotencyKey??await de("compose",[e.project,t,e.seed??"auto"]);p(e,"idempotency_key",{scope:"compose",key:o,overridden:!!e.idempotencyKey,seed:e.seed??null});let r=C(`Starting compose for ${t}\u2026`,e.json),n,i=!1;try{let u={suggestionId:t};if(e.critique!==void 0&&(u.critique=e.critique),e.clientNonce!==void 0&&(u.clientNonce=e.clientNonce),e.baseline!==void 0&&(u.parentJobId=e.baseline),e.maxCandidates!==void 0&&(u.maxCandidates=e.maxCandidates),e.holdAt!==void 0&&e.holdAt.length>0&&(u.holdAt=e.holdAt),e.seed!==void 0){let d=Number(e.seed);Number.isInteger(d)&&(u.seed=d)}let c=await k(`/v1/projects/${e.project}/compose`,{method:"POST",headers:{"content-type":"application/json","idempotency-key":o},body:JSON.stringify(u)});if(c.status>=400){let d=c.body?.error,h=d?.message??c.statusText;throw new I(c.status,{code:d?.code??"unknown",message:h})}n=c.body,i=c.headers["idempotency-replay"]==="true"}catch(u){r.fail(`Failed to start compose: ${v(u)}`),g(e,"compose_create",u,y(u)),l(y(u))}i?(p(e,"compose_idempotent_replay",{composeJobId:n.composeJobId,projectId:n.projectId,workflowId:n.workflowId,idempotencyKey:o}),r.text=`Compose already in flight or complete (job ${n.composeJobId})\u2026`):(p(e,"compose_started",{composeJobId:n.composeJobId,projectId:n.projectId,workflowId:n.workflowId}),r.text=`Composing (job ${n.composeJobId})\u2026`);let s,a,f=Date.now();try{s=await sr(e.project,n.composeJobId,{onTypedEvent:u=>{if(p(e,`compose:${u.event}`,{composeJobId:n.composeJobId,...u.data,timestamp:u.timestamp}),e.json)return;let c=Math.round((Date.now()-f)/1e3),d=u.data;if(u.event==="job_started")r.text=`Composing\u2026 ${d.candidateCount??"?"} candidates (${c}s)`;else if(u.event==="candidate_phase_started")r.text=`Candidate ${d.candidateIndex} starting (${c}s)`;else if(u.event==="candidate_phase_evaluated"){let h=d.perCriterion,x=h?`E${(h.editorial?.score??0).toFixed(1)} S${(h.spatial?.score??0).toFixed(1)} B${(h.brand?.score??0).toFixed(1)} C${(h.caption?.score??0).toFixed(1)}`:"";r.text=`Candidate ${d.candidateIndex} evaluated \xB7 ${x} (${c}s)`}else if(u.event==="critique_retry_started")r.text=`Candidate ${d.candidateIndex} retry ${d.attemptNumber} (${c}s)`;else if(u.event==="candidate_completed"){let h=typeof d.composite=="number"?d.composite.toFixed(2):"?";r.text=`Candidate ${d.candidateIndex} done \xB7 composite ${h} (${c}s)`}else if(u.event==="winner_selected"){let h=typeof d.composite=="number"?d.composite.toFixed(2):"?";(d.route==="publish"||d.route==="handoff")&&(a=d.route);let x=a==="handoff"?" \xB7 \u2691 handoff":a==="publish"?" \xB7 \u2713 publish":"";r.text=`Picked candidate ${d.candidateIndex} \xB7 composite ${h}${x} (${c}s)`}}})}catch(u){r.fail(`Compose watch failed: ${v(u)}`),g(e,"compose_watch",u,y(u)),l(y(u))}if(s.kind==="checkpoint"){r.warn(`Compose paused at the "${s.stage}" checkpoint (version ${s.version}) \u2014 awaiting your review.`),p(e,"compose_checkpoint",{composeJobId:n.composeJobId,projectId:e.project,...s.checkpointId?{checkpointId:s.checkpointId}:{},stage:s.stage,version:s.version,...s.artifactSummary?{artifactSummary:s.artifactSummary}:{}}),e.json||(console.log(`
63
- Stage "${s.stage}" (version ${s.version}) is ready for review.`),s.artifactSummary&&console.log(` ${s.artifactSummary}`),s.checkpointId?(console.log(`
64
- Review the packet (artifact, stills, verdicts, quote):`),console.log(` GET /v1/checkpoints/${s.checkpointId}`),console.log(" Then answer it:"),console.log(` cueframe compose resume ${s.checkpointId} --approve -t ${e.target} (or --revise --comments @notes.json [--edits @edits.json] / --abandon)`)):(console.log(`
65
- Inspect it:`),console.log(` cueframe compose inspect ${n.composeJobId} --project ${e.project} -t ${e.target}`)));return}if(s.kind==="complete"){r.succeed(`Compose complete (job ${n.composeJobId})`),p(e,"compose_complete",{composeJobId:n.composeJobId,projectId:e.project,compositionId:s.compositionId,etag:s.etag}),e.json||(console.log(`
66
- Project: ${e.project}`),s.compositionId&&console.log(` Composition: ${s.compositionId}`),s.etag&&console.log(` ETag: ${s.etag}`),a==="publish"?console.log(" Verdict: \u2713 publish \u2014 clears the quality bar, ships autonomously"):a==="handoff"&&console.log(" Verdict: \u2691 handoff \u2014 below bar / floor violation; review in your NLE before publishing"),console.log(`
67
- \u2192 Render with: cueframe render ${e.project} -t ${e.target}`));return}s.kind==="cancelled"&&(r.warn(`Compose cancelled: ${s.reason}`),p(e,"compose_cancelled",{composeJobId:n.composeJobId,reason:s.reason}),l(m.UserError)),r.fail(`Compose failed: ${s.message}`),g(e,"compose_run",new Error(s.message),m.ApiServerError),l(m.ApiServerError)}async function wt(t){let e=t.aspect?{aspectRatio:t.aspect,fps:t.fps??30,resolution:t.resolution??"fhd"}:void 0;if(t.dryRun){if(p(t,"project_create_dry_run",{name:t.name,target:t.target,format:e??null,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1,wouldCall:t.fromSuggestion?t.cheap?"POST /v1/projects \u2192 POST /v1/projects/:id/composition/from-suggestion (sync translator)":"POST /v1/projects \u2192 POST /v1/projects/:id/compose (async) \u2192 SSE watch":"POST /v1/projects"}),!t.json){let n=t.cheap?" (--cheap: deterministic translator)":"";console.log(`[dry-run] Would create project "${t.name}" on ${t.target}`+(t.fromSuggestion?` from suggestion ${t.fromSuggestion}${n}.`:"."))}return}w(t.target),p(t,"project_create_prepare",{name:t.name,target:t.target,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1});let o=C(`Creating project "${t.name}"\u2026`,t.json),r;try{r=await L.createProject({name:t.name,format:e}),o.succeed(`Created: ${r.id}`)}catch(n){o.fail(`Failed: ${v(n)}`),g(t,"project_create",n,y(n)),l(y(n))}if(p(t,"project_create_complete",{project:r}),!t.json&&!t.fromSuggestion&&console.log(`
68
- ${r.id} ${r.name}`),t.fromSuggestion&&(t.cheap?await ce(r.id,{target:t.target,suggestionId:t.fromSuggestion,json:t.json,force:!0}):await yt(t.fromSuggestion,{target:t.target,project:r.id,json:t.json}),!t.json)){let n=t.cheap?"(--cheap)":"(composed)";console.log(`
69
- ${r.id} ${r.name} \u2190 composed from ${t.fromSuggestion} ${n}`)}}async function bt(t,e){E(t,"projectId",e),w(e.target),p(e,"project_delete_prepare",{projectId:t});try{await L.deleteProject(t),p(e,"project_delete_complete",{projectId:t}),j(e,{ok:!0,projectId:t},()=>{console.log(`Project ${t} deleted.`)})}catch(o){g(e,"project_delete",o,y(o)),e.json||console.error(`\u2716 project delete: ${v(o)}`),l(y(o))}}async function vt(t,e){E(t,"mediaId",e),w(e.target),p(e,"media_delete_prepare",{mediaId:t});try{await F.deleteMedia(t),p(e,"media_delete_complete",{mediaId:t}),j(e,{ok:!0,mediaId:t},()=>{console.log(`Media ${t} deleted.`)})}catch(o){g(e,"media_delete",o,y(o)),e.json||console.error(`\u2716 media delete: ${v(o)}`),l(y(o))}}import{writeFileSync as ar}from"fs";import{resolve as cr}from"path";var jt=1500,dr=4e3,mr=1800*1e3;async function me(t,e,o={}){let r=Date.now()+(o.timeoutMs??mr),n=Date.now();for(;Date.now()<r;){let i=null,s=!1;try{for await(let a of Oe(t,e)){if(a.event==="progress"){let f=Math.round((Date.now()-n)/1e3);if(o.spinner){let u=Math.round(a.data.percent*100);o.spinner.text=`Rendering\u2026 ${a.data.phase}${u>0?` \xB7 ${u}%`:""} (${f}s)`}o.onProgress?.({phase:a.data.phase,percent:a.data.percent,elapsedSec:f});continue}a.event==="complete"?i={kind:"complete",outputUrl:a.data.outputUrl,outputExpiresAt:a.data.outputExpiresAt,duration:a.data.duration}:i={kind:"failed",message:a.data.message};break}}catch(a){if(a instanceof I)s=!0;else{await new Promise(f=>setTimeout(f,jt));continue}}if(i)return i;if(s){let a=await lr(t,e);if(a)return a;await new Promise(f=>setTimeout(f,dr));continue}await new Promise(a=>setTimeout(a,jt))}return{kind:"failed",message:`Timed out waiting for render to reach a terminal state. Render ID: ${e}, Project ID: ${t}.`}}async function lr(t,e){let o=await Pe.getRender(t,e);return o.status==="complete"?{kind:"complete",outputUrl:o.outputUrl??null,outputExpiresAt:null,duration:null}:o.status==="error"||o.status==="cancelled"?{kind:"failed",message:o.error??`Render ${o.status}`}:null}async function Et(t,e){E(t,"renderId",e),E(e.project,"projectId",e),w(e.target),p(e,"render_watch_prepare",{renderId:t,projectId:e.project,target:e.target});let o=C(`Watching render ${t}\u2026`,e.json),r;try{r=await me(e.project,t,{spinner:o,onProgress:i=>p(e,"render_progress",{renderId:t,...i})})}catch(i){o.fail(`Failed to watch render: ${v(i)}`),g(e,"render_watch",i,y(i)),l(y(i))}r.kind==="failed"&&(o.fail(r.message),g(e,"render_watch",new Error(r.message),m.ApiServerError),l(m.ApiServerError)),o.succeed(`Render complete (${t})`);let n=null;e.download&&r.outputUrl?n=await le(r.outputUrl,e.out??`./reel-${t.slice(0,8)}.mp4`,e.json):r.outputUrl||(g(e,"render_watch",new Error("Render reported complete but no outputUrl was returned."),m.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
70
- Re-fetch via GET /v1/projects/${e.project}/renders/${t}.`),l(m.ApiServerError)),p(e,"render_complete",{renderId:t,projectId:e.project,outputUrl:r.outputUrl,outputExpiresAt:r.outputExpiresAt,duration:r.duration,outputPath:n}),e.json||(r.outputUrl&&console.log(`MP4 URL: ${r.outputUrl}`),r.outputExpiresAt&&console.log(`Expires: ${r.outputExpiresAt}`),r.duration!=null&&console.log(`Duration: ${r.duration}s`))}async function le(t,e,o){let r=cr(e),n=C(`Downloading \u2192 ${r}\u2026`,o);try{let i=await fetch(t);if(!i.ok)throw new Error(`HTTP ${i.status}`);let s=Buffer.from(await i.arrayBuffer());return ar(r,s),n.succeed(`Saved: ${r} (${(s.length/1024/1024).toFixed(1)} MB)`),r}catch(i){n.fail(`Download failed: ${v(i)}`),console.error(`
71
- MP4 URL (1-hour TTL): ${t}`),l(m.NetworkError)}}async function ur(t){let e=await k(`/v1/projects/${t}/composition`,{method:"GET"});return e.status===404?"no-composition":e.status>=400?"unknown-composition":e.headers.etag??"no-etag"}async function xt(t,e){if(E(t,"projectId",e),e.dryRun){p(e,"render_dry_run",{projectId:t,target:e.target,wouldCall:"POST /v1/projects/:id/renders \u2192 SSE watch \u2192 download MP4"}),e.json||console.log(`[dry-run] Would render project ${t} on ${e.target}.`);return}w(e.target),p(e,"render_prepare",{projectId:t,target:e.target});let o;try{o=e.idempotencyKey??await de("render",[t,await ur(t)]),p(e,"idempotency_key",{scope:"render",key:o,overridden:!!e.idempotencyKey})}catch(c){o="",p(e,"idempotency_key",{scope:"render",key:null,skipped:!0,reason:c instanceof Error?c.message:String(c)})}let r=C("Queuing render\u2026",e.json),n,i,s=!1;try{let c=e.aspect?{format:{aspectRatio:e.aspect,fps:e.fps??30,resolution:e.resolution??"fhd"}}:{};e.priority&&(c.priority=e.priority),e.intent&&(c.intent=e.intent);let d={"content-type":"application/json"};o&&(d["idempotency-key"]=o);let h=await k(`/v1/projects/${t}/renders`,{method:"POST",headers:d,body:JSON.stringify(c)});if(h.status>=400){let b=h.body?.error;throw new I(h.status,{code:b?.code??"unknown",message:b?.message??h.statusText})}let x=h.body;n=x.id,i=x.status,s=h.headers["idempotency-replay"]==="true",r.succeed(s?`Render replayed: ${n} (status: ${i})`:`Render queued: ${n}`)}catch(c){r.fail(`Failed: ${v(c)}`),g(e,"render_prepare",c,y(c)),l(y(c))}s?p(e,"render_idempotent_replay",{renderId:n,projectId:t,status:i,idempotencyKey:o}):p(e,"render_queued",{renderId:n,projectId:t});let a=C("Rendering\u2026",e.json),f;try{f=await me(t,n,{spinner:a,onProgress:c=>p(e,"render_progress",{renderId:n,...c})})}catch(c){a.fail(`Failed to watch render: ${v(c)}`),g(e,"render_progress",c,y(c)),l(y(c))}f.kind==="failed"&&(a.fail(f.message),g(e,"render_progress",new Error(f.message),m.ApiServerError),l(m.ApiServerError)),a.succeed("Render complete"),f.outputUrl||(g(e,"render_complete",new Error("Render reported complete but no outputUrl was returned."),m.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
72
- Render ID: ${n}
42
+ Run \`cueframe analyze ${a} --target ${e.target}\` to generate clip suggestions.`)})}function vt(t){let e=Math.floor(t/60),r=Math.floor(t%60);return`${e}:${String(r).padStart(2,"0")}`}async function pr(t,e){t!==void 0&&R(t,"mediaItemId",e),T(e.target),h(e,"clips_prepare",{target:e.target,mode:t?"suggestions":"media-list",...t?{mediaItemId:t}:{}});try{if(!t){let n=await oe.listMedia();if(h(e,"clips_complete",{mode:"media-list",count:n.data.length,media:n.data}),!e.json){if(n.data.length===0){console.log("No media items found. Import a video first.");return}console.log("Media items (pass the ID to `cueframe clips <id>`):"),console.log("");for(let o of n.data){let s=o.duration?`${vt(o.duration)} `:"",i=o.processingStatus?.phase??"unknown",a=i==="complete"?"":` [${i}]`;console.log(` ${o.id} ${o.name} ${s}${a}`)}}return}let r=await $t.listMediaSuggestions(t);if(h(e,"clips_complete",{mode:"suggestions",mediaItemId:t,count:r.suggestions.length,suggestions:r.suggestions}),!e.json){if(r.suggestions.length===0){console.log("No clip suggestions found for this media item."),console.log("If analysis is still running, try again shortly. Otherwise the video may not have suitable clips.");return}console.log(`${r.suggestions.length} clip suggestion${r.suggestions.length!==1?"s":""}:`),console.log("");for(let n of r.suggestions){let o=`${vt(n.trim.start)} \u2192 ${vt(n.trim.end)}`,s=(n.trim.end-n.trim.start).toFixed(1);console.log(` ${n.id}`),console.log(` ${n.title}`),console.log(` ${o} (${s}s) ${n.format} score: ${n.score}`),n.reason&&console.log(` ${n.reason}`),console.log("")}}}catch(r){x(e,"clips",r,_(r)),m(_(r))}}import{readFileSync as rs}from"fs";async function gr(t,e){R(t,"projectId",e),T(e.target),h(e,"composition_get_prepare",{projectId:t});let r=await Ze(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_get");r.status>=400&&(We(r,e,"composition_get"),m(U(r.status)));let n=r.headers.etag,o=n&&vr(n);h(e,"composition_get_complete",{projectId:t,etag:o,status:r.status}),$(e,{etag:o,composition:r.body},()=>{o&&console.log(`# ETag: ${o}`),console.log(JSON.stringify(r.body,null,2))})}async function hr(t,e){R(t,"projectId",e),e.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),m(p.UserError)),T(e.target);let r=await _t(t,e),n=await _r(e.body);h(e,"composition_put_prepare",{projectId:t,ifMatch:r});let o=new Headers({"content-type":"application/json","if-match":r}),s=await Ze(`/v1/projects/${t}/composition`,{method:"PUT",headers:o,body:n},e,"composition_put");s.status>=400&&(We(s,e,"composition_put"),m(U(s.status)));let i=s.headers.etag;h(e,"composition_put_complete",{projectId:t,etag:i,status:s.status,response:s.body}),$(e,{etag:i,response:s.body},()=>{console.log(`Composition saved (ETag: ${i??"unknown"}).`),s.body&&typeof s.body=="object"&&console.log(JSON.stringify(s.body,null,2))})}async function ct(t,e){R(t,"projectId",e),e.suggestionId||(console.error("--suggestion <suggestionId> is required"),m(p.UserError)),T(e.target);let r=await _t(t,e),n;if(e.format)try{n=JSON.parse(e.format)}catch{console.error(`--format must be JSON, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`),m(p.UserError)}let o=JSON.stringify({suggestionId:e.suggestionId,...n?{format:n}:{}});h(e,"composition_from_suggestion_prepare",{projectId:t,suggestionId:e.suggestionId,ifMatch:r});let s,i=r,a=0,u=3;for(;;){a++;let c=new Headers({"content-type":"application/json","if-match":i});if(s=await Ze(`/v1/projects/${t}/composition/from-suggestion`,{method:"POST",headers:c,body:o},e,"composition_from_suggestion"),!(s.status===409&&s.body?.error?.code==="stale_etag"))break;if(a>u){h(e,"composition_from_suggestion_etag_retries_exhausted",{projectId:t,attempts:u});break}h(e,"composition_from_suggestion_etag_retry",{projectId:t,attempt:a,reason:"stale_etag"}),i=await _t(t,e)}s.status>=400&&(We(s,e,"composition_from_suggestion"),m(U(s.status)));let d=s.headers.etag;h(e,"composition_from_suggestion_complete",{projectId:t,suggestionId:e.suggestionId,etag:d,status:s.status,response:s.body,attempts:a}),$(e,{etag:d,response:s.body},()=>{console.log(`Composition built from suggestion ${e.suggestionId} (ETag: ${d??"unknown"}).`),s.body&&typeof s.body=="object"&&console.log(JSON.stringify(s.body,null,2))})}async function yr(t){t.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),m(p.UserError)),T(t.target);let e=await _r(t.body);h(t,"composition_validate_prepare",{});let r=new Headers({"content-type":"application/json"}),n=await Ze("/v1/composition/validate",{method:"POST",headers:r,body:e},t,"composition_validate");n.status>=400&&(We(n,t,"composition_validate"),m(U(n.status))),h(t,"composition_validate_complete",{status:n.status}),$(t,{valid:!0},()=>{console.log("\u2713 Composition is valid.")})}function vr(t){return t.replace(/^W\//,"").replace(/-gzip(?=("?)$)/,"")}async function _t(t,e){if(e.force)return"*";if(e.ifMatch)return e.ifMatch;let r=await Ze(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_etag_fetch");if(r.status===404)return J("No existing composition; treating as create (If-Match: *).",e),"*";r.status>=400&&(We(r,e,"composition_etag_fetch"),m(U(r.status)));let n=r.headers.etag;return n||(x(e,"composition_etag_fetch",new Error("Server returned no ETag on composition GET; cannot safely thread If-Match. Pass --force to overwrite anyway."),p.ApiServerError),m(p.ApiServerError)),vr(n)}async function _r(t){if(t.startsWith("@")){let e=t.slice(1);if(e==="-"){let r=[];for await(let n of process.stdin)r.push(Buffer.isBuffer(n)?n:Buffer.from(n));return Buffer.concat(r).toString("utf-8")}return rs(e,"utf-8")}return t}async function Ze(t,e,r,n){try{return await W(t,e)}catch(o){x(r,n,o,p.NetworkError),m(p.NetworkError)}}function We(t,e,r){let n=t.body?.error,o=n?.code??"unknown",s=n?.message??t.statusText,i=ns(o,t.status,n?.details),a=U(t.status);e.json?x(e,r,Object.assign(new Error(s),{code:o,status:t.status,details:n?.details,advice:i}),a):(process.stderr.write(`\u2716 ${r}: ${s} (${o}, ${t.status})
43
+ `),i&&process.stderr.write(` \u2192 ${i}
44
+ `))}function ns(t,e,r){let n=new Z(e,{code:t,message:"",details:r&&typeof r=="object"?r:void 0}),o=jt(n);return o||(e===404?"Project or composition not found. Run `cueframe list` to confirm the project ID; the composition may not yet exist.":null)}async function xr(t){let e=t.aspect?{aspectRatio:t.aspect,fps:t.fps??30,resolution:t.resolution??"fhd"}:void 0;if(t.dryRun){if(h(t,"project_create_dry_run",{name:t.name,target:t.target,format:e??null,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1,wouldCall:t.fromSuggestion?t.cheap?"POST /v1/projects \u2192 POST /v1/projects/:id/composition/from-suggestion (sync translator)":"POST /v1/projects \u2192 POST /v1/projects/:id/compose (async) \u2192 SSE watch":"POST /v1/projects"}),!t.json){let o=t.cheap?" (--cheap: deterministic translator)":"";console.log(`[dry-run] Would create project "${t.name}" on ${t.target}`+(t.fromSuggestion?` from suggestion ${t.fromSuggestion}${o}.`:"."))}return}T(t.target),h(t,"project_create_prepare",{name:t.name,target:t.target,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1});let r=P(`Creating project "${t.name}"\u2026`,t.json),n;try{n=await Se.createProject({name:t.name,format:e}),r.succeed(`Created: ${n.id}`)}catch(o){r.fail(`Failed: ${O(o)}`),A(t,"project_create",o,_(o)),m(_(o))}if(h(t,"project_create_complete",{project:n}),!t.json&&!t.fromSuggestion&&console.log(`
45
+ ${n.id} ${n.name}`),t.fromSuggestion){let o=!1;if(o||await ct(n.id,{target:t.target,suggestionId:t.fromSuggestion,json:t.json,force:!0}),!t.json){let s=o?"(composed)":"(translated)";console.log(`
46
+ ${n.id} ${n.name} \u2190 composed from ${t.fromSuggestion} ${s}`)}}}async function wr(t,e){R(t,"projectId",e),T(e.target),h(e,"project_delete_prepare",{projectId:t});try{await Se.deleteProject(t),h(e,"project_delete_complete",{projectId:t}),$(e,{ok:!0,projectId:t},()=>{console.log(`Project ${t} deleted.`)})}catch(r){x(e,"project_delete",r,_(r)),m(_(r))}}async function kr(t,e){R(t,"mediaId",e),T(e.target),h(e,"media_delete_prepare",{mediaId:t});try{await oe.deleteMedia(t),h(e,"media_delete_complete",{mediaId:t}),$(e,{ok:!0,mediaId:t},()=>{console.log(`Media ${t} deleted.`)})}catch(r){x(e,"media_delete",r,_(r)),m(_(r))}}import{writeFileSync as os}from"fs";import{resolve as ss}from"path";var is=1500,as=4e3,cs=1800*1e3,br=5;async function xt(t,e,r={}){let n=Date.now()+(r.timeoutMs??cs),o=r.reconnectBackoffMs??is,s=Date.now(),i=0;for(;Date.now()<n;){let a=null,u=!1;try{for await(let d of Tt(t,e)){if(i=0,d.event==="progress"){let c=Math.round((Date.now()-s)/1e3);if(r.spinner){let l=Math.round(d.data.percent*100);r.spinner.text=`Rendering\u2026 ${d.data.phase}${l>0?` \xB7 ${l}%`:""} (${c}s)`}r.onProgress?.({phase:d.data.phase,percent:d.data.percent,elapsedSec:c});continue}d.event==="complete"?a={kind:"complete",outputUrl:d.data.outputUrl,outputExpiresAt:d.data.outputExpiresAt,duration:d.data.duration}:a={kind:"failed",message:d.data.message};break}}catch(d){if(d instanceof Z)u=!0;else{if(i++,i>=br)throw Object.assign(new Error(`Render stream unreachable after ${br} consecutive transport failures: ${d instanceof Error?d.message:String(d)}`),{cause:d});await new Promise(c=>setTimeout(c,o));continue}}if(a)return a;if(u){let d=await ds(t,e);if(d)return d;await new Promise(c=>setTimeout(c,as));continue}await new Promise(d=>setTimeout(d,o))}return{kind:"failed",message:`Timed out waiting for render to reach a terminal state. Render ID: ${e}, Project ID: ${t}.`}}async function ds(t,e){let r=await Rt.getRender(t,e);return r.status==="complete"?{kind:"complete",outputUrl:r.outputUrl??null,outputExpiresAt:null,duration:null}:r.status==="error"||r.status==="cancelled"?{kind:"failed",message:r.error??`Render ${r.status}`}:null}async function Er(t,e){R(t,"renderId",e),R(e.project,"projectId",e),T(e.target),h(e,"render_watch_prepare",{renderId:t,projectId:e.project,target:e.target});let r=P(`Watching render ${t}\u2026`,e.json),n;try{n=await xt(e.project,t,{spinner:r,onProgress:s=>h(e,"render_progress",{renderId:t,...s})})}catch(s){r.fail(`Failed to watch render: ${O(s)}`),A(e,"render_watch",s,_(s)),m(_(s))}n.kind==="failed"&&(r.fail(n.message),A(e,"render_watch",new Error(n.message),p.ApiServerError),m(p.ApiServerError)),r.succeed(`Render complete (${t})`);let o=null;e.download&&n.outputUrl?o=await wt(n.outputUrl,e.out??`./reel-${t.slice(0,8)}.mp4`,e.json):n.outputUrl||(x(e,"render_watch",new Error("Render reported complete but no outputUrl was returned."),p.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
47
+ Re-fetch via GET /v1/projects/${e.project}/renders/${t}.`),m(p.ApiServerError)),h(e,"render_complete",{renderId:t,projectId:e.project,outputUrl:n.outputUrl,outputExpiresAt:n.outputExpiresAt,duration:n.duration,outputPath:o}),e.json||(n.outputUrl&&console.log(`MP4 URL: ${n.outputUrl}`),n.outputExpiresAt&&console.log(`Expires: ${n.outputExpiresAt}`),n.duration!=null&&console.log(`Duration: ${n.duration}s`))}async function wt(t,e,r){let n=ss(e),o=P(`Downloading \u2192 ${n}\u2026`,r);try{let s=await fetch(t);if(!s.ok)throw new Error(`HTTP ${s.status}`);let i=Buffer.from(await s.arrayBuffer());return os(n,i),o.succeed(`Saved: ${n} (${(i.length/1024/1024).toFixed(1)} MB)`),n}catch(s){o.fail(`Download failed: ${O(s)}`),console.error(`
48
+ MP4 URL (1-hour TTL): ${t}`),m(p.NetworkError)}}async function Sr(t,e){let r=e.map(i=>i==null?"null":String(i)).join(":"),n=`${t}:${r}`,o=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join("")}async function us(t){let e=await W(`/v1/projects/${t}/composition`,{method:"GET"});return e.status===404?"no-composition":e.status>=400?"unknown-composition":e.headers.etag??"no-etag"}async function Cr(t,e){if(R(t,"projectId",e),e.dryRun){h(e,"render_dry_run",{projectId:t,target:e.target,wouldCall:"POST /v1/projects/:id/renders \u2192 SSE watch \u2192 download MP4"}),e.json||console.log(`[dry-run] Would render project ${t} on ${e.target}.`);return}T(e.target),h(e,"render_prepare",{projectId:t,target:e.target});let r;try{r=e.idempotencyKey??await Sr("render",[t,await us(t)]),h(e,"idempotency_key",{scope:"render",key:r,overridden:!!e.idempotencyKey})}catch(c){r="",h(e,"idempotency_key",{scope:"render",key:null,skipped:!0,reason:c instanceof Error?c.message:String(c)})}let n=P("Queuing render\u2026",e.json),o,s,i=!1;try{let c=e.aspect?{format:{aspectRatio:e.aspect,fps:e.fps??30,resolution:e.resolution??"fhd"}}:{};e.priority&&(c.priority=e.priority),e.intent&&(c.intent=e.intent);let l={"content-type":"application/json"};r&&(l["idempotency-key"]=r);let S=await W(`/v1/projects/${t}/renders`,{method:"POST",headers:l,body:JSON.stringify(c)});if(S.status>=400){let ne=S.body?.error;throw new Z(S.status,{code:ne?.code??"unknown",message:ne?.message??S.statusText})}let I=S.body;o=I.id,s=I.status,i=S.headers["idempotency-replay"]==="true",n.succeed(i?`Render replayed: ${o} (status: ${s})`:`Render queued: ${o}`)}catch(c){n.fail(`Failed: ${O(c)}`),A(e,"render_prepare",c,_(c)),m(_(c))}i?h(e,"render_idempotent_replay",{renderId:o,projectId:t,status:s,idempotencyKey:r}):h(e,"render_queued",{renderId:o,projectId:t});let a=P("Rendering\u2026",e.json),u;try{u=await xt(t,o,{spinner:a,onProgress:c=>h(e,"render_progress",{renderId:o,...c})})}catch(c){a.fail(`Failed to watch render: ${O(c)}`),A(e,"render_progress",c,_(c)),m(_(c))}u.kind==="failed"&&(a.fail(u.message),A(e,"render_progress",new Error(u.message),p.ApiServerError),m(p.ApiServerError)),a.succeed("Render complete"),u.outputUrl||(x(e,"render_complete",new Error("Render reported complete but no outputUrl was returned."),p.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
49
+ Render ID: ${o}
73
50
  Project ID: ${t}
74
- Re-fetch via GET /v1/projects/${t}/renders/${n} once the URL is signed.`),l(m.ApiServerError));let u=await le(f.outputUrl,e.out??`./reel-${n.slice(0,8)}.mp4`,e.json);p(e,"render_complete",{renderId:n,projectId:t,outputUrl:f.outputUrl,outputExpiresAt:f.outputExpiresAt,duration:f.duration,outputPath:u})}import pr from"open";import{createAuthClient as fr}from"better-auth/client";import{deviceAuthorizationClient as gr}from"better-auth/client/plugins";async function St(t){let e=N(t.target),o=fr({baseURL:e,plugins:[gr()]}),r=C("Requesting device code\u2026",t.json),n;try{let{data:u,error:c}=await o.device.code({client_id:"cueframe-cli",scope:"openid profile email"});(c||!u)&&(r.fail(`Could not start login: ${c?.message??"unknown error"}`),l(m.NetworkError)),n=u}catch(u){r.fail(`Could not start login: ${u instanceof Error?u.message:String(u)}`),l(m.NetworkError)}r.succeed("Device code issued");let i=n.verification_uri_complete??n.verification_uri;T("",t),T(` Visit: ${i}`,t),T(` Code: ${n.user_code}`,t),T("",t);try{await pr(i)}catch{}let s=C("Waiting for approval in browser\u2026",t.json),a=Date.now()+n.expires_in*1e3,f=n.interval*1e3;for(;Date.now()<a;){await new Promise(u=>setTimeout(u,f));try{let{data:u,error:c}=await o.device.token({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:n.device_code,client_id:"cueframe-cli"});if(u?.access_token){let x=u.access_token;Z(x,t.target,t.url),s.succeed(`Logged in. Token saved for target "${t.target}".`),j(t,{ok:!0,target:t.target,apiUrl:e},()=>{});return}let d=u??c,h=d?.error;h==="authorization_pending"||(h==="slow_down"?f+=5e3:h==="access_denied"?(s.fail("Access denied in the browser."),l(m.UserError)):h==="expired_token"?(s.fail("Device code expired before approval. Run `cueframe login` again."),l(m.UserError)):h&&(s.fail(`Login failed: ${d?.error_description??h}`),l(m.ApiClientError)))}catch{}}s.fail("Timed out waiting for approval. Run `cueframe login` again."),l(m.UserError)}import{readFileSync as hr}from"fs";var Ct=new Set(["GET","POST","PUT","PATCH","DELETE"]);async function _t(t,e,o){let r=t.toUpperCase();Ct.has(r)||(console.error(`Unsupported method: ${t}. Allowed: ${[...Ct].join(", ")}.`),l(m.UserError)),e.startsWith("/")||(console.error(`Path must start with '/'. Got: ${e}`),l(m.UserError)),w(o.target);let n=br(o.header??[]),i=await vr(o.body,r);i!==void 0&&!n.has("content-type")&&n.set("content-type","application/json");let s;try{s=await k(e,{method:r,headers:n,body:i})}catch(a){console.error(a instanceof Error?a.message:String(a)),l(m.NetworkError)}wr(s,{include:!!o.include,json:!!o.json,method:r,path:e}),l(yr(s.status))}function yr(t){return t===402?m.PaymentRequired:t>=500?m.ApiServerError:t>=400?m.ApiClientError:m.Success}function wr(t,{include:e,json:o,method:r,path:n}){if(o){console.log(JSON.stringify({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}));return}if(e){process.stdout.write(`HTTP/1.1 ${t.status} ${t.statusText}
75
- `);for(let[i,s]of Object.entries(t.headers))process.stdout.write(`${i}: ${s}
51
+ Re-fetch via GET /v1/projects/${t}/renders/${o} once the URL is signed.`),m(p.ApiServerError));let d=await wt(u.outputUrl,e.out??`./reel-${o.slice(0,8)}.mp4`,e.json);h(e,"render_complete",{renderId:o,projectId:t,outputUrl:u.outputUrl,outputExpiresAt:u.outputExpiresAt,duration:u.duration,outputPath:d})}import ls from"open";import{createAuthClient as ms}from"better-auth/client";import{deviceAuthorizationClient as fs}from"better-auth/client/plugins";async function jr(t){let e=Ce(t.target),r=ms({baseURL:e,plugins:[fs()]}),n=P("Requesting device code\u2026",t.json),o;try{let{data:d,error:c}=await r.device.code({client_id:"cueframe-cli",scope:"openid profile email"});(c||!d)&&(n.fail(`Could not start login: ${c?.message??"unknown error"}`),m(p.NetworkError)),o=d}catch(d){n.fail(`Could not start login: ${d instanceof Error?d.message:String(d)}`),m(p.NetworkError)}n.succeed("Device code issued");let s=o.verification_uri_complete??o.verification_uri;J("",t),J(` Visit: ${s}`,t),J(` Code: ${o.user_code}`,t),J("",t);try{await ls(s)}catch{}let i=P("Waiting for approval in browser\u2026",t.json),a=Date.now()+o.expires_in*1e3,u=o.interval*1e3;for(;Date.now()<a;){await new Promise(d=>setTimeout(d,u));try{let{data:d,error:c}=await r.device.token({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:o.device_code,client_id:"cueframe-cli"});if(d?.access_token){let I=d.access_token;qe(I,t.target,t.url),i.succeed(`Logged in. Token saved for target "${t.target}".`),$(t,{ok:!0,target:t.target,apiUrl:e},()=>{});return}let l=d??c,S=l?.error;S==="authorization_pending"||(S==="slow_down"?u+=5e3:S==="access_denied"?(i.fail("Access denied in the browser."),m(p.UserError)):S==="expired_token"?(i.fail("Device code expired before approval. Run `cueframe login` again."),m(p.UserError)):S&&(i.fail(`Login failed: ${l?.error_description??S}`),m(p.ApiClientError)))}catch{}}i.fail("Timed out waiting for approval. Run `cueframe login` again."),m(p.UserError)}import{readFileSync as ps}from"fs";var Tr=new Set(["GET","POST","PUT","PATCH","DELETE"]);async function Or(t,e,r){let n=t.toUpperCase();Tr.has(n)||(x(r,"api",new Error(`Unsupported method: ${t}. Allowed: ${[...Tr].join(", ")}.`),p.UserError),m(p.UserError)),e.startsWith("/")||(x(r,"api",new Error(`Path must start with '/'. Got: ${e}`),p.UserError),m(p.UserError)),T(r.target);let o=hs(r.header??[]),s=await ys(r.body,n);s!==void 0&&!o.has("content-type")&&o.set("content-type","application/json");let i;try{i=await W(e,{method:n,headers:o,body:s})}catch(u){x(r,"api",u,_(u)),m(_(u))}gs(i,{include:!!r.include,json:!!r.json,method:n,path:e});let a=U(i.status);a!==p.Success&&x(r,"api",Object.assign(new Error(`${n} ${e} \u2192 ${i.status} ${i.statusText}`),{code:i.body?.error?.code,status:i.status}),a),process.exitCode=a}function gs(t,{include:e,json:r,method:n,path:o}){if(r){console.log(JSON.stringify({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}));return}if(e){process.stdout.write(`HTTP/1.1 ${t.status} ${t.statusText}
52
+ `);for(let[s,i]of Object.entries(t.headers))process.stdout.write(`${s}: ${i}
76
53
  `);process.stdout.write(`
77
- `),$t(t.body,t.status>=400);return}if(t.status===204||t.body===null){console.error(`${r} ${n} \u2192 ${t.status} (no content)`);return}$t(t.body,t.status>=400)}function $t(t,e){let o=e?process.stderr:process.stdout;t!=null&&(typeof t=="string"?o.write(t.endsWith(`
54
+ `),$r(t.body,t.status>=400);return}if(t.status===204||t.body===null){console.error(`${n} ${o} \u2192 ${t.status} (no content)`);return}$r(t.body,t.status>=400)}function $r(t,e){let r=e?process.stderr:process.stdout;t!=null&&(typeof t=="string"?r.write(t.endsWith(`
78
55
  `)?t:t+`
79
- `):o.write(JSON.stringify(t,null,2)+`
80
- `))}function br(t){let e=new Headers;for(let o of t){let r=o.indexOf(":");r===-1&&(console.error(`Invalid --header (expected "Name: value"): ${o}`),l(m.UserError));let n=o.slice(0,r).trim(),i=o.slice(r+1).trim();e.set(n,i)}return e}async function vr(t,e){if(t){if(t.startsWith("@")){let o=t.slice(1);return o==="-"?kt():hr(o,"utf-8")}return t}if(!(e==="GET"||e==="DELETE")&&!process.stdin.isTTY)return kt()}async function kt(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));return Buffer.concat(t).toString("utf-8")}var It=/#\/components\/schemas\/([A-Za-z0-9_]+)/g;function jr(t,e){let o=new Set,r=[e];for(;r.length;){let n=r.pop();if(o.has(n)||!(n in t))continue;o.add(n);let i=JSON.stringify(t[n]),s;for(It.lastIndex=0;s=It.exec(i);)r.push(s[1])}return o}function Er(t){let e=t?.paths??{};for(let o of Object.values(e))if(o?.put?.operationId==="putComposition"){let r=o.put?.requestBody?.content?.["application/json"]?.schema?.$ref,n=typeof r=="string"?r.match(/#\/components\/schemas\/(.+)$/):null;if(n)return n[1]}return null}async function Rt(t,e){t!=="composition"&&(console.error(`Unknown schema '${t}'. Supported: composition.`),l(m.UserError)),Ie({baseUrl:N(e.target)});let o;try{o=await k("/v1/openapi.json",{method:"GET"})}catch(u){g(e,"schema",u,m.NetworkError),l(m.NetworkError)}if(o.status>=400){let u=A(o.status);g(e,"schema",new Error(`Failed to fetch /v1/openapi.json (${o.status})`),u),l(u)}let r=o.body,n=r?.components?.schemas??{},i=Er(r);(!i||!(i in n))&&(g(e,"schema",new Error("Could not locate the composition schema in openapi.json (putComposition body ref not found)."),m.ApiServerError),l(m.ApiServerError));let s=jr(n,i);s.delete(i);let a={};for(let u of[...s].sort())a[u]=n[u];let f={name:i,schema:n[i],referenced:a};j(e,f,()=>{console.log(JSON.stringify(f,null,2))})}import{writeFileSync as xr}from"fs";import{resolve as Sr}from"path";var Tt=1800*1e3,Cr=5e3;async function $e(t,e){E(e.projectId,"projectId",e),E(e.suggestionId,"suggestionId",e),w(e.target),p(e,"export_prepare",{projectId:e.projectId,suggestionId:e.suggestionId,format:t,target:e.target});let o=C(`Queuing ${t} export\u2026`,e.json),r;try{r=(await(t==="fcpxml"?Q.createFcpxmlExport:Q.createPremiereExport)(e.projectId,{clipSuggestionId:e.suggestionId})).id,o.succeed(`Export queued: ${r}`)}catch(f){o.fail(`Failed: ${v(f)}`),g(e,"export_prepare",f,y(f)),l(y(f))}if(p(e,"export_queued",{exportId:r,projectId:e.projectId,format:t}),!e.wait){T(`Poll status with: cueframe api GET /v1/projects/${e.projectId}/exports/${r}`,e);return}let n=await $r(e.projectId,r,e);n.kind==="failed"&&(g(e,"export_progress",Object.assign(new Error(n.message),n.error?{details:n.error}:{}),m.ApiServerError),e.json||console.error(`Export failed: ${n.message}`),l(m.ApiServerError)),n.outputUrl||(g(e,"export_complete",new Error("Export reported complete but no outputUrl was returned."),m.ApiServerError),e.json||console.error(`Export reported complete but no outputUrl was returned.
81
- Export ID: ${r}
82
- Re-fetch via GET /v1/projects/${e.projectId}/exports/${r}.`),l(m.ApiServerError));let s=e.out??`./export-${r.slice(0,8)}.zip`,a=await kr(n.outputUrl,s,e.json);p(e,"export_complete",{exportId:r,projectId:e.projectId,format:t,outputUrl:n.outputUrl,outputExpiresAt:n.outputExpiresAt,outputSizeBytes:n.outputSizeBytes,trimCacheHit:n.trimCacheHit,outputPath:a})}async function $r(t,e,o){let r=Date.now()+(o.timeoutMs??Tt),n=o.pollIntervalMs??Cr,i=Date.now(),s=C("Exporting\u2026",o.json);try{for(;Date.now()<r;){let a;try{a=await Q.getExport(t,e)}catch(c){if(c instanceof I&&c.status>=500){await Ot(n);continue}throw s.fail(`Failed to poll: ${v(c)}`),c}let f=Math.round((Date.now()-i)/1e3),u=Math.round((a.progress??0)*100);if(s.text=`Exporting\u2026 ${a.status}${u>0?` \xB7 ${u}%`:""} (${f}s)`,p(o,"export_progress",{exportId:e,status:a.status,progress:a.progress,elapsedSec:f}),a.status==="complete")return s.succeed(`Export complete (${f}s)`),{kind:"complete",outputUrl:a.outputUrl??null,outputExpiresAt:a.outputExpiresAt??null,outputSizeBytes:a.outputSizeBytes??null,trimCacheHit:a.trimCacheHit??null};if(a.status==="error"||a.status==="cancelled"){let c=a.error?.message??`Export ${a.status}`;return s.fail(c),{kind:"failed",message:c,error:a.error?{phase:a.error.phase,retryable:!!a.error.retryable}:null}}await Ot(n)}return s.fail(`Timed out waiting for export (${Math.round((Date.now()-i)/1e3)}s)`),{kind:"failed",message:`Timed out after ${Math.round((o.timeoutMs??Tt)/1e3)}s`,error:null}}catch(a){g(o,"export_progress",a,y(a)),l(y(a))}}async function kr(t,e,o){let r=Sr(e),n=C(`Downloading \u2192 ${r}\u2026`,o);try{let i=await fetch(t);if(!i.ok)throw new Error(`HTTP ${i.status}`);let s=Buffer.from(await i.arrayBuffer());return xr(r,s),n.succeed(`Saved: ${r} (${(s.length/1024/1024).toFixed(1)} MB)`),r}catch(i){n.fail(`Download failed: ${v(i)}`),o||console.error(`
83
- Export URL (7-day TTL): ${t}`),l(m.NetworkError)}}function Ot(t){return new Promise(e=>setTimeout(e,t))}async function Pt(t){w(t.target),p(t,"sessions_list_prepare",{});try{let e=await q.listSessions();p(t,"sessions_list_complete",{count:e.data.length}),j(t,e,()=>{if(e.data.length===0){console.log("No sessions yet. Create one with `cueframe sessions create --name <n> --files <mediaId:role> \u2026`");return}for(let o of e.data){let r=o.muxStatus??"pending";console.log(`${o.id} ${o.fileCount} files mux:${r} ${o.name}`)}e.pagination.hasMore&&console.log(`# more \u2014 pass --after ${e.pagination.nextCursor} (raw via \`cueframe api\`)`)})}catch(e){g(t,"sessions_list",e,y(e)),t.json||console.error(`\u2716 sessions list: ${v(e)}`),l(y(e))}}async function At(t,e){E(t,"sessionId",e),w(e.target),p(e,"sessions_get_prepare",{sessionId:t});try{let o=await q.getSession(t);p(e,"sessions_get_complete",{sessionId:t}),j(e,o,()=>{console.log(JSON.stringify(o,null,2))})}catch(o){g(e,"sessions_get",o,y(o)),e.json||console.error(`\u2716 sessions get: ${v(o)}`),l(y(o))}}async function Ft(t){t.name||(console.error("--name is required"),l(m.UserError)),(!t.files||t.files.length===0)&&(console.error("At least one --file <mediaId:role> is required"),l(m.UserError));let e=t.files.map((o,r)=>{let n=o.indexOf(":");return n===-1&&(console.error(`--file[${r}] must be <mediaId>:<role>. Got: ${o}`),l(m.UserError)),{mediaId:o.slice(0,n).trim(),role:o.slice(n+1).trim()}});w(t.target),p(t,"sessions_create_prepare",{name:t.name,fileCount:e.length});try{let o=await q.createSession({name:t.name,files:e});p(t,"sessions_create_complete",{sessionId:o.id}),j(t,o,()=>{console.log(`Session created: ${o.id}`),console.log(JSON.stringify(o,null,2))})}catch(o){g(t,"sessions_create",o,y(o)),t.json||console.error(`\u2716 sessions create: ${v(o)}`),l(y(o))}}async function Mt(t,e){E(t,"sessionId",e),w(e.target),p(e,"sessions_delete_prepare",{sessionId:t});try{await q.deleteSession(t),p(e,"sessions_delete_complete",{sessionId:t}),j(e,{ok:!0,sessionId:t},()=>{console.log(`Session ${t} deleted.`)})}catch(o){g(e,"sessions_delete",o,y(o)),e.json||console.error(`\u2716 sessions delete: ${v(o)}`),l(y(o))}}function Ut(t){let e=t.commands.map(Ut);return{name:t.name(),description:t.description(),arguments:t.registeredArguments.map(o=>({name:o.name(),required:o.required,description:o.description})),options:t.options.map(o=>({flags:o.flags,description:o.description,...o.defaultValue!==void 0?{default:o.defaultValue}:{}})),...e.length>0?{subcommands:e}:{}}}function Dt(t,e){let o=t.commands.map(Ut);if(e.json){p(e,"describe_complete",{name:t.name(),version:t.version()??null,commands:o});return}console.log(`${t.name()} ${t.version()??""}`.trim());for(let r of o){console.log(`
84
- ${r.name} \u2014 ${r.description}`);for(let n of r.subcommands??[])console.log(` ${r.name} ${n.name} \u2014 ${n.description}`)}}function Nt(t){if(!t)return;let e=parseInt(t,10);if(e===24||e===30||e===60)return e;console.error(`Invalid --fps ${t}. Allowed: 24, 30, 60.`),l(m.UserError)}function Lt(){let t=new _r;t.name("cueframe").description("AI-assisted video editing and rendering").version("0.1.2").option("--json","Emit a structured JSON document on stdout instead of human-formatted output. Spinners are silenced.").option("--dry-run","Validate inputs and report what would happen \u2014 no API calls, no mutations. Applies to upload, analyze, project create, render.");let e=()=>t.opts();t.command("install").description('One-line setup: wire the CueFrame MCP server into every installed agent (Claude Code / Cursor / Codex / Claude Desktop) and install the agent skills. No API key \u2014 auth is a browser "Allow" on first call.').option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Ne({json:e().json,target:c.target,dryRun:e().dryRun})),t.command("init").description("Scaffold a CueFrame component workspace (cueframe.json + components dir) in the current repo, so `eject` / `new component` have a home and the render harness can discover them.").action(()=>ze({json:e().json,dryRun:e().dryRun})),t.command("eject").description("Fork a built-in CueFrame primitive into cueframe/components/<id> as owned, editable source (renders on CueFrame).").argument("<primitive>","Primitive id (e.g. cinematic-title, heroText)").option("-f, --force","Overwrite an existing ejected component dir").action((c,d)=>Ve(c,{json:e().json,dryRun:e().dryRun,force:d.force})),t.command("new").description("Scaffold new owned source in the component workspace").command("component").description("Scaffold a blank custom component in cueframe/components/<name>").argument("<name>","Component id (e.g. my-badge)").option("-f, --force","Overwrite an existing non-empty component dir").action((c,d)=>Ye(c,{json:e().json,dryRun:e().dryRun,force:d.force})),t.command("push").description("Publish a locally-authored component (cueframe/components/<id>/index.tsx) to CueFrame so it renders server-side. Upserts by id.").argument("[id]","Component id to push (omit and use `cueframe sync` to push all)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>tt(c,{target:d.target,json:e().json})),t.command("sync").description("Publish EVERY component in the workspace (cueframe/components/*) to CueFrame. Upserts each by id.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>ot({target:c.target,json:e().json}));let r=t.command("keys").description("Manage API keys. `keys create` mints a scoped key \u2014 run `cueframe login` first (keys cannot mint keys).");r.command("create").description("Mint a scoped API key (cf_*). Requires a logged-in session.").requiredOption("-n, --name <name>","Key name, e.g. vaaya-staging").option("-s, --scope <scope>","Comma-separated resource:actions, e.g. media:rw,projects:rw,renders:rw (resources: media,sessions,projects,renders,webhooks; actions r/w)").option("--preset <preset>","Scope preset instead of --scope: readonly (read all) | editall (read+write all)").option("--expires <days>","Expire after N days (default: never)").action(c=>nt({...c,json:e().json})),r.command("list").description("List your API keys.").action(()=>it({json:e().json})),r.command("revoke").description("Revoke an API key by id.").argument("<keyId>","Key id (from `cueframe keys list`)").action(c=>st(c,{json:e().json})),t.command("login").description("Browser-mediated sign-in (OAuth device flow). Recommended for laptops.").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action(c=>St({...c,json:e().json})),t.command("auth").description("Save a static API key (cf_live_\u2026 / cf_test_\u2026). Use for CI / headless environments.").argument("<api-key>","Your CueFrame API key").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action((c,d)=>{Z(c,d.target,d.url),e().json?console.log(JSON.stringify({ok:!0,target:d.target},null,2)):console.log(`API key saved for target "${d.target}"`)}),t.command("list").description("List projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-n, --limit <n>","Max projects to show","10").action(c=>at({target:c.target,limit:parseInt(c.limit),json:e().json}));let n=t.command("project").description("Project commands");n.command("create").description("Create a new project. With --from-suggestion, atomically build the composition from a clip suggestion in one round-trip \u2014 the project is then immediately renderable via `cueframe render <projectId>`.").requiredOption("-n, --name <name>","Project name").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9","9:16").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("--from-suggestion <sug>","Clip suggestion publicId (sug_\u2026) \u2014 atomically builds the composition after project creation so render needs no further args").option("--cheap","With --from-suggestion: use the deterministic translator (no LLM, ~100ms) instead of the AI authoring pass. Useful for tests / programmatic flows.").action(c=>wt({name:c.name,target:c.target,aspect:c.aspect,fps:Nt(c.fps),resolution:c.resolution,fromSuggestion:c.fromSuggestion,cheap:c.cheap,json:e().json,dryRun:e().dryRun})),n.command("delete").description("Permanently delete a project (irreversible cleanup \u2014 removes the composition and render history).").argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>bt(c,{target:d.target,json:e().json})),t.command("media").description("Media library cleanup commands").command("delete").description("Permanently delete a media item (irreversible cleanup \u2014 removes the source and its derived assets).").argument("<mediaId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>vt(c,{target:d.target,json:e().json})),t.command("upload").description("Upload a video file and process it").argument("<file>","Path to video file").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --analyze","Run clip analysis after processing completes").option("-r, --audio-role <role>","Declare the audio role (vo|music|sfx|ambience) \u2014 routes ingest enrichment: vo\u2192transcript, music\u2192beat grid, sfx/ambience\u2192envelope").action((c,d)=>dt(c,{target:d.target,analyze:d.analyze,audioRole:d.audioRole,json:e().json,dryRun:e().dryRun})),t.command("analyze").description("Trigger AI clip suggestion analysis for a media item").argument("<mediaItemId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-w, --wait","Wait for analysis to complete and show results").action((c,d)=>Fe(c,{target:d.target,wait:d.wait,json:e().json,dryRun:e().dryRun})),t.command("clips").description("List AI-generated clip suggestions for a media item").argument("[mediaItemId]","Media item ID (omit to list your media library)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>mt(c,{target:d.target,json:e().json}));let s=t.command("render").description("Render a project to MP4 (queues, watches via SSE, downloads). Renders whatever composition is saved on the project \u2014 build it first via `project create --from-suggestion` or `composition from-suggestion`.").allowExcessArguments(!1).argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9 (defaults to project format)").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("-o, --out <path>","Output file path (default: ./reel-<id>.mp4)").option("--idempotency-key <key>",'Override the auto-derived Idempotency-Key. Default: sha256("render:<projectId>:<currentCompositionETag>"). Pass a fresh UUID to force a new render row.').option("--priority <p>","Routing intent: interactive (low-latency, access-gated), standard (default), background (lowest queue weight).").option("--intent <i>","Encode-quality hint: preview (fast / low-bitrate, for editor scrubbing) or final (default, full Format).").action((c,d)=>xt(c,{target:d.target,aspect:d.aspect,fps:Nt(d.fps),resolution:d.resolution,out:d.out,json:e().json,dryRun:e().dryRun,...d.idempotencyKey?{idempotencyKey:d.idempotencyKey}:{},...d.priority?{priority:d.priority}:{},...d.intent?{intent:d.intent}:{}}));t.command("api").description("Raw API call against the v1 surface (escape hatch \u2014 like `gh api`).").argument("<method>","HTTP method: GET, POST, PUT, PATCH, DELETE").argument("<path>","API path starting with /v1, e.g. /v1/projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-b, --body <body>","Request body (inline JSON, @file.json to read from disk, @- for stdin)").option("-H, --header <header...>",'Additional header (repeatable), e.g. -H "If-Match: \\"abc\\""').option("-i, --include","Include response status line + headers in stdout (curl-style). Lets agents read ETag etc.").action((c,d,h)=>_t(c,d,{target:h.target,body:h.body,header:h.header,include:h.include,json:e().json})),t.command("schema").description("Print the live composition wire schema from the server (/v1/openapi.json) \u2014 discover the contract instead of guessing.").argument("[resource]","Schema to print (currently: composition)","composition").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>Rt(c,{target:d.target,json:e().json}));let a=t.command("composition").description("Read/write a project's composition. ETag is threaded automatically.");a.command("validate").description("Validate a composition body against the live schema WITHOUT saving or rendering. Returns per-field errors \u2014 author safely before paying for a render.").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>pt({target:c.target,body:c.body,json:e().json})),a.command("get").description("Fetch the project's composition and ETag").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>lt(c,{target:d.target,json:e().json})),a.command("put").description("Replace the composition. GETs ETag first for safe concurrent writes.").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite \u2014 may clobber concurrent edits)").action((c,d)=>ut(c,{target:d.target,body:d.body,ifMatch:d.ifMatch,force:d.force,json:e().json})),a.command("from-suggestion").description("Build the composition from an existing clip suggestion").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--format <json>",`Optional format override, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`).option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite)").action((c,d)=>ce(c,{target:d.target,suggestionId:d.suggestion,format:d.format,ifMatch:d.ifMatch,force:d.force,json:e().json})),s.command("watch").description("Reattach to an existing render and stream progress to terminal state").argument("<renderId>","Render ID (from `cueframe render` output)").requiredOption("-p, --project <projectId>","Project the render belongs to").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--no-download","Print the MP4 URL but skip downloading the file").option("-o, --out <path>","Output file path when downloading (default: ./reel-<id>.mp4)").action((c,d,h)=>{let x=h?.parent?.opts?.()?.target??d.target;return Et(c,{target:x,project:d.project,out:d.out,download:d.download!==!1,json:e().json})});let f=t.command("export").description("Hand the timeline off to a real NLE (Final Cut Pro / Premiere Pro)");f.command("fcpxml").description("Build a Final Cut Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,d)=>$e("fcpxml",{target:d.target,projectId:c,suggestionId:d.suggestion,out:d.out,wait:d.wait,json:e().json})),f.command("premiere").description("Build a Premiere Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,d)=>$e("premiere",{target:d.target,projectId:c,suggestionId:d.suggestion,out:d.out,wait:d.wait,json:e().json}));let u=t.command("sessions").description("Multi-file ingest sessions (camera A/B/screen \u2192 muxed composition)");u.command("list").description("List sessions in this org").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Pt({target:c.target,json:e().json})),u.command("get").description("Get a single session by ID").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>At(c,{target:d.target,json:e().json})),u.command("create").description("Create a session from one or more media files").requiredOption("-n, --name <name>","Session name").requiredOption("-f, --file <entry...>","Each entry is <mediaId>:<role> (repeatable)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Ft({target:c.target,name:c.name,files:c.file,json:e().json})),u.command("delete").description("Delete a session (server checks for compositions referencing it)").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>Mt(c,{target:d.target,json:e().json})),t.command("describe").description("Print the CLI command tree as structured JSON (agent introspection)").action(()=>Dt(t,{json:e().json})),t.parse()}Lt();
56
+ `):r.write(JSON.stringify(t,null,2)+`
57
+ `))}function hs(t){let e=new Headers;for(let r of t){let n=r.indexOf(":");n===-1&&(console.error(`Invalid --header (expected "Name: value"): ${r}`),m(p.UserError));let o=r.slice(0,n).trim(),s=r.slice(n+1).trim();e.set(o,s)}return e}async function ys(t,e){if(t){if(t.startsWith("@")){let r=t.slice(1);return r==="-"?Rr():ps(r,"utf-8")}return t}if(!(e==="GET"||e==="DELETE")&&!process.stdin.isTTY)return Rr()}async function Rr(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));return Buffer.concat(t).toString("utf-8")}var Ar=/#\/components\/schemas\/([A-Za-z0-9_]+)/g;function vs(t,e){let r=new Set,n=[e];for(;n.length;){let o=n.pop();if(r.has(o)||!(o in t))continue;r.add(o);let s=JSON.stringify(t[o]),i;for(Ar.lastIndex=0;i=Ar.exec(s);)n.push(i[1])}return r}function _s(t){let e=t?.paths??{};for(let r of Object.values(e))if(r?.put?.operationId==="putComposition"){let n=r.put?.requestBody?.content?.["application/json"]?.schema?.$ref,o=typeof n=="string"?n.match(/#\/components\/schemas\/(.+)$/):null;if(o)return o[1]}return null}async function Ir(t,e){t!=="composition"&&(console.error(`Unknown schema '${t}'. Supported: composition.`),m(p.UserError)),St({baseUrl:Ce(e.target)});let r;try{r=await W("/v1/openapi.json",{method:"GET"})}catch(d){x(e,"schema",d,p.NetworkError),m(p.NetworkError)}if(r.status>=400){let d=U(r.status);x(e,"schema",new Error(`Failed to fetch /v1/openapi.json (${r.status})`),d),m(d)}let n=r.body,o=n?.components?.schemas??{},s=_s(n);(!s||!(s in o))&&(x(e,"schema",new Error("Could not locate the composition schema in openapi.json (putComposition body ref not found)."),p.ApiServerError),m(p.ApiServerError));let i=vs(o,s);i.delete(s);let a={};for(let d of[...i].sort())a[d]=o[d];let u={name:s,schema:o[s],referenced:a};$(e,u,()=>{console.log(JSON.stringify(u,null,2))})}import{writeFileSync as xs}from"fs";import{resolve as ws}from"path";var Pr=1800*1e3,ks=5e3;async function kt(t,e){R(e.projectId,"projectId",e),R(e.suggestionId,"suggestionId",e),T(e.target),h(e,"export_prepare",{projectId:e.projectId,suggestionId:e.suggestionId,format:t,target:e.target});let r=P(`Queuing ${t} export\u2026`,e.json),n;try{n=(await(t==="fcpxml"?Be.createFcpxmlExport:Be.createPremiereExport)(e.projectId,{clipSuggestionId:e.suggestionId})).id,r.succeed(`Export queued: ${n}`)}catch(u){r.fail(`Failed: ${O(u)}`),A(e,"export_prepare",u,_(u)),m(_(u))}if(h(e,"export_queued",{exportId:n,projectId:e.projectId,format:t}),!e.wait){J(`Poll status with: cueframe api GET /v1/projects/${e.projectId}/exports/${n}`,e);return}let o=await bs(e.projectId,n,e);o.kind==="failed"&&(x(e,"export_progress",Object.assign(new Error(o.message),o.error?{details:o.error}:{}),p.ApiServerError),e.json||console.error(`Export failed: ${o.message}`),m(p.ApiServerError)),o.outputUrl||(x(e,"export_complete",new Error("Export reported complete but no outputUrl was returned."),p.ApiServerError),e.json||console.error(`Export reported complete but no outputUrl was returned.
58
+ Export ID: ${n}
59
+ Re-fetch via GET /v1/projects/${e.projectId}/exports/${n}.`),m(p.ApiServerError));let i=e.out??`./export-${n.slice(0,8)}.zip`,a=await Es(o.outputUrl,i,e.json);h(e,"export_complete",{exportId:n,projectId:e.projectId,format:t,outputUrl:o.outputUrl,outputExpiresAt:o.outputExpiresAt,outputSizeBytes:o.outputSizeBytes,trimCacheHit:o.trimCacheHit,outputPath:a})}async function bs(t,e,r){let n=Date.now()+(r.timeoutMs??Pr),o=r.pollIntervalMs??ks,s=Date.now(),i=P("Exporting\u2026",r.json);try{for(;Date.now()<n;){let a;try{a=await Be.getExport(t,e)}catch(c){if(c instanceof Z&&c.status>=500){await Nr(o);continue}throw i.fail(`Failed to poll: ${O(c)}`),c}let u=Math.round((Date.now()-s)/1e3),d=Math.round((a.progress??0)*100);if(i.text=`Exporting\u2026 ${a.status}${d>0?` \xB7 ${d}%`:""} (${u}s)`,h(r,"export_progress",{exportId:e,status:a.status,progress:a.progress,elapsedSec:u}),a.status==="complete")return i.succeed(`Export complete (${u}s)`),{kind:"complete",outputUrl:a.outputUrl??null,outputExpiresAt:a.outputExpiresAt??null,outputSizeBytes:a.outputSizeBytes??null,trimCacheHit:a.trimCacheHit??null};if(a.status==="error"||a.status==="cancelled"){let c=a.error?.message??`Export ${a.status}`;return i.fail(c),{kind:"failed",message:c,error:a.error?{phase:a.error.phase,retryable:!!a.error.retryable}:null}}await Nr(o)}return i.fail(`Timed out waiting for export (${Math.round((Date.now()-s)/1e3)}s)`),{kind:"failed",message:`Timed out after ${Math.round((r.timeoutMs??Pr)/1e3)}s`,error:null}}catch(a){x(r,"export_progress",a,_(a)),m(_(a))}}async function Es(t,e,r){let n=ws(e),o=P(`Downloading \u2192 ${n}\u2026`,r);try{let s=await fetch(t);if(!s.ok)throw new Error(`HTTP ${s.status}`);let i=Buffer.from(await s.arrayBuffer());return xs(n,i),o.succeed(`Saved: ${n} (${(i.length/1024/1024).toFixed(1)} MB)`),n}catch(s){o.fail(`Download failed: ${O(s)}`),r||console.error(`
60
+ Export URL (7-day TTL): ${t}`),m(p.NetworkError)}}function Nr(t){return new Promise(e=>setTimeout(e,t))}async function Mr(t){T(t.target),h(t,"sessions_list_prepare",{});try{let e=await Me.listSessions();h(t,"sessions_list_complete",{count:e.data.length}),$(t,e,()=>{if(e.data.length===0){console.log("No sessions yet. Create one with `cueframe sessions create --name <n> --files <mediaId:role> \u2026`");return}for(let r of e.data){let n=r.muxStatus??"pending";console.log(`${r.id} ${r.fileCount} files mux:${n} ${r.name}`)}e.pagination.hasMore&&console.log(`# more \u2014 pass --after ${e.pagination.nextCursor} (raw via \`cueframe api\`)`)})}catch(e){x(t,"sessions_list",e,_(e)),m(_(e))}}async function Ur(t,e){R(t,"sessionId",e),T(e.target),h(e,"sessions_get_prepare",{sessionId:t});try{let r=await Me.getSession(t);h(e,"sessions_get_complete",{sessionId:t}),$(e,r,()=>{console.log(JSON.stringify(r,null,2))})}catch(r){x(e,"sessions_get",r,_(r)),m(_(r))}}async function Fr(t){t.name||(console.error("--name is required"),m(p.UserError)),(!t.files||t.files.length===0)&&(console.error("At least one --file <mediaId:role> is required"),m(p.UserError));let e=t.files.map((r,n)=>{let o=r.indexOf(":");return o===-1&&(console.error(`--file[${n}] must be <mediaId>:<role>. Got: ${r}`),m(p.UserError)),{mediaId:r.slice(0,o).trim(),role:r.slice(o+1).trim()}});T(t.target),h(t,"sessions_create_prepare",{name:t.name,fileCount:e.length});try{let r=await Me.createSession({name:t.name,files:e});h(t,"sessions_create_complete",{sessionId:r.id}),$(t,r,()=>{console.log(`Session created: ${r.id}`),console.log(JSON.stringify(r,null,2))})}catch(r){x(t,"sessions_create",r,_(r)),m(_(r))}}async function Dr(t,e){R(t,"sessionId",e),T(e.target),h(e,"sessions_delete_prepare",{sessionId:t});try{await Me.deleteSession(t),h(e,"sessions_delete_complete",{sessionId:t}),$(e,{ok:!0,sessionId:t},()=>{console.log(`Session ${t} deleted.`)})}catch(r){x(e,"sessions_delete",r,_(r)),m(_(r))}}function Lr(t){let e=t.commands.map(Lr);return{name:t.name(),description:t.description(),arguments:t.registeredArguments.map(r=>({name:r.name(),required:r.required,description:r.description})),options:t.options.map(r=>({flags:r.flags,description:r.description,...r.defaultValue!==void 0?{default:r.defaultValue}:{}})),...e.length>0?{subcommands:e}:{}}}function zr(t,e){let r=t.commands.map(Lr);if(e.json){h(e,"describe_complete",{name:t.name(),version:t.version()??null,commands:r});return}console.log(`${t.name()} ${t.version()??""}`.trim());for(let n of r){console.log(`
61
+ ${n.name} \u2014 ${n.description}`);for(let o of n.subcommands??[])console.log(` ${n.name} ${o.name} \u2014 ${o.description}`)}}var Zr=["prod","dev","local"];function D(t){if(t===void 0)return"prod";if(Zr.includes(t))return t;console.error(`Invalid --target ${t}. Allowed: ${Zr.join(", ")}.`),m(p.UserError)}function Wr(t){if(!t)return;let e=parseInt(t,10);if(e===24||e===30||e===60)return e;console.error(`Invalid --fps ${t}. Allowed: 24, 30, 60.`),m(p.UserError)}async function Vr(){let t=new Ss;t.name("cueframe").description("AI-assisted video editing and rendering").version("0.4.3").option("--json","Emit a structured JSON document on stdout instead of human-formatted output. Spinners are silenced.").option("--dry-run","Validate inputs and report what would happen \u2014 no API calls, no mutations. Applies to upload, analyze, project create, render.");let e=()=>t.opts();t.command("install").description('One-line setup: wire the CueFrame MCP server into every installed agent (Claude Code / Cursor / Codex) and install the agent skills. No API key \u2014 auth is a browser "Allow" on first call.').option("-t, --target <target>","Target environment: prod (default), dev, local").option("-f, --force","Overwrite skills that are already installed in ~/.claude/skills").action(c=>Pt({json:e().json,target:D(c.target),dryRun:e().dryRun,force:c.force})),t.command("init").description("Scaffold a CueFrame component workspace (cueframe.json + components dir) in the current repo, so `new component` has a home and the render harness can discover it.").action(()=>Ut({json:e().json,dryRun:e().dryRun})),t.command("new").description("Scaffold new owned source in the component workspace").command("component").description("Scaffold a blank custom component in cueframe/components/<name>").argument("<name>","Component id (e.g. my-badge)").option("-f, --force","Overwrite an existing non-empty component dir").action((c,l)=>Qt(c,{json:e().json,dryRun:e().dryRun,force:l.force})),t.command("push").description("Publish a locally-authored component (cueframe/components/<id>/index.tsx) to CueFrame so it renders server-side. Upserts by id.").argument("[id]","Component id to push (omit and use `cueframe sync` to push all)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>rr(c,{target:D(l.target),json:e().json})),t.command("sync").description("Publish EVERY component in the workspace (cueframe/components/*) to CueFrame. Upserts each by id.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>nr({target:D(c.target),json:e().json}));let n=t.command("keys").description("Manage API keys. `keys create` mints a scoped key \u2014 run `cueframe login` first (keys cannot mint keys).");n.command("create").description("Mint a scoped API key (cf_*). Requires a logged-in session.").requiredOption("-n, --name <name>","Key name, e.g. ci-runner").option("-s, --scope <scope>","Comma-separated resource:actions, e.g. media:rw,projects:rw,renders:rw (resources: media,sessions,projects,renders,webhooks; actions r/w)").option("--preset <preset>","Scope preset instead of --scope: readonly (read all) | editall (read+write all)").option("--expires <days>","Expire after N days (default: never)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>sr({...c,target:D(c.target),json:e().json})),n.command("list").description("List your API keys.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>ir({target:D(c.target),json:e().json})),n.command("revoke").description("Revoke an API key by id.").argument("<keyId>","Key id (from `cueframe keys list`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>ar(c,{target:D(l.target),json:e().json})),t.command("login").description("Browser-mediated sign-in (OAuth device flow). Recommended for laptops.").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action(c=>jr({...c,target:D(c.target),json:e().json})),t.command("auth").description("Save a static API key (cf_live_\u2026 / cf_test_\u2026). Use for CI / headless environments.").argument("<api-key>","Your CueFrame API key").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action((c,l)=>{let S=D(l.target);qe(c,S,l.url),e().json?console.log(JSON.stringify({ok:!0,target:S},null,2)):console.log(`API key saved for target "${S}"`)}),t.command("list").description("List projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-n, --limit <n>","Max projects to show","10").action(c=>cr({target:D(c.target),limit:parseInt(c.limit),json:e().json}));let o=t.command("project").description("Project commands");o.command("create").description("Create a new project. With --from-suggestion, atomically build the composition from a clip suggestion in one round-trip \u2014 the project is then immediately renderable via `cueframe render <projectId>`.").requiredOption("-n, --name <name>","Project name").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9","9:16").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("--from-suggestion <sug>","Clip suggestion publicId (sug_\u2026) \u2014 atomically builds the composition after project creation so render needs no further args").option("--cheap","With --from-suggestion: use the deterministic translator (no LLM, ~100ms) instead of the AI authoring pass. Useful for tests / programmatic flows.").action(c=>xr({name:c.name,target:D(c.target),aspect:c.aspect,fps:Wr(c.fps),resolution:c.resolution,fromSuggestion:c.fromSuggestion,cheap:c.cheap,json:e().json,dryRun:e().dryRun})),o.command("delete").description("Permanently delete a project (irreversible cleanup \u2014 removes the composition and render history).").argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>wr(c,{target:D(l.target),json:e().json})),t.command("media").description("Media library cleanup commands").command("delete").description("Permanently delete a media item (irreversible cleanup \u2014 removes the source and its derived assets).").argument("<mediaId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>kr(c,{target:D(l.target),json:e().json})),t.command("upload").description("Upload a video file and process it").argument("<file>","Path to video file").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --analyze","Run clip analysis after processing completes").option("-r, --audio-role <role>","Declare the audio role (vo|music|sfx|ambience) \u2014 routes ingest enrichment: vo\u2192transcript, music\u2192beat grid, sfx/ambience\u2192envelope").action((c,l)=>fr(c,{target:D(l.target),analyze:l.analyze,audioRole:l.audioRole,json:e().json,dryRun:e().dryRun})),t.command("analyze").description("Trigger AI clip suggestion analysis for a media item").argument("<mediaItemId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-w, --wait","Wait for analysis to complete and show results").action((c,l)=>Ot(c,{target:D(l.target),wait:l.wait,json:e().json,dryRun:e().dryRun})),t.command("clips").description("List AI-generated clip suggestions for a media item").argument("[mediaItemId]","Media item ID (omit to list your media library)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>pr(c,{target:D(l.target),json:e().json}));let i=t.command("render").description("Render a project to MP4 (queues, watches via SSE, downloads). Renders whatever composition is saved on the project \u2014 build it first via `project create --from-suggestion` or `composition from-suggestion`.").allowExcessArguments(!1).argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9 (defaults to project format)").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("-o, --out <path>","Output file path (default: ./reel-<id>.mp4)").option("--idempotency-key <key>",'Override the auto-derived Idempotency-Key. Default: sha256("render:<projectId>:<currentCompositionETag>"). Pass a fresh UUID to force a new render row.').option("--priority <p>","Routing intent: interactive (low-latency, access-gated), standard (default), background (lowest queue weight).").option("--intent <i>","Encode-quality hint: preview (fast / low-bitrate, for editor scrubbing) or final (default, full Format).").action((c,l)=>Cr(c,{target:l.target,aspect:l.aspect,fps:Wr(l.fps),resolution:l.resolution,out:l.out,json:e().json,dryRun:e().dryRun,...l.idempotencyKey?{idempotencyKey:l.idempotencyKey}:{},...l.priority?{priority:l.priority}:{},...l.intent?{intent:l.intent}:{}}));t.command("api").description("Raw API call against the v1 surface (escape hatch \u2014 like `gh api`).").argument("<method>","HTTP method: GET, POST, PUT, PATCH, DELETE").argument("<path>","API path starting with /v1, e.g. /v1/projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-b, --body <body>","Request body (inline JSON, @file.json to read from disk, @- for stdin)").option("-H, --header <header...>",'Additional header (repeatable), e.g. -H "If-Match: \\"abc\\""').option("-i, --include","Include response status line + headers in stdout (curl-style). Lets agents read ETag etc.").action((c,l,S)=>Or(c,l,{target:S.target,body:S.body,header:S.header,include:S.include,json:e().json})),t.command("schema").description("Print the live composition wire schema from the server (/v1/openapi.json) \u2014 discover the contract instead of guessing.").argument("[resource]","Schema to print (currently: composition)","composition").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>Ir(c,{target:l.target,json:e().json}));let a=t.command("composition").description("Read/write a project's composition. ETag is threaded automatically.");a.command("validate").description("Validate a composition body against the live schema WITHOUT saving or rendering. Returns per-field errors \u2014 author safely before paying for a render.").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>yr({target:c.target,body:c.body,json:e().json})),a.command("get").description("Fetch the project's composition and ETag").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>gr(c,{target:l.target,json:e().json})),a.command("put").description("Replace the composition. GETs ETag first for safe concurrent writes.").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite \u2014 may clobber concurrent edits)").action((c,l)=>hr(c,{target:l.target,body:l.body,ifMatch:l.ifMatch,force:l.force,json:e().json})),a.command("from-suggestion").description("Build the composition from an existing clip suggestion").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--format <json>",`Optional format override, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`).option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite)").action((c,l)=>ct(c,{target:l.target,suggestionId:l.suggestion,format:l.format,ifMatch:l.ifMatch,force:l.force,json:e().json})),i.command("watch").description("Reattach to an existing render and stream progress to terminal state").argument("<renderId>","Render ID (from `cueframe render` output)").requiredOption("-p, --project <projectId>","Project the render belongs to").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--no-download","Print the MP4 URL but skip downloading the file").option("-o, --out <path>","Output file path when downloading (default: ./reel-<id>.mp4)").action((c,l,S)=>{let I=S?.parent?.opts?.()?.target??l.target;return Er(c,{target:I,project:l.project,out:l.out,download:l.download!==!1,json:e().json})});let u=t.command("export").description("Hand the timeline off to a real NLE (Final Cut Pro / Premiere Pro)");u.command("fcpxml").description("Build a Final Cut Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,l)=>kt("fcpxml",{target:l.target,projectId:c,suggestionId:l.suggestion,out:l.out,wait:l.wait,json:e().json})),u.command("premiere").description("Build a Premiere Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,l)=>kt("premiere",{target:l.target,projectId:c,suggestionId:l.suggestion,out:l.out,wait:l.wait,json:e().json}));let d=t.command("sessions").description("Multi-file ingest sessions (camera A/B/screen \u2192 muxed composition)");d.command("list").description("List sessions in this org").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Mr({target:c.target,json:e().json})),d.command("get").description("Get a single session by ID").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>Ur(c,{target:l.target,json:e().json})),d.command("create").description("Create a session from one or more media files").requiredOption("-n, --name <name>","Session name").requiredOption("-f, --file <entry...>","Each entry is <mediaId>:<role> (repeatable)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Fr({target:c.target,name:c.name,files:c.file,json:e().json})),d.command("delete").description("Delete a session (server checks for compositions referencing it)").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,l)=>Dr(c,{target:l.target,json:e().json})),t.command("describe").description("Print the CLI command tree as structured JSON (agent introspection)").action(()=>zr(t,{json:e().json}));try{await t.parseAsync()}catch(c){let l=_(c);x(e(),"cli",Object.assign(new Error(O(c)),{code:c?.code,status:c?.status}),l),m(l)}}await Vr();