@enhance-eng/enhance-dev 0.1.15-dev.sha-09805341372a → 0.1.17-dev.sha-91b0d30866d2
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/{cli-output-identity.lib-DiyUPF-a.mjs → cli-output-identity.lib-CPk2NGO2.mjs} +1 -1
- package/dist/main.mjs +3 -3
- package/dist/mcp-main.mjs +1 -1
- package/dist/{mcp-server.adapter-7LLa2h2J.mjs → mcp-server.adapter-DVBG_1F_.mjs} +1 -1
- package/dist/mcp.mjs +1 -1
- package/dist/{mutation-key.adapter-DSHM0rrk.mjs → mutation-key.adapter-BW070ttm.mjs} +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{FailedToExitError as e,parseRouter as t}from"trpc-cli";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{TRPCError as i,initTRPC as a}from"@trpc/server";import{middlewareMarker as o}from"@trpc/server/unstable-core-do-not-import";import{Buffer as s}from"node:buffer";import{TRPCClientError as c}from"@trpc/client";var l=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const u=2048,d=1e4,ee=1024,te=ee*ee;n.object({cursor:n.string().nullable().default(null),limit:n.number().int().min(1).max(100).default(20)});const f=e=>n.object({items:n.array(e),truncated:n.boolean()}),ne=n.enum([`never-captured`,`capture-pending`,`extension-unavailable`,`capture-failed`,`source-mismatch`,`upload-incomplete`,`blob-missing`,`image-load-failed`,`unsupported-legacy-state`]),re=n.object({thumbnailId:n.uuid(),url:n.string().max(4096),width:n.literal(528),height:n.literal(312),bytes:n.number().int().min(1).max(1048576)}),ie=n.object({canvasId:n.uuid(),thumbnailId:n.uuid(),clientReleaseIdentity:n.string().min(1).max(100),attemptedOperation:n.literal(`thumbnail-download`),recoveryOutcome:n.literal(`fallback-shown`)}),ae=n.object({recorded:n.literal(!0)}),p=n.enum([`invite-only`,`link-view`,`link-comment`]),m=n.enum([`owner`,`can-comment`,`can-view`]),oe=n.enum([`can-comment`,`can-view`]),h=n.object({read:n.boolean(),comment:n.enum([`yes`,`sign-in`,`no`]),share:n.boolean(),manage:n.boolean()}),g=n.object({id:n.uuid(),title:n.string().min(1).max(200),accessState:p,organisationId:n.uuid().nullable(),sourceUrl:n.string().max(u).nullable(),unresolvedCount:n.number().int().min(0),viewerCan:h,createdAt:n.iso.datetime(),lastActivityAt:n.iso.datetime()}),se=n.object({title:n.string().trim().min(1).max(200),organisationId:n.uuid().nullable().default(null),sourceUrl:n.string().max(u).nullable().default(null)}),ce=n.object({canvasId:n.uuid()}),le=n.union([n.literal(`own`),n.literal(`everything`),n.uuid()]),ue=n.object({collection:le.default(`own`),title:n.string().trim().min(1).max(200).optional().describe(`Title text to match before returning canvas ids.`),deleted:n.boolean().default(!1),accessState:p.optional(),scope:n.enum([`all`,`mine`,`shared`]).default(`all`),hasUnresolved:n.boolean().default(!1)}),de=g.extend({screenCount:n.number().int().min(0),hasRecording:n.boolean()}),fe=f(n.union([de.extend({thumbnail:re}),de.extend({thumbnail:n.null(),thumbnailFallbackReason:ne})])),pe=n.object({canvasId:n.uuid(),title:n.string().trim().min(1).max(200)}),me=n.object({canvasId:n.uuid()}),he=n.object({canvasId:n.uuid(),deletedAt:n.iso.datetime()}),ge=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)])}),_e=n.object({canvas:g}),ve=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),ye=n.object({canvas:g}),be=n.object({canvasId:n.uuid(),confirmation:n.string().min(1).max(200)}),xe=n.object({canvasId:n.uuid()}),Se=n.object({canvasId:n.uuid(),accessState:p}),Ce=n.object({canvas:g,widened:n.boolean()}),we=n.object({canvasId:n.uuid()}),Te=n.object({lastViewedAt:n.iso.datetime().nullable()}),Ee=n.object({canvasId:n.uuid()}),De=n.object({canvasId:n.uuid()}),Oe=new Set([`aspect-ratio`,`-webkit-line-clamp`,`line-clamp`,`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`,`grid-area`,`grid-row`,`grid-column`,`grid-row-start`,`grid-row-end`,`grid-column-start`,`grid-column-end`]),ke=(e,t)=>typeof t==`number`&&!Oe.has(e.toLowerCase())?`${String(t)}px`:String(t),Ae=[`top`,`right`,`bottom`,`left`],je=[`grid-template-rows`,`grid-template-columns`,`grid-template-areas`],Me={gap:[`row-gap`,`column-gap`],padding:Ae.map(e=>`padding-${e}`),margin:Ae.map(e=>`margin-${e}`),flex:[`flex-grow`,`flex-shrink`,`flex-basis`],"flex-flow":[`flex-direction`,`flex-wrap`],"place-content":[`align-content`,`justify-content`],"place-items":[`align-items`,`justify-items`],"place-self":[`align-self`,`justify-self`],"grid-template":je,grid:[...je,`grid-auto-rows`,`grid-auto-columns`,`grid-auto-flow`],"grid-row":[`grid-row-start`,`grid-row-end`],"grid-column":[`grid-column-start`,`grid-column-end`],"grid-area":[`grid-row-start`,`grid-column-start`,`grid-row-end`,`grid-column-end`]},Ne=e=>Me[e.toLowerCase()]??[e.toLowerCase()],Pe=(e,t)=>{if(e.isEscaped)return{...e,isEscaped:!1};if(t===`\\`)return{...e,isEscaped:!0};if(e.quote!==``)return{...e,quote:e.quote===t?``:e.quote};if([`"`,`'`].includes(t))return{...e,quote:t};let n=[`(`,`[`,`{`].includes(t)?1:[`)`,`]`,`}`].includes(t)?-1:0;return{...e,depth:e.depth+n}},Fe=(e,t=`space`)=>{let n=[],r=``,i={depth:0,quote:``,isEscaped:!1};for(let a of e){let e=i.depth===0&&i.quote===``&&!i.isEscaped;i=Pe(i,a),e&&(t===`space`?/\s/u.test(a):a===t)?((t!==`space`||r!==``)&&n.push(r.trim()),r=``):r+=a}return(t!==`space`||r!==``)&&n.push(r.trim()),n},Ie=e=>/^(?:--|-?[_a-z\u{80}-\u{FFFF}])[-\w\u{80}-\u{FFFF}]*$/iu.test(e)&&!/^(?:auto|span|initial|unset)$/iu.test(e)?e:`auto`,Le=(e,t,n)=>{let r=Fe(t,`/`),i=r[0]??t;if(e!==`grid-area`)return r[n]??Ie(i);let a=r[1]??Ie(i);return[i,a,r[2]??Ie(i),r[3]??Ie(a)][n]??t},Re=(e,t,n)=>{let r=Fe(n?e:t),i=r.filter(e=>!/^(?:auto-flow|dense)$/iu.test(e)).join(` `),a=`${n?`row`:`column`}${r.some(e=>/^dense$/iu.test(e))?` dense`:``}`;return[n?`none`:e,n?t:`none`,`none`,n&&i!==``?i:`auto`,!n&&i!==``?i:`auto`,a]},ze=(e,t,n)=>{if(/^(?:none|initial|unset)$/iu.test(t))return[`none`,`none`,`none`,`auto`,`auto`,`row`][n]??t;let r=Fe(t,`/`),i=r[0]??t,a=r[1];if(i===``||a===``||r.length>2)return t;let o=Fe(i).some(e=>e.toLowerCase()===`auto-flow`),s=a!==void 0&&Fe(a).some(e=>e.toLowerCase()===`auto-flow`);if(e===`grid`&&a!==void 0&&o!==s)return Re(i,a,o)[n]??t;if(o||s)return t;let c=/["']/u.test(i);return a===void 0&&!c?t:[c?t:i,a??`none`,c?i:`none`,`auto`,`auto`,`row`][n]??t},Be=e=>{let t=[],n=`0%`;for(let r of e)/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(r)&&t.length<2?t.push(r):n=r;return[t[0]??`1`,t[1]??`1`,n]},Ve=(e,t,n)=>{if(/(?:var|env)\(|^(?:inherit|revert(?:-layer)?)$/iu.test(t))return t;if(/^grid-(?:area|row|column)$/u.test(e))return Le(e,t,n);if(e===`grid-template`||e===`grid`)return ze(e,t,n);let r=Fe(t);return e===`flex-flow`?n===0?r.find(e=>/^(?:row|column)(?:-reverse)?$/u.test(e))??`row`:r.find(e=>/^(?:nowrap|wrap|wrap-reverse)$/u.test(e))??`nowrap`:e===`flex`?t===`none`?[`0`,`0`,`auto`][n]??t:t===`initial`?[`0`,`1`,`auto`][n]??t:Be(r)[n]??t:r[n]??(n===3?r[1]:void 0)??r[0]??t},He=e=>e.additionalStyles===void 0?{}:Object.fromEntries(e.additionalStyles.declarations.filter(e=>e.enabled).map(e=>[e.property,e.value])),Ue=e=>{let t=new Set(e.additionalStyles?.declarations.map(e=>e.property.toLowerCase()));return{...Object.fromEntries(Object.entries(e.styles).filter(([e])=>!t.has(e.toLowerCase()))),...He(e)}},We=e=>/!important\s*$/iu.test(String(e)),Ge=(e,t)=>{let n=String(e).replace(/\s*!important\s*$/iu,``).trim();return t||n.includes(`(`)?n:n.toLowerCase()},Ke=(e,t)=>{let n=null,r=!1,i=Object.entries(Ue(e));for(let[e,a]of i){let i=Ne(e),o=i.indexOf(t);if(o===-1)continue;let s=We(a);if(r&&!s)continue;let c=Ge(a,/^grid(?:-|$)/iu.test(e));n=i.length===1?c:Ve(e.toLowerCase(),c,o),r=s}return n??void 0},qe=(e,t)=>{let n=new Set(Object.entries(Ue(e)).filter(([,e])=>We(e)).flatMap(([e])=>Ne(e)));return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ne(e).some(e=>n.has(e))&&!We(t)?`${ke(e,t)} !important`:t]))},Je=(e,t)=>{let n=new Set,r=e;for(;r!==void 0&&!n.has(r.id);){n.add(r.id);let e=Ke(r,`writing-mode`);if(e!==void 0&&e!==`inherit`&&e!==`unset`)return e;if(t===void 0)break;let i=t.relationships[r.id]?.parentId;if(i===void 0)break;r=t.nodes[i]}return`horizontal-tb`},Ye=(e,t,n)=>{let r=/^(?:vertical|sideways)-/u.test(Je(e,n));return[t===`horizontal`?`width`:`height`,t===`vertical`===r?`inline-size`:`block-size`]},Xe=e=>{if(e===void 0)return`freeform`;let t=Ke(e,`display`);if(t!==void 0)return/^(?:(?:inline|block)\s+|inline-)?grid$/u.test(t)?`grid`:/^(?:(?:inline|block)\s+|inline-)?flex$/u.test(t)?`flex`:`freeform`;let n=e.layout?.container;return n===void 0?`freeform`:n.gridColumns!==void 0||n.gridAutoRepeat!==void 0?`grid`:`flex`},Ze=(e,t)=>{if(e===void 0||Xe(e)!==`flex`)return;let n=e.layout?.container?.direction??(t=>Ke(e,t))(`flex-direction`)??`row`;if(!/^(?:row|column)(?:-reverse)?$/u.test(n))return;let r=/^(?:vertical|sideways)-/u.test(Je(e,t));return n.startsWith(`column`)===r?`horizontal`:`vertical`},_=1e5,v=n.number().min(-1e5).max(_),y=n.number().nonnegative().max(_),Qe=n.object({ratio:y,offset:v.optional()}),$e=n.object({min:y.optional(),max:y.optional(),minParent:Qe.optional(),maxParent:Qe.optional()}).refine(({min:e,max:t})=>e===void 0||t===void 0||e<=t,`size minimum cannot exceed maximum`),et=n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`fixed`),value:y}).strict(),$e.extend({mode:n.literal(`hug`)}).strict(),$e.extend({mode:n.literal(`fill`),offset:v.optional()}).strict()]),tt=n.object({top:y,right:y,bottom:y,left:y}),nt=n.union([n.literal(`auto`),v]),rt=n.object({top:nt,right:nt,bottom:nt,left:nt}),it=n.object({mode:n.enum([`auto-fill`,`auto-fit`]),minimum:n.number().positive().max(_)}),at=n.object({x:v,y:v}),ot=n.object({direction:n.enum([`row`,`column`]),alignItems:n.enum([`start`,`center`,`end`,`stretch`]),alignContent:n.enum([`start`,`center`,`end`,`stretch`,`space-between`,`space-around`,`space-evenly`]).optional(),justifyContent:n.enum([`start`,`center`,`end`,`space-between`,`space-around`,`space-evenly`]),gap:y,rowGap:y.optional(),columnGap:y.optional(),wrap:n.enum([`nowrap`,`wrap`]).optional(),gridColumns:n.number().int().positive().max(_).optional(),gridAutoRepeat:it.optional(),padding:tt}).strict(),st=n.object({rotation:v.optional(),flipHorizontal:n.boolean().optional(),flipVertical:n.boolean().optional(),aspectRatioLocked:n.boolean().optional(),aspectRatio:n.number().positive().max(_).optional(),horizontal:et.optional(),vertical:et.optional(),position:n.enum([`flow`,`absolute`]).optional(),alignSelf:n.enum([`auto`,`start`,`center`,`end`,`stretch`]).optional(),flexGrow:y.optional(),flexShrink:y.optional(),flexBasis:n.union([n.literal(`auto`),y,Qe]).optional(),flowOffset:at.optional(),order:v.int().optional(),margin:rt.partial().optional(),clipContent:n.boolean().optional(),container:ot.partial().extend({padding:tt.partial().optional()}).optional()}).strict(),ct=v,b=y,x=n.number().min(0).max(1),lt=n.string().min(1).max(200),ut=n.object({space:n.enum([`srgb`,`display-p3`]),red:x,green:x,blue:x,alpha:x}),dt=n.object({id:lt,position:x,color:ut}),ft=n.object({x,y:x}),pt=n.object({id:lt,visible:n.boolean(),opacity:x}),mt=n.discriminatedUnion(`kind`,[pt.extend({kind:n.literal(`solid`),color:ut}),pt.extend({kind:n.literal(`linear-gradient`),angle:ct,stops:n.array(dt).min(2).max(32)}),pt.extend({kind:n.literal(`radial-gradient`),center:ft,radius:ft,stops:n.array(dt).min(2).max(32)}),pt.extend({kind:n.literal(`image`),assetId:n.string().min(1).max(500),fit:n.enum([`fill`,`fit`,`crop`,`tile`]),crop:n.object({x,y:x,width:x,height:x}).optional()})]),ht=n.object({topLeft:b,topRight:b,bottomRight:b,bottomLeft:b,smoothing:x.optional()}),gt=n.object({visible:n.boolean(),width:n.object({top:b,right:b,bottom:b,left:b}),style:n.enum([`solid`,`dashed`,`dotted`]),paint:mt,alignment:n.enum([`inside`,`center`,`outside`])}),_t=n.object({visible:n.boolean(),width:b,offset:ct,style:n.enum([`solid`,`dashed`,`dotted`]),paint:mt}),vt=n.object({id:lt,visible:n.boolean(),kind:n.enum([`outer`,`inner`]),color:ut,offsetX:ct,offsetY:ct,blur:b,spread:ct}),S=n.object({id:lt,visible:n.boolean()}),yt=n.discriminatedUnion(`kind`,[S.extend({kind:n.literal(`blur`),value:b}),S.extend({kind:n.literal(`brightness`),value:b}),S.extend({kind:n.literal(`contrast`),value:b}),S.extend({kind:n.literal(`grayscale`),value:x}),S.extend({kind:n.literal(`hue-rotate`),value:ct}),S.extend({kind:n.literal(`invert`),value:x}),S.extend({kind:n.literal(`saturate`),value:b}),S.extend({kind:n.literal(`sepia`),value:x})]),bt=n.enum([`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`plus-lighter`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`]);n.object({opacity:x,blendMode:bt,fills:n.array(mt).max(32),border:gt,outline:_t,radius:ht,shadows:n.array(vt).max(32),filters:n.array(yt).max(32),backdropFilters:n.array(yt).max(32)});const xt=n.object({opacity:x.optional(),blendMode:bt.optional(),fills:n.array(mt).max(32).optional(),border:gt.optional(),outline:_t.optional(),radius:ht.optional(),shadows:n.array(vt).max(32).optional(),filters:n.array(yt).max(32).optional(),backdropFilters:n.array(yt).max(32).optional()}).refine(e=>Object.keys(e).length>0,`appearance values cannot be empty`),St=[`opacity`,`blendMode`,`fills`,`border`,`outline`,`radius`,`shadows`,`filters`,`backdropFilters`],Ct=n.enum(St),wt=n.object({opacity:x.optional(),blendMode:bt.optional(),fills:n.array(mt).max(32).optional(),border:gt.optional(),outline:_t.optional(),radius:ht.optional(),shadows:n.array(vt).max(32).optional(),filters:n.array(yt).max(32).optional(),backdropFilters:n.array(yt).max(32).optional(),clear:n.array(Ct).min(1).max(St.length).optional()}).refine(e=>Object.keys(e).length>0,`appearance patch cannot be empty`).refine(({clear:e,...t})=>e===void 0||e.every(e=>t[e]===void 0),`appearance patch cannot set and clear the same property`),Tt=n.number().min(-1e5).max(_),Et=n.number().nonnegative().max(_),Dt=n.object({family:n.string().min(1).max(500),fallbackFamilies:n.array(n.string().min(1).max(500)).max(20),size:Et,weight:n.number().int().min(1).max(1e3),style:n.enum([`normal`,`italic`,`oblique`]),lineHeight:n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`normal`)}),n.object({mode:n.literal(`fixed`),value:Et})]),letterSpacing:Tt,align:n.enum([`left`,`center`,`right`,`justify`]),verticalAlign:n.enum([`top`,`middle`,`bottom`]),transform:n.enum([`none`,`uppercase`,`lowercase`,`capitalize`]),decoration:n.object({line:n.enum([`none`,`underline`,`line-through`]),style:n.enum([`solid`,`double`,`dotted`,`dashed`,`wavy`]),color:ut.optional(),thickness:Et.optional()}),stroke:n.object({width:Et,paint:mt}).optional(),wrapping:n.enum([`wrap`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]),truncation:n.object({mode:n.enum([`none`,`ellipsis`]),maxLines:n.number().int().min(1).max(_).nullable()}).optional(),insets:n.object({top:Tt,right:Tt,bottom:Tt,left:Tt}).optional()}),Ot=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,kt=/^(?:behavior|-moz-binding)$/iu,At=n.string().min(1).max(200).regex(/^(?:--[\w-]+|-(?:webkit|moz|ms|o)-[a-z][a-z\d-]*|[a-z][a-z\d-]*)$/iu).refine(e=>!kt.test(e),`unsafe CSS property`),jt=n.string().max(1e4).refine(e=>!Ot.test(e),`unsafe CSS value`),Mt=n.object({id:n.string().min(1).max(200),property:At,value:jt,enabled:n.boolean()}),Nt=n.object({declarations:n.array(Mt).max(128)}).refine(({declarations:e})=>new Set(e.map(e=>e.id)).size===e.length,`additional style ids must be unique`),Pt=n.literal(3,{error:`This editor uses an unsupported document format. Update the editor before changing this canvas.`}),C=n.object({x:n.number(),y:n.number(),width:n.number().nonnegative(),height:n.number().nonnegative()}),Ft=n.enum([`start`,`center`,`end`,`stretch`,`scale`]),It=n.object({x:Ft,y:Ft}),Lt=n.enum([`source`,`generated`,`user`]),Rt=n.looseObject({id:n.string().min(1).max(200),label:n.string().max(500),component:n.string().min(1).max(100),labelOrigin:Lt.optional(),visible:n.boolean().optional(),locked:n.boolean().optional(),constraints:It.optional(),styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:st.optional(),responsive:n.never().optional(),appearance:xt.optional(),typography:Dt.optional(),additionalStyles:Nt.optional(),props:n.record(n.string(),n.unknown()).optional(),box:C.optional()}),zt=n.object({version:n.literal(3),nodes:n.record(n.string(),Rt),relationships:n.record(n.string(),n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)})),tombstones:n.record(n.string(),n.literal(!0)).default({})}),Bt=n.record(n.string(),n.unknown()),Vt=e=>{let t=Bt.safeParse(e.layout).data;if(t===void 0)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`gridTrack`)),r=Bt.safeParse(n.container).data;r!==void 0&&(n.container=Object.fromEntries(Object.entries(r).filter(([e])=>e!==`materialized`)));for(let e of[`horizontal`,`vertical`]){let t=Bt.safeParse(n[e]).data;t?.mode===`hug`&&(n[e]=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`basis`)))}return{...e,layout:n}},Ht=e=>{if(Object.keys(e).length===0)return Wt();let t=n.record(n.string(),Bt).safeParse(e.nodes).data;return t===void 0?e:{...e,version:3,nodes:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Vt(t)]))}},Ut=n.preprocess(e=>{let t=Bt.safeParse(e).data;if(t===void 0)return e;let n=t.version;return new Set([void 0,1,2]).has(n)?Ht(t):t},zt),Wt=()=>({version:3,nodes:{root:{id:`root`,label:`Canvas`,component:`root`,labelOrigin:`generated`,visible:!0,locked:!1,styles:{}}},relationships:{},tombstones:{}}),Gt=3e4,w=5e4,Kt=n.string().min(1).max(200),qt=n.object({code:n.enum([`asset-unavailable`,`content-omitted`,`cross-origin-frame`,`nodes-truncated`,`responsive-behavior-not-editable`,`style-degraded`,`unsupported-surface`]),message:n.string().min(1).max(500),temporaryId:Kt.optional()}),Jt=n.object({nodeCount:n.number().int().positive().max(Gt),sourceNodeCount:n.number().int().positive().max(w).optional(),collapsedNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedNeutralWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedTransferredWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),layoutContainerCount:n.number().int().nonnegative().max(Gt).optional(),removedLeafNodeCount:n.number().int().nonnegative().max(w).optional(),retainedSemanticOwnerNodeCount:n.number().int().nonnegative().max(w).optional(),truncatedNodeCount:n.number().int().nonnegative().max(w*2).optional(),addedLayoutNodeCount:n.number().int().nonnegative().max(w).optional(),issues:n.array(qt).max(w)}).refine(({collapsedNeutralWrapperNodeCount:e,collapsedTransferredWrapperNodeCount:t,collapsedWrapperNodeCount:n})=>n===void 0||e===void 0||t===void 0||e+t===n,`wrapper collapse proof classes must explain the collapsed wrapper count`).refine(({collapsedNodeCount:e,collapsedWrapperNodeCount:t,removedLeafNodeCount:n})=>e===void 0||t===void 0||n===void 0||t+n===e,`collapsed node kinds must explain the total collapsed node count`).refine(({addedLayoutNodeCount:e,collapsedNodeCount:t,nodeCount:n,sourceNodeCount:r,truncatedNodeCount:i})=>r===void 0||t===void 0||r+(e??0)-n===t+(i??0),`added, collapsed and truncated node counts must explain the source to editable difference`).refine(({layoutContainerCount:e,nodeCount:t})=>e===void 0||e<=t,`layout container count cannot exceed editable node count`),Yt=Rt.omit({id:!0}).extend({temporaryId:Kt}),Xt=n.object({temporaryId:Kt,parentTemporaryId:Kt,sortKey:n.string().min(1).max(500)}),Zt=n.object({version:n.literal(1),rootTemporaryId:Kt,nodes:n.array(Yt).min(1).max(Gt),relationships:n.array(Xt).max(Gt-1),report:Jt}),Qt=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,mutationId:n.uuid(),baseVersion:n.number().int().positive(),screenNodeId:n.string().min(1).max(200),draft:Zt}),$t=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),rootNodeId:n.string().min(1).max(200),idMap:n.record(Kt,n.string().min(1).max(200)),insertedNodeIds:n.array(n.string().min(1).max(200)),removedNodeIds:n.array(n.string().min(1).max(200)),boxes:n.record(n.string().min(1).max(200),C),affectedBounds:C}),T=n.object({url:n.url(),expiresAt:n.iso.datetime(),headers:n.record(n.string(),n.string())}),en=n.object({url:n.url(),expiresAt:n.iso.datetime(),bytes:n.number().int().min(0)}),tn=[`queued`,`claimed`,`grant`,`navigate`,`document`,`sources`,`fonts`,`layout`,`target`,`capture`,`serialize`,`compile`,`commit`,`upload`,`complete`],nn=[`queued`,`running`,`succeeded`,`failed`,`cancelled`,`expired`],rn=[`VERSION_CHANGED`,`TARGET_NOT_FOUND`,`TARGET_INVALID`,`OUTPUT_TOO_LARGE`,`READINESS_TIMEOUT`,`SOURCE_FAILED`,`BROWSER_CRASH`,`CAPTURE_FAILED`,`CONVERSION_FAILED`,`UPLOAD_FAILED`,`WORKER_UNAVAILABLE`,`CANCELLED`,`EXPIRED`,`INTERNAL`],an=[`ASSET_UNAVAILABLE`,`FONT_FALLBACK`,`SOURCE_FALLBACK`,`SCALE_REDUCED`],on=32*te,sn=64*te,cn=1e5,ln=.1,E=n.object({x:n.number(),y:n.number(),width:n.number().positive().max(cn),height:n.number().positive().max(cn)}),D=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`content`)}),n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`bounds`),bounds:E})]),un=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),dn=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative()}),fn=n.object({recordingId:n.uuid(),atMs:n.number().int().nonnegative(),screenId:n.uuid(),screenNodeId:n.string().min(1).max(200),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),box:E,version:n.number().int().positive(),alreadyPresent:n.boolean()}),pn=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional(),target:D.default({kind:`content`}),sourceState:un.optional(),scale:n.number().min(ln).max(4).default(1),format:n.literal(`png`).default(`png`)}).refine(e=>e.sourceState===void 0||e.target.kind===`node`,{message:`a source state requires a node render target`,path:[`sourceState`]}),mn=n.enum(tn);n.enum(nn);const hn=n.enum(rn),gn=n.enum(an),_n=n.object({code:gn,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),vn=n.object({reason:hn,phase:mn,message:n.string().min(1).max(500),retryable:n.boolean(),sourceId:n.string().min(1).max(200).nullable()}),yn=n.object({phase:mn,durationMs:n.number().int().min(0)}),bn=n.object({canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),target:D,sourceState:dn.optional(),snapshot:fn.optional(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive().max(on),warnings:n.array(_n),timings:n.array(yn),expiresAt:n.iso.datetime()}).refine(e=>e.width*e.height<=16e6,{message:`render output may contain at most 16000000 pixels`,path:[`width`]}),xn=n.object({id:n.uuid(),canvasId:n.uuid(),purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),phase:mn,requestedVersion:n.number().int().positive(),target:D,sourceState:un.optional(),scale:n.number().positive(),format:n.literal(`png`),attempt:n.number().int().min(0),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),Sn=n.discriminatedUnion(`state`,[xn.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),xn.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),xn.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:bn,failure:n.null()}),xn.extend({state:n.literal(`failed`),result:n.null(),failure:vn}),xn.extend({state:n.literal(`cancelled`),result:n.null(),failure:vn.extend({reason:n.literal(`CANCELLED`)})}),xn.extend({state:n.literal(`expired`),result:n.null(),failure:vn.extend({reason:n.literal(`EXPIRED`)})})]),Cn=n.object({job:Sn,alreadyExists:n.boolean()}),wn=n.object({jobId:n.uuid()}),Tn=n.object({job:Sn}),En=n.object({jobId:n.uuid()}),Dn=n.object({job:Sn}),On=n.object({jobId:n.uuid()}),kn=n.object({jobId:n.uuid(),download:en}),An=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),jn=n.object({job:Sn,alreadyExists:n.boolean()}),Mn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`adjacent`)}),n.object({kind:n.literal(`insert-children`),targetNodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`replace`),targetNodeId:n.string().min(1).max(200)})]),Nn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),html:n.string().min(1).max(262144),label:n.string().min(1).max(500),idPrefix:n.string().min(1).max(80).regex(/^[\w-]+$/u).optional()})]),Pn=n.object({source:Nn,destination:Mn}).superRefine((e,t)=>{e.source.kind===`screen`&&e.destination.kind!==`adjacent`&&t.addIssue({code:`custom`,message:`stored screens convert beside their source`,path:[`destination`]}),e.source.kind===`html`&&e.destination.kind===`adjacent`&&t.addIssue({code:`custom`,message:`authored HTML requires an editable destination`,path:[`destination`]})}),Fn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),label:n.string().min(1).max(500)})]),In=n.object({id:n.uuid(),canvasId:n.uuid(),source:Fn,destination:Mn,phase:mn,requestedVersion:n.number().int().positive(),attempt:n.number().int().nonnegative(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),Ln=n.discriminatedUnion(`state`,[In.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),In.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),In.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:$t.extend({report:Jt}),failure:n.null()}),In.extend({state:n.literal(`failed`),result:n.null(),failure:vn}),In.extend({state:n.literal(`cancelled`),result:n.null(),failure:vn.extend({reason:n.literal(`CANCELLED`)})}),In.extend({state:n.literal(`expired`),result:n.null(),failure:vn.extend({reason:n.literal(`EXPIRED`)})})]),Rn=Pn.and(n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional()})),zn=n.object({job:Ln,alreadyExists:n.boolean()}),Bn=n.object({jobId:n.uuid()}),Vn=n.object({job:Ln}),Hn=n.object({jobId:n.uuid()}),Un=n.object({job:Ln});n.discriminatedUnion(`state`,[n.object({state:n.literal(`loading`),jobId:n.uuid()}),n.object({state:n.literal(`ready`),jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Zt}),n.object({state:n.literal(`failed`),jobId:n.uuid(),message:n.string().min(1).max(500)})]);const Wn=n.record(n.string(),n.unknown()),Gn=n.object({canvasId:n.uuid()}),Kn=n.object({screenId:n.uuid(),route:n.string().max(u).nullable(),title:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),atMs:n.number().int().min(0).nullable(),sourceRecordingId:n.uuid().nullable(),assetBundle:n.object({assetBundleId:n.uuid(),sourceUrl:n.string().max(u),assets:n.array(n.object({url:n.string().max(u),contentType:n.string().max(200),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}).nullable(),download:en.nullable()}),qn=n.object({version:n.number().int().min(1),document:Wn,screens:n.array(Kn)}),Jn=n.object({canvasId:n.uuid(),baseVersion:n.number().int().min(1),document:Wn.refine(e=>zt.safeParse(e).success,`A save requires a valid current-format canvas document.`),screenIds:n.array(n.uuid()).max(2e3)}),Yn=n.discriminatedUnion(`outcome`,[n.object({outcome:n.literal(`saved`),version:n.number().int().min(1)}),n.object({outcome:n.literal(`conflict`),version:n.number().int().min(1),document:Wn})]),Xn=n.object({canvasId:n.uuid(),contentType:n.enum([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),bytes:n.number().int().positive().max(20971520)}),Zn=n.object({assetId:n.uuid(),path:n.string().startsWith(`/v1/canvas-assets/`),upload:T}),Qn=(e,t)=>`/v1/canvas-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,$n=n.enum([`position`,`layout`,`clip`,`cornerRadius`,`blending`,`typography`,`nativeControl`,`textDecoration`,`fill`,`outline`,`textStroke`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`vector`,`export`,`source`]),er=n.object({id:n.string().min(1).max(200),label:n.string().max(500),kind:n.string().min(1).max(100),parentId:n.string().min(1).max(200).nullable(),childCount:n.number().int().min(0),box:E.nullable(),propertySections:n.array($n)}),tr=n.object({canvasId:n.uuid()}),nr=n.object({canvasId:n.uuid(),openUrl:n.url(),title:n.string().min(1),version:n.number().int().positive(),nodeCount:n.number().int().min(0),rootChildCount:n.number().int().min(0),bounds:E.nullable(),kinds:n.record(n.string(),n.number().int().min(0)),next:n.array(n.string().min(1))}),rr=n.object({canvasId:n.uuid()}),ir=n.object({canvasId:n.uuid(),version:n.number().int().positive(),nodes:n.array(er)}),ar=n.object({canvasId:n.uuid(),nodeId:n.string().min(1).max(200)}),or=n.object({canvasId:n.uuid(),version:n.number().int().positive(),node:er.extend({styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:st.optional(),appearance:xt.optional(),typography:Dt.optional(),additionalStyles:Nt.optional(),props:n.record(n.string(),n.unknown()),children:n.array(n.string().min(1).max(200))}),next:n.array(n.string().min(1))}),sr=[[`alignSelf`,`align-self`],[`order`,`order`],[`flexGrow`,`flex-grow`],[`flexShrink`,`flex-shrink`],[`flexBasis`,`flex-basis`],[`aspectRatio`,`aspect-ratio`]],cr=[[`direction`,`flex-direction`],[`wrap`,`flex-wrap`],[`alignItems`,`align-items`],[`alignContent`,`align-content`],[`justifyContent`,`justify-content`],[`rowGap`,`row-gap`],[`columnGap`,`column-gap`]],lr=[`top`,`right`,`bottom`,`left`],ur=(e,t,n)=>{let r={...e};for(let e of lr)n.has(`${t}-${e}`)&&Reflect.deleteProperty(r,e);return r},dr=(e,t)=>{let n=new Set([...t].flatMap(e=>Ne(e))),r={...e};for(let[e,t]of sr)n.has(t)&&Reflect.deleteProperty(r,e);if(r.margin!==void 0&&(r.margin=ur(r.margin,`margin`,n)),r.container===void 0)return r;let i={...r.container};(n.has(`row-gap`)||n.has(`column-gap`))&&i.gap!==void 0&&(i.rowGap??=i.gap,i.columnGap??=i.gap,Reflect.deleteProperty(i,`gap`));for(let[e,t]of cr)n.has(t)&&Reflect.deleteProperty(i,e);return i.padding!==void 0&&(i.padding=ur(i.padding,`padding`,n)),n.has(`grid-template-columns`)&&(Reflect.deleteProperty(i,`gridColumns`),Reflect.deleteProperty(i,`gridAutoRepeat`)),r.container=i,r},fr=(e,t,n)=>{if(e===void 0||e.mode===`fixed`)return e;let r={...e};for(let e of[`min`,`max`])t.every(t=>!n.has(`${e}-${t}`))||(Reflect.deleteProperty(r,e),Reflect.deleteProperty(r,`${e}Parent`));return r},pr=(e,t,n)=>{let r=new Set([...t].flatMap(e=>Ne(e))),i=dr(e,r);if([`overflow`,`overflow-x`,`overflow-y`].some(e=>r.has(e))&&Reflect.deleteProperty(i,`clipContent`),r.has(`position`)&&Reflect.deleteProperty(i,`position`),r.has(`transform`))for(let e of[`rotation`,`flipHorizontal`,`flipVertical`])Reflect.deleteProperty(i,e);[`inset`,`left`,`right`,`top`,`bottom`].some(e=>r.has(e))&&Reflect.deleteProperty(i,`flowOffset`);for(let e of[`horizontal`,`vertical`]){let t=n[e].some(e=>r.has(e))?void 0:fr(i[e],n[e],r);t===void 0?Reflect.deleteProperty(i,e):i[e]=t}return i},mr=[`position`,`layout`,`cornerRadius`,`blending`,`fill`,`outline`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`export`],hr=[`position`,`layout`,`clip`,...mr.filter(e=>e!==`position`&&e!==`layout`)],gr=[...mr,`vector`],_r=Object.fromEntries([{objectKind:`prototype`,label:`Prototype`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`node`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`]},{objectKind:`root`,label:`Canvas`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!0,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`page`,label:`Page`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!1,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`screen`,label:`Screen`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`screen`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`,`source`]},{objectKind:`frame`,label:`Frame`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:hr},{objectKind:`group`,label:`Group`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`,`blending`,`additionalStyles`,`export`]},{objectKind:`rectangle`,label:`Rectangle`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:mr},{objectKind:`image`,label:`Image`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:mr},{objectKind:`svg`,label:`SVG`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},capture:{preservesVectorData:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:gr},{objectKind:`recording`,label:`Recording`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1},capture:{preservesAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:[]},{objectKind:`text`,label:`Text`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`text`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!1},propertySections:[`position`,`layout`,`typography`,`nativeControl`,`textDecoration`,`textStroke`,`blending`,`fill`,`outerShadow`,`filters`,`additionalStyles`,`export`]}].map(e=>[e.objectKind,e])),vr=e=>_r[e]??null,yr=e=>vr(e)?.propertySections??[],br=n.string().regex(/^(?:\d+(?:\.\d+)?|\.\d+)px$/u),xr=n.string().regex(/^-?(?:\d+(?:\.\d+)?|\.\d+)px$/u),O={color:n.union([n.enum([`var(--note-ink)`,`var(--note-slate)`,`var(--note-red)`,`var(--note-orange)`,`var(--note-amber)`,`var(--note-green)`,`var(--note-teal)`,`var(--note-blue)`,`var(--note-violet)`,`var(--note-magenta)`]),n.string().regex(/^#[\da-f]{6}$/iu)]),"font-family":n.enum([`var(--sans)`,`var(--mono)`]),"font-size":n.union([n.literal(16),n.literal(24),n.literal(40),n.literal(64),n.literal(96)]),"font-weight":n.enum([`400`,`700`]),"font-style":n.enum([`normal`,`italic`,`oblique`]),"letter-spacing":n.number().min(-100).max(100),"line-height":n.union([n.number().positive().max(1e4),n.string().regex(/^(?:\d+(?:\.\d+)?(?:px|em|rem|%)?|normal)$/u)]),"text-align":n.enum([`left`,`center`,`right`]),"white-space":n.enum([`normal`,`nowrap`,`pre`,`pre-wrap`,`pre-line`,`break-spaces`])},Sr=n.strictObject({color:O.color.optional(),"font-family":O[`font-family`].optional(),"font-size":O[`font-size`].optional(),"font-weight":O[`font-weight`].optional(),"font-style":O[`font-style`].optional(),"letter-spacing":O[`letter-spacing`].optional(),"line-height":O[`line-height`].optional(),"text-align":O[`text-align`].optional(),"white-space":O[`white-space`].optional()}),Cr=n.strictObject({color:O.color.nullable().optional(),"font-family":O[`font-family`].nullable().optional(),"font-size":n.union([y,br]).nullable().optional(),"font-weight":n.string().regex(/^(?:[1-9]\d{0,2}|1000)$/u).nullable().optional(),"font-style":O[`font-style`].nullable().optional(),"font-stretch":n.union([n.enum([`normal`,`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`]),n.string().regex(/^\d+(?:\.\d+)?%$/u)]).nullable().optional(),"letter-spacing":n.union([v,xr,n.literal(`normal`)]).nullable().optional(),"line-height":O[`line-height`].nullable().optional(),"text-align":O[`text-align`].nullable().optional(),"text-indent":n.union([v,xr]).nullable().optional(),"white-space":O[`white-space`].nullable().optional(),"word-spacing":n.union([v,xr,n.literal(`normal`)]).nullable().optional()}),wr=Mt.shape.value,k=n.union([n.string(),v]),A=n.union([Mt.shape.value,v]).nullable().optional(),Tr=Cr.extend({"align-content":A,"align-items":A,"align-self":A,"aspect-ratio":A,"block-size":A,bottom:A,"box-sizing":A,display:A,flex:A,"flex-basis":A,"flex-direction":A,"flex-grow":A,"flex-shrink":A,"flex-wrap":A,height:A,"inline-size":A,inset:A,"inset-block":A,"inset-block-end":A,"inset-block-start":A,"inset-inline":A,"inset-inline-end":A,"inset-inline-start":A,"justify-content":A,left:A,margin:A,"margin-block":A,"margin-block-end":A,"margin-block-start":A,"margin-inline":A,"margin-inline-end":A,"margin-inline-start":A,"max-block-size":A,"max-height":A,"max-inline-size":A,"max-width":A,"min-block-size":A,"min-height":A,"min-inline-size":A,"min-width":A,order:A,padding:A,"padding-block":A,"padding-block-end":A,"padding-block-start":A,"padding-inline":A,"padding-inline-end":A,"padding-inline-start":A,position:A,right:A,top:A,width:A,background:n.string().nullable().optional(),"background-color":n.string().nullable().optional(),"border-bottom-left-radius":k.optional(),"border-bottom-right-radius":k.optional(),"border-bottom-width":k.optional(),"border-color":n.string().nullable().optional(),"border-left-width":k.optional(),"border-radius":k.nullable().optional(),"border-right-width":k.optional(),"border-style":n.enum([`none`,`solid`,`dashed`,`dotted`]).nullable().optional(),"border-top-left-radius":k.optional(),"border-top-right-radius":k.optional(),"border-top-width":k.optional(),"border-width":k.nullable().optional(),"box-shadow":n.string().nullable().optional(),"column-gap":k.optional(),gap:k.optional(),"margin-bottom":k.optional(),"margin-left":k.optional(),"margin-right":k.optional(),"margin-top":k.optional(),opacity:n.union([n.string(),n.number()]).nullable().optional(),"outline-offset":k.optional(),"outline-width":k.optional(),overflow:wr.nullable().optional(),"overflow-x":wr.nullable().optional(),"overflow-y":wr.nullable().optional(),"padding-bottom":k.optional(),"padding-left":k.optional(),"padding-right":k.optional(),"padding-top":k.optional(),"row-gap":k.optional(),"stroke-width":k.optional()}),Er=n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)}),Dr=n.object({op:n.literal(`insertConvertedSubtree`),destination:Mn,sourceNodeId:n.string().min(1).max(200).optional(),rootNodeId:n.string().min(1).max(200),nodes:n.record(n.string().min(1).max(200),Rt).refine(e=>Object.keys(e).length<=Gt),relationships:n.record(n.string().min(1).max(200),Er).refine(e=>Object.keys(e).length<Gt)}),Or=1e5,kr=1e3,j=n.string().min(1).max(200),Ar=n.string().min(1).max(500),jr=C.extend({width:n.number().positive(),height:n.number().positive()}),Mr=n.object({parentId:j,afterId:j.optional()}),Nr=n.object({parentId:j,sortKey:Ar}),Pr=n.object({op:n.literal(`setStyles`),nodeId:j,styles:Tr,clear:n.array(Tr.keyof()).min(1).max(Object.keys(Tr.shape).length).refine(e=>new Set(e).size===e.length).optional()}).refine(e=>(e.clear??[]).every(t=>!Object.hasOwn(e.styles,t))),Fr=n.discriminatedUnion(`op`,[Dr,n.object({op:n.literal(`insertNode`),node:Rt,parentage:Nr}),Mr.extend({op:n.literal(`insertText`),nodeId:j,label:n.string().max(500).default(`Text`),text:n.string().max(Or),box:jr,styles:Sr.default({})}),Mr.extend({op:n.literal(`insertPrototype`),nodeId:j,label:n.string().max(500).default(`Prototype`),prototypeId:n.uuid(),deploymentId:n.uuid(),box:jr,canvasPageId:j.optional()}),n.object({op:n.literal(`setPrototypeDeployment`),nodeId:j,prototypeId:n.uuid(),deploymentId:n.uuid()}),n.object({op:n.literal(`setText`),nodeId:j,text:n.string().max(Or)}),n.object({op:n.literal(`setBox`),nodeId:j,box:n.union([C,n.literal(`default`)])}),n.object({op:n.literal(`setLabel`),nodeId:j,label:n.string().trim().min(1).max(500),labelOrigin:Lt.nullable().optional()}),n.object({op:n.literal(`setContainerKind`),nodeId:j,component:n.enum([`frame`,`group`])}),n.object({op:n.literal(`setVisibility`),nodeId:j,visible:n.boolean().nullable()}),n.object({op:n.literal(`setLocked`),nodeId:j,locked:n.boolean()}),n.object({op:n.literal(`setConstraints`),nodeId:j,constraints:It}),Pr,n.object({op:n.literal(`setAppearance`),nodeId:j,appearance:wt}),n.object({op:n.literal(`setLayout`),nodeId:j,layout:n.union([st,n.literal(`default`)])}),n.object({op:n.literal(`setTypography`),nodeId:j,typography:n.union([Dt,n.literal(`default`)])}),n.object({op:n.literal(`setAdditionalStyles`),nodeId:j,additionalStyles:n.union([Nt,n.literal(`default`)])}),n.object({op:n.literal(`setProps`),nodeId:j,props:n.union([n.record(n.string(),n.unknown()),n.literal(`default`)])}),n.object({op:n.literal(`setParentage`),nodeId:j,parentage:Nr}),Mr.extend({op:n.literal(`move`),nodeId:j}),n.object({op:n.literal(`remove`),nodeId:j})]),Ir=n.object({canvasId:n.uuid(),mutationId:n.uuid(),documentFormatVersion:Pt,baseVersion:n.number().int().positive(),operations:n.array(Fr).min(1).max(kr)}),Lr=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),insertedNodeIds:n.array(j),changedNodeIds:n.array(j),removedNodeIds:n.array(j),boxes:n.record(j,C),affectedBounds:jr.nullable(),next:n.array(n.string().min(1))}),Rr=$t.extend({operation:Dr,next:n.array(n.string().min(1))}),zr=`enhance3.canvas.v1`,Br=n.enum([`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`]),Vr=n.object({kind:n.literal(`person`),connectionId:n.uuid(),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:Br}),Hr=n.object({kind:n.literal(`guest`),connectionId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:Br}),Ur=n.discriminatedUnion(`kind`,[Vr,Hr]),Wr=n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),tokenLabel:n.string().min(1).max(100),colour:Br}),Gr=n.discriminatedUnion(`kind`,[Vr.omit({connectionId:!0}),Wr]),Kr=n.object({x:n.number(),y:n.number()}),qr=C.extend({width:n.number().positive(),height:n.number().positive()}),Jr=n.object({kind:n.enum([`drag`,`resize`]),baseVersion:n.number().int().positive(),boxes:n.record(n.string().min(1).max(200),qr)}),Yr=n.object({cursor:Kr.nullable().optional(),input:n.enum([`pointer`,`touch`,`keyboard`]).optional(),focused:n.boolean().optional(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100).optional(),visibleWorldBox:qr.optional(),gesture:Jr.nullable().optional(),cursorChat:n.string().max(140).nullable().optional()}).refine(e=>Object.keys(e).length>0,`presence patch cannot be empty`),Xr=n.object({actor:Ur,seq:n.number().int().nonnegative(),cursor:Kr.nullable(),input:n.enum([`pointer`,`touch`,`keyboard`]),focused:n.boolean(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100),visibleWorldBox:qr.nullable(),gesture:Jr.nullable(),cursorChat:n.string().max(140).nullable().default(null),expiresAt:n.iso.datetime()}),Zr=n.enum([`reading`,`writing`,`creating`,`deleting`,`rendering`]),Qr=n.object({activityId:n.uuid(),canvasId:n.uuid(),actor:Wr,phase:Zr,nodeIds:n.array(n.string().min(1).max(200)).max(100),bounds:qr.nullable(),expiresAt:n.iso.datetime()}),$r=n.object({canvasId:n.uuid(),protocols:n.array(n.literal(zr)).min(1).max(1)}),ei=n.object({endpoint:n.url(),ticket:n.string().min(1).max(4096),protocol:n.literal(zr),expiresAt:n.iso.datetime()}),ti=n.object({canvasId:n.uuid(),phase:Zr,nodeIds:n.array(n.string().min(1).max(200)).max(100).default([]),bounds:qr.nullable().default(null)}),ni=n.object({activityId:n.uuid(),expiresAt:n.iso.datetime(),renewAfterMs:n.number().int().positive()}),ri=ti.extend({activityId:n.uuid()}),ii=n.object({canvasId:n.uuid(),activityId:n.uuid()}),ai=n.object({ended:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({v:n.literal(1),type:n.literal(`presence.patch`),seq:n.number().int().nonnegative(),payload:Yr}),n.object({v:n.literal(1),type:n.literal(`room.pong`),seq:n.number().int().nonnegative(),payload:n.object({pingId:n.uuid()})})]);const M={v:n.literal(1),seq:n.number().int().nonnegative()};n.discriminatedUnion(`type`,[n.object({...M,type:n.literal(`room.snapshot`),payload:n.object({connectionId:n.uuid(),peers:n.array(Xr),activities:n.array(Qr),documentVersion:n.number().int().positive()})}),n.object({...M,type:n.literal(`presence.patch`),payload:Xr}),n.object({...M,type:n.literal(`presence.left`),payload:n.object({connectionId:n.uuid()})}),n.object({...M,type:n.literal(`agent.activity`),payload:n.object({activityId:n.uuid(),activity:Qr.nullable()})}),n.object({...M,type:n.literal(`document.committed`),payload:n.object({mutationId:n.uuid(),actor:Gr,previousVersion:n.number().int().positive(),version:n.number().int().positive(),operations:n.array(Fr).min(1)})}),n.object({...M,type:n.literal(`sync.required`),payload:n.object({version:n.number().int().positive(),reason:n.enum([`gap`,`relay`,`replace`,`history-restored`])})}),n.object({...M,type:n.literal(`room.ping`),payload:n.object({pingId:n.uuid(),sentAt:n.iso.datetime()})}),n.object({...M,type:n.literal(`room.error`),payload:n.object({code:n.enum([`auth`,`permission`,`protocol`,`payload`,`rate`,`unavailable`]),message:n.string().min(1).max(200)})})]);const oi=n.object({jobId:n.uuid()}),si=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),target:D,sourceState:un.optional()}),ci=n.discriminatedUnion(`purpose`,[si.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),scale:n.number().positive().max(4),format:n.literal(`png`)}),si.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:Pn,scale:n.literal(1),format:n.literal(`json`)})]);n.object({jobId:n.uuid()}),n.object({jobId:n.uuid()});const li=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),grantToken:n.string().startsWith(`rgr_`).min(40).max(100),grantCookieName:n.string().min(1).max(100),renderUrl:n.url(),releaseIdentity:n.string().min(1).max(100)});n.discriminatedUnion(`purpose`,[li.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),target:D,sourceState:un.optional(),scale:n.number().positive(),outputKey:n.string().min(1).max(500)}),li.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:Pn,scale:n.literal(1)})]),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),bytes:n.number().int().positive().max(on),storageKey:n.string().min(1).max(500),warnings:n.array(_n),timings:n.array(yn),sourceState:dn.optional(),snapshot:n.object({artifactBytes:n.number().int().positive().max(sn),artifactStorageKey:n.string().min(1).max(500),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}).optional()}),n.object({accepted:n.literal(!0)}),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Zt}),n.object({accepted:n.literal(!0)}),n.object({recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative(),artifact:n.string().min(1).max(sn),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}),n.object({jobId:n.uuid(),failure:vn}),n.object({accepted:n.literal(!0),willRetry:n.boolean()}),n.object({workerId:n.string().regex(/^[\w.-]+$/u).min(1).max(100),releaseIdentity:n.string().min(1).max(100),timestamp:n.coerce.number().int().nonnegative(),nonce:n.uuid(),mac:n.base64().min(32).max(200)});const ui=n.object({total:n.number().int().nonnegative(),loading:n.number().int().nonnegative(),unavailable:n.number().int().nonnegative()}),di=n.object({jobId:n.uuid(),canvasId:n.uuid().nullable(),requestedVersion:n.number().int().positive().nullable(),loadedVersion:n.number().int().positive().nullable(),phase:mn.exclude([`queued`,`claimed`,`capture`,`upload`,`complete`]),sources:ui,warnings:n.array(_n),timings:n.array(yn),sourceState:dn.optional()}),fi=n.object({selector:n.string().min(1).max(500),contentSelector:n.string().min(1).max(500).optional(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive()});n.discriminatedUnion(`state`,[di.extend({state:n.literal(`loading`),capture:n.null(),failure:n.null()}),di.extend({state:n.literal(`ready`),phase:n.literal(`target`),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),capture:fi,failure:n.null()}),di.extend({state:n.literal(`failed`),failure:n.object({reason:hn,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),capture:n.null()})]);const pi=n.string().min(1).max(200),mi=n.object({canvasId:n.uuid()}),hi=n.object({canvasId:n.uuid(),status:n.enum([`selected`,`none`,`offline`,`stale`]),documentVersion:n.number().int().positive(),selectionRevision:n.number().int().positive().nullable(),selectionChangedAt:n.iso.datetime().nullable(),selectedNodeIds:n.array(pi),missingNodeIds:n.array(pi),nodes:n.array(er),contextRootId:pi.nullable(),visibleWorldBox:E.nullable(),next:n.array(n.string().min(1)).max(12)}),gi=1e3,_i=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2)}),n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2),tokenLabel:n.string().min(1).max(200)})]),vi=n.object({id:n.uuid(),canvasId:n.uuid(),documentVersion:n.number().int().positive(),origin:n.enum([`automatic`,`manual`,`restore`]),restoreRole:n.enum([`before`,`result`]).nullable(),retention:n.enum([`automatic`,`named`,`restore-boundary`]),title:n.string().min(1).max(200).nullable(),description:n.string().max(gi).nullable(),actor:_i,sourceVersionEntryId:n.uuid().nullable(),expiresAt:n.iso.datetime().nullable(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime(),screenCount:n.number().int().min(0)}),yi=n.object({canvasId:n.uuid(),limit:n.number().int().min(1).max(100).default(50),cursor:n.string().min(1).max(1e3).optional(),includeAutomatic:n.boolean().default(!1),actor:n.enum([`all`,`mine`]).default(`all`)}),bi=n.object({current:n.object({documentVersion:n.number().int().positive(),updatedAt:n.iso.datetime()}),items:n.array(vi),nextCursor:n.string().min(1).nullable(),hasExpiredHistory:n.boolean()}),xi=n.object({canvasId:n.uuid(),versionId:n.uuid()}),Si=n.object({outcome:n.literal(`ready`),entry:vi,document:Wn,screens:n.array(Kn)}),Ci=n.object({outcome:n.literal(`missing-resources`),entry:vi,document:Wn,screens:n.array(Kn),missingScreenIds:n.array(n.uuid()).min(1)}),wi=n.discriminatedUnion(`outcome`,[Si,Ci,n.object({outcome:n.literal(`corrupt`),entry:vi})]),Ti=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`current`),expectedVersion:n.number().int().positive()}),n.object({kind:n.literal(`version`),versionId:n.uuid()})]),Ei=n.object({canvasId:n.uuid(),target:Ti,title:n.string().trim().min(1).max(200),description:n.string().trim().max(gi).nullable().default(null)}),Di=n.object({canvasId:n.uuid(),versionId:n.uuid(),title:n.string().trim().min(1).max(200),description:n.string().trim().max(gi).nullable().default(null)}),Oi=n.object({canvasId:n.uuid(),versionId:n.uuid()}),ki=n.object({entry:vi}),Ai=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,versionId:n.uuid(),expectedVersion:n.number().int().positive()}),ji=n.object({canvasId:n.uuid(),version:n.number().int().positive(),beforeVersionId:n.uuid(),restoredVersionId:n.uuid(),restoreFenceVersion:n.number().int().positive()}),Mi=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,versionId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),Ni=n.object({canvasId:n.uuid(),title:n.string().min(1).max(200),version:n.literal(1)}),Pi=n.object({inviteId:n.uuid(),email:n.string().max(254),accessLevel:oe,sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),Fi=n.object({canvasTitle:n.string().min(1),invitedBy:n.string().min(1),email:n.string().max(254).pipe(n.email()),accessLevel:oe,expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),Ii=n.object({canvasId:n.uuid(),email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email()),accessLevel:oe}),Li=n.object({invite:Pi,acceptToken:n.string().max(512).optional()}),Ri=n.object({canvasId:n.uuid()}),zi=f(Pi),Bi=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),Vi=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),Hi=n.string().min(1).max(512),Ui=n.object({token:Hi}),Wi=n.object({token:Hi}),Gi=n.object({canvasId:n.uuid(),accessLevel:oe}),Ki=n.object({personId:n.uuid().nullable(),email:n.string().max(254).nullable(),displayName:n.string().max(120).nullable(),initials:n.string().max(4).nullable(),avatarUrl:n.string().max(u).nullable(),accessLevel:m,isPending:n.boolean(),reviewState:n.enum([`not-started`,`in-progress`,`done`]).nullable(),lastViewedAt:n.iso.datetime().nullable()}),qi=n.object({canvasId:n.uuid()}),Ji=f(Ki),Yi=n.object({canvasId:n.uuid(),personId:n.uuid(),accessLevel:oe}),Xi=n.object({canvasId:n.uuid(),personId:n.uuid()}),Zi=n.object({personId:n.uuid(),revoked:n.boolean()}),Qi=n.object({canvasId:n.uuid(),reviewState:n.enum([`not-started`,`in-progress`,`done`])}),$i=n.object({reviewState:Qi.shape.reviewState.nullable()}),ea=n.object({selector:n.string().min(1).max(2e3),tagName:n.string().min(1).max(40),label:n.string().max(80).nullable(),source:n.object({file:n.string().min(1).max(1024),line:n.number().int().min(0).nullable()}).nullable()}),ta=n.object({x:n.number(),y:n.number()}),na=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1)}),ra=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1),width:n.number().min(0).max(1),height:n.number().min(0).max(1)}),ia=ea.extend({role:n.string().min(1).max(80).optional()}),aa=n.object({path:n.array(n.number().int().min(0)).max(64),offset:n.number().int().min(0)}),oa=n.discriminatedUnion(`kind`,[n.object({version:n.literal(1),kind:n.literal(`element`),locator:ia,attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`text`),root:ia,quote:n.object({exact:n.string().min(1).max(1e3),prefix:n.string().max(120),suffix:n.string().max(120)}),range:n.object({start:aa,end:aa}),attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`elements`),members:n.array(ia).min(2).max(32),truncated:n.boolean(),attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`area`),bounds:ra,attachment:na})]),sa=n.discriminatedUnion(`on`,[n.object({on:n.literal(`canvas`),point:ta}),n.object({on:n.literal(`node`),nodeId:n.string().min(1).max(120),point:ta,element:n.null()}),n.object({on:n.literal(`screen`),nodeId:n.string().min(1).max(120),screenId:n.uuid(),point:ta,element:ea.nullable(),target:oa.optional()})]),ca=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(u).nullable(),tokenLabel:n.string().max(120).nullable()}),la=n.object({personId:n.uuid(),name:n.string().min(1).max(120)}),ua=n.object({emoji:n.string().min(1).max(16),people:n.array(la).min(1)}),da=n.object({messageId:n.uuid(),seq:n.number().int().min(1),body:n.string().min(1),author:ca,createdAt:n.iso.datetime(),editedAt:n.iso.datetime().nullable(),mentions:n.array(la),reactions:n.array(ua)}),fa=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),tokenLabel:n.string().max(120).nullable()}),pa=n.object({threadId:n.uuid(),canvasId:n.uuid(),anchor:sa,author:ca,messages:n.array(da).min(1).max(50),messageCount:n.number().int().min(1),hasMoreMessages:n.boolean(),isResolved:n.boolean(),resolvedAt:n.iso.datetime().nullable(),resolvedBy:fa.nullable(),createdAt:n.iso.datetime(),lastMessageAt:n.iso.datetime()}),ma=n.object({canvasId:n.uuid(),filter:n.enum([`open`,`resolved`,`all`]).default(`open`),authorPersonId:n.uuid().optional(),agentActionable:n.boolean().default(!1),query:n.string().trim().max(200).optional()}),ha=f(pa),ga=n.object({canvasId:n.uuid(),clientThreadId:n.uuid(),anchor:sa,body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),_a=n.object({canvasId:n.uuid(),threadId:n.uuid(),clientMessageId:n.uuid(),body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),va=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),ya=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),emoji:n.string().trim().min(1).max(16),reacted:n.boolean()}),ba=n.object({canvasId:n.uuid(),threadId:n.uuid(),anchor:sa}),xa=n.object({canvasId:n.uuid(),threadId:n.uuid(),resolved:n.boolean()}),Sa=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid().optional()}),Ca=n.object({deletedThreadIds:n.array(n.uuid()),deletedMessageIds:n.array(n.uuid())}),wa=`root`,Ta=e=>`a${String(e).padStart(4,`0`)}`,Ea=()=>({version:3,nodes:{[wa]:{id:wa,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Da=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:wa,sortKey:Ta(Object.keys(e.relationships).length)}}}),Oa=(e,t)=>Da(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),ka=n.enum([`owner`,`admin`,`member`]),Aa=n.object({id:n.uuid(),name:n.string().min(1).max(120),role:ka}),ja=n.object({}),Ma=f(Aa),Na=n.object({name:n.string().trim().min(1).max(120)}),Pa=n.object({organisation:Aa}),Fa=n.object({organisationId:n.uuid(),name:n.string().trim().min(1).max(120)}),Ia=n.object({organisationId:n.uuid()}),La=n.object({organisationId:n.uuid(),movedCanvasCount:n.number().int().min(0)}),Ra=n.object({personId:n.uuid(),displayName:n.string().max(120),initials:n.string().max(4),email:n.string().max(254).nullable(),role:ka}),za=n.object({organisationId:n.uuid()}),Ba=f(Ra),Va=n.object({organisationId:n.uuid(),email:n.email().trim().toLowerCase().max(254),role:n.enum([`admin`,`member`]).default(`member`)}),Ha=n.object({personId:n.uuid()}),Ua=n.object({organisationId:n.uuid(),personId:n.uuid(),role:n.enum([`admin`,`member`])}),Wa=Ua.pick({personId:!0,role:!0}),Ga=n.object({organisationId:n.uuid(),personId:n.uuid()}),Ka=n.object({personId:n.uuid(),removed:n.literal(!0)}),qa=n.object({organisationId:n.uuid(),personId:n.uuid()}),Ja=n.object({ownerPersonId:n.uuid()}),Ya=n.object({inviteId:n.uuid(),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),Xa=n.object({organisationId:n.uuid(),email:n.string().trim().toLowerCase().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]).default(`member`)}),Za=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`member`),personId:n.uuid()}),n.object({kind:n.literal(`invitation`),invite:Ya})]),Qa=n.object({invite:Ya}),$a=n.object({organisationId:n.uuid()}),eo=f(Ya),to=n.object({organisationId:n.uuid(),inviteId:n.uuid()}),no=to.extend({}),ro=n.string().min(1).max(512),io=n.object({token:ro}),ao=n.object({token:ro}),oo=n.object({teamName:n.string().min(1).max(120),invitedBy:n.string().min(1).max(120),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),so=n.object({organisationId:n.uuid()}),co=n.object({id:n.uuid(),label:n.string().min(1).max(120),createdAt:n.iso.datetime(),lastUsedAt:n.iso.datetime().nullable(),expiresAt:n.iso.datetime().nullable(),revoked:n.boolean()}),lo=n.object({label:n.string().trim().min(1).max(120).describe(`Label naming the agent.`),expiresAt:n.iso.datetime().nullable().describe(`Expiry timestamp, or null for a token that does not expire.`)}),uo=n.object({token:n.string().startsWith(`enh_`),agentToken:co}),fo=n.object({}),po=n.object({items:n.array(co),isConnected:n.boolean()}),mo=n.object({tokenId:n.uuid()}),ho=n.object({tokenId:n.uuid(),revoked:n.literal(!0)}),go=n.discriminatedUnion(`method`,[n.object({method:n.literal(`token`)}),n.object({method:n.literal(`browser`),issuer:n.url(),clientId:n.string().min(1),scope:n.literal(`openid`)})]),_o=n.object({id:n.uuid(),preparedCanvasId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(u).nullable(),email:n.string().max(254).nullable(),createdAt:n.iso.datetime()}),vo=n.object({}),yo=n.object({person:_o.nullable(),authentication:n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`anonymous`)}),n.object({kind:n.literal(`person`)}),n.object({kind:n.literal(`agent`),tokenId:n.uuid(),tokenLabel:n.string(),expiresAt:n.iso.datetime().nullable()}),n.object({kind:n.literal(`oauth-agent`),tokenId:n.uuid(),tokenLabel:n.string(),clientId:n.string().min(1),scopes:n.array(n.string()),expiresAt:n.iso.datetime(),resource:n.url()})])}),bo=n.object({displayName:n.string().trim().min(1).max(120)}),xo=n.object({person:_o}),So=n.string().trim().toLowerCase().min(3).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/,`letters, digits, dot, underscore and dash only`),Co=n.enum([`cookie`,`token`]).default(`cookie`),wo=n.object({username:So,password:n.string().min(10).max(200),displayName:n.string().trim().min(1).max(120),deliver:Co,email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email())}),To=n.object({username:So,password:n.string().min(1).max(200),deliver:Co}),Eo=n.object({person:_o,token:n.string().nullable()}),Do=Eo.extend({preparedCanvasId:n.uuid()}),Oo=n.object({}),ko=n.object({signedOut:n.literal(!0)}),Ao=n.string().max(254).pipe(n.email()),jo=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),email:Ao}),n.object({kind:n.literal(`email`),email:Ao})]),Mo=n.object({query:n.string().trim().min(1).max(200)}),No=n.object({recipients:n.array(jo).max(5)}),Po=n.object({}),Fo=No.extend({}),Io=`enhance3:session-handoff`;n.union([n.object({kind:n.literal(Io),body:n.object({token:n.string().min(1),displayName:n.string().min(1)})}),n.object({kind:n.literal(Io),signedOut:n.literal(!0)})]);const Lo=n.string().min(1).max(500).refine(e=>!e.startsWith(`/`)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),Ro=n.object({path:Lo,contentType:n.string().min(1).max(200),bytes:n.number().int().nonnegative().max(26214400)}),zo=n.enum([`uploading`,`verifying`,`ready`,`failed`,`abandoned`]),Bo=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1).max(200),title:n.string().trim().min(1).max(200),entryPath:Lo.default(`index.html`),files:n.array(Ro).min(1).max(2e3),box:C.extend({width:n.number().positive(),height:n.number().positive()})}),Vo=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),state:zo,alreadyExists:n.boolean(),fileCount:n.number().int().positive(),totalBytes:n.number().int().positive().max(262144e3)}),Ho=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),cursor:n.number().int().min(0).default(0)}),Uo=n.object({path:Lo,upload:T}),Wo=n.object({deploymentId:n.uuid(),uploads:n.array(Uo).max(50),nextCursor:n.number().int().min(0).optional()}),Go=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive(),canvasPageId:n.string().min(1).max(200).optional()}),Ko=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)}),qo=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid()}),Jo=n.object({deploymentId:n.uuid(),origin:n.url(),bootUrl:n.url(),expiresAt:n.iso.datetime()}),Yo=`__enhance/manifest.json`,Xo=n.string().length(64).refine(e=>{for(let t of e)if(!/[\da-f]/u.test(t))return!1;return!0}),Zo=e=>{for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e===127||e<=31))return!0}return!1},Qo=e=>e.normalize(`NFKC`).toUpperCase().toLowerCase(),$o=n.string().min(1).refine(e=>e===e.normalize(`NFC`),{message:`prototype paths must use NFC Unicode normalization`}).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:\//u.test(e)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!Zo(e)&&!e.startsWith(`__enhance/`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),es=n.object({path:$o,contentType:n.string().trim().min(1).max(200).refine(e=>!Zo(e)),bytes:n.number().int().nonnegative().max(2**53-1),sha256:Xo}),ts=n.object({version:n.literal(1),entryPath:$o,files:n.array(es).min(1)}),ns=n.object({artifactBytes:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1),fileBytes:n.number().int().positive().max(2**53-1),manifestBytes:n.number().int().positive().max(2**53-1),fileCount:n.number().int().positive().max(2**53-1),pathBytes:n.number().int().positive().max(2**53-1)}),rs=n.object({}),is=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),limits:ns}),as=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),bytes:n.number().int().positive().max(2**53-1),sha256:Xo,fileCount:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1)}),os=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1),title:n.string().trim().min(1).max(200),entryPath:$o,artifact:as,box:C.extend({width:n.number().positive(),height:n.number().positive()})}),ss=n.enum([`uploading`,`queued`,`ingesting`,`ready`,`failed`,`abandoned`]),cs=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),alreadyExists:n.boolean(),artifact:as}),ls=n.discriminatedUnion(`state`,[cs.extend({state:n.literal(`uploading`),upload:T}),cs.extend({state:n.enum([`queued`,`ingesting`,`ready`,`failed`,`abandoned`])})]),us=n.object({canvasId:n.uuid(),deploymentId:n.uuid()}),ds=n.object({deploymentId:n.uuid(),state:ss}),fs=n.object(us.shape),ps=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),fileCount:n.number().int().nonnegative(),totalBytes:n.number().int().nonnegative().max(2**53-1),processedFiles:n.number().int().nonnegative()}),ms=n.discriminatedUnion(`state`,[ps.extend({state:n.literal(`failed`),failure:n.object({code:n.string().min(1),message:n.string().min(1),path:$o.optional()})}),ps.extend({state:n.enum([`uploading`,`queued`,`ingesting`,`ready`,`abandoned`])})]),hs=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive(),canvasPageId:n.string().min(1).max(200).optional()}),gs=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)});n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.capture`),requestId:n.uuid()}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.ready`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.escape`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.zoom`),deltaX:n.number(),deltaY:n.number(),deltaMode:n.union([n.literal(0),n.literal(1),n.literal(2)]),anchorX:n.number().min(0).max(1),anchorY:n.number().min(0).max(1)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigate`),direction:n.enum([`back`,`forward`])}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigation`),canGoBack:n.boolean(),canGoForward:n.boolean()});const _s=n.object({artifact:n.string().min(1),viewport:n.object({width:n.number().positive(),height:n.number().positive()}),title:n.string()}),vs=n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.captured`),requestId:n.uuid()});n.discriminatedUnion(`outcome`,[vs.extend({outcome:n.literal(`captured`),screen:_s}),vs.extend({outcome:n.literal(`failed`),error:n.string().min(1)})]);const ys=2166136261,bs=Number.parseInt(`9e3779b9`,16),xs=Number.parseInt(`85ebca6b`,16),Ss=Number.parseInt(`c2b2ae35`,16);ys^bs,ys^xs,ys^Ss;const Cs=(e,t)=>`/v1/recording-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,ws=n.object({width:n.number().int().positive(),height:n.number().int().positive()}),Ts=16*te,Es=8*te,Ds=u,Os=n.object({mimeType:n.string().min(1).max(100),sampleRate:n.number().int().min(8e3).max(192e3)}),ks=n.object({sourceUrl:n.string().max(Ds),viewport:ws,pageTitle:n.string().max(200).nullable(),audio:Os.nullable().default(null)}),As=n.object({recordingId:n.uuid(),ownerPersonId:n.uuid(),chunkIndex:n.literal(0),upload:T,audioUpload:T.nullable()}),js=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),eventCount:n.number().int().min(0),continues:n.boolean().default(!1),bytes:n.number().int().min(1).max(Ts),etag:n.string().min(1).max(200).optional()}),Ms=n.object({nextChunkIndex:n.number().int().min(1),upload:T}),Ns=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),bytes:n.number().int().min(1).max(Ts),epoch:n.number().int().min(0).default(0),startsEpoch:n.boolean().default(!1),etag:n.string().min(1).max(200).optional()}),Ps=n.object({nextChunkIndex:n.number().int().min(1),upload:T}),Fs=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0).max(144e5),viewport:ws,sourceUrl:n.string().max(Ds),interrupted:n.boolean().default(!1),canvasId:n.uuid().optional(),organisationId:n.uuid().optional(),audioChunkCount:n.number().int().min(0).default(0),hasRecoverableBytes:n.boolean().default(!1)}).refine(e=>e.canvasId===void 0||e.organisationId===void 0,{message:`choose an existing canvas or a team for a new canvas, not both`}),Is=n.enum([`whole`,`recovering`,`partial`]),Ls=n.enum([`dom`,`audio`]),Rs=n.object({recordingId:n.uuid(),canvasId:n.uuid(),canvasTitle:n.string().min(1).max(200),isNewCanvas:n.boolean(),storedChunkCount:n.number().int().min(0),missingChunkIndexes:n.array(n.number().int().min(0)).max(64),missingChunkCount:n.number().int().min(0),storedAudioChunkCount:n.number().int().min(0),missingAudioChunkIndexes:n.array(n.number().int().min(0)).max(64),missingAudioChunkCount:n.number().int().min(0),integrity:Is}),zs=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:ws,interrupted:n.boolean(),chunkCount:n.number().int().min(0),startedAt:n.iso.datetime()}),Bs=n.object({recordingId:n.uuid(),assets:n.array(n.object({url:n.url().max(Ds),contentType:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Es)})).max(400)}),Vs=n.object({reserved:n.array(n.object({url:n.string(),upload:T}))}),Hs=n.object({recordingId:n.uuid(),arrived:n.array(n.object({url:n.url().max(Ds),etag:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Es)})).max(400)}),Us=n.object({missingAssetCount:n.number().int().min(0)}),Ws=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),Gs=n.object({seq:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),continues:n.boolean()}),Ks=n.discriminatedUnion(`state`,[Gs.extend({state:n.literal(`available`),download:en}),Gs.extend({state:n.literal(`missing`)})]),qs=n.object({seq:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),epoch:n.number().int().min(0),startsEpoch:n.boolean()}),Js=n.discriminatedUnion(`state`,[qs.extend({state:n.literal(`available`),download:en}),qs.extend({state:n.literal(`missing`)})]),Ys=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:ws,sourceUrl:n.string().max(Ds),interrupted:n.boolean(),integrity:Is,chunks:n.array(Ks),audio:n.object({mimeType:n.string(),chunks:n.array(Js)}).nullable(),assets:n.array(n.object({url:n.string(),contentType:n.string(),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0),missingAssetUrls:n.array(n.string()).optional()}),Xs=n.object({recordingId:n.uuid(),track:Ls,index:n.number().int().min(0)}),Zs=n.object({upload:T}),Qs=Xs.extend({etag:n.string().min(1).max(200)}),$s=n.object({integrity:Is}),ec=n.object({canvasId:n.uuid()}),tc=f(zs),nc=n.object({recordingId:n.uuid()}),rc=n.object({recordingId:n.uuid(),discarded:n.literal(!0)}),ic=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),ac=n.object({recordingId:n.uuid(),detachedScreenCount:n.number().int().min(0)});[`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
|
|
2
|
+
import{FailedToExitError as e,parseRouter as t}from"trpc-cli";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{TRPCError as i,initTRPC as a}from"@trpc/server";import{middlewareMarker as o}from"@trpc/server/unstable-core-do-not-import";import{Buffer as s}from"node:buffer";import{TRPCClientError as c}from"@trpc/client";var l=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const u=2048,d=1e4,ee=1024,te=ee*ee;n.object({cursor:n.string().nullable().default(null),limit:n.number().int().min(1).max(100).default(20)});const f=e=>n.object({items:n.array(e),truncated:n.boolean()}),ne=n.enum([`never-captured`,`capture-pending`,`extension-unavailable`,`capture-failed`,`source-mismatch`,`upload-incomplete`,`blob-missing`,`image-load-failed`,`unsupported-legacy-state`]),re=n.object({thumbnailId:n.uuid(),url:n.string().max(4096),width:n.literal(528),height:n.literal(312),bytes:n.number().int().min(1).max(1048576)}),ie=n.object({canvasId:n.uuid(),thumbnailId:n.uuid(),clientReleaseIdentity:n.string().min(1).max(100),attemptedOperation:n.literal(`thumbnail-download`),recoveryOutcome:n.literal(`fallback-shown`)}),ae=n.object({recorded:n.literal(!0)}),p=n.enum([`invite-only`,`link-view`,`link-comment`]),m=n.enum([`owner`,`can-comment`,`can-view`]),oe=n.enum([`can-comment`,`can-view`]),h=n.object({read:n.boolean(),comment:n.enum([`yes`,`sign-in`,`no`]),share:n.boolean(),manage:n.boolean()}),g=n.object({id:n.uuid(),title:n.string().min(1).max(200),accessState:p,organisationId:n.uuid().nullable(),sourceUrl:n.string().max(u).nullable(),unresolvedCount:n.number().int().min(0),viewerCan:h,createdAt:n.iso.datetime(),lastActivityAt:n.iso.datetime()}),se=n.object({title:n.string().trim().min(1).max(200),organisationId:n.uuid().nullable().default(null),sourceUrl:n.string().max(u).nullable().default(null)}),ce=n.object({canvasId:n.uuid()}),le=n.union([n.literal(`own`),n.literal(`everything`),n.uuid()]),ue=n.object({collection:le.default(`own`),title:n.string().trim().min(1).max(200).optional().describe(`Title text to match before returning canvas ids.`),deleted:n.boolean().default(!1),accessState:p.optional(),scope:n.enum([`all`,`mine`,`shared`]).default(`all`),hasUnresolved:n.boolean().default(!1)}),de=g.extend({screenCount:n.number().int().min(0),hasRecording:n.boolean()}),fe=f(n.union([de.extend({thumbnail:re}),de.extend({thumbnail:n.null(),thumbnailFallbackReason:ne})])),pe=n.object({canvasId:n.uuid(),title:n.string().trim().min(1).max(200)}),me=n.object({canvasId:n.uuid()}),he=n.object({canvasId:n.uuid(),deletedAt:n.iso.datetime()}),ge=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)])}),_e=n.object({canvas:g}),ve=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),ye=n.object({canvas:g}),be=n.object({canvasId:n.uuid(),confirmation:n.string().min(1).max(200)}),xe=n.object({canvasId:n.uuid()}),Se=n.object({canvasId:n.uuid(),accessState:p}),Ce=n.object({canvas:g,widened:n.boolean()}),we=n.object({canvasId:n.uuid()}),Te=n.object({lastViewedAt:n.iso.datetime().nullable()}),Ee=n.object({canvasId:n.uuid()}),De=n.object({canvasId:n.uuid()}),Oe=new Set([`aspect-ratio`,`-webkit-line-clamp`,`line-clamp`,`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`,`grid-area`,`grid-row`,`grid-column`,`grid-row-start`,`grid-row-end`,`grid-column-start`,`grid-column-end`]),ke=(e,t)=>typeof t==`number`&&!Oe.has(e.toLowerCase())?`${String(t)}px`:String(t),Ae=[`top`,`right`,`bottom`,`left`],je=[`grid-template-rows`,`grid-template-columns`,`grid-template-areas`],Me={gap:[`row-gap`,`column-gap`],padding:Ae.map(e=>`padding-${e}`),margin:Ae.map(e=>`margin-${e}`),flex:[`flex-grow`,`flex-shrink`,`flex-basis`],"flex-flow":[`flex-direction`,`flex-wrap`],"place-content":[`align-content`,`justify-content`],"place-items":[`align-items`,`justify-items`],"place-self":[`align-self`,`justify-self`],"grid-template":je,grid:[...je,`grid-auto-rows`,`grid-auto-columns`,`grid-auto-flow`],"grid-row":[`grid-row-start`,`grid-row-end`],"grid-column":[`grid-column-start`,`grid-column-end`],"grid-area":[`grid-row-start`,`grid-column-start`,`grid-row-end`,`grid-column-end`]},Ne=e=>Me[e.toLowerCase()]??[e.toLowerCase()],Pe=(e,t)=>{if(e.isEscaped)return{...e,isEscaped:!1};if(t===`\\`)return{...e,isEscaped:!0};if(e.quote!==``)return{...e,quote:e.quote===t?``:e.quote};if([`"`,`'`].includes(t))return{...e,quote:t};let n=[`(`,`[`,`{`].includes(t)?1:[`)`,`]`,`}`].includes(t)?-1:0;return{...e,depth:e.depth+n}},Fe=(e,t=`space`)=>{let n=[],r=``,i={depth:0,quote:``,isEscaped:!1};for(let a of e){let e=i.depth===0&&i.quote===``&&!i.isEscaped;i=Pe(i,a),e&&(t===`space`?/\s/u.test(a):a===t)?((t!==`space`||r!==``)&&n.push(r.trim()),r=``):r+=a}return(t!==`space`||r!==``)&&n.push(r.trim()),n},Ie=e=>/^(?:--|-?[_a-z\u{80}-\u{FFFF}])[-\w\u{80}-\u{FFFF}]*$/iu.test(e)&&!/^(?:auto|span|initial|unset)$/iu.test(e)?e:`auto`,Le=(e,t,n)=>{let r=Fe(t,`/`),i=r[0]??t;if(e!==`grid-area`)return r[n]??Ie(i);let a=r[1]??Ie(i);return[i,a,r[2]??Ie(i),r[3]??Ie(a)][n]??t},Re=(e,t,n)=>{let r=Fe(n?e:t),i=r.filter(e=>!/^(?:auto-flow|dense)$/iu.test(e)).join(` `),a=`${n?`row`:`column`}${r.some(e=>/^dense$/iu.test(e))?` dense`:``}`;return[n?`none`:e,n?t:`none`,`none`,n&&i!==``?i:`auto`,!n&&i!==``?i:`auto`,a]},ze=(e,t,n)=>{if(/^(?:none|initial|unset)$/iu.test(t))return[`none`,`none`,`none`,`auto`,`auto`,`row`][n]??t;let r=Fe(t,`/`),i=r[0]??t,a=r[1];if(i===``||a===``||r.length>2)return t;let o=Fe(i).some(e=>e.toLowerCase()===`auto-flow`),s=a!==void 0&&Fe(a).some(e=>e.toLowerCase()===`auto-flow`);if(e===`grid`&&a!==void 0&&o!==s)return Re(i,a,o)[n]??t;if(o||s)return t;let c=/["']/u.test(i);return a===void 0&&!c?t:[c?t:i,a??`none`,c?i:`none`,`auto`,`auto`,`row`][n]??t},Be=e=>{let t=[],n=`0%`;for(let r of e)/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(r)&&t.length<2?t.push(r):n=r;return[t[0]??`1`,t[1]??`1`,n]},Ve=(e,t,n)=>{if(/(?:var|env)\(|^(?:inherit|revert(?:-layer)?)$/iu.test(t))return t;if(/^grid-(?:area|row|column)$/u.test(e))return Le(e,t,n);if(e===`grid-template`||e===`grid`)return ze(e,t,n);let r=Fe(t);return e===`flex-flow`?n===0?r.find(e=>/^(?:row|column)(?:-reverse)?$/u.test(e))??`row`:r.find(e=>/^(?:nowrap|wrap|wrap-reverse)$/u.test(e))??`nowrap`:e===`flex`?t===`none`?[`0`,`0`,`auto`][n]??t:t===`initial`?[`0`,`1`,`auto`][n]??t:Be(r)[n]??t:r[n]??(n===3?r[1]:void 0)??r[0]??t},He=e=>e.additionalStyles===void 0?{}:Object.fromEntries(e.additionalStyles.declarations.filter(e=>e.enabled).map(e=>[e.property,e.value])),Ue=e=>{let t=new Set(e.additionalStyles?.declarations.map(e=>e.property.toLowerCase()));return{...Object.fromEntries(Object.entries(e.styles).filter(([e])=>!t.has(e.toLowerCase()))),...He(e)}},We=e=>/!important\s*$/iu.test(String(e)),Ge=(e,t)=>{let n=String(e).replace(/\s*!important\s*$/iu,``).trim();return t||n.includes(`(`)?n:n.toLowerCase()},Ke=(e,t)=>{let n=null,r=!1,i=Object.entries(Ue(e));for(let[e,a]of i){let i=Ne(e),o=i.indexOf(t);if(o===-1)continue;let s=We(a);if(r&&!s)continue;let c=Ge(a,/^grid(?:-|$)/iu.test(e));n=i.length===1?c:Ve(e.toLowerCase(),c,o),r=s}return n??void 0},qe=(e,t)=>{let n=new Set(Object.entries(Ue(e)).filter(([,e])=>We(e)).flatMap(([e])=>Ne(e)));return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ne(e).some(e=>n.has(e))&&!We(t)?`${ke(e,t)} !important`:t]))},Je=(e,t)=>{let n=new Set,r=e;for(;r!==void 0&&!n.has(r.id);){n.add(r.id);let e=Ke(r,`writing-mode`);if(e!==void 0&&e!==`inherit`&&e!==`unset`)return e;if(t===void 0)break;let i=t.relationships[r.id]?.parentId;if(i===void 0)break;r=t.nodes[i]}return`horizontal-tb`},Ye=(e,t,n)=>{let r=/^(?:vertical|sideways)-/u.test(Je(e,n));return[t===`horizontal`?`width`:`height`,t===`vertical`===r?`inline-size`:`block-size`]},Xe=e=>{if(e===void 0)return`freeform`;let t=Ke(e,`display`);if(t!==void 0)return/^(?:(?:inline|block)\s+|inline-)?grid$/u.test(t)?`grid`:/^(?:(?:inline|block)\s+|inline-)?flex$/u.test(t)?`flex`:`freeform`;let n=e.layout?.container;return n===void 0?`freeform`:n.gridColumns!==void 0||n.gridAutoRepeat!==void 0?`grid`:`flex`},Ze=(e,t)=>{if(e===void 0||Xe(e)!==`flex`)return;let n=e.layout?.container?.direction??(t=>Ke(e,t))(`flex-direction`)??`row`;if(!/^(?:row|column)(?:-reverse)?$/u.test(n))return;let r=/^(?:vertical|sideways)-/u.test(Je(e,t));return n.startsWith(`column`)===r?`horizontal`:`vertical`},_=1e5,v=n.number().min(-1e5).max(_),y=n.number().nonnegative().max(_),Qe=n.object({ratio:y,offset:v.optional()}),$e=n.object({min:y.optional(),max:y.optional(),minParent:Qe.optional(),maxParent:Qe.optional()}).refine(({min:e,max:t})=>e===void 0||t===void 0||e<=t,`size minimum cannot exceed maximum`),et=n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`fixed`),value:y}).strict(),$e.extend({mode:n.literal(`hug`)}).strict(),$e.extend({mode:n.literal(`fill`),offset:v.optional()}).strict()]),tt=n.object({top:y,right:y,bottom:y,left:y}),nt=n.union([n.literal(`auto`),v]),rt=n.object({top:nt,right:nt,bottom:nt,left:nt}),it=n.object({mode:n.enum([`auto-fill`,`auto-fit`]),minimum:n.number().positive().max(_)}),at=n.object({x:v,y:v}),ot=n.object({direction:n.enum([`row`,`column`]),alignItems:n.enum([`start`,`center`,`end`,`stretch`]),alignContent:n.enum([`start`,`center`,`end`,`stretch`,`space-between`,`space-around`,`space-evenly`]).optional(),justifyContent:n.enum([`start`,`center`,`end`,`space-between`,`space-around`,`space-evenly`]),gap:y,rowGap:y.optional(),columnGap:y.optional(),wrap:n.enum([`nowrap`,`wrap`]).optional(),gridColumns:n.number().int().positive().max(_).optional(),gridAutoRepeat:it.optional(),padding:tt}).strict(),st=n.object({rotation:v.optional(),flipHorizontal:n.boolean().optional(),flipVertical:n.boolean().optional(),aspectRatioLocked:n.boolean().optional(),aspectRatio:n.number().positive().max(_).optional(),horizontal:et.optional(),vertical:et.optional(),position:n.enum([`flow`,`absolute`]).optional(),alignSelf:n.enum([`auto`,`start`,`center`,`end`,`stretch`]).optional(),flexGrow:y.optional(),flexShrink:y.optional(),flexBasis:n.union([n.literal(`auto`),y,Qe]).optional(),flowOffset:at.optional(),order:v.int().optional(),margin:rt.partial().optional(),clipContent:n.boolean().optional(),container:ot.partial().extend({padding:tt.partial().optional()}).optional()}).strict(),ct=v,b=y,x=n.number().min(0).max(1),lt=n.string().min(1).max(200),ut=n.object({space:n.enum([`srgb`,`display-p3`]),red:x,green:x,blue:x,alpha:x}),dt=n.object({id:lt,position:x,color:ut}),ft=n.object({x,y:x}),pt=n.object({id:lt,visible:n.boolean(),opacity:x}),mt=n.discriminatedUnion(`kind`,[pt.extend({kind:n.literal(`solid`),color:ut}),pt.extend({kind:n.literal(`linear-gradient`),angle:ct,stops:n.array(dt).min(2).max(32)}),pt.extend({kind:n.literal(`radial-gradient`),center:ft,radius:ft,stops:n.array(dt).min(2).max(32)}),pt.extend({kind:n.literal(`image`),assetId:n.string().min(1).max(500),fit:n.enum([`fill`,`fit`,`crop`,`tile`]),crop:n.object({x,y:x,width:x,height:x}).optional()})]),ht=n.object({topLeft:b,topRight:b,bottomRight:b,bottomLeft:b,smoothing:x.optional()}),gt=n.object({visible:n.boolean(),width:n.object({top:b,right:b,bottom:b,left:b}),style:n.enum([`solid`,`dashed`,`dotted`]),paint:mt,alignment:n.enum([`inside`,`center`,`outside`])}),_t=n.object({visible:n.boolean(),width:b,offset:ct,style:n.enum([`solid`,`dashed`,`dotted`]),paint:mt}),vt=n.object({id:lt,visible:n.boolean(),kind:n.enum([`outer`,`inner`]),color:ut,offsetX:ct,offsetY:ct,blur:b,spread:ct}),S=n.object({id:lt,visible:n.boolean()}),yt=n.discriminatedUnion(`kind`,[S.extend({kind:n.literal(`blur`),value:b}),S.extend({kind:n.literal(`brightness`),value:b}),S.extend({kind:n.literal(`contrast`),value:b}),S.extend({kind:n.literal(`grayscale`),value:x}),S.extend({kind:n.literal(`hue-rotate`),value:ct}),S.extend({kind:n.literal(`invert`),value:x}),S.extend({kind:n.literal(`saturate`),value:b}),S.extend({kind:n.literal(`sepia`),value:x})]),bt=n.enum([`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`plus-lighter`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`]);n.object({opacity:x,blendMode:bt,fills:n.array(mt).max(32),border:gt,outline:_t,radius:ht,shadows:n.array(vt).max(32),filters:n.array(yt).max(32),backdropFilters:n.array(yt).max(32)});const xt=n.object({opacity:x.optional(),blendMode:bt.optional(),fills:n.array(mt).max(32).optional(),border:gt.optional(),outline:_t.optional(),radius:ht.optional(),shadows:n.array(vt).max(32).optional(),filters:n.array(yt).max(32).optional(),backdropFilters:n.array(yt).max(32).optional()}).refine(e=>Object.keys(e).length>0,`appearance values cannot be empty`),St=[`opacity`,`blendMode`,`fills`,`border`,`outline`,`radius`,`shadows`,`filters`,`backdropFilters`],Ct=n.enum(St),wt=n.object({opacity:x.optional(),blendMode:bt.optional(),fills:n.array(mt).max(32).optional(),border:gt.optional(),outline:_t.optional(),radius:ht.optional(),shadows:n.array(vt).max(32).optional(),filters:n.array(yt).max(32).optional(),backdropFilters:n.array(yt).max(32).optional(),clear:n.array(Ct).min(1).max(St.length).optional()}).refine(e=>Object.keys(e).length>0,`appearance patch cannot be empty`).refine(({clear:e,...t})=>e===void 0||e.every(e=>t[e]===void 0),`appearance patch cannot set and clear the same property`),Tt=n.number().min(-1e5).max(_),Et=n.number().nonnegative().max(_),Dt=n.object({family:n.string().min(1).max(500),fallbackFamilies:n.array(n.string().min(1).max(500)).max(20),size:Et,weight:n.number().int().min(1).max(1e3),style:n.enum([`normal`,`italic`,`oblique`]),lineHeight:n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`normal`)}),n.object({mode:n.literal(`fixed`),value:Et})]),letterSpacing:Tt,align:n.enum([`left`,`center`,`right`,`justify`]),verticalAlign:n.enum([`top`,`middle`,`bottom`]),transform:n.enum([`none`,`uppercase`,`lowercase`,`capitalize`]),decoration:n.object({line:n.enum([`none`,`underline`,`line-through`]),style:n.enum([`solid`,`double`,`dotted`,`dashed`,`wavy`]),color:ut.optional(),thickness:Et.optional()}),stroke:n.object({width:Et,paint:mt}).optional(),wrapping:n.enum([`wrap`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]),truncation:n.object({mode:n.enum([`none`,`ellipsis`]),maxLines:n.number().int().min(1).max(_).nullable()}).optional(),insets:n.object({top:Tt,right:Tt,bottom:Tt,left:Tt}).optional()}),Ot=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,kt=/^(?:behavior|-moz-binding)$/iu,At=n.string().min(1).max(200).regex(/^(?:--[\w-]+|-(?:webkit|moz|ms|o)-[a-z][a-z\d-]*|[a-z][a-z\d-]*)$/iu).refine(e=>!kt.test(e),`unsafe CSS property`),jt=n.string().max(1e4).refine(e=>!Ot.test(e),`unsafe CSS value`),Mt=n.object({id:n.string().min(1).max(200),property:At,value:jt,enabled:n.boolean()}),Nt=n.object({declarations:n.array(Mt).max(128)}).refine(({declarations:e})=>new Set(e.map(e=>e.id)).size===e.length,`additional style ids must be unique`),Pt=n.literal(3,{error:`This editor uses an unsupported document format. Update the editor before changing this canvas.`}),C=n.object({x:n.number(),y:n.number(),width:n.number().nonnegative(),height:n.number().nonnegative()}),Ft=n.enum([`start`,`center`,`end`,`stretch`,`scale`]),It=n.object({x:Ft,y:Ft}),Lt=n.enum([`source`,`generated`,`user`]),Rt=n.looseObject({id:n.string().min(1).max(200),label:n.string().max(500),component:n.string().min(1).max(100),labelOrigin:Lt.optional(),visible:n.boolean().optional(),locked:n.boolean().optional(),constraints:It.optional(),styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:st.optional(),responsive:n.never().optional(),appearance:xt.optional(),typography:Dt.optional(),additionalStyles:Nt.optional(),props:n.record(n.string(),n.unknown()).optional(),box:C.optional()}),zt=n.object({version:n.literal(3),nodes:n.record(n.string(),Rt),relationships:n.record(n.string(),n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)})),tombstones:n.record(n.string(),n.literal(!0)).default({})}),Bt=n.record(n.string(),n.unknown()),Vt=e=>{let t=Bt.safeParse(e.layout).data;if(t===void 0)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`gridTrack`)),r=Bt.safeParse(n.container).data;r!==void 0&&(n.container=Object.fromEntries(Object.entries(r).filter(([e])=>e!==`materialized`)));for(let e of[`horizontal`,`vertical`]){let t=Bt.safeParse(n[e]).data;t?.mode===`hug`&&(n[e]=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`basis`)))}return{...e,layout:n}},Ht=e=>{if(Object.keys(e).length===0)return Wt();let t=n.record(n.string(),Bt).safeParse(e.nodes).data;return t===void 0?e:{...e,version:3,nodes:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Vt(t)]))}},Ut=n.preprocess(e=>{let t=Bt.safeParse(e).data;if(t===void 0)return e;let n=t.version;return new Set([void 0,1,2]).has(n)?Ht(t):t},zt),Wt=()=>({version:3,nodes:{root:{id:`root`,label:`Canvas`,component:`root`,labelOrigin:`generated`,visible:!0,locked:!1,styles:{}}},relationships:{},tombstones:{}}),Gt=3e4,w=5e4,Kt=n.string().min(1).max(200),qt=n.object({code:n.enum([`asset-unavailable`,`content-omitted`,`cross-origin-frame`,`nodes-truncated`,`responsive-behavior-not-editable`,`style-degraded`,`unsupported-surface`]),message:n.string().min(1).max(500),temporaryId:Kt.optional()}),Jt=n.object({nodeCount:n.number().int().positive().max(Gt),sourceNodeCount:n.number().int().positive().max(w).optional(),collapsedNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedNeutralWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),collapsedTransferredWrapperNodeCount:n.number().int().nonnegative().max(w).optional(),layoutContainerCount:n.number().int().nonnegative().max(Gt).optional(),removedLeafNodeCount:n.number().int().nonnegative().max(w).optional(),retainedSemanticOwnerNodeCount:n.number().int().nonnegative().max(w).optional(),truncatedNodeCount:n.number().int().nonnegative().max(w*2).optional(),addedLayoutNodeCount:n.number().int().nonnegative().max(w).optional(),issues:n.array(qt).max(w)}).refine(({collapsedNeutralWrapperNodeCount:e,collapsedTransferredWrapperNodeCount:t,collapsedWrapperNodeCount:n})=>n===void 0||e===void 0||t===void 0||e+t===n,`wrapper collapse proof classes must explain the collapsed wrapper count`).refine(({collapsedNodeCount:e,collapsedWrapperNodeCount:t,removedLeafNodeCount:n})=>e===void 0||t===void 0||n===void 0||t+n===e,`collapsed node kinds must explain the total collapsed node count`).refine(({addedLayoutNodeCount:e,collapsedNodeCount:t,nodeCount:n,sourceNodeCount:r,truncatedNodeCount:i})=>r===void 0||t===void 0||r+(e??0)-n===t+(i??0),`added, collapsed and truncated node counts must explain the source to editable difference`).refine(({layoutContainerCount:e,nodeCount:t})=>e===void 0||e<=t,`layout container count cannot exceed editable node count`),Yt=Rt.omit({id:!0}).extend({temporaryId:Kt}),Xt=n.object({temporaryId:Kt,parentTemporaryId:Kt,sortKey:n.string().min(1).max(500)}),Zt=n.object({version:n.literal(1),rootTemporaryId:Kt,nodes:n.array(Yt).min(1).max(Gt),relationships:n.array(Xt).max(Gt-1),report:Jt}),Qt=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,mutationId:n.uuid(),baseVersion:n.number().int().positive(),screenNodeId:n.string().min(1).max(200),draft:Zt}),$t=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),rootNodeId:n.string().min(1).max(200),idMap:n.record(Kt,n.string().min(1).max(200)),insertedNodeIds:n.array(n.string().min(1).max(200)),removedNodeIds:n.array(n.string().min(1).max(200)),boxes:n.record(n.string().min(1).max(200),C),affectedBounds:C}),T=n.object({url:n.url(),expiresAt:n.iso.datetime(),headers:n.record(n.string(),n.string())}),en=n.object({url:n.url(),expiresAt:n.iso.datetime(),bytes:n.number().int().min(0)}),tn=[`queued`,`claimed`,`grant`,`navigate`,`document`,`sources`,`fonts`,`layout`,`target`,`capture`,`serialize`,`compile`,`commit`,`upload`,`complete`],nn=[`queued`,`running`,`succeeded`,`failed`,`cancelled`,`expired`],rn=[`VERSION_CHANGED`,`TARGET_NOT_FOUND`,`TARGET_INVALID`,`OUTPUT_TOO_LARGE`,`READINESS_TIMEOUT`,`SOURCE_FAILED`,`BROWSER_CRASH`,`CAPTURE_FAILED`,`CONVERSION_FAILED`,`UPLOAD_FAILED`,`WORKER_UNAVAILABLE`,`CANCELLED`,`EXPIRED`,`INTERNAL`],an=[`ASSET_UNAVAILABLE`,`FONT_FALLBACK`,`SOURCE_FALLBACK`,`SCALE_REDUCED`],on=32*te,sn=64*te,cn=1e5,ln=.1,E=n.object({x:n.number(),y:n.number(),width:n.number().positive().max(cn),height:n.number().positive().max(cn)}),D=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`content`)}),n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`bounds`),bounds:E})]),un=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),dn=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative()}),fn=n.object({recordingId:n.uuid(),atMs:n.number().int().nonnegative(),screenId:n.uuid(),screenNodeId:n.string().min(1).max(200),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),box:E,version:n.number().int().positive(),alreadyPresent:n.boolean()}),pn=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional(),target:D.default({kind:`content`}),sourceState:un.optional(),scale:n.number().min(ln).max(4).default(1),format:n.literal(`png`).default(`png`)}).refine(e=>e.sourceState===void 0||e.target.kind===`node`,{message:`a source state requires a node render target`,path:[`sourceState`]}),mn=n.enum(tn);n.enum(nn);const hn=n.enum(rn),gn=n.enum(an),_n=n.object({code:gn,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),vn=n.object({reason:hn,phase:mn,message:n.string().min(1).max(500),retryable:n.boolean(),sourceId:n.string().min(1).max(200).nullable()}),yn=n.object({phase:mn,durationMs:n.number().int().min(0)}),bn=n.object({canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),target:D,sourceState:dn.optional(),snapshot:fn.optional(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive().max(on),warnings:n.array(_n),timings:n.array(yn),expiresAt:n.iso.datetime()}).refine(e=>e.width*e.height<=16e6,{message:`render output may contain at most 16000000 pixels`,path:[`width`]}),xn=n.object({id:n.uuid(),canvasId:n.uuid(),purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),phase:mn,requestedVersion:n.number().int().positive(),target:D,sourceState:un.optional(),scale:n.number().positive(),format:n.literal(`png`),attempt:n.number().int().min(0),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),Sn=n.discriminatedUnion(`state`,[xn.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),xn.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),xn.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:bn,failure:n.null()}),xn.extend({state:n.literal(`failed`),result:n.null(),failure:vn}),xn.extend({state:n.literal(`cancelled`),result:n.null(),failure:vn.extend({reason:n.literal(`CANCELLED`)})}),xn.extend({state:n.literal(`expired`),result:n.null(),failure:vn.extend({reason:n.literal(`EXPIRED`)})})]),Cn=n.object({job:Sn,alreadyExists:n.boolean()}),wn=n.object({jobId:n.uuid()}),Tn=n.object({job:Sn}),En=n.object({jobId:n.uuid()}),Dn=n.object({job:Sn}),On=n.object({jobId:n.uuid()}),kn=n.object({jobId:n.uuid(),download:en}),An=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),jn=n.object({job:Sn,alreadyExists:n.boolean()}),Mn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`adjacent`)}),n.object({kind:n.literal(`insert-children`),targetNodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`replace`),targetNodeId:n.string().min(1).max(200)})]),Nn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),html:n.string().min(1).max(262144),label:n.string().min(1).max(500),idPrefix:n.string().min(1).max(80).regex(/^[\w-]+$/u).optional()})]),Pn=n.object({source:Nn,destination:Mn}).superRefine((e,t)=>{e.source.kind===`screen`&&e.destination.kind!==`adjacent`&&t.addIssue({code:`custom`,message:`stored screens convert beside their source`,path:[`destination`]}),e.source.kind===`html`&&e.destination.kind===`adjacent`&&t.addIssue({code:`custom`,message:`authored HTML requires an editable destination`,path:[`destination`]})}),Fn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),label:n.string().min(1).max(500)})]),In=n.object({id:n.uuid(),canvasId:n.uuid(),source:Fn,destination:Mn,phase:mn,requestedVersion:n.number().int().positive(),attempt:n.number().int().nonnegative(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),Ln=n.discriminatedUnion(`state`,[In.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),In.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),In.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:$t.extend({report:Jt}),failure:n.null()}),In.extend({state:n.literal(`failed`),result:n.null(),failure:vn}),In.extend({state:n.literal(`cancelled`),result:n.null(),failure:vn.extend({reason:n.literal(`CANCELLED`)})}),In.extend({state:n.literal(`expired`),result:n.null(),failure:vn.extend({reason:n.literal(`EXPIRED`)})})]),Rn=Pn.and(n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional()})),zn=n.object({job:Ln,alreadyExists:n.boolean()}),Bn=n.object({jobId:n.uuid()}),Vn=n.object({job:Ln}),Hn=n.object({jobId:n.uuid()}),Un=n.object({job:Ln});n.discriminatedUnion(`state`,[n.object({state:n.literal(`loading`),jobId:n.uuid()}),n.object({state:n.literal(`ready`),jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Zt}),n.object({state:n.literal(`failed`),jobId:n.uuid(),message:n.string().min(1).max(500)})]);const Wn=n.record(n.string(),n.unknown()),Gn=n.object({canvasId:n.uuid()}),Kn=n.object({screenId:n.uuid(),route:n.string().max(u).nullable(),title:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),atMs:n.number().int().min(0).nullable(),sourceRecordingId:n.uuid().nullable(),assetBundle:n.object({assetBundleId:n.uuid(),sourceUrl:n.string().max(u),assets:n.array(n.object({url:n.string().max(u),contentType:n.string().max(200),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}).nullable(),download:en.nullable()}),qn=n.object({version:n.number().int().min(1),document:Wn,screens:n.array(Kn)}),Jn=n.object({canvasId:n.uuid(),baseVersion:n.number().int().min(1),document:Wn.refine(e=>zt.safeParse(e).success,`A save requires a valid current-format canvas document.`),screenIds:n.array(n.uuid()).max(2e3)}),Yn=n.discriminatedUnion(`outcome`,[n.object({outcome:n.literal(`saved`),version:n.number().int().min(1)}),n.object({outcome:n.literal(`conflict`),version:n.number().int().min(1),document:Wn})]),Xn=n.object({canvasId:n.uuid(),contentType:n.enum([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),bytes:n.number().int().positive().max(20971520)}),Zn=n.object({assetId:n.uuid(),path:n.string().startsWith(`/v1/canvas-assets/`),upload:T}),Qn=(e,t)=>`/v1/canvas-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,$n=n.enum([`position`,`layout`,`clip`,`cornerRadius`,`blending`,`typography`,`nativeControl`,`textDecoration`,`fill`,`outline`,`textStroke`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`vector`,`export`,`source`]),er=n.object({id:n.string().min(1).max(200),label:n.string().max(500),kind:n.string().min(1).max(100),parentId:n.string().min(1).max(200).nullable(),childCount:n.number().int().min(0),box:E.nullable(),propertySections:n.array($n)}),tr=n.object({canvasId:n.uuid()}),nr=n.object({canvasId:n.uuid(),openUrl:n.url(),title:n.string().min(1),version:n.number().int().positive(),nodeCount:n.number().int().min(0),rootChildCount:n.number().int().min(0),bounds:E.nullable(),kinds:n.record(n.string(),n.number().int().min(0)),next:n.array(n.string().min(1))}),rr=n.object({canvasId:n.uuid()}),ir=n.object({canvasId:n.uuid(),version:n.number().int().positive(),nodes:n.array(er)}),ar=n.object({canvasId:n.uuid(),nodeId:n.string().min(1).max(200)}),or=n.object({canvasId:n.uuid(),version:n.number().int().positive(),node:er.extend({styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:st.optional(),appearance:xt.optional(),typography:Dt.optional(),additionalStyles:Nt.optional(),props:n.record(n.string(),n.unknown()),children:n.array(n.string().min(1).max(200))}),next:n.array(n.string().min(1))}),sr=[[`alignSelf`,`align-self`],[`order`,`order`],[`flexGrow`,`flex-grow`],[`flexShrink`,`flex-shrink`],[`flexBasis`,`flex-basis`],[`aspectRatio`,`aspect-ratio`]],cr=[[`direction`,`flex-direction`],[`wrap`,`flex-wrap`],[`alignItems`,`align-items`],[`alignContent`,`align-content`],[`justifyContent`,`justify-content`],[`rowGap`,`row-gap`],[`columnGap`,`column-gap`]],lr=[`top`,`right`,`bottom`,`left`],ur=(e,t,n)=>{let r={...e};for(let e of lr)n.has(`${t}-${e}`)&&Reflect.deleteProperty(r,e);return r},dr=(e,t)=>{let n=new Set([...t].flatMap(e=>Ne(e))),r={...e};for(let[e,t]of sr)n.has(t)&&Reflect.deleteProperty(r,e);if(r.margin!==void 0&&(r.margin=ur(r.margin,`margin`,n)),r.container===void 0)return r;let i={...r.container};(n.has(`row-gap`)||n.has(`column-gap`))&&i.gap!==void 0&&(i.rowGap??=i.gap,i.columnGap??=i.gap,Reflect.deleteProperty(i,`gap`));for(let[e,t]of cr)n.has(t)&&Reflect.deleteProperty(i,e);return i.padding!==void 0&&(i.padding=ur(i.padding,`padding`,n)),n.has(`grid-template-columns`)&&(Reflect.deleteProperty(i,`gridColumns`),Reflect.deleteProperty(i,`gridAutoRepeat`)),r.container=i,r},fr=(e,t,n)=>{if(e===void 0||e.mode===`fixed`)return e;let r={...e};for(let e of[`min`,`max`])t.every(t=>!n.has(`${e}-${t}`))||(Reflect.deleteProperty(r,e),Reflect.deleteProperty(r,`${e}Parent`));return r},pr=(e,t,n)=>{let r=new Set([...t].flatMap(e=>Ne(e))),i=dr(e,r);if([`overflow`,`overflow-x`,`overflow-y`].some(e=>r.has(e))&&Reflect.deleteProperty(i,`clipContent`),r.has(`position`)&&Reflect.deleteProperty(i,`position`),r.has(`transform`))for(let e of[`rotation`,`flipHorizontal`,`flipVertical`])Reflect.deleteProperty(i,e);[`inset`,`left`,`right`,`top`,`bottom`].some(e=>r.has(e))&&Reflect.deleteProperty(i,`flowOffset`);for(let e of[`horizontal`,`vertical`]){let t=n[e].some(e=>r.has(e))?void 0:fr(i[e],n[e],r);t===void 0?Reflect.deleteProperty(i,e):i[e]=t}return i},mr=[`position`,`layout`,`cornerRadius`,`blending`,`fill`,`outline`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`export`],hr=[`position`,`layout`,`clip`,...mr.filter(e=>e!==`position`&&e!==`layout`)],gr=[...mr,`vector`],_r=Object.fromEntries([{objectKind:`prototype`,label:`Prototype`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`node`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`]},{objectKind:`root`,label:`Canvas`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!0,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`page`,label:`Page`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!1,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`screen`,label:`Screen`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`screen`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`,`source`]},{objectKind:`frame`,label:`Frame`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:hr},{objectKind:`group`,label:`Group`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:[`position`,`layout`,`blending`,`additionalStyles`,`export`]},{objectKind:`rectangle`,label:`Rectangle`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!0},propertySections:mr},{objectKind:`image`,label:`Image`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:mr},{objectKind:`svg`,label:`SVG`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},capture:{preservesVectorData:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:gr},{objectKind:`recording`,label:`Recording`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1},capture:{preservesAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,canLockAspectRatio:!0},propertySections:[]},{objectKind:`text`,label:`Text`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`text`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,canLockAspectRatio:!1},propertySections:[`position`,`layout`,`typography`,`nativeControl`,`textDecoration`,`textStroke`,`blending`,`fill`,`outerShadow`,`filters`,`additionalStyles`,`export`]}].map(e=>[e.objectKind,e])),vr=e=>_r[e]??null,yr=e=>vr(e)?.propertySections??[],br=n.string().regex(/^(?:\d+(?:\.\d+)?|\.\d+)px$/u),xr=n.string().regex(/^-?(?:\d+(?:\.\d+)?|\.\d+)px$/u),O={color:n.union([n.enum([`var(--note-ink)`,`var(--note-slate)`,`var(--note-red)`,`var(--note-orange)`,`var(--note-amber)`,`var(--note-green)`,`var(--note-teal)`,`var(--note-blue)`,`var(--note-violet)`,`var(--note-magenta)`]),n.string().regex(/^#[\da-f]{6}$/iu)]),"font-family":n.enum([`var(--sans)`,`var(--mono)`]),"font-size":n.union([n.literal(16),n.literal(24),n.literal(40),n.literal(64),n.literal(96)]),"font-weight":n.enum([`400`,`700`]),"font-style":n.enum([`normal`,`italic`,`oblique`]),"letter-spacing":n.number().min(-100).max(100),"line-height":n.union([n.number().positive().max(1e4),n.string().regex(/^(?:\d+(?:\.\d+)?(?:px|em|rem|%)?|normal)$/u)]),"text-align":n.enum([`left`,`center`,`right`]),"white-space":n.enum([`normal`,`nowrap`,`pre`,`pre-wrap`,`pre-line`,`break-spaces`])},Sr=n.strictObject({color:O.color.optional(),"font-family":O[`font-family`].optional(),"font-size":O[`font-size`].optional(),"font-weight":O[`font-weight`].optional(),"font-style":O[`font-style`].optional(),"letter-spacing":O[`letter-spacing`].optional(),"line-height":O[`line-height`].optional(),"text-align":O[`text-align`].optional(),"white-space":O[`white-space`].optional()}),Cr=n.strictObject({color:O.color.nullable().optional(),"font-family":O[`font-family`].nullable().optional(),"font-size":n.union([y,br]).nullable().optional(),"font-weight":n.string().regex(/^(?:[1-9]\d{0,2}|1000)$/u).nullable().optional(),"font-style":O[`font-style`].nullable().optional(),"font-stretch":n.union([n.enum([`normal`,`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`]),n.string().regex(/^\d+(?:\.\d+)?%$/u)]).nullable().optional(),"letter-spacing":n.union([v,xr,n.literal(`normal`)]).nullable().optional(),"line-height":O[`line-height`].nullable().optional(),"text-align":O[`text-align`].nullable().optional(),"text-indent":n.union([v,xr]).nullable().optional(),"white-space":O[`white-space`].nullable().optional(),"word-spacing":n.union([v,xr,n.literal(`normal`)]).nullable().optional()}),wr=Mt.shape.value,k=n.union([n.string(),v]),A=n.union([Mt.shape.value,v]).nullable().optional(),Tr=Cr.extend({"align-content":A,"align-items":A,"align-self":A,"aspect-ratio":A,"block-size":A,bottom:A,"box-sizing":A,display:A,flex:A,"flex-basis":A,"flex-direction":A,"flex-grow":A,"flex-shrink":A,"flex-wrap":A,height:A,"inline-size":A,inset:A,"inset-block":A,"inset-block-end":A,"inset-block-start":A,"inset-inline":A,"inset-inline-end":A,"inset-inline-start":A,"justify-content":A,left:A,margin:A,"margin-block":A,"margin-block-end":A,"margin-block-start":A,"margin-inline":A,"margin-inline-end":A,"margin-inline-start":A,"max-block-size":A,"max-height":A,"max-inline-size":A,"max-width":A,"min-block-size":A,"min-height":A,"min-inline-size":A,"min-width":A,order:A,padding:A,"padding-block":A,"padding-block-end":A,"padding-block-start":A,"padding-inline":A,"padding-inline-end":A,"padding-inline-start":A,position:A,right:A,top:A,width:A,background:n.string().nullable().optional(),"background-color":n.string().nullable().optional(),"border-bottom-left-radius":k.optional(),"border-bottom-right-radius":k.optional(),"border-bottom-width":k.optional(),"border-color":n.string().nullable().optional(),"border-left-width":k.optional(),"border-radius":k.nullable().optional(),"border-right-width":k.optional(),"border-style":n.enum([`none`,`solid`,`dashed`,`dotted`]).nullable().optional(),"border-top-left-radius":k.optional(),"border-top-right-radius":k.optional(),"border-top-width":k.optional(),"border-width":k.nullable().optional(),"box-shadow":n.string().nullable().optional(),"column-gap":k.optional(),gap:k.optional(),"margin-bottom":k.optional(),"margin-left":k.optional(),"margin-right":k.optional(),"margin-top":k.optional(),opacity:n.union([n.string(),n.number()]).nullable().optional(),"outline-offset":k.optional(),"outline-width":k.optional(),overflow:wr.nullable().optional(),"overflow-x":wr.nullable().optional(),"overflow-y":wr.nullable().optional(),"padding-bottom":k.optional(),"padding-left":k.optional(),"padding-right":k.optional(),"padding-top":k.optional(),"row-gap":k.optional(),"stroke-width":k.optional()}),Er=n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)}),Dr=n.object({op:n.literal(`insertConvertedSubtree`),destination:Mn,sourceNodeId:n.string().min(1).max(200).optional(),rootNodeId:n.string().min(1).max(200),nodes:n.record(n.string().min(1).max(200),Rt).refine(e=>Object.keys(e).length<=Gt),relationships:n.record(n.string().min(1).max(200),Er).refine(e=>Object.keys(e).length<Gt)}),Or=1e5,kr=1e3,j=n.string().min(1).max(200),Ar=n.string().min(1).max(500),jr=C.extend({width:n.number().positive(),height:n.number().positive()}),Mr=n.object({parentId:j,afterId:j.optional()}),Nr=n.object({parentId:j,sortKey:Ar}),Pr=n.object({op:n.literal(`setStyles`),nodeId:j,styles:Tr,clear:n.array(Tr.keyof()).min(1).max(Object.keys(Tr.shape).length).refine(e=>new Set(e).size===e.length).optional()}).refine(e=>(e.clear??[]).every(t=>!Object.hasOwn(e.styles,t))),Fr=n.discriminatedUnion(`op`,[Dr,n.object({op:n.literal(`insertNode`),node:Rt,parentage:Nr}),Mr.extend({op:n.literal(`insertText`),nodeId:j,label:n.string().max(500).default(`Text`),text:n.string().max(Or),box:jr,styles:Sr.default({})}),Mr.extend({op:n.literal(`insertPrototype`),nodeId:j,label:n.string().max(500).default(`Prototype`),prototypeId:n.uuid(),deploymentId:n.uuid(),box:jr,canvasPageId:j.optional()}),n.object({op:n.literal(`setPrototypeDeployment`),nodeId:j,prototypeId:n.uuid(),deploymentId:n.uuid()}),n.object({op:n.literal(`setText`),nodeId:j,text:n.string().max(Or)}),n.object({op:n.literal(`setBox`),nodeId:j,box:n.union([C,n.literal(`default`)])}),n.object({op:n.literal(`setLabel`),nodeId:j,label:n.string().trim().min(1).max(500),labelOrigin:Lt.nullable().optional()}),n.object({op:n.literal(`setContainerKind`),nodeId:j,component:n.enum([`frame`,`group`])}),n.object({op:n.literal(`setVisibility`),nodeId:j,visible:n.boolean().nullable()}),n.object({op:n.literal(`setLocked`),nodeId:j,locked:n.boolean().nullable()}),n.object({op:n.literal(`setConstraints`),nodeId:j,constraints:It}),Pr,n.object({op:n.literal(`setAppearance`),nodeId:j,appearance:wt}),n.object({op:n.literal(`setLayout`),nodeId:j,layout:n.union([st,n.literal(`default`)])}),n.object({op:n.literal(`setTypography`),nodeId:j,typography:n.union([Dt,n.literal(`default`)])}),n.object({op:n.literal(`setAdditionalStyles`),nodeId:j,additionalStyles:n.union([Nt,n.literal(`default`)])}),n.object({op:n.literal(`setProps`),nodeId:j,props:n.union([n.record(n.string(),n.unknown()),n.literal(`default`)])}),n.object({op:n.literal(`setParentage`),nodeId:j,parentage:Nr}),Mr.extend({op:n.literal(`move`),nodeId:j}),n.object({op:n.literal(`remove`),nodeId:j})]),Ir=n.object({canvasId:n.uuid(),mutationId:n.uuid(),documentFormatVersion:Pt,baseVersion:n.number().int().positive(),operations:n.array(Fr).min(1).max(kr)}),Lr=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),insertedNodeIds:n.array(j),changedNodeIds:n.array(j),removedNodeIds:n.array(j),boxes:n.record(j,C),affectedBounds:jr.nullable(),next:n.array(n.string().min(1))}),Rr=$t.extend({operation:Dr,next:n.array(n.string().min(1))}),zr=`enhance3.canvas.v1`,Br=n.enum([`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`]),Vr=n.object({kind:n.literal(`person`),connectionId:n.uuid(),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:Br}),Hr=n.object({kind:n.literal(`guest`),connectionId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:Br}),Ur=n.discriminatedUnion(`kind`,[Vr,Hr]),Wr=n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),tokenLabel:n.string().min(1).max(100),colour:Br}),Gr=n.discriminatedUnion(`kind`,[Vr.omit({connectionId:!0}),Wr]),Kr=n.object({x:n.number(),y:n.number()}),qr=C.extend({width:n.number().positive(),height:n.number().positive()}),Jr=n.object({kind:n.enum([`drag`,`resize`]),baseVersion:n.number().int().positive(),boxes:n.record(n.string().min(1).max(200),qr)}),Yr=n.object({cursor:Kr.nullable().optional(),input:n.enum([`pointer`,`touch`,`keyboard`]).optional(),focused:n.boolean().optional(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100).optional(),visibleWorldBox:qr.optional(),gesture:Jr.nullable().optional(),cursorChat:n.string().max(140).nullable().optional()}).refine(e=>Object.keys(e).length>0,`presence patch cannot be empty`),Xr=n.object({actor:Ur,seq:n.number().int().nonnegative(),cursor:Kr.nullable(),input:n.enum([`pointer`,`touch`,`keyboard`]),focused:n.boolean(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100),visibleWorldBox:qr.nullable(),gesture:Jr.nullable(),cursorChat:n.string().max(140).nullable().default(null),expiresAt:n.iso.datetime()}),Zr=n.enum([`reading`,`writing`,`creating`,`deleting`,`rendering`]),Qr=n.object({activityId:n.uuid(),canvasId:n.uuid(),actor:Wr,phase:Zr,nodeIds:n.array(n.string().min(1).max(200)).max(100),bounds:qr.nullable(),expiresAt:n.iso.datetime()}),$r=n.object({canvasId:n.uuid(),protocols:n.array(n.literal(zr)).min(1).max(1)}),ei=n.object({endpoint:n.url(),ticket:n.string().min(1).max(4096),protocol:n.literal(zr),expiresAt:n.iso.datetime()}),ti=n.object({canvasId:n.uuid(),phase:Zr,nodeIds:n.array(n.string().min(1).max(200)).max(100).default([]),bounds:qr.nullable().default(null)}),ni=n.object({activityId:n.uuid(),expiresAt:n.iso.datetime(),renewAfterMs:n.number().int().positive()}),ri=ti.extend({activityId:n.uuid()}),ii=n.object({canvasId:n.uuid(),activityId:n.uuid()}),ai=n.object({ended:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({v:n.literal(1),type:n.literal(`presence.patch`),seq:n.number().int().nonnegative(),payload:Yr}),n.object({v:n.literal(1),type:n.literal(`room.pong`),seq:n.number().int().nonnegative(),payload:n.object({pingId:n.uuid()})})]);const M={v:n.literal(1),seq:n.number().int().nonnegative()};n.discriminatedUnion(`type`,[n.object({...M,type:n.literal(`room.snapshot`),payload:n.object({connectionId:n.uuid(),peers:n.array(Xr),activities:n.array(Qr),documentVersion:n.number().int().positive()})}),n.object({...M,type:n.literal(`presence.patch`),payload:Xr}),n.object({...M,type:n.literal(`presence.left`),payload:n.object({connectionId:n.uuid()})}),n.object({...M,type:n.literal(`agent.activity`),payload:n.object({activityId:n.uuid(),activity:Qr.nullable()})}),n.object({...M,type:n.literal(`document.committed`),payload:n.object({mutationId:n.uuid(),actor:Gr,previousVersion:n.number().int().positive(),version:n.number().int().positive(),operations:n.array(Fr).min(1)})}),n.object({...M,type:n.literal(`sync.required`),payload:n.object({version:n.number().int().positive(),reason:n.enum([`gap`,`relay`,`replace`,`history-restored`])})}),n.object({...M,type:n.literal(`room.ping`),payload:n.object({pingId:n.uuid(),sentAt:n.iso.datetime()})}),n.object({...M,type:n.literal(`room.error`),payload:n.object({code:n.enum([`auth`,`permission`,`protocol`,`payload`,`rate`,`unavailable`]),message:n.string().min(1).max(200)})})]);const oi=n.object({jobId:n.uuid()}),si=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),target:D,sourceState:un.optional()}),ci=n.discriminatedUnion(`purpose`,[si.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),scale:n.number().positive().max(4),format:n.literal(`png`)}),si.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:Pn,scale:n.literal(1),format:n.literal(`json`)})]);n.object({jobId:n.uuid()}),n.object({jobId:n.uuid()});const li=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),grantToken:n.string().startsWith(`rgr_`).min(40).max(100),grantCookieName:n.string().min(1).max(100),renderUrl:n.url(),releaseIdentity:n.string().min(1).max(100)});n.discriminatedUnion(`purpose`,[li.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),target:D,sourceState:un.optional(),scale:n.number().positive(),outputKey:n.string().min(1).max(500)}),li.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:Pn,scale:n.literal(1)})]),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),bytes:n.number().int().positive().max(on),storageKey:n.string().min(1).max(500),warnings:n.array(_n),timings:n.array(yn),sourceState:dn.optional(),snapshot:n.object({artifactBytes:n.number().int().positive().max(sn),artifactStorageKey:n.string().min(1).max(500),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}).optional()}),n.object({accepted:n.literal(!0)}),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Zt}),n.object({accepted:n.literal(!0)}),n.object({recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative(),artifact:n.string().min(1).max(sn),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}),n.object({jobId:n.uuid(),failure:vn}),n.object({accepted:n.literal(!0),willRetry:n.boolean()}),n.object({workerId:n.string().regex(/^[\w.-]+$/u).min(1).max(100),releaseIdentity:n.string().min(1).max(100),timestamp:n.coerce.number().int().nonnegative(),nonce:n.uuid(),mac:n.base64().min(32).max(200)});const ui=n.object({total:n.number().int().nonnegative(),loading:n.number().int().nonnegative(),unavailable:n.number().int().nonnegative()}),di=n.object({jobId:n.uuid(),canvasId:n.uuid().nullable(),requestedVersion:n.number().int().positive().nullable(),loadedVersion:n.number().int().positive().nullable(),phase:mn.exclude([`queued`,`claimed`,`capture`,`upload`,`complete`]),sources:ui,warnings:n.array(_n),timings:n.array(yn),sourceState:dn.optional()}),fi=n.object({selector:n.string().min(1).max(500),contentSelector:n.string().min(1).max(500).optional(),bounds:E,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive()});n.discriminatedUnion(`state`,[di.extend({state:n.literal(`loading`),capture:n.null(),failure:n.null()}),di.extend({state:n.literal(`ready`),phase:n.literal(`target`),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),capture:fi,failure:n.null()}),di.extend({state:n.literal(`failed`),failure:n.object({reason:hn,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),capture:n.null()})]);const pi=n.string().min(1).max(200),mi=n.object({canvasId:n.uuid()}),hi=n.object({canvasId:n.uuid(),status:n.enum([`selected`,`none`,`offline`,`stale`]),documentVersion:n.number().int().positive(),selectionRevision:n.number().int().positive().nullable(),selectionChangedAt:n.iso.datetime().nullable(),selectedNodeIds:n.array(pi),missingNodeIds:n.array(pi),nodes:n.array(er),contextRootId:pi.nullable(),visibleWorldBox:E.nullable(),next:n.array(n.string().min(1)).max(12)}),gi=1e3,_i=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2)}),n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2),tokenLabel:n.string().min(1).max(200)})]),vi=n.object({id:n.uuid(),canvasId:n.uuid(),documentVersion:n.number().int().positive(),origin:n.enum([`automatic`,`manual`,`restore`]),restoreRole:n.enum([`before`,`result`]).nullable(),retention:n.enum([`automatic`,`named`,`restore-boundary`]),title:n.string().min(1).max(200).nullable(),description:n.string().max(gi).nullable(),actor:_i,sourceVersionEntryId:n.uuid().nullable(),expiresAt:n.iso.datetime().nullable(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime(),screenCount:n.number().int().min(0)}),yi=n.object({canvasId:n.uuid(),limit:n.number().int().min(1).max(100).default(50),cursor:n.string().min(1).max(1e3).optional(),includeAutomatic:n.boolean().default(!1),actor:n.enum([`all`,`mine`]).default(`all`)}),bi=n.object({current:n.object({documentVersion:n.number().int().positive(),updatedAt:n.iso.datetime()}),items:n.array(vi),nextCursor:n.string().min(1).nullable(),hasExpiredHistory:n.boolean()}),xi=n.object({canvasId:n.uuid(),versionId:n.uuid()}),Si=n.object({outcome:n.literal(`ready`),entry:vi,document:Wn,screens:n.array(Kn)}),Ci=n.object({outcome:n.literal(`missing-resources`),entry:vi,document:Wn,screens:n.array(Kn),missingScreenIds:n.array(n.uuid()).min(1)}),wi=n.discriminatedUnion(`outcome`,[Si,Ci,n.object({outcome:n.literal(`corrupt`),entry:vi})]),Ti=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`current`),expectedVersion:n.number().int().positive()}),n.object({kind:n.literal(`version`),versionId:n.uuid()})]),Ei=n.object({canvasId:n.uuid(),target:Ti,title:n.string().trim().min(1).max(200),description:n.string().trim().max(gi).nullable().default(null)}),Di=n.object({canvasId:n.uuid(),versionId:n.uuid(),title:n.string().trim().min(1).max(200),description:n.string().trim().max(gi).nullable().default(null)}),Oi=n.object({canvasId:n.uuid(),versionId:n.uuid()}),ki=n.object({entry:vi}),Ai=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,versionId:n.uuid(),expectedVersion:n.number().int().positive()}),ji=n.object({canvasId:n.uuid(),version:n.number().int().positive(),beforeVersionId:n.uuid(),restoredVersionId:n.uuid(),restoreFenceVersion:n.number().int().positive()}),Mi=n.object({canvasId:n.uuid(),documentFormatVersion:Pt,versionId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),Ni=n.object({canvasId:n.uuid(),title:n.string().min(1).max(200),version:n.literal(1)}),Pi=n.object({inviteId:n.uuid(),email:n.string().max(254),accessLevel:oe,sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),Fi=n.object({canvasTitle:n.string().min(1),invitedBy:n.string().min(1),email:n.string().max(254).pipe(n.email()),accessLevel:oe,expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),Ii=n.object({canvasId:n.uuid(),email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email()),accessLevel:oe}),Li=n.object({invite:Pi,acceptToken:n.string().max(512).optional()}),Ri=n.object({canvasId:n.uuid()}),zi=f(Pi),Bi=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),Vi=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),Hi=n.string().min(1).max(512),Ui=n.object({token:Hi}),Wi=n.object({token:Hi}),Gi=n.object({canvasId:n.uuid(),accessLevel:oe}),Ki=n.object({personId:n.uuid().nullable(),email:n.string().max(254).nullable(),displayName:n.string().max(120).nullable(),initials:n.string().max(4).nullable(),avatarUrl:n.string().max(u).nullable(),accessLevel:m,isPending:n.boolean(),reviewState:n.enum([`not-started`,`in-progress`,`done`]).nullable(),lastViewedAt:n.iso.datetime().nullable()}),qi=n.object({canvasId:n.uuid()}),Ji=f(Ki),Yi=n.object({canvasId:n.uuid(),personId:n.uuid(),accessLevel:oe}),Xi=n.object({canvasId:n.uuid(),personId:n.uuid()}),Zi=n.object({personId:n.uuid(),revoked:n.boolean()}),Qi=n.object({canvasId:n.uuid(),reviewState:n.enum([`not-started`,`in-progress`,`done`])}),$i=n.object({reviewState:Qi.shape.reviewState.nullable()}),ea=n.object({selector:n.string().min(1).max(2e3),tagName:n.string().min(1).max(40),label:n.string().max(80).nullable(),source:n.object({file:n.string().min(1).max(1024),line:n.number().int().min(0).nullable()}).nullable()}),ta=n.object({x:n.number(),y:n.number()}),na=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1)}),ra=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1),width:n.number().min(0).max(1),height:n.number().min(0).max(1)}),ia=ea.extend({role:n.string().min(1).max(80).optional()}),aa=n.object({path:n.array(n.number().int().min(0)).max(64),offset:n.number().int().min(0)}),oa=n.discriminatedUnion(`kind`,[n.object({version:n.literal(1),kind:n.literal(`element`),locator:ia,attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`text`),root:ia,quote:n.object({exact:n.string().min(1).max(1e3),prefix:n.string().max(120),suffix:n.string().max(120)}),range:n.object({start:aa,end:aa}),attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`elements`),members:n.array(ia).min(2).max(32),truncated:n.boolean(),attachment:na,fallbackBounds:ra}),n.object({version:n.literal(1),kind:n.literal(`area`),bounds:ra,attachment:na})]),sa=n.discriminatedUnion(`on`,[n.object({on:n.literal(`canvas`),point:ta}),n.object({on:n.literal(`node`),nodeId:n.string().min(1).max(120),point:ta,element:n.null()}),n.object({on:n.literal(`screen`),nodeId:n.string().min(1).max(120),screenId:n.uuid(),point:ta,element:ea.nullable(),target:oa.optional()})]),ca=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(u).nullable(),tokenLabel:n.string().max(120).nullable()}),la=n.object({personId:n.uuid(),name:n.string().min(1).max(120)}),ua=n.object({emoji:n.string().min(1).max(16),people:n.array(la).min(1)}),da=n.object({messageId:n.uuid(),seq:n.number().int().min(1),body:n.string().min(1),author:ca,createdAt:n.iso.datetime(),editedAt:n.iso.datetime().nullable(),mentions:n.array(la),reactions:n.array(ua)}),fa=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),tokenLabel:n.string().max(120).nullable()}),pa=n.object({threadId:n.uuid(),canvasId:n.uuid(),anchor:sa,author:ca,messages:n.array(da).min(1).max(50),messageCount:n.number().int().min(1),hasMoreMessages:n.boolean(),isResolved:n.boolean(),resolvedAt:n.iso.datetime().nullable(),resolvedBy:fa.nullable(),createdAt:n.iso.datetime(),lastMessageAt:n.iso.datetime()}),ma=n.object({canvasId:n.uuid(),filter:n.enum([`open`,`resolved`,`all`]).default(`open`),authorPersonId:n.uuid().optional(),agentActionable:n.boolean().default(!1),query:n.string().trim().max(200).optional()}),ha=f(pa),ga=n.object({canvasId:n.uuid(),clientThreadId:n.uuid(),anchor:sa,body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),_a=n.object({canvasId:n.uuid(),threadId:n.uuid(),clientMessageId:n.uuid(),body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),va=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),body:n.string().trim().min(1).max(d),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),ya=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),emoji:n.string().trim().min(1).max(16),reacted:n.boolean()}),ba=n.object({canvasId:n.uuid(),threadId:n.uuid(),anchor:sa}),xa=n.object({canvasId:n.uuid(),threadId:n.uuid(),resolved:n.boolean()}),Sa=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid().optional()}),Ca=n.object({deletedThreadIds:n.array(n.uuid()),deletedMessageIds:n.array(n.uuid())}),wa=`root`,Ta=e=>`a${String(e).padStart(4,`0`)}`,Ea=()=>({version:3,nodes:{[wa]:{id:wa,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Da=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:wa,sortKey:Ta(Object.keys(e.relationships).length)}}}),Oa=(e,t)=>Da(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),ka=n.enum([`owner`,`admin`,`member`]),Aa=n.object({id:n.uuid(),name:n.string().min(1).max(120),role:ka}),ja=n.object({}),Ma=f(Aa),Na=n.object({name:n.string().trim().min(1).max(120)}),Pa=n.object({organisation:Aa}),Fa=n.object({organisationId:n.uuid(),name:n.string().trim().min(1).max(120)}),Ia=n.object({organisationId:n.uuid()}),La=n.object({organisationId:n.uuid(),movedCanvasCount:n.number().int().min(0)}),Ra=n.object({personId:n.uuid(),displayName:n.string().max(120),initials:n.string().max(4),email:n.string().max(254).nullable(),role:ka}),za=n.object({organisationId:n.uuid()}),Ba=f(Ra),Va=n.object({organisationId:n.uuid(),email:n.email().trim().toLowerCase().max(254),role:n.enum([`admin`,`member`]).default(`member`)}),Ha=n.object({personId:n.uuid()}),Ua=n.object({organisationId:n.uuid(),personId:n.uuid(),role:n.enum([`admin`,`member`])}),Wa=Ua.pick({personId:!0,role:!0}),Ga=n.object({organisationId:n.uuid(),personId:n.uuid()}),Ka=n.object({personId:n.uuid(),removed:n.literal(!0)}),qa=n.object({organisationId:n.uuid(),personId:n.uuid()}),Ja=n.object({ownerPersonId:n.uuid()}),Ya=n.object({inviteId:n.uuid(),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),Xa=n.object({organisationId:n.uuid(),email:n.string().trim().toLowerCase().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]).default(`member`)}),Za=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`member`),personId:n.uuid()}),n.object({kind:n.literal(`invitation`),invite:Ya})]),Qa=n.object({invite:Ya}),$a=n.object({organisationId:n.uuid()}),eo=f(Ya),to=n.object({organisationId:n.uuid(),inviteId:n.uuid()}),no=to.extend({}),ro=n.string().min(1).max(512),io=n.object({token:ro}),ao=n.object({token:ro}),oo=n.object({teamName:n.string().min(1).max(120),invitedBy:n.string().min(1).max(120),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),so=n.object({organisationId:n.uuid()}),co=n.object({id:n.uuid(),label:n.string().min(1).max(120),createdAt:n.iso.datetime(),lastUsedAt:n.iso.datetime().nullable(),expiresAt:n.iso.datetime().nullable(),revoked:n.boolean()}),lo=n.object({label:n.string().trim().min(1).max(120).describe(`Label naming the agent.`),expiresAt:n.iso.datetime().nullable().describe(`Expiry timestamp, or null for a token that does not expire.`)}),uo=n.object({token:n.string().startsWith(`enh_`),agentToken:co}),fo=n.object({}),po=n.object({items:n.array(co),isConnected:n.boolean()}),mo=n.object({tokenId:n.uuid()}),ho=n.object({tokenId:n.uuid(),revoked:n.literal(!0)}),go=n.discriminatedUnion(`method`,[n.object({method:n.literal(`token`)}),n.object({method:n.literal(`browser`),issuer:n.url(),clientId:n.string().min(1),scope:n.literal(`openid`)})]),_o=n.object({id:n.uuid(),preparedCanvasId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(u).nullable(),email:n.string().max(254).nullable(),createdAt:n.iso.datetime()}),vo=n.object({}),yo=n.object({person:_o.nullable(),authentication:n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`anonymous`)}),n.object({kind:n.literal(`person`)}),n.object({kind:n.literal(`agent`),tokenId:n.uuid(),tokenLabel:n.string(),expiresAt:n.iso.datetime().nullable()}),n.object({kind:n.literal(`oauth-agent`),tokenId:n.uuid(),tokenLabel:n.string(),clientId:n.string().min(1),scopes:n.array(n.string()),expiresAt:n.iso.datetime(),resource:n.url()})])}),bo=n.object({displayName:n.string().trim().min(1).max(120)}),xo=n.object({person:_o}),So=n.string().trim().toLowerCase().min(3).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/,`letters, digits, dot, underscore and dash only`),Co=n.enum([`cookie`,`token`]).default(`cookie`),wo=n.object({username:So,password:n.string().min(10).max(200),displayName:n.string().trim().min(1).max(120),deliver:Co,email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email())}),To=n.object({username:So,password:n.string().min(1).max(200),deliver:Co}),Eo=n.object({person:_o,token:n.string().nullable()}),Do=Eo.extend({preparedCanvasId:n.uuid()}),Oo=n.object({}),ko=n.object({signedOut:n.literal(!0)}),Ao=n.string().max(254).pipe(n.email()),jo=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),email:Ao}),n.object({kind:n.literal(`email`),email:Ao})]),Mo=n.object({query:n.string().trim().min(1).max(200)}),No=n.object({recipients:n.array(jo).max(5)}),Po=n.object({}),Fo=No.extend({}),Io=`enhance3:session-handoff`;n.union([n.object({kind:n.literal(Io),body:n.object({token:n.string().min(1),displayName:n.string().min(1)})}),n.object({kind:n.literal(Io),signedOut:n.literal(!0)})]);const Lo=n.string().min(1).max(500).refine(e=>!e.startsWith(`/`)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),Ro=n.object({path:Lo,contentType:n.string().min(1).max(200),bytes:n.number().int().nonnegative().max(26214400)}),zo=n.enum([`uploading`,`verifying`,`ready`,`failed`,`abandoned`]),Bo=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1).max(200),title:n.string().trim().min(1).max(200),entryPath:Lo.default(`index.html`),files:n.array(Ro).min(1).max(2e3),box:C.extend({width:n.number().positive(),height:n.number().positive()})}),Vo=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),state:zo,alreadyExists:n.boolean(),fileCount:n.number().int().positive(),totalBytes:n.number().int().positive().max(262144e3)}),Ho=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),cursor:n.number().int().min(0).default(0)}),Uo=n.object({path:Lo,upload:T}),Wo=n.object({deploymentId:n.uuid(),uploads:n.array(Uo).max(50),nextCursor:n.number().int().min(0).optional()}),Go=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive(),canvasPageId:n.string().min(1).max(200).optional()}),Ko=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)}),qo=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid()}),Jo=n.object({deploymentId:n.uuid(),origin:n.url(),bootUrl:n.url(),expiresAt:n.iso.datetime()}),Yo=`__enhance/manifest.json`,Xo=n.string().length(64).refine(e=>{for(let t of e)if(!/[\da-f]/u.test(t))return!1;return!0}),Zo=e=>{for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e===127||e<=31))return!0}return!1},Qo=e=>e.normalize(`NFKC`).toUpperCase().toLowerCase(),$o=n.string().min(1).refine(e=>e===e.normalize(`NFC`),{message:`prototype paths must use NFC Unicode normalization`}).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:\//u.test(e)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!Zo(e)&&!e.startsWith(`__enhance/`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),es=n.object({path:$o,contentType:n.string().trim().min(1).max(200).refine(e=>!Zo(e)),bytes:n.number().int().nonnegative().max(2**53-1),sha256:Xo}),ts=n.object({version:n.literal(1),entryPath:$o,files:n.array(es).min(1)}),ns=n.object({artifactBytes:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1),fileBytes:n.number().int().positive().max(2**53-1),manifestBytes:n.number().int().positive().max(2**53-1),fileCount:n.number().int().positive().max(2**53-1),pathBytes:n.number().int().positive().max(2**53-1)}),rs=n.object({}),is=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),limits:ns}),as=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),bytes:n.number().int().positive().max(2**53-1),sha256:Xo,fileCount:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1)}),os=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1),title:n.string().trim().min(1).max(200),entryPath:$o,artifact:as,box:C.extend({width:n.number().positive(),height:n.number().positive()})}),ss=n.enum([`uploading`,`queued`,`ingesting`,`ready`,`failed`,`abandoned`]),cs=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),alreadyExists:n.boolean(),artifact:as}),ls=n.discriminatedUnion(`state`,[cs.extend({state:n.literal(`uploading`),upload:T}),cs.extend({state:n.enum([`queued`,`ingesting`,`ready`,`failed`,`abandoned`])})]),us=n.object({canvasId:n.uuid(),deploymentId:n.uuid()}),ds=n.object({deploymentId:n.uuid(),state:ss}),fs=n.object(us.shape),ps=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),fileCount:n.number().int().nonnegative(),totalBytes:n.number().int().nonnegative().max(2**53-1),processedFiles:n.number().int().nonnegative()}),ms=n.discriminatedUnion(`state`,[ps.extend({state:n.literal(`failed`),failure:n.object({code:n.string().min(1),message:n.string().min(1),path:$o.optional()})}),ps.extend({state:n.enum([`uploading`,`queued`,`ingesting`,`ready`,`abandoned`])})]),hs=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive(),canvasPageId:n.string().min(1).max(200).optional()}),gs=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)});n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.capture`),requestId:n.uuid()}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.ready`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.escape`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.zoom`),deltaX:n.number(),deltaY:n.number(),deltaMode:n.union([n.literal(0),n.literal(1),n.literal(2)]),anchorX:n.number().min(0).max(1),anchorY:n.number().min(0).max(1)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigate`),direction:n.enum([`back`,`forward`])}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigation`),canGoBack:n.boolean(),canGoForward:n.boolean()});const _s=n.object({artifact:n.string().min(1),viewport:n.object({width:n.number().positive(),height:n.number().positive()}),title:n.string()}),vs=n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.captured`),requestId:n.uuid()});n.discriminatedUnion(`outcome`,[vs.extend({outcome:n.literal(`captured`),screen:_s}),vs.extend({outcome:n.literal(`failed`),error:n.string().min(1)})]);const ys=2166136261,bs=Number.parseInt(`9e3779b9`,16),xs=Number.parseInt(`85ebca6b`,16),Ss=Number.parseInt(`c2b2ae35`,16);ys^bs,ys^xs,ys^Ss;const Cs=(e,t)=>`/v1/recording-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,ws=n.object({width:n.number().int().positive(),height:n.number().int().positive()}),Ts=16*te,Es=8*te,Ds=u,Os=n.object({mimeType:n.string().min(1).max(100),sampleRate:n.number().int().min(8e3).max(192e3)}),ks=n.object({sourceUrl:n.string().max(Ds),viewport:ws,pageTitle:n.string().max(200).nullable(),audio:Os.nullable().default(null)}),As=n.object({recordingId:n.uuid(),ownerPersonId:n.uuid(),chunkIndex:n.literal(0),upload:T,audioUpload:T.nullable()}),js=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),eventCount:n.number().int().min(0),continues:n.boolean().default(!1),bytes:n.number().int().min(1).max(Ts),etag:n.string().min(1).max(200).optional()}),Ms=n.object({nextChunkIndex:n.number().int().min(1),upload:T}),Ns=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),bytes:n.number().int().min(1).max(Ts),epoch:n.number().int().min(0).default(0),startsEpoch:n.boolean().default(!1),etag:n.string().min(1).max(200).optional()}),Ps=n.object({nextChunkIndex:n.number().int().min(1),upload:T}),Fs=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0).max(144e5),viewport:ws,sourceUrl:n.string().max(Ds),interrupted:n.boolean().default(!1),canvasId:n.uuid().optional(),organisationId:n.uuid().optional(),audioChunkCount:n.number().int().min(0).default(0),hasRecoverableBytes:n.boolean().default(!1)}).refine(e=>e.canvasId===void 0||e.organisationId===void 0,{message:`choose an existing canvas or a team for a new canvas, not both`}),Is=n.enum([`whole`,`recovering`,`partial`]),Ls=n.enum([`dom`,`audio`]),Rs=n.object({recordingId:n.uuid(),canvasId:n.uuid(),canvasTitle:n.string().min(1).max(200),isNewCanvas:n.boolean(),storedChunkCount:n.number().int().min(0),missingChunkIndexes:n.array(n.number().int().min(0)).max(64),missingChunkCount:n.number().int().min(0),storedAudioChunkCount:n.number().int().min(0),missingAudioChunkIndexes:n.array(n.number().int().min(0)).max(64),missingAudioChunkCount:n.number().int().min(0),integrity:Is}),zs=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:ws,interrupted:n.boolean(),chunkCount:n.number().int().min(0),startedAt:n.iso.datetime()}),Bs=n.object({recordingId:n.uuid(),assets:n.array(n.object({url:n.url().max(Ds),contentType:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Es)})).max(400)}),Vs=n.object({reserved:n.array(n.object({url:n.string(),upload:T}))}),Hs=n.object({recordingId:n.uuid(),arrived:n.array(n.object({url:n.url().max(Ds),etag:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Es)})).max(400)}),Us=n.object({missingAssetCount:n.number().int().min(0)}),Ws=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),Gs=n.object({seq:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),continues:n.boolean()}),Ks=n.discriminatedUnion(`state`,[Gs.extend({state:n.literal(`available`),download:en}),Gs.extend({state:n.literal(`missing`)})]),qs=n.object({seq:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),epoch:n.number().int().min(0),startsEpoch:n.boolean()}),Js=n.discriminatedUnion(`state`,[qs.extend({state:n.literal(`available`),download:en}),qs.extend({state:n.literal(`missing`)})]),Ys=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:ws,sourceUrl:n.string().max(Ds),interrupted:n.boolean(),integrity:Is,chunks:n.array(Ks),audio:n.object({mimeType:n.string(),chunks:n.array(Js)}).nullable(),assets:n.array(n.object({url:n.string(),contentType:n.string(),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0),missingAssetUrls:n.array(n.string()).optional()}),Xs=n.object({recordingId:n.uuid(),track:Ls,index:n.number().int().min(0)}),Zs=n.object({upload:T}),Qs=Xs.extend({etag:n.string().min(1).max(200)}),$s=n.object({integrity:Is}),ec=n.object({canvasId:n.uuid()}),tc=f(zs),nc=n.object({recordingId:n.uuid()}),rc=n.object({recordingId:n.uuid(),discarded:n.literal(!0)}),ic=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),ac=n.object({recordingId:n.uuid(),detachedScreenCount:n.number().int().min(0)});[`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
|
|
3
3
|
align-items: center !important;
|
|
4
4
|
background-color: #f7f7f8 !important;
|
|
5
5
|
background-image: linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
|
package/dist/main.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as e,A as t,D as n,Dt as r,E as i,Et as a,F as o,I as s,L as c,M as l,O as u,Ot as ee,P as te,Q as ne,R as re,T as ie,Tt as d,a as ae,c as oe,d as se,et as ce,f as le,g as ue,gt as de,h as f,i as fe,j as p,k as m,kt as pe,l as me,lt as h,n as g,nt as he,o as _,ot as ge,p as _e,pt as ve,rt as ye,t as be,tt as xe,u as v,ut as Se,wt as y,xt as b,z as Ce}from"./cli-output-identity.lib-
|
|
2
|
+
import{$ as e,A as t,D as n,Dt as r,E as i,Et as a,F as o,I as s,L as c,M as l,O as u,Ot as ee,P as te,Q as ne,R as re,T as ie,Tt as d,a as ae,c as oe,d as se,et as ce,f as le,g as ue,gt as de,h as f,i as fe,j as p,k as m,kt as pe,l as me,lt as h,n as g,nt as he,o as _,ot as ge,p as _e,pt as ve,rt as ye,t as be,tt as xe,u as v,ut as Se,wt as y,xt as b,z as Ce}from"./cli-output-identity.lib-CPk2NGO2.mjs";import{a as we,c as Te,d as Ee,f as De,i as x,l as Oe,m as ke,n as Ae,o as je,p as Me,r as Ne,s as Pe,t as Fe,u as S}from"./mutation-key.adapter-BW070ttm.mjs";import{t as Ie}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as Le}from"commander";import{createCli as Re,parseRouter as ze}from"trpc-cli";import{z as C}from"zod";import{hostname as Be,tmpdir as Ve}from"node:os";import w from"node:process";import{createInterface as He}from"node:readline";import{chmodSync as Ue,existsSync as We,lstatSync as Ge,mkdirSync as Ke,readFileSync as qe,readdirSync as Je,statSync as Ye,unlinkSync as Xe,writeFileSync as T}from"node:fs";import E from"node:path";import{createHash as Ze,randomUUID as D}from"node:crypto";import{readFile as Qe}from"node:fs/promises";import{proxify as $e}from"trpc-cli/dist/proxify.js";const et=e=>`${JSON.stringify(e)}\n`,tt=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
|
|
3
3
|
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=et(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},nt=(e,t)=>{let n=tt(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},O=[`recording.start`,`recording.appendChunk`,`recording.complete`],rt=e=>async t=>{let n=Ce.parse(await e.mutate(O[0],{sourceUrl:t.sourceUrl,viewport:t.viewport,pageTitle:t.pageTitle,audio:null})),r=n.upload;try{let i=nt(t.entries,8388608);for(let[t,a]of i.entries()){let i=new TextEncoder().encode(a.body),o=await e.upload({url:r.url,headers:r.headers,body:i});r=c.parse(await e.mutate(O[1],{recordingId:n.recordingId,index:t,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:i.byteLength,etag:o})).upload}let a=Math.max(0,...t.entries.map(e=>e.atMs));return re.parse(await e.mutate(O[2],{recordingId:n.recordingId,durationMs:a,viewport:t.viewport,sourceUrl:t.sourceUrl,interrupted:!1,...t.canvasId!==void 0&&{canvasId:t.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new p(`Recording ${n.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${n.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},it=[`screen.create`,`screen.complete`],at=e=>async t=>{let n=s.parse(await e.mutate(it[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let r=await e.upload({url:n.upload.url,headers:n.upload.headers,body:t.body}),i=o.parse(await e.mutate(it[1],{screenId:n.screenId,etag:r}));return{screenId:i.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:i.storedBytes}}catch{throw new p(`Screen ${n.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},k=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],ot=(t,n)=>async r=>{let i=ne.parse(await t.mutate(k[0],{name:r.organisationName})).organisation,a=pe.parse(await t.mutate(k[1],{title:r.canvasTitle,organisationId:i.id,sourceUrl:null}));try{let o=[];for(let e of r.screens)o.push(await n(e));let s=h.parse(await t.query(k[4],{canvasId:a.id})),c=e();for(let[e,t]of o.entries())c=ce(c,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:r.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=Se.parse(await t.mutate(k[5],{canvasId:a.id,baseVersion:s.version,document:c,screenIds:o.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new p(`World canvas ${a.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${a.id}' before adding the screens.`);return{organisationId:i.id,canvasId:a.id,screenIds:o.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof p?e:new p(`Organisation ${i.id} and canvas ${a.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${a.id}' before retrying any missing steps.`)}},st=async(e,t)=>{if(e!==void 0&&e!==``)return e.trim();if(w.stdin.isTTY)throw new l(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${t}'.`);let n=He({input:w.stdin,crlfDelay:1/0});for await(let e of n){n.close();let t=e.trim();if(t!==``)return t;break}throw new l(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${t}'.`)},ct=async e=>{if(e!==void 0)return e.trim();if(w.stdin.isTTY)return null;let t=He({input:w.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},lt=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await ct(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${Be()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},A=1e3,ut=C.coerce.number().int().positive(),dt=C.coerce.number().min(.1).max(4),ft=C.uuid(),pt=C.union([C.string(),C.number(),C.null()]),mt=C.record(C.string(),pt),ht=C.array(C.object({nodeId:C.string().min(1).max(200),textContent:C.string().max(1e5)})).min(1).max(A),gt=C.array(C.object({nodeId:C.string().min(1).max(200),name:C.string().max(500)})).min(1).max(A),_t=C.array(C.object({nodeIds:C.array(C.string().min(1).max(200)).min(1).max(100),styles:mt})).min(1).max(100),vt=C.array(C.object({id:C.string().min(1).max(200),parentId:C.string().min(1).max(200).optional()})).min(1).max(100),yt=C.array(C.union([C.object({nodeId:C.string().min(1).max(200),before:C.string().min(1).max(200)}),C.object({nodeId:C.string().min(1).max(200),after:C.string().min(1).max(200)}),C.object({nodeId:C.string().min(1).max(200),parentId:C.string().min(1).max(200),index:C.number().int().nonnegative().optional()})])).min(1).max(100),j=C.array(C.string().min(1).max(200)).min(1).max(A),bt=C.coerce.number().int().min(0).max(20),xt=C.uuid().nullable(),M=(e,t,n)=>{let r=e.safeParse(t);if(r.success)return r.data;throw new l(`BAD_REQUEST`,`${n} is invalid.`,`Run the command with --help.`)},N=e=>M(ut,e,`--base-version`),P=(e,t,n)=>{let r=xt.safeParse(t??null);if(!r.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(r.data,n)},F=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),St=async(e,r,i,a)=>{P(e,r.clientToken,!1);let o=t(r.canvas),s=N(r.baseVersion);return o.nodeIds.length>0&&n(o,await S(e,o.canvasId,s),a),Ee(e.remote).execute({canvasId:o.canvasId,mutationId:F(e,i),baseVersion:s,operations:[...a]})},I=async(e,n,r,i)=>{P(e,n.clientToken,!1);let a=t(n.canvas);return Oe(e.remote).execute({...a,baseVersion:N(n.baseVersion),mutationId:F(e,`canvas.edit`),edits:r,...i!==void 0&&{idPrefix:i}})},Ct=C.array(ge).min(1).max(ye),wt=e=>{if(!e.startsWith(`@`))return e;let t=e.slice(1);if(t===``)throw new l(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let n=E.resolve(t);try{let e=Ye(n);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return qe(n,`utf8`)}catch{throw new l(`BAD_REQUEST`,`Could not read a bounded operations file at ${n}.`,`Use a regular JSON file no larger than 1 MiB.`)}},Tt=e=>{try{return JSON.parse(wt(e))}catch(e){throw e instanceof l?e:new l(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},Et=e=>{let t=Tt(e),n=Ct.safeParse(t);if(!n.success){let e=n.error.issues[0];throw new l(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return n.data},L=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},Dt=C.coerce.number().int().positive(),Ot=e=>{let t=Dt.safeParse(e);if(t.success)return t.data;throw new l(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},kt=(e,t)=>{let n=C.uuid().nullable().safeParse(t??null);if(!n.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},At=(e,r)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, setTypography, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
4
|
`)).action(async e=>{kt(r,e.clientToken);let i=t(e.canvas),a=Ot(e.baseVersion),o=Et(e.operations);i.nodeIds.length>0&&n(i,await S(r,i.canvasId,a),o);let s=await r.invocation.invoke({capability:L(r.catalog(),`canvas.apply`),arguments:{canvasId:i.canvasId,baseVersion:a,operations:[...o]},clientToken:e.clientToken??null});r.output.result(s)})},jt=e=>{try{return JSON.parse(e)}catch{return}},R=e=>{if(e===void 0)return null;let t=de.safeParse(jt(e));if(t.success)return t.data;throw new l(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},z=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Mt=(e,t)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let n=he.safeParse(e.phase);if(!n.success)throw new l(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let r=m(e.canvas),i=xe.parse(await t.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:r,phase:n.data,nodeIds:z(e.nodeIds),bounds:R(e.bounds)}));t.output.result({...i,next:[`enhance canvas work update --canvas ${r} --activity-id ${i.activityId} --phase ${n.data}`,`enhance canvas finish-working-on-nodes --canvas ${r} --activity-id ${i.activityId}`]})})},Nt=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(xe.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:m(e.canvas),activityId:ft.parse(e.activityId),phase:he.parse(e.phase),nodeIds:z(e.nodeIds),bounds:R(e.bounds)})))})},Pt=(e,t)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await De(t.remote).finish(m(e.canvas),ft.parse(e.activityId)))throw new l(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);t.output.result({ended:!0,activityId:e.activityId})})},Ft=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Mt(n,t),Nt(n,t),Pt(e,t)},B=(e,t,n)=>{if(!e.startsWith(`@`))return e;let r=e.slice(1);if(r===``)throw new l(`BAD_REQUEST`,`${n} @ must name a file.`,`Pass ${n} @/absolute/path/to/file or an inline value.`);let i=E.resolve(r);try{let e=Ye(i);if(!e.isFile()||e.size>t)throw Error(`invalid size`);return qe(i,`utf8`)}catch{throw new l(`BAD_REQUEST`,`Could not read a bounded file at ${i}.`,`Use a regular UTF-8 file no larger than ${String(t)} bytes.`)}},V=(e,t,n)=>{let r=(()=>{try{return JSON.parse(B(e,1048576,n))}catch(e){throw e instanceof l?e:new l(`BAD_REQUEST`,`${n} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),i=t.safeParse(r);if(i.success)return i.data;let a=i.error.issues[0];throw new l(`BAD_REQUEST`,`${n} is invalid${a===void 0||a.path.length===0?``:` at ${a.path.join(`.`)}`}.`,a?.message??`Correct the JSON shape and retry.`)},It=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,ht,`--updates`).map(e=>({kind:`set_text`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await I(t,e,n))})},Lt=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,gt,`--updates`).map(e=>({kind:`rename`,nodeId:e.nodeId,name:e.name}));t.output.result(await I(t,e,n))})},Rt=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.nodeIds,j,`--node-ids`);t.output.result(await St(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},zt=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,_t,`--updates`);t.output.result(await I(t,e,n.map(e=>({kind:`set_styles`,...e}))))})},Bt=(e,t)=>{e.command(`edit`).description(`Apply an atomic canvas edit batch.`).requiredOption(`--canvas <url-or-id>`,`Canvas or selection URL, or canvas UUID.`).requiredOption(`--base-version <integer>`,`Canvas version to edit; use the previous write result to continue.`).requiredOption(`--edits <json-or-@path>`,`Array of edits with kind set_text, set_styles, rename, duplicate or move.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).addHelpText(`after`,`
|
|
5
5
|
Edit shapes (combine related edits in one array):
|
|
@@ -11,7 +11,7 @@ Edit shapes (combine related edits in one array):
|
|
|
11
11
|
Move destinations also accept {"kind":"after","nodeId":"other"} or {"kind":"parent","parentId":"screen","index":0}.
|
|
12
12
|
Use input-version IDs. Duplicate mappings are returned for a subsequent call.
|
|
13
13
|
`).action(async e=>{let n=V(e.edits,ie,`--edits`);t.output.result(await I(t,e,n))})},Vt=(e,t)=>{Bt(e,t),It(e,t),Lt(e,t),Rt(e,t),zt(e,t)},Ht=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),H=e=>e===`start`||e===`end`?`flex-${e}`:e,Ut=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},Wt=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=Ut(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},Gt=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=Wt(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},Kt=(e,t)=>{let n=e.box;if(n===void 0)return{};let r=d(e),i=e.layout?.position??y(e,`position`),o=i===void 0||[`absolute`,`fixed`].includes(i),s=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>r[e]!==void 0),c=n=>a(e,n,t).some(t=>r[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...r[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...o&&r.position===void 0&&{position:`absolute`},...o&&!s(`horizontal`)&&{left:n.x},...o&&!s(`vertical`)&&{top:n.y},...o&&e.layout?.horizontal===void 0&&!c(`horizontal`)&&{width:n.width},...o&&e.layout?.vertical===void 0&&!c(`vertical`)&&{height:n.height}}},qt=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},Jt=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=qt(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...y(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":H(n.alignItems)},...n.alignContent!==void 0&&{"align-content":H(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":H(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},Yt=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&y(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?Ut(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},Xt=e=>{let t=[...e.rotation===void 0||e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},Zt=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:H(e.alignSelf),Qt=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||d(e)[r]!==void 0?{}:{[r]:0}},$t=(e,t)=>{let n=e.layout;if(n===void 0)return{};let i=t?.relationships[e.id]?.parentId,a=r(i===void 0?void 0:t?.nodes[i],t),o=n.position??y(e,`position`),s=o===`flow`||o!==`absolute`&&o!==`fixed`&&(o!==void 0||e.box===void 0),c=a===`horizontal`?n.horizontal:n.vertical,l=a===`horizontal`?n.vertical:n.horizontal,u=Zt(n,l);return{...n.position!==void 0&&{position:s?`relative`:`absolute`},...Gt(`width`,n.horizontal,s&&(a===`horizontal`||u===`stretch`)),...Gt(`height`,n.vertical,s&&(a===`vertical`||u===`stretch`)),...s&&a!==void 0&&Yt(e,c),...s&&u!==void 0&&{"align-self":u},...s&&Qt(e,a),...u===`stretch`&&l?.mode===`hug`&&a!==void 0&&{[a===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...Xt(n)}},en=(e,t)=>Object.fromEntries(Object.entries({...Kt(e,t),...ee(e,{...$t(e,t),...Jt(e)})}).map(([e,t])=>[e,typeof t==`number`&&!Ht.has(e)?`${String(t)}px`:t])),U=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,W=e=>{if(!e.visible)return null;if(e.kind===`solid`)return U(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${U(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},tn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},nn=e=>e?.flatMap(e=>{let t=W(e);return t===null?[]:[t]})??[],rn=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},an=e=>{if(e?.visible!==!0)return{};let t=W(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},on=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${U(e.color)}`),n=e.filters?.filter(e=>e.visible).map(tn),r=e.backdropFilters?.filter(e=>e.visible).map(tn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},sn=e=>{if(e===void 0)return{};let t=nn(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...rn(e.border),...an(e.outline),...on(e)}},cn=e=>e===void 0?{}:{"font-family":[e.family,...e.fallbackFamilies].join(`, `),"font-size":`${String(e.size)}px`,"font-weight":e.weight,"font-style":e.style,"line-height":e.lineHeight.mode===`normal`?`normal`:`${String(e.lineHeight.value)}px`,"letter-spacing":`${String(e.letterSpacing)}px`,"text-align":e.align,"text-transform":e.transform,"text-decoration-line":e.decoration.line,"text-decoration-style":e.decoration.style,"white-space":e.wrapping},ln=(e,t)=>({...Object.fromEntries(Object.entries(d(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...cn(e.typography),...sn(e.appearance),...en(e,t),...e.visible===!1&&{display:`none`}}),un=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),G=(e,t)=>{let n=e.nodes[t];if(n===void 0)throw new l(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},K=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},dn=e=>`{${JSON.stringify(e)}}`,fn=(e,t,n,r)=>{let i=G(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(ln(i,e))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(K(i,`alt`))} src=${JSON.stringify(K(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?dn(K(i,`text`)):``,l=(n>=r?[]:un(e,t)).map(t=>fn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
14
|
-
`)},pn=(e,t,n)=>fn(e,t,0,n),mn=(e,t)=>t.map(t=>{let n=G(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:ln(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),hn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},gn=async(e,t)=>{let n=h.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:b.parse(n.document)}},_n=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(hn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a);i(r,s,[e.nodeId]),n.output.result({canvasId:a,version:o.version,nodeId:e.nodeId,jsx:pn(s,e.nodeId,M(bt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a),c=V(e.nodeIds,j,`--node-ids`);i(r,s,c),n.output.result({canvasId:a,version:o.version,nodes:mn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},vn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.nodes,vt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},yn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.moves,yt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},bn=(e,t)=>{vn(e,t),yn(e,t)},xn=262144,Sn=e=>{let t=B(e,xn,`--html`);if(Buffer.byteLength(t,`utf8`)>xn)throw new l(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},Cn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),wn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new l(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new l(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);P(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=N(n.baseVersion);e.output.result(await e.invocation.invoke({capability:L(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Sn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:M(dt,n.scale,`--scale`),renderTimeoutMs:M(ut,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},Tn=(e,t)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
14
|
+
`)},pn=(e,t,n)=>fn(e,t,0,n),mn=(e,t)=>t.map(t=>{let n=G(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:ln(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),hn={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Multiple screens: publish each populated screen before authoring the next so users see progress. Prepare only what that screen needs; do not prepare the whole set before the first write.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},gn=async(e,t)=>{let n=h.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:b.parse(n.document)}},_n=(e,n)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{n.output.result(hn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a);i(r,s,[e.nodeId]),n.output.result({canvasId:a,version:o.version,nodeId:e.nodeId,jsx:pn(s,e.nodeId,M(bt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let r=t(e.canvas),a=r.canvasId,{held:o,document:s}=await gn(n,a),c=V(e.nodeIds,j,`--node-ids`);i(r,s,c),n.output.result({canvasId:a,version:o.version,nodes:mn(s,c),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},vn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.nodes,vt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),e.idPrefix),{duplicatedNodes:r,...i}=n;t.output.result({...n,duplicatedNodes:r,apply:i})})},yn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await I(t,e,V(e.moves,yt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},bn=(e,t)=>{vn(e,t),yn(e,t)},xn=262144,Sn=e=>{let t=B(e,xn,`--html`);if(Buffer.byteLength(t,`utf8`)>xn)throw new l(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return t},Cn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),wn=async(e,n)=>{if(![`insert-children`,`replace`].includes(n.mode))throw new l(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(n.review))throw new l(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);P(e,n.clientToken,!0);let r=n.mode===`replace`?`replace`:`insert-children`,i=t(n.canvas),a=N(n.baseVersion);e.output.result(await e.invocation.invoke({capability:L(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:n.targetNodeId,mode:r,html:Sn(n.html),...n.idPrefix!==void 0&&{idPrefix:n.idPrefix},baseVersion:a,review:n.review,renderOutputPath:n.output??null,overwriteRender:n.force===!0,renderScale:M(dt,n.scale,`--scale`),renderTimeoutMs:M(ut,n.timeoutMs,`--timeout-ms`)},clientToken:n.clientToken??null}))},Tn=(e,t)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
15
15
|
Write one visual group at a time. Use --review none for a committed receipt, then render its version and inspect the PNG. Use flex, padding and gap; use targeted commands for later edits.
|
|
16
16
|
`).action(async e=>wn(t,e))},En=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Dn=(e,t)=>typeof t==`number`&&!Cn.has(e)?`${String(t)}px`:String(t),On=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=En(e);return`${n}:${Dn(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),kn=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,An=(e,t)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let n=V(e.styles,mt,`--styles`);if(n.width===void 0||n.height===void 0)throw new l(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);P(t,e.clientToken,!0);let r=m(e.canvas),i=N(e.baseVersion),a=await S(t,r,i),o=Object.entries(a.relationships).flatMap(([e,t])=>{let n=a.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),s={display:`flex`,flexDirection:`column`,left:kn(o),top:0,...n,position:`absolute`},c=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);t.output.result(await Te(t.remote,t.render).execute({canvasId:r,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${c}" data-enhance-kind="frame" style="${On(s)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:r})}`,baseVersion:i,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},jn=(e,t)=>{Tn(e,t),An(e,t)},Mn=(e,t)=>{_n(e,t),jn(e,t),Vt(e,t),bn(e,t),Ft(e,t)},Nn=e=>{let n=e.getOptionValue(`canvas`),r=e.getOptionValue(`canvasId`);if(n!==void 0&&r!==void 0)throw new l(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let i=n??r;if(typeof i!=`string`)throw new l(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:t(i),url:i}},Pn=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new l(`BAD_REQUEST`,`--node-id or a single-node selection link is required.`,`Choose one node, or use canvas tree to inspect the linked selection.`);return n},Fn=async(e,t,n,r)=>{let a=h.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId})),o=b.parse(a.document),s=u(n,o),c=Object.values(o.nodes).filter(e=>s.has(e.id)).map(e=>({...e,kind:e.component,parentId:o.relationships[e.id]?.parentId??null,children:Object.entries(o.relationships).filter(([,t])=>t.parentId===e.id).map(([e])=>e)})),l={canvasId:n.canvasId,version:a.version,source:`selection-link`,selectedNodeIds:n.nodeIds,next:[`Keep this selection link as --canvas for every edit: ${r}`,`Edit only these nodes or their descendants; other canvas content is outside the request.`]};if(e.name()===`node`){let t=Pn(e,n);return i(n,o,[t]),{...l,node:c.find(e=>e.id===t)}}return{...l,nodes:c}},In=(e,t)=>{for(let n of[`inspect`,`tree`,`node`,`selection`]){let r=e.commands.find(e=>e.name()===n),i=r?.options.find(e=>e.long===`--canvas-id`);r!==void 0&&i!==void 0&&(i.makeOptionMandatory(!1),r.options.find(e=>e.long===`--node-id`)?.makeOptionMandatory(!1),r.option(`--canvas <url-or-id>`,`Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.`),r.action(async()=>{let{reference:e,url:i}=Nn(r),a=e.nodeIds.length>0?await Fn(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:Pn(r,e)}});t.output.result(a)}))}},Ln=C.coerce.number().int().positive(),Rn=C.coerce.number().int().nonnegative(),zn=C.coerce.number().min(ve).max(4),q=(e,t,n,r=`canvas render`)=>{let i=e.safeParse(t);if(!i.success)throw new l(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${r} --help'.`);return i.data},Bn=e=>{if(e===void 0)return null;try{let t=de.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new l(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},Vn=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},Hn=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return C.uuid().safeParse(e.slice(4)).data},Un=(e,t)=>{let n=C.uuid().nullable().safeParse(t??null);if(!n.success)throw new l(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},Wn=async(e,n)=>{let r=t(e.canvas??``);if(r.nodeIds.length===0)return e.nodeId;let a=e.nodeId??(r.nodeIds.length===1?r.nodeIds[0]:void 0);if(a===void 0||e.bounds!==void 0)throw new l(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Pass --node-id for one node in the selection; bounds and whole-canvas renders would include unrelated content.`);let o=h.parse(await n.remote.query(`canvas.document.get`,{canvasId:r.canvasId}));return i(r,b.parse(o.document),[a]),a},Gn=async(e,n)=>{if(e.canvas===void 0)throw new l(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new l(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let r=await Wn(e,n);if(r===void 0&&e.atMs!==void 0)throw new l(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:Hn(r);if(i===void 0&&e.atMs!==void 0)throw new l(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");Un(n,e.clientToken);let a=await n.invocation.invoke({capability:L(n.catalog(),`canvas.render`),arguments:{canvasId:t(e.canvas).canvasId,expectedVersion:e.expectedVersion===void 0?null:q(Ln,e.expectedVersion,`--expected-version`),target:Vn(r,Bn(e.bounds)),sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:q(Rn,e.atMs??``,`--at-ms`)},scale:q(zn,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:q(Ln,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});n.output.result(a)},Kn=(e,t)=>{e.option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
17
17
|
For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
|
|
@@ -20,4 +20,4 @@ For transcript-led selection, inspect nearby --at-ms renders and reject transiti
|
|
|
20
20
|
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
21
21
|
`).action(async e=>{let n=C.uuid().nullable().safeParse(e.clientToken??null),r=C.uuid().safeParse(e.recordingId);if(!n.success||!r.success)throw new l(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");t.output.result(await t.invocation.invoke({capability:L(t.catalog(),`recording.snapshot`),arguments:{canvasId:m(e.canvas),recordingId:r.data,atMs:Ar(e.atMs,`--at-ms`,!1),timeoutMs:Ar(e.timeoutMs,`--timeout-ms`,!0)},clientToken:n.data}))})},Mr=(e,t,n)=>{if(e!==`canvas.document.save`||typeof n!=`object`||!n||!(`outcome`in n)||n.outcome!==`conflict`)return n;throw new l(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof t==`object`&&t&&`canvasId`in t&&typeof t.canvasId==`string`?t.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},Nr=(e,t)=>$e(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>Mr(e,n,await t.mutate(e,n))}})),Pr=(e,t)=>{let n=e.commands.find(e=>e.name()===`transcript`);if(n===void 0)throw TypeError(`the API router did not supply transcript commands`);n.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let n=C.uuid().safeParse(e.recordingId);if(!n.success)throw new l(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");t.output.result(await t.invocation.invoke({capability:L(t.catalog(),`transcript.read`),arguments:{canvasId:m(e.canvas),recordingId:n.data},clientToken:null}))})},Fr={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},Ir=e=>{let t=e.state;return{logger:e.output.logger,prompts:Fr.prompts,process:Xn(),formatError:e=>{let n=_(e,t.pendingParserMessage);return t.exitCode=ae(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},Lr=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Rr=e=>{let t=Lr(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},zr=e=>{let t=ze({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=Rr(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},Br=()=>{let e=null;return()=>(e??=se(),e)},Vr=(e,t,n)=>{let r=at(t.remote),i=je({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});lt(e,ke(t.credentials,t.remote,we(t.remote)),t.output),hr(e,i,n,t.output),gr(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Tr(e,{screen:r,recording:rt(t.remote),world:ot(t.remote,r)},t.output),mr(e,t.output,n),qn(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),jr(e,{invocation:i,catalog:n,output:t.output}),kr(e,i,n,t.output),Pr(e,{invocation:i,catalog:n,output:t.output})},Hr=e=>{let t=le(),n=Br(),{descriptions:r,mutationPaths:i}=zr(t),a=Re({router:Nr(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:Fr.jsonInput}),o=Ir(e),s=a.buildProgram(o);if(!(s instanceof Le))throw TypeError(`trpc-cli did not return a Commander program`);dr(s),Vr(s,e,n),sr(s,{descriptions:r,mutationPaths:i,mutationKey:e.mutationKey,output:e.output}),s.description(`Operate Enhance as the authenticated person.`);let c=e.state;return{program:s,run:async()=>{try{await a.run(o,s)}catch(t){if(!(t instanceof v))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=_(t,c.pendingParserMessage);c.exitCode=ae(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},Ur=e=>w.exit(e),Wr=36e5,X=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gr=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!X(e)||!Array.isArray(e.items))return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(X(e)?{...e,truncated:n}:{value:e,truncated:n}))},Kr=e=>{let t=`${e.join(`
|
|
22
22
|
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){w.stdout.write(t);return}let n=Ze(`sha256`).update(t).digest(`hex`).slice(0,16),r=E.join(Ve(),`enhance-${n}.ndjson`);T(r,t,{mode:384}),w.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},qr=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},Z=e=>typeof e==`string`?qr(e):Array.isArray(e)?e.some(e=>Z(e)):X(e)?Object.values(e).some(e=>Z(e)):!1,Q=e=>{Ke(e,{recursive:!0,mode:448}),Ue(e,448)},Jr=e=>{if(!We(e))return;let t=Date.now()-Wr,n=Je(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=E.join(e,r.name);Ge(n).mtimeMs<t&&Xe(n)}},$=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+Wr).toISOString()}),Yr=(e,t)=>{let n=Gr(e),r=`${n.join(`
|
|
23
|
-
`)}\n`;Q(t);let i=E.join(t,`result-${D()}.ndjson`);T(i,r,{mode:384,flag:`wx`}),w.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Xr=e=>X(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Zr=(e,t,n)=>{let r=`${t.value}\n`;Q(n);let i=E.join(n,`result-${D()}.token`);T(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));w.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},Qr=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),$r=te.omit({fields:!0}).extend({remediation:C.string(),fields:C.array(C.object({path:C.string(),message:C.string()})).optional()}),ei=e=>{try{let t=JSON.parse(e),n=$r.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},ti=(e,t)=>{if(typeof e==`string`&&Qr(e)){w.stdout.write(e);return}let n=Xr(e);if(n!==null&&X(e)){Zr(e,n,t);return}if(Z(e)){Yr(e,t);return}let r=fe(e);if(r!==null){let e=null;if(r.detail!==null){Q(t);let n=E.join(t,`result-${D()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;T(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}w.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}Kr(Gr(e))},ni=e=>{w.stderr.write(`${JSON.stringify(e)}\n`)},ri=(e,t,n=`enhance`)=>{let r=e,i=E.join(t,`sensitive`);return Jr(i),{result:e=>{ti(g(e,n),i)},failure:e=>{ni(be(e,n))},logger:{info:(...e)=>{ti(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=ei(t);i===null?r.pendingParserMessage=t:ni(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ri(e,x.configDirectory,x.commandName),n=Ne(x.configDirectory),r=Fe(),i=Hr({version:`0.1.
|
|
23
|
+
`)}\n`;Q(t);let i=E.join(t,`result-${D()}.ndjson`);T(i,r,{mode:384,flag:`wx`}),w.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},Xr=e=>X(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Zr=(e,t,n)=>{let r=`${t.value}\n`;Q(n);let i=E.join(n,`result-${D()}.token`);T(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));w.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},Qr=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),$r=te.omit({fields:!0}).extend({remediation:C.string(),fields:C.array(C.object({path:C.string(),message:C.string()})).optional()}),ei=e=>{try{let t=JSON.parse(e),n=$r.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},ti=(e,t)=>{if(typeof e==`string`&&Qr(e)){w.stdout.write(e);return}let n=Xr(e);if(n!==null&&X(e)){Zr(e,n,t);return}if(Z(e)){Yr(e,t);return}let r=fe(e);if(r!==null){let e=null;if(r.detail!==null){Q(t);let n=E.join(t,`result-${D()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;T(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}w.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}Kr(Gr(e))},ni=e=>{w.stderr.write(`${JSON.stringify(e)}\n`)},ri=(e,t,n=`enhance`)=>{let r=e,i=E.join(t,`sensitive`);return Jr(i),{result:e=>{ti(g(e,n),i)},failure:e=>{ni(be(e,n))},logger:{info:(...e)=>{ti(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=ei(t);i===null?r.pendingParserMessage=t:ni(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=ri(e,x.configDirectory,x.commandName),n=Ne(x.configDirectory),r=Fe(),i=Hr({version:`0.1.17-dev.sha-91b0d30866d2`,credentials:n,remote:Ae(x.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:x.configDirectory,commandName:x.commandName});try{await i.run()}catch(n){n instanceof v&&Ur(n.requestedCode===0?0:e.exitCode),t.failure(_(n,null)),Ur(1)}})();export{};
|
package/dist/mcp-main.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{d as e,m as t,o as n}from"./cli-output-identity.lib-
|
|
2
|
+
import{d as e,m as t,o as n}from"./cli-output-identity.lib-CPk2NGO2.mjs";import{a as r,i,m as a,n as o,o as s,r as c,t as l}from"./mutation-key.adapter-BW070ttm.mjs";import{t as u}from"./mcp-server.adapter-DVBG_1F_.mjs";import{z as d}from"zod";import f from"node:process";import{serveStdio as p}from"@modelcontextprotocol/server/stdio";const m=d.object({openBrowser:d.boolean()}),h=(e,t)=>{let i=a(e,t,r(t)),o=null,s=null;return{login:async e=>{if(o!==null)return o.ready;let t=m.parse(e),r=new AbortController,a=Promise.withResolvers();s=null;let c=(async()=>{try{await i.loginWithBrowser({label:`Agent plugin`,openBrowser:t.openBrowser,signal:r.signal,onReady:e=>{s={authenticated:!1,status:`waiting_for_browser`,url:e},a.resolve(s)}}),s=null}catch(e){s={authenticated:!1,status:`failed`,error:n(e,null)},a.reject(e)}finally{o=null}})();return o={controller:r,ready:a.promise,completion:c},a.promise},status:async()=>s===null?await e.read()===null?{authenticated:!1}:i.status():s,logout:async()=>(o?.controller.abort(),await o?.completion,s=null,i.logout())}},g=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),_=async e=>{switch(e.capability){case`auth.login`:return e.auth.login(e.arguments);case`auth.logout`:return e.auth.logout();case`auth.status`:return e.auth.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status,...t.error!==void 0&&{error:t.error}},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},v=(e,t,n,r)=>{let i=o(e,t,l()),a=h(t,i);return{invoke:async c=>{if(g.has(c.capability.id))return _({capability:c.capability.id,arguments:c.arguments,credentials:t,remote:i,version:r,auth:a});let u=l();return s({remote:o(e,t,u),mutationKey:u,configDirectory:n}).invoke(c)}}},y=d.object({authenticated:d.literal(!1)}),b=d.object({authenticated:d.literal(!1),status:d.literal(`waiting_for_browser`),url:d.url()}),x=d.object({authenticated:d.literal(!1),status:d.literal(`failed`),error:d.object({code:d.string(),message:d.string(),remediation:d.string()})}),S=d.object({authenticated:d.literal(!0),personId:d.uuid(),displayName:d.string().min(1),tokenId:d.uuid(),tokenLabel:d.string().min(1),expiresAt:d.iso.datetime().nullable()}),C=d.object({openBrowser:d.boolean().default(!0).describe(`Open the system browser for human sign-in; return its URL immediately.`)}),w=d.strictObject({}),T=d.union([b,x,y,S]),E=d.object({loggedOut:d.boolean()}),D=d.object({status:d.enum([`ok`,`degraded`]),runtimeVersion:d.string().min(1),api:d.object({reachable:d.boolean(),status:d.number().int().nullable(),error:d.string().optional()}),credential:d.object({present:d.boolean()})}),O=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),k=e=>t({...e,source:`composite`,idempotency:e.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:e.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:e.guide.examples[0]?.input,outputExample:e.guide.examples[0]?.output}),A=[k({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:C,outputSchema:b,guide:O({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Returns waiting_for_browser and the exact sign-in URL immediately. Show this URL to the person if their browser restores another page. Consent continues in the background; auth.status reports completion or a failure.`,next:[`Show the sign-in URL, then check auth.status after the person finishes. Only report success after authenticated is true and a canvas read succeeds.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!1,status:`waiting_for_browser`,url:`https://app.example.test/oauth/authorize?client_id=client_enhance_cli`}})}),k({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:w,outputSchema:E,guide:O({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),k({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:T,guide:O({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata, a pending sign-in URL, a sign-in failure, or authenticated false; never a credential value.`,next:[`While waiting_for_browser, show the URL and let the person finish. After failure, report the error before retrying auth.login. Continue the workflow only when authenticated is true.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),k({id:`doctor`,operation:`query`,effect:`read`,inputSchema:w,outputSchema:D,guide:O({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.17`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),j=()=>A,M=c(i.configDirectory),N=v(i.apiUrl,M,i.configDirectory,`0.1.17-dev.sha-91b0d30866d2`),P=[...e(),...j()];p(()=>u({version:`0.1.17-dev.sha-91b0d30866d2`,name:i.mcpServiceName,commandName:i.commandName,invocation:N,catalog:P,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>f.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,E as t,M as n,d as r,ht as i,i as a,l as o,lt as s,mt as c,n as l,o as u,r as d,s as f,t as p,w as m,xt as h,y as ee}from"./cli-output-identity.lib-
|
|
2
|
+
import{A as e,E as t,M as n,d as r,ht as i,i as a,l as o,lt as s,mt as c,n as l,o as u,r as d,s as f,t as p,w as m,xt as h,y as ee}from"./cli-output-identity.lib-CPk2NGO2.mjs";import{z as g}from"zod";import{createHash as _,randomUUID as v}from"node:crypto";import{readFile as y,rm as b}from"node:fs/promises";import{McpServer as x}from"@modelcontextprotocol/server";const S=g.object({ok:g.literal(!1),error:g.object({code:g.string(),message:g.string(),remediation:g.string(),fields:g.array(g.object({path:g.string(),message:g.string()})).optional()})}),C=g.object({uri:g.string(),mimeType:g.string(),bytes:g.number().int().nonnegative()}),te=g.object({ok:g.literal(!0),artifact:C}),w=g.object({id:g.string(),operation:g.enum([`query`,`mutation`]),effect:g.enum([`read`,`write`,`delete`,`external`]),idempotency:g.enum([`none`,`single`,`composite`]),summary:g.string(),useWhen:g.string(),preconditions:g.array(g.string()),inputSchema:g.unknown(),exampleInput:g.unknown(),output:g.array(g.object({name:g.string(),required:g.boolean(),meaning:g.string()})),result:g.string(),recovery:g.array(g.string()),next:g.array(g.string()),schemaDigest:g.string(),guidanceDigest:g.string(),behaviorDigest:g.string()}),T=w.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),E=g.union([g.object({ok:g.literal(!0),result:g.unknown(),artifact:C.optional(),detail:C.optional()}),te,S]),D=g.union([g.object({ok:g.literal(!0),result:g.object({matches:g.array(T),totalMatches:g.number().int().nonnegative(),truncated:g.boolean(),bestContract:w.optional(),detailRequired:g.object({capability:g.string()}).optional()})}),S]),O=g.union([g.object({ok:g.literal(!0),result:w}),S]),k=g.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),A=ee.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:g.string().min(1).describe(`Canvas UUID or complete canvas/selection URL. Preserve a supplied selection URL.`),mode:g.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:k}),j=m.extend({clientToken:k}),M=g.object({canvas:g.string().min(1),expectedVersion:g.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:i.default({kind:`content`}),sourceState:c.nullable().default(null),scale:g.number().min(.1).max(4).default(1)}),N=async(e,t,n,r=null)=>{let i=e.catalog.find(e=>e.id===t);if(i===void 0)throw TypeError(`Missing canvas capability ${t}`);return e.invocation.invoke({capability:i,arguments:n,clientToken:r})},P=async(r,i)=>{let a=e(i.canvas);if(a.nodeIds.length===0)return{canvasId:a.canvasId,target:i.target};let o=i.target.kind===`node`?i.target.nodeId:i.target.kind===`content`&&a.nodeIds.length===1?a.nodeIds[0]:void 0;if(o===void 0)throw new n(`BAD_REQUEST`,`A selection link requires one selected node to render.`,`Choose a node target inside the selection; bounds or whole-canvas renders can include unrelated content.`);let c=s.parse(await N(r,`canvas.document.get`,{canvasId:a.canvasId}));if(c.version!==i.expectedVersion)throw new n(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return t(a,h.parse(c.document),[o]),{canvasId:a.canvasId,target:{kind:`node`,nodeId:o}}},F=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},I=(t,n)=>{n.catalog.some(e=>e.id===`canvas.writeHtml`)&&t.registerTool(`canvas_write_html`,{title:`Design editable canvas content`,description:`Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. If starting state is unknown, call capability_query with {"capability":"canvas.inspect","input":{"canvasId":"<UUID from canvas URL>"}}. When nodeCount is 0, use targetNodeId "root" and the returned version. Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.`,inputSchema:A,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({canvas:r,clientToken:i,...a})=>F(t,n,async()=>{let t=e(r);return N(n,`canvas.writeHtml`,{...a,canvasId:t.canvasId,...t.nodeIds.length>0&&{selectionNodeIds:t.nodeIds},review:`none`,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},i??null)}))},L=(e,t)=>{t.catalog.some(e=>e.id===`canvas.edit`)&&e.registerTool(`canvas_edit`,{title:`Edit existing canvas content`,description:`Apply text, styles, rename, duplicate or move edits together in one atomic mutation. Use ids from the input version and the latest successful read or write version; no intermediate read is required just to advance a version. Keep the complete selection URL. Read only the missing subtree when ids are unknown. Returns a compact committed receipt; render after the requested changes are complete.`,inputSchema:j,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({clientToken:n,...r})=>F(e,t,async()=>N(t,`canvas.edit`,r,n??null)))},R=(e,t)=>{t.catalog.some(e=>e.id===`canvas.render`)&&e.registerTool(`canvas_render`,{title:`Review canvas pixels`,description:`Render the version returned by a successful read or write and inspect its native PNG. Target the affected screen/node; a blank canvas does not need a pre-render. For a selection link use one node inside the selection. Review after a meaningful visual change, and repeat only after further changes or a real discrepancy.`,inputSchema:M,outputSchema:E,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async n=>F(e,t,async()=>N(t,`canvas.render`,{...await P(t,n),expectedVersion:n.expectedVersion,sourceState:n.sourceState,scale:n.scale,outputPath:null,overwrite:!1,timeoutMs:12e4})))},z=e=>({register:t=>{I(t,e),L(t,e),R(t,e)}}),B=e=>e.replaceAll(/\s+/gu,` `).trim(),ne=e=>{let t=`${e.id} [${e.effect}] — `,n=B(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},V=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>ne(e)),r=_(`sha256`).update(n.join(`
|
|
3
3
|
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
4
|
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},H=(e,t,n=`enhance`)=>{let r=V(e,t),i=String(l(r.text,n));return{register:t=>{t.registerTool(`capability_catalogue`,{title:`Scan every Enhance capability`,description:`Return the complete bounded capability inventory when the task is broad, uncertain, or capability_search does not find the right words. Call capability_describe with one exact id before invoking it.`,inputSchema:g.strictObject({}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":e.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":e.length}},()=>({content:[{type:`text`,text:i}]}))}}},U=g.object({capability:g.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),W=(e,t)=>({register:r=>{r.registerTool(`capability_describe`,{title:`Load one Enhance capability contract`,description:`Load the exact input schema, example, preconditions, result guidance, recovery, and next steps for one id returned by capability_search or capability_catalogue.`,inputSchema:U,outputSchema:O,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=e.describe(r);return i===null?t.failure(new n(`BAD_REQUEST`,`Unknown shared capability: ${r}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):t.inline(i)})}}),G=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,K=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,q=e=>JSON.stringify(e),J=(e,t=``)=>typeof e==`string`?K.test(e)||G.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>J(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>J(t,e)),Y=async(e,t,n)=>{let r=await y(t.path),i=v(),a=`enhance://artifact/${i}`;if(n===`embedded`&&t.cleanup===`unlink-after-use`)try{await b(t.path,{force:!0})}catch{}return n===`linked`&&e.registerResource(`artifact-${i}`,a,{title:`Enhance artifact`,mimeType:t.contentType},e=>({contents:[{uri:e.href,mimeType:t.contentType,blob:r.toString(`base64`)}]})),{metadata:d.omit({path:!0,sensitive:!0,cleanup:!0,deleteAfter:!0}).parse(t),artifact:{uri:a,mimeType:t.contentType,bytes:r.byteLength},image:{type:`image`,data:r.toString(`base64`),mimeType:t.contentType}}},X=(e,t,n)=>{let r=v(),i=`enhance://result/${r}`,a=Buffer.byteLength(t);if(n===`embedded`){let e={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:q(e)},{type:`resource`,resource:{uri:i,mimeType:`application/json`,text:t}}],structuredContent:e}}e.registerResource(`result-${r}`,i,{title:`Protected Enhance result`,mimeType:`application/json`},e=>({contents:[{uri:e.href,mimeType:`application/json`,text:t}]}));let o={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:q(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},Z=e=>new n(`BAD_REQUEST`,`Input validation error.`,`Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.`,Object.fromEntries(e.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),re=async(e,t,n)=>{let r=d.safeParse(t);if(r.success){let t=await Y(e,r.data,n);return{value:t.metadata,detail:null,attachment:t}}let i=a(t);if(i===null)return{value:t,detail:null,attachment:null};let o=i.detail??i.value,s=d.safeParse(o.review);if(!s.success)return{...i,attachment:null};try{let t=await Y(e,s.data,n),r={...o,review:{...t.metadata,artifact:t.artifact}},i=a(r);return{value:i?.value??r,detail:i?.detail??null,attachment:t}}catch{let e={...o,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:o.version,retry:{tool:`canvas_render`,arguments:{canvas:o.canvasId,expectedVersion:o.version,target:s.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=a(e);return{value:t?.value??e,detail:t?.detail??null,attachment:null}}},ie=(e,t)=>{let n={ok:!0,result:l(e,t)};return{content:[{type:`text`,text:q(n)}],structuredContent:n}},ae=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=l(n,t),a=await re(e,i,r),o=a.attachment,s=q(a.value);if(J(a.value)||o===null&&a.detail===null&&Buffer.byteLength(s)>2e4)return X(e,s,r);let c=a.detail===null?null:X(e,q(a.detail),r),u={ok:!0,result:a.value,...o!==null&&{artifact:o.artifact},...c!==null&&{detail:c.structuredContent.artifact}};return{content:[{type:`text`,text:q(u)},...o===null?[]:[o.image],...c?.content.filter(e=>e.type!==`text`)??[]],structuredContent:u}},inline:e=>ie(e,t),failure:n=>{let r=p(u(n instanceof g.ZodError?Z(n):n,null),t),i={ok:!1,error:r.code===`UNAUTHORIZED`?{...r,remediation:e}:r};return{content:[{type:`text`,text:q(i)}],structuredContent:i,isError:!0}}}),oe=g.object({query:g.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:g.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Filter dispatch, not effect. Omit if unknown; render uses mutation.`),limit:g.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),se=g.object({capability:g.string().min(1).describe(`Exact query id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),Q=g.object({capability:g.string().min(1).describe(`Exact mutation id from an available complete contract.`),input:g.record(g.string(),g.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:g.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),$=(e,t,r)=>{let i=e.find(e=>e.id===t);if(i===void 0)throw new n(`BAD_REQUEST`,`Unknown shared capability: ${t}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`});if(i.operation!==r){let e=i.operation===`query`?`capability_query`:`capability_mutate`;throw new n(`BAD_REQUEST`,`${t} is a ${i.operation}, not a ${r}.`,`Call ${e} with the same capability and input.`,{capability:`Use ${e} for this capability.`})}return i},ce=(e,t,n,r)=>{e.registerTool(`capability_search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns relevant summaries and a complete bestContract when it fits. Invoke from that contract directly; call capability_describe only when detailRequired is returned or a different match is needed.`,inputSchema:oe,outputSchema:D,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i})=>r.inline(n.search({query:e,operation:t,limit:i})))},le=(e,t,n,r)=>{e.registerTool(`capability_query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.`,inputSchema:se,outputSchema:E,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a})=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},ue=(e,t,n,r)=>{e.registerTool(`capability_mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using an available complete contract. Respect its preconditions and reuse clientToken only when retrying the identical mutation.`,inputSchema:Q,outputSchema:E,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o})=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},de=e=>{let t=new x({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}},...e.exposures?.includes(`mcp-transport`)===!0&&{instructions:`Transport attachment is not Enhance sign-in, even when the host reports mcp_auth success. Use capability_query with capability auth.status to check the person. If authenticated is false or a read returns UNAUTHORIZED, use capability_mutate with capability auth.login and input {"openBrowser":true}, then show the returned sign-in URL and let the person complete browser sign-in. If their browser restores a canvas or another page, direct them to this exact URL. A waiting_for_browser result is pending, not authenticated. Verify auth.status and a read such as canvas.list before reporting setup complete.`}}),n=f(e.catalog??r(),e.exposures??[`shared`]),i=o(n),a=e.delivery??`linked`,s=ae(e.exposures?.includes(`mcp-transport`)===!0?`Call capability_mutate with capability auth.login and input {"openBrowser":true}. Show the returned sign-in URL, complete browser sign-in, then verify auth.status and a read such as canvas.list.`:`Reconnect this hosted MCP server through your host’s browser OAuth sign-in. Then verify person.me and a read such as canvas.list.`,e.commandName);H(n,e.version,e.commandName).register(t),ce(t,n,i,s),W(i,s).register(t);let c={delivery:a,results:s};return le(t,n,e.invocation,c),ue(t,n,e.invocation,c),z({catalog:n,invocation:e.invocation,...c}).register(t),t};export{de as t};
|
package/dist/mcp.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as e,d as t}from"./cli-output-identity.lib-
|
|
2
|
+
import{c as e,d as t}from"./cli-output-identity.lib-CPk2NGO2.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-DVBG_1F_.mjs";export{t as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,e as toSharedCapabilities};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as e,B as t,C as n,Ct as r,D as i,E as a,Et as o,G as s,H as c,J as l,K as u,M as d,N as f,S as p,St as ee,U as te,V as ne,W as re,X as ie,Y as ae,Z as oe,_ as se,_t as ce,at as le,b as ue,bt as m,ct as de,dt as fe,ft as pe,it as me,j as he,lt as ge,q as _e,st as h,tt as ve,v as ye,vt as be,w as xe,x as Se,xt as Ce,y as we,yt as Te}from"./cli-output-identity.lib-DiyUPF-a.mjs";import{z as g}from"zod";import{homedir as Ee,tmpdir as De}from"node:os";import _ from"node:process";import{generateKeyBetween as Oe,generateNKeysBetween as ke}from"fractional-indexing";import{chmodSync as Ae,createReadStream as v,createWriteStream as je,mkdirSync as Me,writeFileSync as Ne}from"node:fs";import y from"node:path";import{createHash as b,randomBytes as Pe,randomUUID as x}from"node:crypto";import{setTimeout as Fe}from"node:timers/promises";import{chmod as Ie,mkdir as Le,mkdtemp as Re,readFile as ze,realpath as Be,rename as Ve,rm as He,stat as Ue,unlink as We,writeFile as Ge}from"node:fs/promises";import{Readable as Ke,Transform as qe}from"node:stream";import{pipeline as Je}from"node:stream/promises";import{ZipFile as Ye}from"yazl";import{createTRPCUntypedClient as Xe,httpLink as Ze}from"@trpc/client";import{spawn as Qe}from"node:child_process";import{createServer as $e}from"node:http";const et=/^enh_[\w-]{43}$/,S=e=>{let t=ae.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new d(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},tt=(e,t,n)=>({loginWithToken:async n=>{if(!et.test(n))throw new d(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=S(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=ie.parse(await t.authenticationConfig());if(i.method===`token`)throw new d(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=oe.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=S(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async()=>{if(await e.read()===null)throw new d(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return S(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),nt=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),rt=e=>{if(e.byteLength<24||nt.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},it=async(e,t)=>{let n=Te.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=rt(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new d(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return r},C=[`canvas.render.create`,`canvas.render.get`],w=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),at=e=>{let t=e.failure;if(t===null)return w(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new d(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase})},ot=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),st=async(e,t)=>{let n=m.safeParse(await e.query(C[1],{jobId:t}));if(!n.success)throw w(`render status`);return n.data.job},ct=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline)throw new d(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase});await ot(250),a=await st(e,a.id)}if(a.state!==`succeeded`)throw at(a);return a},lt=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},ut=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:lt(e)}),dt=async(e,t)=>{let n=ce.safeParse(await e.remote.mutate(C[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw w(`render creation`);let r=await ct(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await it(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return ut(r,a)},ft=(e,t,n,r=()=>null)=>({execute:async i=>dt({remote:e,files:t,now:n,progress:r},i)}),T={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},E=async e=>{try{return await e(),!0}catch{return!1}},pt=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await E(async()=>e.mutate(T.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await E(async()=>e.mutate(T.end,{canvasId:i.canvasId,activityId:n})))}}},D=e=>({begin:async t=>{try{let n=ve.safeParse(await e.mutate(T.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?pt(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>E(async()=>e.mutate(T.end,{canvasId:t,activityId:n}))}),mt=new Set([`insertPrototype`,`insertText`,`setBox`]),ht=e=>mt.has(e.op),gt=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,_t=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],vt=e=>[...new Set(e.operations.flatMap(e=>_t(e)))].slice(0,100),yt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:ht(e)?e.box==="default"?null:e.box:null,bt=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},xt=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:3}),r=le.safeParse(n);if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},O=e=>({execute:async(t,n)=>{if(n?.activity===!1)return xt(e,t);let r=await D(e).begin({canvasId:t.canvasId,phase:gt(t),nodeIds:vt(t),bounds:bt(t.operations.flatMap(e=>{let t=yt(e);return t===null?[]:[t]}))});try{return await xt(e,t)}finally{await r?.finish()}}}),k=async(e,t,n)=>{let r=ge.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(r.data.version!==n)throw new d(`CONFLICT`,`Canvas version ${String(r.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(r.data.version)} before submitting a new edit.`);let i=Ce.safeParse(r.data.document);if(i.success)return i.data;throw new d(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},A=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),St=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),j=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Ct=(e,t)=>{let n=new Set,r=t=>{for(let i of A(e,t))n.add(i),r(i)};return r(t),n},M=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},wt=e=>{let t=0;return n=>(t+=1,`${M(e)}_${M(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},N=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of A(e,t))r(n)};return r(t),n},Tt=(e,t,n)=>Object.fromEntries(N(e,t).map(t=>[t,n(j(e,t).label)])),Et=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=j(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Dt=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=j(t,n.id);if(n.id===`root`)throw new d(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!St(t.nodes[s]))throw new d(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Tt(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=N(t,n.id).map(e=>Et(l,e)),f=c[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:f,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Ot=(e,t,n)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=wt(n),i=t.map((t,n)=>Dt({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},kt=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,A(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),At=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},jt=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},Mt=(e,t)=>`parentId`in e?At(e,t):jt(e,t),Nt=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Ct(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!St(n.document.nodes[t.parentId]))throw new d(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Pt=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=Oe(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=ke(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},Ft=(e,t)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=kt(e),r=[];return{operations:t.flatMap(e=>{let t=Mt(e,n);Nt(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Pt(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},It=e=>typeof e==`number`?e:/^(?:\d+(?:\.\d+)?|\.\d+)px$/u.test(String(e))?Number(String(e).replace(`px`,``)):NaN,Lt=e=>e===`normal`?400:e===`bold`?700:Number(e),Rt=(e,t)=>{if(e.typography===void 0)return null;let n=[`font-family`,`font-size`,`font-weight`,`font-style`];if(n.every(e=>!Object.hasOwn(t,e)))return null;if(n.some(e=>t[e]===null))throw new d(`BAD_REQUEST`,`Imported typography needs an explicit font value.`,`Replace the font family, pixel size, weight or style instead of clearing that field.`);let i={...e.typography},a=t[`font-family`];if(a!==void 0){let e=String(a).split(`,`).map(e=>e.trim().replaceAll(/^(?:"|')|(?:"|')$/gu,``)).filter(e=>e!==``);i.family=e[0]??``,i.fallbackFamilies=e.slice(1)}t[`font-size`]!==void 0&&(i.size=It(t[`font-size`])),t[`font-weight`]!==void 0&&(i.weight=Lt(t[`font-weight`]));let o=r.safeParse({...i,...t[`font-style`]!==void 0&&{style:t[`font-style`]}});if(!o.success)throw new d(`BAD_REQUEST`,`The font edit cannot be represented by editable typography.`,`Use a font family list, numeric or pixel size, weight from 1 to 1000, and normal, italic or oblique style.`);return{op:`setTypography`,nodeId:e.id,typography:o.data}},zt=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Bt=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e]));for(let[e,r]of Object.entries(t)){if(r===null||h.safeParse({[e]:r}).success){n.delete(e);continue}let t=ee.safeParse({id:n.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:String(r),enabled:!0});if(!t.success)throw new d(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(e,t.data)}let r=[];for(let e of n.values()){if(r.length===128)throw new d(`BAD_REQUEST`,`Too many additional CSS declarations.`,`Remove unused declarations before adding more; no styles were changed.`);r.push(e)}return JSON.stringify(r)===JSON.stringify(e.additionalStyles?.declarations??[])?null:{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:r}}},Vt=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...o(t,r,e),...o(n,r,e)],s=de(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(s[t]={mode:n})}return JSON.stringify(s)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(s).length===0?`default`:s}},Ht=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of o(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},Ut=(e,t,n)=>{let r=Ht(e,t,n),i=Bt(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>h.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&i.additionalStyles!=="default"&&{additionalStyles:i.additionalStyles}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=Vt(e,t,o,n),c=Rt(t,r),l=(t.component===`text`?[`color`]:[`background`,`background-color`,`background-image`]).some(e=>Object.hasOwn(r,e))&&t.appearance?.fills!==void 0?[{op:`setAppearance`,nodeId:t.id,appearance:{clear:[`fills`]}}]:[];return[...Object.keys(a).length>0?[{op:`setStyles`,nodeId:t.id,styles:h.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},Wt=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=zt(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},Gt=(e,t)=>{let n=[...Wt(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return Ut(e,r,n)});if(n.length===0)throw new d(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},Kt=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);if(e.component===`text`&&t.styles[`line-height`]===void 0){let e=t.styles[`font-size`];typeof e==`number`?n[`line-height`]=`${String(Math.round(e*1.35))}px`:e===null&&Reflect.deleteProperty(n,`line-height`)}return{...e,styles:n}},qt=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`setLayout`,`setAdditionalStyles`,`setParentage`]),Jt=e=>qt.has(e.op),Yt=(e,t)=>{let n={...e};return t==="default"?Reflect.deleteProperty(n,`typography`):n.typography=t,n},Xt=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new d(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return Kt(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`setTypography`:return Yt(e,t.typography);case`setLayout`:{let n={...e};return t.layout==="default"?Reflect.deleteProperty(n,`layout`):n.layout=t.layout,n}case`setAdditionalStyles`:{let n={...e};return t.additionalStyles==="default"?Reflect.deleteProperty(n,`additionalStyles`):n.additionalStyles=t.additionalStyles,n}}},Zt=(e,t)=>{if(!Jt(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new d(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=j(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Xt(n,t)}}},Qt=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},$t=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return Gt(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Ot(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=Ft(t.scene,[Qt(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},en=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=$t(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=Zt(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:A(r.scene,e)}))}},P=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},tn=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:P(e),nn=(e,t)=>{if(e.edits.length===0||e.edits.length>1e3)throw new d(`BAD_REQUEST`,`The edit batch exceeds the canonical operation limit.`,`Split larger changes into bounded batches.`);let n=new Set(e.edits.flatMap(e=>P(e)));if(n.size>1e3)throw new d(`BAD_REQUEST`,`A batch may target at most 1,000 nodes.`,`Split the edit into smaller batches.`);for(let e of n)j(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[]};for(let n of e.edits)a(r,t,tn(n,t))},F=e=>({execute:async t=>{let n=await k({remote:e},t.canvasId,t.baseVersion);nn(t,n);let r=en(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);i({canvasId:t.canvasId,nodeIds:t.nodeIds??[]},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=me.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:3,baseVersion:t.baseVersion,operations:r.operations});if(!a.success)throw new d(`BAD_REQUEST`,`The edit exceeds canonical canvas limits.`,a.error.issues[0]?.message??`Reduce the edit batch.`);let o=le.parse(await O(e).execute(a.data));return{...o,next:[`Reuse version ${String(o.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(o.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),I=`canvas.render.getImport`,L=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),rn=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),an=e=>{let t=e.failure;return new d(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},on=async(e,t)=>{let n=pe.safeParse(await e.query(I,{jobId:t}));if(!n.success)throw L(`HTML import status`);return n.data.job},sn=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await rn(250),i=await on(e,i.id)}if(i.state!==`succeeded`)throw an(i);return i},cn=async(e,t)=>{let n=fe.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw L(`HTML import creation`);return sn(e,n.data.job,t.renderTimeoutMs)},ln=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof d?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),un=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return ln(e,t,n.result.version)}},dn=async(e,t)=>{let n=await k({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},R=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),fn=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:I,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),z=(e,t)=>({execute:async n=>{if(n.selectionNodeIds!==void 0&&n.selectionNodeIds.length>0){let t=await k({remote:e},n.canvasId,n.baseVersion);a({canvasId:n.canvasId,nodeIds:n.selectionNodeIds},t,[n.targetNodeId])}let r=await D(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await cn(e,n);if(i.state!==`succeeded`)return fn(i);if(n.review===`none`)return R(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await un(t,n,i),o=[];try{o=await dn(e,i)}catch{o=[]}return{...R(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),B=(e,t,n)=>{try{Ne(e,t,{flag:n?`w`:`wx`,mode:384}),Ae(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new d(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},V=e=>({write:t=>{if(t.outputPath!==null){let e=y.resolve(t.outputPath);return B(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=y.join(e,`sensitive`);Me(n,{recursive:!0,mode:448}),Ae(n,448);let r=y.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return B(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),H=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],U=e=>new d(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),pn=async(e,t)=>{let n=Date.now()+3e5,r=50;for(;Date.now()<n;){let n=s.safeParse(await e.query(H[3],t));if(!n.success)throw U(`status`);if(n.data.state===`ready`||n.data.state===`failed`)return n.data;if(n.data.state===`abandoned`)throw new d(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Fe(r),r=Math.min(r*2,1e3)}throw Error(`prototype ingestion is still running`)},mn=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(H[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw U(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),(i.data.state===`uploading`||i.data.state===`queued`)&&!l.safeParse(await e.mutate(H[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw U(`artifact submission`);return i.data},hn=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new d(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},gn=async(e,t,n)=>{let r=re.safeParse(await e.query(H[0],{}));if(!r.success)throw U(`capabilities`);let i=await t.package({directory:n.directory,entryPath:n.entryPath,limits:r.data.limits}),a={deploymentId:null};try{let t=await mn(e,n,i,e=>{a.deploymentId=e}),r=await pn(e,{canvasId:n.canvasId,deploymentId:t.deploymentId});hn(r);let o=ne.safeParse(await e.mutate(H[4],{canvasId:n.canvasId,deploymentId:t.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw U(`attachment`);return{...o.data,fileCount:r.fileCount,totalBytes:r.totalBytes,alreadyExists:t.alreadyExists,next:[o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof d&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||a.deploymentId===null?e:new he(`Prototype deployment ${a.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`)}finally{await i.dispose()}},_n=(e,t)=>({execute:async n=>gn(e,t,n)}),vn=[`transcript.get`],yn=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),bn=e=>({execute:async t=>{let n=f.safeParse(await e.query(vn[0],t));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:yn(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),W=[`canvas.render.get`,`canvas.render.snapshot`],xn=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Sn=e=>new d(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Cn=async(e,t)=>{let n=m.safeParse(await e.query(W[0],{jobId:t}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},wn=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let t=Date.now(),l=`${o.state}:${o.phase}`;if((l!==c||t-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:t-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=t,c=l),t>=i)throw new d(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase});await xn(),o=await Cn(e,o.id)}if(o.state!==`succeeded`||o.result.snapshot===void 0)throw Sn(o);return{...o,result:{...o.result,snapshot:o.result.snapshot}}},Tn=async(e,t,n)=>{let r=be.safeParse(await e.mutate(W[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let i=await wn(e,r.data.job,n,t),a=i.result.snapshot;return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${a.screenNodeId}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${a.screenNodeId} --expected-version ${String(a.version)}`]}},En=(e,t)=>({execute:async n=>Tn(e,t,n)}),G=new Date(`1980-01-01T00:00:00.000Z`),Dn=33188,On=(e,t)=>new d(`BAD_REQUEST`,e,t),kn=(e,t)=>{let n=b(`sha256`),r=0;return new qe({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},An=e=>{let n=u.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),r=Buffer.from(JSON.stringify(n),`utf8`);if(r.byteLength>e.limits.manifestBytes)throw On(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(r,t,{mtime:G,mode:Dn,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),n},jn=async e=>{let t=new Ye,n=b(`sha256`),r=new qe({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Je(t.outputStream,r,je(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=An({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:G,mode:Dn,compress:!0,forceDosTimestamp:!0},e=>{e(null,v(n.absolutePath).pipe(kn(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await Ue(e.artifactPath);if(c.size>e.limits.artifactBytes)throw On(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},Mn={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},Nn=e=>Mn[y.extname(e).toLowerCase()]??`application/octet-stream`,Pn=async e=>{try{return await Ue(e)}catch{return null}},Fn=e=>Buffer.byteLength(e,`utf8`),K=(e,t)=>new d(`BAD_REQUEST`,e,t),In=(e,t)=>{if(!_e.safeParse(e).success)throw K(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Fn(e)>t.pathBytes)throw K(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Ln=async(e,t,n,r)=>{let i=await Be(t);if(n.has(i))throw K(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=y.join(t,n.name),o=await Pn(i);if(o?.isDirectory()===!0){c.push(...await Ln(e,i,a,r));continue}if(o?.isFile()!==!0)throw K(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=y.relative(e,i).split(y.sep).join(`/`).normalize(`NFC`);In(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:Nn(i)})}return c},Rn=(e,t,n)=>{if(e.length===0)throw K(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw K(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=te(t.path);if(r.has(e))throw K(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw K(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw K(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw K(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw K(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},zn=async e=>{let t=y.resolve(e.directory),n=await Pn(t);if(n===null)throw new d(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw K(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(y.sep).join(`/`).normalize(`NFC`);In(r,e.limits);let i=await Ln(t,t,new Set,e.limits);Rn(i,r,e.limits);let a=await Re(y.join(De(),`enhance-prototype-artifact-`)),o=y.join(a,`artifact.zip`);try{let t=await jn({artifactPath:o,files:i,entryPath:r,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>v(o),dispose:async()=>He(a,{recursive:!0})}}catch(e){throw await He(a,{recursive:!0}),e}},Bn=()=>({package:zn}),Vn=e=>ft(e.remote,V(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Hn=async(e,t)=>{let n=se.parse(t);return O(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Un=async(e,t,n)=>{let r=ye.parse(t);return Vn(e).execute({...r,retryClientToken:n})},Wn=async(e,t)=>{let n=we.parse(t);return z(e.remote,Vn(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Gn=async(e,t)=>{let n=ue.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Kn=async(e,t,n)=>{let r=Se.parse(t);return _n(e.remote,Bn()).execute({...r,clientToken:n})},qn=async(e,t,n)=>{let r=p.parse(t);return En(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Jn=async(e,t)=>{let r=n.parse(t);return bn(e.remote).execute(r)},Yn=async(t,n,r,i)=>{switch(n){case`canvas.edit`:{let n=xe.parse(r),i=e(n.canvas);return F(t.remote).execute({canvasId:i.canvasId,nodeIds:i.nodeIds,baseVersion:n.baseVersion,edits:n.edits,mutationId:t.mutationKey.current(`canvas.applyOperations`,n)})}case`canvas.apply`:return Hn(t,r);case`canvas.render`:return Un(t,r,i);case`canvas.writeHtml`:return Wn(t,r);case`comment.attention`:return Gn(t,r);case`prototype.publish`:return Kn(t,r,i);case`recording.snapshot`:return qn(t,r,i);case`transcript.read`:return Jn(t,r);default:throw TypeError(`${n} has no composite execution`)}},Xn=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??x();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Yn(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Zn=`/callback`,Qn=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),$n=e=>{let t=_.platform===`darwin`?{executable:`open`,arguments:[e]}:_.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Qe(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},er=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Zn){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},tr=e=>{let t=Qn(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},nr=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=$e((n,r)=>{er({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${Zn}`,a=tr({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&$n(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},rr=e=>({authorize:async t=>{try{let n=Pe(32).toString(`base64url`),r=b(`sha256`).update(n).digest(`base64url`),i=Pe(32).toString(`base64url`),a=await nr({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new d(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),q=e=>e===void 0||e===``?void 0:e,ir=((e,t,n)=>{let r=q(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=q(e.ENHANCE3_API_URL),a=y.join(t,`.config`,n.configDirectoryName),o=q(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&y.resolve(o)!==y.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(_.env,Ee(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),ar=g.object({token:g.string().startsWith(`enh_`)}),or=e=>{let t=y.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await ze(t,`utf8`));return ar.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Le(e,{recursive:!0,mode:448}),await Ie(e,448);let r=y.join(e,`credentials.${String(_.pid)}.tmp`);await Ge(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ve(r,t),await Ie(t,384)},remove:async()=>{try{return await We(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},sr=g.object({access_token:g.string().min(1)}),cr=g.object({code:g.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),J=`Check network access and proxy settings for this API, then run enhance doctor again.`,Y=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,lr=e=>{let t=cr.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?lr(e.cause):e instanceof Error?e.name:`Network request failed`},X=(e,t)=>new d(`INTERNAL`,`${Y(e)} answered HTTP ${String(t)}.`,J),Z=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new d(`INTERNAL`,`Could not reach ${Y(e)}: ${lr(t)}.`,J)}},ur=async(e,t)=>{let n=await Z(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw X(e,n.status);return n},Q=(e,t,n=null)=>Xe({links:[Ze({url:`${e}/trpc`,fetch:async(e,t)=>ur(e,{...t,signal:t?.signal??null}),headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),dr=async e=>{let t=await fetch(e);if(!t.ok)throw new d(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},fr=async e=>{let t=await Z(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new d(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new d(`INTERNAL`,`${Y(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,J);return t.json()},pr=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Z(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw X(e,n.status);return n.json()},mr=async e=>{let t=await Z(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new d(`INTERNAL`,`${Y(e.issuer)} token exchange answered HTTP ${String(t.status)}`,J);return sr.parse(await t.json()).access_token},hr=async e=>{try{let t=await Z(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:X(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Y(e)}.`}}},gr=(e,t,n)=>{let r=e.replace(/\/$/,``);return{authenticationConfig:async()=>fr(r),oauthMetadata:pr,exchangeOauthCode:mr,query:async(e,n)=>Q(r,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(r,n).query(e,t),mutate:async(e,i)=>Q(r,await t.read(),n.current(e,i)).mutation(e,i),mutateWithToken:async(e,t,n)=>Q(r,n).mutation(e,t),download:dr,upload:async e=>{let t=!(e.body instanceof Uint8Array),n=t?Ke.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new d(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new d(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},health:async()=>hr(r)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),_r=(e,t,n)=>b(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),vr=()=>{let e=x(),t=!1;return{current:(n,r)=>t?_r(e,n,r):e,select:(n,r)=>{e=n??x(),t=r}}};export{rr as a,z as c,O as d,D as f,ir as i,F as l,tt as m,gr as n,Xn as o,ft as p,or as r,V as s,vr as t,k as u};
|
|
2
|
+
import{A as e,B as t,C as n,Ct as r,D as i,E as a,Et as o,G as s,H as c,J as l,K as u,M as d,N as f,S as p,St as ee,U as te,V as ne,W as re,X as ie,Y as ae,Z as oe,_ as se,_t as ce,at as le,b as ue,bt as m,ct as de,dt as fe,ft as pe,it as me,j as he,lt as ge,q as _e,st as h,tt as ve,v as ye,vt as be,w as xe,x as Se,xt as Ce,y as we,yt as Te}from"./cli-output-identity.lib-CPk2NGO2.mjs";import{z as g}from"zod";import{homedir as Ee,tmpdir as De}from"node:os";import _ from"node:process";import{generateKeyBetween as Oe,generateNKeysBetween as ke}from"fractional-indexing";import{chmodSync as Ae,createReadStream as v,createWriteStream as je,mkdirSync as Me,writeFileSync as Ne}from"node:fs";import y from"node:path";import{createHash as b,randomBytes as Pe,randomUUID as x}from"node:crypto";import{setTimeout as Fe}from"node:timers/promises";import{chmod as Ie,mkdir as Le,mkdtemp as Re,readFile as ze,realpath as Be,rename as Ve,rm as He,stat as Ue,unlink as We,writeFile as Ge}from"node:fs/promises";import{Readable as Ke,Transform as qe}from"node:stream";import{pipeline as Je}from"node:stream/promises";import{ZipFile as Ye}from"yazl";import{createTRPCUntypedClient as Xe,httpLink as Ze}from"@trpc/client";import{spawn as Qe}from"node:child_process";import{createServer as $e}from"node:http";const et=/^enh_[\w-]{43}$/,S=e=>{let t=ae.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new d(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},tt=(e,t,n)=>({loginWithToken:async n=>{if(!et.test(n))throw new d(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=S(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=ie.parse(await t.authenticationConfig());if(i.method===`token`)throw new d(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=oe.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=S(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async()=>{if(await e.read()===null)throw new d(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return S(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),nt=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),rt=e=>{if(e.byteLength<24||nt.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},it=async(e,t)=>{let n=Te.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=rt(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new d(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return r},C=[`canvas.render.create`,`canvas.render.get`],w=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),at=e=>{let t=e.failure;if(t===null)return w(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new d(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase})},ot=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),st=async(e,t)=>{let n=m.safeParse(await e.query(C[1],{jobId:t}));if(!n.success)throw w(`render status`);return n.data.job},ct=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline)throw new d(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase});await ot(250),a=await st(e,a.id)}if(a.state!==`succeeded`)throw at(a);return a},lt=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},ut=(e,t)=>({jobId:e.id,canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:lt(e)}),dt=async(e,t)=>{let n=ce.safeParse(await e.remote.mutate(C[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw w(`render creation`);let r=await ct(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await it(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return ut(r,a)},ft=(e,t,n,r=()=>null)=>({execute:async i=>dt({remote:e,files:t,now:n,progress:r},i)}),T={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},E=async e=>{try{return await e(),!0}catch{return!1}},pt=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await E(async()=>e.mutate(T.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await E(async()=>e.mutate(T.end,{canvasId:i.canvasId,activityId:n})))}}},D=e=>({begin:async t=>{try{let n=ve.safeParse(await e.mutate(T.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?pt(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>E(async()=>e.mutate(T.end,{canvasId:t,activityId:n}))}),mt=new Set([`insertPrototype`,`insertText`,`setBox`]),ht=e=>mt.has(e.op),gt=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,_t=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],vt=e=>[...new Set(e.operations.flatMap(e=>_t(e)))].slice(0,100),yt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:ht(e)?e.box==="default"?null:e.box:null,bt=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},xt=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:3}),r=le.safeParse(n);if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},O=e=>({execute:async(t,n)=>{if(n?.activity===!1)return xt(e,t);let r=await D(e).begin({canvasId:t.canvasId,phase:gt(t),nodeIds:vt(t),bounds:bt(t.operations.flatMap(e=>{let t=yt(e);return t===null?[]:[t]}))});try{return await xt(e,t)}finally{await r?.finish()}}}),k=async(e,t,n)=>{let r=ge.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(r.data.version!==n)throw new d(`CONFLICT`,`Canvas version ${String(r.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(r.data.version)} before submitting a new edit.`);let i=Ce.safeParse(r.data.document);if(i.success)return i.data;throw new d(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},A=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),St=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),j=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Ct=(e,t)=>{let n=new Set,r=t=>{for(let i of A(e,t))n.add(i),r(i)};return r(t),n},M=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},wt=e=>{let t=0;return n=>(t+=1,`${M(e)}_${M(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},N=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of A(e,t))r(n)};return r(t),n},Tt=(e,t,n)=>Object.fromEntries(N(e,t).map(t=>[t,n(j(e,t).label)])),Et=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=j(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Dt=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=j(t,n.id);if(n.id===`root`)throw new d(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!St(t.nodes[s]))throw new d(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Tt(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=N(t,n.id).map(e=>Et(l,e)),f=c[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:f,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Ot=(e,t,n)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=wt(n),i=t.map((t,n)=>Dt({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},kt=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,A(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),At=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},jt=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new d(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},Mt=(e,t)=>`parentId`in e?At(e,t):jt(e,t),Nt=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new d(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Ct(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!St(n.document.nodes[t.parentId]))throw new d(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Pt=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=Oe(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=ke(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},Ft=(e,t)=>{if(t.length===0)throw new d(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=kt(e),r=[];return{operations:t.flatMap(e=>{let t=Mt(e,n);Nt(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Pt(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},It=e=>typeof e==`number`?e:/^(?:\d+(?:\.\d+)?|\.\d+)px$/u.test(String(e))?Number(String(e).replace(`px`,``)):NaN,Lt=e=>e===`normal`?400:e===`bold`?700:Number(e),Rt=(e,t)=>{if(e.typography===void 0)return null;let n=[`font-family`,`font-size`,`font-weight`,`font-style`];if(n.every(e=>!Object.hasOwn(t,e)))return null;if(n.some(e=>t[e]===null))throw new d(`BAD_REQUEST`,`Imported typography needs an explicit font value.`,`Replace the font family, pixel size, weight or style instead of clearing that field.`);let i={...e.typography},a=t[`font-family`];if(a!==void 0){let e=String(a).split(`,`).map(e=>e.trim().replaceAll(/^(?:"|')|(?:"|')$/gu,``)).filter(e=>e!==``);i.family=e[0]??``,i.fallbackFamilies=e.slice(1)}t[`font-size`]!==void 0&&(i.size=It(t[`font-size`])),t[`font-weight`]!==void 0&&(i.weight=Lt(t[`font-weight`]));let o=r.safeParse({...i,...t[`font-style`]!==void 0&&{style:t[`font-style`]}});if(!o.success)throw new d(`BAD_REQUEST`,`The font edit cannot be represented by editable typography.`,`Use a font family list, numeric or pixel size, weight from 1 to 1000, and normal, italic or oblique style.`);return{op:`setTypography`,nodeId:e.id,typography:o.data}},zt=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Bt=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e]));for(let[e,r]of Object.entries(t)){if(r===null||h.safeParse({[e]:r}).success){n.delete(e);continue}let t=ee.safeParse({id:n.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:String(r),enabled:!0});if(!t.success)throw new d(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(e,t.data)}let r=[];for(let e of n.values()){if(r.length===128)throw new d(`BAD_REQUEST`,`Too many additional CSS declarations.`,`Remove unused declarations before adding more; no styles were changed.`);r.push(e)}return JSON.stringify(r)===JSON.stringify(e.additionalStyles?.declarations??[])?null:{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:r}}},Vt=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...o(t,r,e),...o(n,r,e)],s=de(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(s[t]={mode:n})}return JSON.stringify(s)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(s).length===0?`default`:s}},Ht=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of o(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},Ut=(e,t,n)=>{let r=Ht(e,t,n),i=Bt(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>h.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&i.additionalStyles!=="default"&&{additionalStyles:i.additionalStyles}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=Vt(e,t,o,n),c=Rt(t,r),l=(t.component===`text`?[`color`]:[`background`,`background-color`,`background-image`]).some(e=>Object.hasOwn(r,e))&&t.appearance?.fills!==void 0?[{op:`setAppearance`,nodeId:t.id,appearance:{clear:[`fills`]}}]:[];return[...Object.keys(a).length>0?[{op:`setStyles`,nodeId:t.id,styles:h.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},Wt=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=zt(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},Gt=(e,t)=>{let n=[...Wt(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return Ut(e,r,n)});if(n.length===0)throw new d(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},Kt=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);if(e.component===`text`&&t.styles[`line-height`]===void 0){let e=t.styles[`font-size`];typeof e==`number`?n[`line-height`]=`${String(Math.round(e*1.35))}px`:e===null&&Reflect.deleteProperty(n,`line-height`)}return{...e,styles:n}},qt=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`setLayout`,`setAdditionalStyles`,`setParentage`]),Jt=e=>qt.has(e.op),Yt=(e,t)=>{let n={...e};return t==="default"?Reflect.deleteProperty(n,`typography`):n.typography=t,n},Xt=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new d(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return Kt(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`setTypography`:return Yt(e,t.typography);case`setLayout`:{let n={...e};return t.layout==="default"?Reflect.deleteProperty(n,`layout`):n.layout=t.layout,n}case`setAdditionalStyles`:{let n={...e};return t.additionalStyles==="default"?Reflect.deleteProperty(n,`additionalStyles`):n.additionalStyles=t.additionalStyles,n}}},Zt=(e,t)=>{if(!Jt(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new d(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=j(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Xt(n,t)}}},Qt=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},$t=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return Gt(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Ot(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=Ft(t.scene,[Qt(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},en=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=$t(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=Zt(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:A(r.scene,e)}))}},P=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},tn=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:P(e),nn=(e,t)=>{if(e.edits.length===0||e.edits.length>1e3)throw new d(`BAD_REQUEST`,`The edit batch exceeds the canonical operation limit.`,`Split larger changes into bounded batches.`);let n=new Set(e.edits.flatMap(e=>P(e)));if(n.size>1e3)throw new d(`BAD_REQUEST`,`A batch may target at most 1,000 nodes.`,`Split the edit into smaller batches.`);for(let e of n)j(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[]};for(let n of e.edits)a(r,t,tn(n,t))},F=e=>({execute:async t=>{let n=await k({remote:e},t.canvasId,t.baseVersion);nn(t,n);let r=en(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);i({canvasId:t.canvasId,nodeIds:t.nodeIds??[]},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=me.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:3,baseVersion:t.baseVersion,operations:r.operations});if(!a.success)throw new d(`BAD_REQUEST`,`The edit exceeds canonical canvas limits.`,a.error.issues[0]?.message??`Reduce the edit batch.`);let o=le.parse(await O(e).execute(a.data));return{...o,next:[`Reuse version ${String(o.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(o.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),I=`canvas.render.getImport`,L=e=>new d(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),rn=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),an=e=>{let t=e.failure;return new d(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},on=async(e,t)=>{let n=pe.safeParse(await e.query(I,{jobId:t}));if(!n.success)throw L(`HTML import status`);return n.data.job},sn=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await rn(250),i=await on(e,i.id)}if(i.state!==`succeeded`)throw an(i);return i},cn=async(e,t)=>{let n=fe.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw L(`HTML import creation`);return sn(e,n.data.job,t.renderTimeoutMs)},ln=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof d?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),un=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return ln(e,t,n.result.version)}},dn=async(e,t)=>{let n=await k({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},R=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),fn=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:I,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),z=(e,t)=>({execute:async n=>{if(n.selectionNodeIds!==void 0&&n.selectionNodeIds.length>0){let t=await k({remote:e},n.canvasId,n.baseVersion);a({canvasId:n.canvasId,nodeIds:n.selectionNodeIds},t,[n.targetNodeId])}let r=await D(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await cn(e,n);if(i.state!==`succeeded`)return fn(i);if(n.review===`none`)return R(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await un(t,n,i),o=[];try{o=await dn(e,i)}catch{o=[]}return{...R(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),B=(e,t,n)=>{try{Ne(e,t,{flag:n?`w`:`wx`,mode:384}),Ae(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new d(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},V=e=>({write:t=>{if(t.outputPath!==null){let e=y.resolve(t.outputPath);return B(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=y.join(e,`sensitive`);Me(n,{recursive:!0,mode:448}),Ae(n,448);let r=y.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return B(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),H=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],U=e=>new d(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),pn=async(e,t)=>{let n=Date.now()+3e5,r=50;for(;Date.now()<n;){let n=s.safeParse(await e.query(H[3],t));if(!n.success)throw U(`status`);if(n.data.state===`ready`||n.data.state===`failed`)return n.data;if(n.data.state===`abandoned`)throw new d(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Fe(r),r=Math.min(r*2,1e3)}throw Error(`prototype ingestion is still running`)},mn=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(H[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw U(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),(i.data.state===`uploading`||i.data.state===`queued`)&&!l.safeParse(await e.mutate(H[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw U(`artifact submission`);return i.data},hn=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new d(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},gn=async(e,t,n)=>{let r=re.safeParse(await e.query(H[0],{}));if(!r.success)throw U(`capabilities`);let i=await t.package({directory:n.directory,entryPath:n.entryPath,limits:r.data.limits}),a={deploymentId:null};try{let t=await mn(e,n,i,e=>{a.deploymentId=e}),r=await pn(e,{canvasId:n.canvasId,deploymentId:t.deploymentId});hn(r);let o=ne.safeParse(await e.mutate(H[4],{canvasId:n.canvasId,deploymentId:t.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw U(`attachment`);return{...o.data,fileCount:r.fileCount,totalBytes:r.totalBytes,alreadyExists:t.alreadyExists,next:[o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof d&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||a.deploymentId===null?e:new he(`Prototype deployment ${a.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`)}finally{await i.dispose()}},_n=(e,t)=>({execute:async n=>gn(e,t,n)}),vn=[`transcript.get`],yn=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),bn=e=>({execute:async t=>{let n=f.safeParse(await e.query(vn[0],t));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:yn(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),W=[`canvas.render.get`,`canvas.render.snapshot`],xn=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Sn=e=>new d(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Cn=async(e,t)=>{let n=m.safeParse(await e.query(W[0],{jobId:t}));if(!n.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},wn=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let t=Date.now(),l=`${o.state}:${o.phase}`;if((l!==c||t-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:t-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=t,c=l),t>=i)throw new d(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase});await xn(),o=await Cn(e,o.id)}if(o.state!==`succeeded`||o.result.snapshot===void 0)throw Sn(o);return{...o,result:{...o.result,snapshot:o.result.snapshot}}},Tn=async(e,t,n)=>{let r=be.safeParse(await e.mutate(W[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs}));if(!r.success)throw new d(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let i=await wn(e,r.data.job,n,t),a=i.result.snapshot;return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${a.screenNodeId}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${a.screenNodeId} --expected-version ${String(a.version)}`]}},En=(e,t)=>({execute:async n=>Tn(e,t,n)}),G=new Date(`1980-01-01T00:00:00.000Z`),Dn=33188,On=(e,t)=>new d(`BAD_REQUEST`,e,t),kn=(e,t)=>{let n=b(`sha256`),r=0;return new qe({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},An=e=>{let n=u.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),r=Buffer.from(JSON.stringify(n),`utf8`);if(r.byteLength>e.limits.manifestBytes)throw On(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(r,t,{mtime:G,mode:Dn,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),n},jn=async e=>{let t=new Ye,n=b(`sha256`),r=new qe({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Je(t.outputStream,r,je(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=An({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:G,mode:Dn,compress:!0,forceDosTimestamp:!0},e=>{e(null,v(n.absolutePath).pipe(kn(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await Ue(e.artifactPath);if(c.size>e.limits.artifactBytes)throw On(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},Mn={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},Nn=e=>Mn[y.extname(e).toLowerCase()]??`application/octet-stream`,Pn=async e=>{try{return await Ue(e)}catch{return null}},Fn=e=>Buffer.byteLength(e,`utf8`),K=(e,t)=>new d(`BAD_REQUEST`,e,t),In=(e,t)=>{if(!_e.safeParse(e).success)throw K(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Fn(e)>t.pathBytes)throw K(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Ln=async(e,t,n,r)=>{let i=await Be(t);if(n.has(i))throw K(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=y.join(t,n.name),o=await Pn(i);if(o?.isDirectory()===!0){c.push(...await Ln(e,i,a,r));continue}if(o?.isFile()!==!0)throw K(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=y.relative(e,i).split(y.sep).join(`/`).normalize(`NFC`);In(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:Nn(i)})}return c},Rn=(e,t,n)=>{if(e.length===0)throw K(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw K(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=te(t.path);if(r.has(e))throw K(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw K(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw K(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw K(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw K(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},zn=async e=>{let t=y.resolve(e.directory),n=await Pn(t);if(n===null)throw new d(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw K(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(y.sep).join(`/`).normalize(`NFC`);In(r,e.limits);let i=await Ln(t,t,new Set,e.limits);Rn(i,r,e.limits);let a=await Re(y.join(De(),`enhance-prototype-artifact-`)),o=y.join(a,`artifact.zip`);try{let t=await jn({artifactPath:o,files:i,entryPath:r,limits:e.limits});return{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>v(o),dispose:async()=>He(a,{recursive:!0})}}catch(e){throw await He(a,{recursive:!0}),e}},Bn=()=>({package:zn}),Vn=e=>ft(e.remote,V(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Hn=async(e,t)=>{let n=se.parse(t);return O(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Un=async(e,t,n)=>{let r=ye.parse(t);return Vn(e).execute({...r,retryClientToken:n})},Wn=async(e,t)=>{let n=we.parse(t);return z(e.remote,Vn(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Gn=async(e,t)=>{let n=ue.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Kn=async(e,t,n)=>{let r=Se.parse(t);return _n(e.remote,Bn()).execute({...r,clientToken:n})},qn=async(e,t,n)=>{let r=p.parse(t);return En(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Jn=async(e,t)=>{let r=n.parse(t);return bn(e.remote).execute(r)},Yn=async(t,n,r,i)=>{switch(n){case`canvas.edit`:{let n=xe.parse(r),i=e(n.canvas);return F(t.remote).execute({canvasId:i.canvasId,nodeIds:i.nodeIds,baseVersion:n.baseVersion,edits:n.edits,mutationId:t.mutationKey.current(`canvas.applyOperations`,n)})}case`canvas.apply`:return Hn(t,r);case`canvas.render`:return Un(t,r,i);case`canvas.writeHtml`:return Wn(t,r);case`comment.attention`:return Gn(t,r);case`prototype.publish`:return Kn(t,r,i);case`recording.snapshot`:return qn(t,r,i);case`transcript.read`:return Jn(t,r);default:throw TypeError(`${n} has no composite execution`)}},Xn=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??x();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Yn(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Zn=`/callback`,Qn=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),$n=e=>{let t=_.platform===`darwin`?{executable:`open`,arguments:[e]}:_.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Qe(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},er=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Zn){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},tr=e=>{let t=Qn(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},nr=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=$e((n,r)=>{er({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${Zn}`,a=tr({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&$n(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},rr=e=>({authorize:async t=>{try{let n=Pe(32).toString(`base64url`),r=b(`sha256`).update(n).digest(`base64url`),i=Pe(32).toString(`base64url`),a=await nr({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new d(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),q=e=>e===void 0||e===``?void 0:e,ir=((e,t,n)=>{let r=q(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=q(e.ENHANCE3_API_URL),a=y.join(t,`.config`,n.configDirectoryName),o=q(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&y.resolve(o)!==y.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(_.env,Ee(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),ar=g.object({token:g.string().startsWith(`enh_`)}),or=e=>{let t=y.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await ze(t,`utf8`));return ar.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Le(e,{recursive:!0,mode:448}),await Ie(e,448);let r=y.join(e,`credentials.${String(_.pid)}.tmp`);await Ge(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ve(r,t),await Ie(t,384)},remove:async()=>{try{return await We(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},sr=g.object({access_token:g.string().min(1)}),cr=g.object({code:g.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),J=`Check network access and proxy settings for this API, then run enhance doctor again.`,Y=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,lr=e=>{let t=cr.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?lr(e.cause):e instanceof Error?e.name:`Network request failed`},X=(e,t)=>new d(`INTERNAL`,`${Y(e)} answered HTTP ${String(t)}.`,J),Z=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new d(`INTERNAL`,`Could not reach ${Y(e)}: ${lr(t)}.`,J)}},ur=async(e,t)=>{let n=await Z(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw X(e,n.status);return n},Q=(e,t,n=null)=>Xe({links:[Ze({url:`${e}/trpc`,fetch:async(e,t)=>ur(e,{...t,signal:t?.signal??null}),headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),dr=async e=>{let t=await fetch(e);if(!t.ok)throw new d(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},fr=async e=>{let t=await Z(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new d(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new d(`INTERNAL`,`${Y(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,J);return t.json()},pr=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Z(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw X(e,n.status);return n.json()},mr=async e=>{let t=await Z(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new d(`INTERNAL`,`${Y(e.issuer)} token exchange answered HTTP ${String(t.status)}`,J);return sr.parse(await t.json()).access_token},hr=async e=>{try{let t=await Z(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:X(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Y(e)}.`}}},gr=(e,t,n)=>{let r=e.replace(/\/$/,``);return{authenticationConfig:async()=>fr(r),oauthMetadata:pr,exchangeOauthCode:mr,query:async(e,n)=>Q(r,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(r,n).query(e,t),mutate:async(e,i)=>Q(r,await t.read(),n.current(e,i)).mutation(e,i),mutateWithToken:async(e,t,n)=>Q(r,n).mutation(e,t),download:dr,upload:async e=>{let t=!(e.body instanceof Uint8Array),n=t?Ke.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new d(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new d(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},health:async()=>hr(r)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),_r=(e,t,n)=>b(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),vr=()=>{let e=x(),t=!1;return{current:(n,r)=>t?_r(e,n,r):e,select:(n,r)=>{e=n??x(),t=r}}};export{rr as a,z as c,O as d,D as f,ir as i,F as l,tt as m,gr as n,Xn as o,ft as p,or as r,V as s,vr as t,k as u};
|