@enhance-eng/enhance-dev 0.1.36-dev.sha-801bf7637a11 → 0.1.36-dev.sha-ec2effb2a792

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$n as e,A as t,An as n,At as r,Bn as i,Bt as a,C as o,Cn as s,Ct as c,Dt as l,En as u,F as d,Fn as f,G as p,Gt as m,H as ee,Hn as te,Ht as ne,J as re,Jn as ie,Jt as ae,K as oe,Kn as se,Kt as ce,Ln as le,Lt as ue,M as de,Mn as fe,N as pe,O as me,On as he,Ot as h,Pn as ge,Q as _e,Qt as ve,Rn as g,S as ye,T as be,Tn as xe,U as Se,Un as _,Ut as Ce,Vn as we,Vt as Te,W as Ee,Wt as De,X as Oe,Xn as ke,Xt as Ae,Y as je,Yt as Me,_t as Ne,at as Pe,bn as Fe,ct as Ie,dr as Le,dt as Re,er as ze,fr as Be,gr as Ve,hr as He,ht as Ue,ir as We,jt as Ge,kn as v,kt as Ke,lt as qe,mr as Je,mt as Ye,nr as y,nt as Xe,or as Ze,ot as Qe,pr as $e,q as et,qn as tt,qt as nt,rr as b,rt,s as it,sr as at,tr as ot,tt as st,ur as ct,ut as lt,v as ut,vn as dt,w as ft,wn as pt,wt as x,x as S,xn as mt,xt as ht,yn as gt,yr as _t,yt as vt,z as yt,zn as bt,zt as xt}from"./cli-output-identity.lib-DtzRTex_.mjs";import C from"node:process";import{z as w}from"zod";import{homedir as St,tmpdir as Ct}from"node:os";import{generateKeyBetween as wt,generateNKeysBetween as Tt}from"fractional-indexing";import{chmodSync as Et,constants as Dt,createReadStream as Ot,createWriteStream as kt,mkdirSync as At,writeFileSync as jt}from"node:fs";import T from"node:path";import{createHash as E,randomBytes as Mt,randomUUID as Nt}from"node:crypto";import{setTimeout as Pt}from"node:timers/promises";import{access as Ft,chmod as It,mkdir as Lt,mkdtemp as Rt,open as zt,readFile as Bt,realpath as Vt,rename as Ht,rm as Ut,stat as Wt,unlink as Gt,writeFile as Kt}from"node:fs/promises";import{isDeepStrictEqual as qt}from"node:util";import{generate as Jt,parse as Yt}from"css-tree";import{parseFragment as Xt,serialize as Zt,serializeOuter as Qt}from"parse5";import{performance as $t}from"node:perf_hooks";import{Readable as en,Transform as tn}from"node:stream";import{pipeline as nn}from"node:stream/promises";import{ZipFile as rn}from"yazl";import{createTRPCUntypedClient as an,httpLink as on}from"@trpc/client";import{spawn as sn}from"node:child_process";import{createServer as cn}from"node:http";const ln=(e,t)=>{let n=new Set(t),r=[],i=new Map,a=r;for(let t of e)n.has(t.id)&&(a=[],i.set(t.id,a)),a.push(t);return[...r,...t.flatMap(e=>i.get(e)??[])]},un=(e,t)=>{let n=new Set(t.clear),r=new Map((e?.declarations??[]).filter(e=>!n.has(e.id)).map(e=>[e.id,e])),i=t.set??[];for(let e of i)r.set(e.id,e);let a=Array.from(r,([,e])=>e);return a.length===0&&(t.empty===`remove`||e===void 0&&t.empty!==`keep`)?null:{declarations:t.order===void 0?a:ln(a,t.order)}},dn=(e,t)=>{let n=new Map(e?.declarations.map(e=>[e.id,e])),r=t?.declarations??[],i=new Set(r.map(e=>e.id)),a=Array.from(n,([e])=>e).filter(e=>!i.has(e)),o=r.filter(e=>{let t=n.get(e.id);return t?.property!==e.property||t.value!==e.value||t.enabled!==e.enabled}),s={...a.length>0&&{clear:a},...o.length>0&&{set:o}},c=un(e,s),l=r.map(e=>e.id),u=JSON.stringify(c?.declarations.map(e=>e.id)??[])!==JSON.stringify(l),d=t===void 0&&e!==void 0?`remove`:e===void 0&&t!==void 0&&r.length===0?`keep`:void 0;return d===void 0&&!u&&o.length===0&&a.length===0?null:{...s,...u&&{order:l},...d!==void 0&&{empty:d}}},fn=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),pn=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,mn=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,hn=e=>!fn.has(e.toLowerCase()),gn=e=>!mn.test(e),_n=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?gn(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!pn.test(t.replaceAll(/[\p{Control}\s]/gu,``))},vn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),D=(e,t)=>{if(!vn(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},yn=(e,t)=>Array.isArray(e)?e.map(e=>{if(!vn(e)||e.kind!==`span`)return e;let n=Array.isArray(e.fills)?e.fills:void 0;return{...e,...n!==void 0&&{fills:n.map(e=>D(e,t))},...Array.isArray(e.children)&&{children:yn(e.children,t)}}}):e,bn=(e,t)=>{let n=e.appearance,r=e.props?.src;return{...e,...n!==void 0&&{appearance:{...n,...n.fills!==void 0&&{fills:n.fills.map(e=>D(e,t))},...n.border!==void 0&&{border:{...n.border,paint:D(n.border.paint,t)}},...n.outline!==void 0&&{outline:{...n.outline,paint:D(n.outline.paint,t)}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:D(e.typography.stroke.paint,t)}}},...e.props!==void 0&&{props:{...e.props,...e.component===`image`&&typeof r==`string`&&{src:t(r)},...e.component===`text`&&e.props.richText!==void 0&&{richText:yn(e.props.richText,t)}}}}},xn=/^enh_[\w-]{43}$/,Sn=e=>{let t=ae.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new r(`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}},Cn=(e,t,n)=>({loginWithToken:async n=>{if(!xn.test(n))throw new r(`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 i=Sn(await t.queryWithToken(`person.me`,{},n));return await e.write(n),i},loginWithBrowser:async i=>{let a=Me.parse(await t.authenticationConfig());if(a.method===`token`)throw new r(`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 o=await n.authorize({issuer:a.issuer,clientId:a.clientId,scope:a.scope,openBrowser:i.openBrowser,onReady:i.onReady,...i.signal!==void 0&&{signal:i.signal}});i.signal?.throwIfAborted();let s=Ae.parse(await t.mutateWithToken(`person.createAgentToken`,{label:i.label,expiresAt:null},o)),c=Sn(await t.queryWithToken(`person.me`,{},s.token));return i.signal?.throwIfAborted(),await e.write(s.token),c},status:async(n=t)=>{if(await e.read()===null)throw new r(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return Sn(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),wn=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),Tn=e=>{if(e.byteLength<24||wn.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)}},En=async(e,t)=>{if(t.result.canvasId!==t.canvasId||t.result.requestedVersion!==t.requestedVersion||t.result.loadedVersion!==t.requestedVersion||JSON.stringify(t.result.target)!==JSON.stringify(t.target))throw new r(`INTERNAL`,`The completed render evidence does not match its requested canvas, revision or target.`,`Do not use the image. Report render job ${t.id}.`);if(t.maxOutputPixels!==void 0&&t.result.width*t.result.height>t.maxOutputPixels)throw new r(`INTERNAL`,`The completed render exceeds its authorised output pixel limit.`,`Do not use the image. Report render job ${t.id}.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});let n=ot.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success||n.data.jobId!==t.id||n.data.download.bytes!==t.result.bytes)throw new r(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let i=await e.download(n.data.download.url),a=Tn(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new r(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return i},Dn=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]},On=(e,t)=>({jobId:e.id,operation:{kind:`canvas-render`,canvasId:e.canvasId,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:Dn(e)}),kn=async(e,t,n,r)=>On(n,t.write({body:await En(e,n),...r})),An=[`canvas.render.create`,`canvas.render.get`],O=e=>new r(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),jn=e=>{let t=e.failure;if(t===null)return O(`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`,i=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 r(n,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},Mn=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Nn=async(e,t)=>{let n=y.safeParse(await e.query(An[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw O(`render status`);return n.data.job},Pn=async(e,t)=>{let n=Date.now(),i=0,a=``,o=t.initial;for(;o.state===`queued`||o.state===`running`;){let s=Date.now(),c=`${o.state}:${o.phase}`;if((c!==a||s-i>=5e3)&&(t.progress({event:`render.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:s-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline){if(t.timeoutOutcome===`pending`)return o;throw new r(`INTERNAL`,`Render ${o.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:o.id,phase:o.phase})}await Mn(250),o=o.purpose===`inspection`&&o.state===`queued`&&o.attempt>0?await t.resume():await Nn(e,o.id)}if(o.state!==`succeeded`)throw jn(o);return o},Fn=async(t,n)=>{let r=e.safeParse(await t.mutate(An[0],{canvasId:n.canvasId,...n.expectedVersion!==null&&{expectedVersion:n.expectedVersion},target:n.target,...n.scope!==void 0&&{scope:n.scope},...n.sourceState!==null&&{sourceState:n.sourceState},scale:n.scale,...n.maxOutputPixels!==void 0&&{maxOutputPixels:n.maxOutputPixels},format:`png`}));if(!r.success)throw O(`render creation`);if(r.data.job.canvasId!==n.canvasId||n.expectedVersion!==null&&r.data.job.requestedVersion!==n.expectedVersion||JSON.stringify(r.data.job.target)!==JSON.stringify(n.target)||r.data.job.scale!==n.scale)throw O(`render identity`);return r.data.job},In=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new r(`INTERNAL`,`This API does not preserve the requested render pixel budget.`,`Update the API and renderer together before rendering a batch.`,{reason:`RENDER_BUDGET_UNSUPPORTED`})},Ln=async(e,t)=>{let n=await Fn(e.remote,t);try{In(n,t);let r=await Pn(e.remote,{initial:n,resume:async()=>Fn(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return In(r,t),r.state===`succeeded`?await kn(e.remote,e.files,r,{outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()}):{state:r.state,phase:r.phase,canvasId:r.canvasId,requestedVersion:r.requestedVersion,target:r.target,operation:{kind:`canvas-render`,canvasId:r.canvasId,jobId:r.id},pixelsDelivered:!1,next:[`Read operation_status with includeImage true. Do not create another render.`,`If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it.`]}}catch(e){let i=JSON.stringify({kind:`canvas-render`,canvasId:t.canvasId,jobId:n.id});throw e instanceof r?new r(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:i}):new r(`INTERNAL`,`The native render outcome could not be confirmed.`,`Read operation_status or retry with the identical request and clientToken.`,{jobId:n.id,operation:i})}},Rn=(e,t,n,r=()=>null)=>({execute:async i=>Ln({remote:e,files:t,now:n,progress:r},i)}),k={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},zn=async e=>{try{return await e(),!0}catch{return!1}},Bn=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await zn(async()=>e.mutate(k.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 zn(async()=>e.mutate(k.end,{canvasId:i.canvasId,activityId:n})))}}},Vn=e=>({begin:async t=>{try{let r=n.safeParse(await e.mutate(k.begin,{...t,nodeIds:[...t.nodeIds]}));return r.success?Bn(e,t,r.data.activityId,r.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>zn(async()=>e.mutate(k.end,{canvasId:t,activityId:n}))}),Hn=new Set([`insertPrototype`,`insertText`,`setBox`]),Un=e=>Hn.has(e.op),Wn=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,Gn=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Kn=e=>[...new Set(e.operations.flatMap(e=>Gn(e)))].slice(0,100),qn=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Un(e)?e.box==="default"?null:e.box:null,Jn=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}},Yn=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:8}),i=g.safeParse(n);if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},A=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Yn(e,t);let r=await Vn(e).begin({canvasId:t.canvasId,phase:Wn(t),nodeIds:Kn(t),bounds:Jn(t.operations.flatMap(e=>{let t=qn(e);return t===null?[]:[t]}))});try{return await Yn(e,t)}finally{await r?.finish()}}}),j=async(e,t,n)=>{let i=_.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==n)throw new r(`CONFLICT`,`Canvas version ${String(i.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(i.data.version)} before submitting a new edit.`);let a=b.safeParse(i.data.document);if(a.success)return a.data;throw new r(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},M=(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),N=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId)??[];e.push(n),t.set(r.parentId,e)}for(let n of t.values())n.sort((t,n)=>{let r=e.relationships[t]?.sortKey??``,i=e.relationships[n]?.sortKey??``;return r===i?t.localeCompare(n):r.localeCompare(i)});return t},Xn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),P=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new r(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Zn=(e,t)=>{let n=new Set,r=t=>{for(let i of M(e,t))n.add(i),r(i)};return r(t),n},F=(e,t)=>{let n=new Set,i=t;for(;i!==void 0;){if(n.has(i))throw new r(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(i),P(e,i).locked===!0)return!0;i=e.relationships[i]?.parentId}return!1},Qn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},$n=e=>{let t=0;return n=>(t+=1,`${Qn(e)}_${Qn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},er=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of M(e,t))r(n)};return r(t),n},tr=(e,t,n)=>Object.fromEntries(er(e,t).map(t=>[t,n(P(e,t).label)])),nr=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=P(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}}},rr=e=>{let{document:t,input:n,inputIndex:i,nextId:a}=e,o=P(t,n.id);if(n.id===`root`)throw new r(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=t.relationships[n.id];if(s===void 0)throw new r(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=n.parentId??s.parentId;if(!Xn(t.nodes[c]))throw new r(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=tr(t,n.id,a),u={document:t,rootId:n.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=er(t,n.id).map(e=>nr(u,e)),f=l[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:d,summary:{sourceId:n.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==n.id))}}},ir=(e,t,n)=>{if(t.length===0)throw new r(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=$n(n),a=t.map((t,n)=>rr({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},ar=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,M(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),or=(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))}},sr=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new r(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let i=t.parentOf.get(n);if(i===void 0)throw new r(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(t.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:i,index:`before`in e?a:a+1}},cr=(e,t)=>`parentId`in e?or(e,t):sr(e,t),lr=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new r(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Zn(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Xn(n.document.nodes[t.parentId]))throw new r(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},ur=(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=wt(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=Tt(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}}},dr=(e,t)=>{if(t.length===0)throw new r(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=ar(e),i=[];return{operations:t.flatMap(e=>{let t=cr(e,n);lr(e,t,n),i.push({nodeId:e.nodeId,...t});let r=ur(e,t,n);return n.document=r.document,r.operations}),moves:i,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},fr=(e,t)=>{let n=gt(new Set(Object.keys(t))).filter(t=>e.typography?.[t]!==void 0);return n.length===0?null:{op:`patchTypography`,nodeId:e.id,typography:{clear:n}}},pr=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),mr=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[e,i]of Object.entries(t)){let t=Array.from(n,([,e])=>e).filter(t=>(e.startsWith(`--`)?t.property:t.property.toLowerCase())===e);for(let e of t)n.delete(e.id);if(i===null||se.safeParse({[e]:i}).success)continue;let a=t[0]?.id??`css-${e}`.slice(0,190),o=a;for(let e=1;n.has(o);e+=1)o=`${a}-${String(e)}`;let s=Ve.safeParse({id:o,property:e,value:String(i),enabled:!0});if(!s.success)throw new r(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(o,s.data)}let i=n.values().toArray(),a=i.length===0&&e.additionalStyles===void 0?void 0:{declarations:i},o=dn(e.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:o}},hr=(e,t,n,r)=>{let a=new Set(Object.keys(r)),o=r=>[...at(t,r,e),...at(n,r,e)],s=i(t.layout??{},a,{horizontal:o(`horizontal`),vertical:o(`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}},gr=(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 at(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},_r=(e,t,n)=>{let r=gr(e,t,n),i=mr(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>se.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:un(t.additionalStyles,i.additionalStyles)??void 0}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=hr(e,t,o,n),c=fr(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:se.parse(a)}]:[],...l,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},vr=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=pr(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},yr=(e,t)=>{let n=[...vr(t)].flatMap(([t,n])=>{let i=e.nodes[t];if(i===void 0)throw new r(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return _r(e,i,n)});if(n.length===0)throw new r(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},br=(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);let i=dt(e.typography,{clear:[...gt(new Set([...Object.keys(t.styles),...r]))]});return I({...e,styles:n},`typography`,i??`default`)},xr=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),Sr=e=>xr.has(e.op),I=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},Cr=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new r(`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 br(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`patchTypography`:return I(e,`typography`,dt(e.typography,t.typography)??`default`);case`setTypography`:return I(e,`typography`,t.typography);case`setLayout`:return I(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=un(e.additionalStyles,t.additionalStyles);return I(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return I(e,`additionalStyles`,t.additionalStyles)}},wr=(e,t)=>{if(!Sr(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new r(`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=P(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Cr(n,t)}}},Tr=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}}}},Er=(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 yr(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=ir(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=dr(t.scene,[Tr(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},Dr=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=Er(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=wr(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:M(r.scene,e)}))}},L=e=>{throw new r(`BAD_REQUEST`,`These nodes are outside the link selection: ${e.join(`, `)}.`,`Keep the complete link. Edit only its page or selection and preserve the destination page.`)},Or=(e,t)=>{if(e.op===`insertNode`)return[e.parentage.parentId];if(e.op===`insertText`||e.op===`insertPrototype`)return[e.parentId,...e.afterId===void 0?[]:[e.afterId]];if(e.op===`insertConvertedSubtree`)return e.destination.kind===`adjacent`?L([`adjacent conversion`]):[e.destination.targetNodeId];if(e.op===`move`||e.op===`setParentage`){let n=e.op===`move`?e.parentId:e.parentage.parentId;return[e.nodeId,...n===t.relationships[e.nodeId]?.parentId?[]:[n],...e.op===`move`&&e.afterId!==void 0?[e.afterId]:[]]}return[e.nodeId]},kr=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],Ar=(e,t)=>{let n=t.destination;if(n.kind===`adjacent`)return L([`adjacent conversion`]);let r=n.kind===`replace`?e.relationships[n.targetNodeId]?.parentId:n.targetNodeId;if(r===void 0)return L([n.targetNodeId]);let i=n.kind===`insert-children`&&n.targetNodeId===`root`?n.pageId??`canvas-page-default`:he(e,n.targetNodeId),a=t.nodes[t.rootNodeId];return a===void 0?L([t.rootNodeId]):{nodes:{...t.nodes,[t.rootNodeId]:{...a,...r===`root`&&i!==null&&{props:{...a.props,canvasPageId:i}}}},relationships:{...t.relationships,[t.rootNodeId]:{parentId:r,sortKey:``}}}},jr=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Mr=(e,t)=>{if(t.op===`insertNode`)return{nodes:{[t.node.id]:t.node},relationships:{[t.node.id]:t.parentage}};if(t.op===`insertText`||t.op===`insertPrototype`)return{nodes:{[t.nodeId]:jr(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return Ar(e,t);if(t.op===`move`||t.op===`setParentage`)return{nodes:{},relationships:{[t.nodeId]:t.op===`move`?{parentId:t.parentId,sortKey:``}:t.parentage}};if(t.op===`setProps`){let n=e.nodes[t.nodeId];if(n!==void 0)return{nodes:{[t.nodeId]:{...n,props:t.props==="default"?{}:t.props}},relationships:{}}}return{nodes:{},relationships:{}}},Nr=(e,t,n,r)=>{let i=kr(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...Or(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&L(o),i},Pr=(e,t,n)=>{if(!l(e))return;let r=new Set(x(e,t)),i=v(e,t);if(!i.ok)return L(e.nodeIds);let a={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of n){let n=Nr(e,a,r,t),o=Mr(a,t);Object.assign(a.nodes,o.nodes),Object.assign(a.relationships,o.relationships);let s=[...Object.keys(o.nodes),...Object.keys(o.relationships)].filter(e=>a.nodes[e]?.component===`page`||he(a,e)!==i.pageId);s.length>0&&L(s);for(let e of n)r.add(e);if(t.op!==`remove`)continue;let c=v({...e,nodeIds:[t.nodeId]},a);if(c.ok)for(let e of c.nodeIds)r.delete(e),Reflect.deleteProperty(a.nodes,e),Reflect.deleteProperty(a.relationships,e)}},Fr=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]}},Ir=(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]:Fr(e),Lr=(e,t)=>{let n=new Set(e.edits.flatMap(e=>Fr(e)));for(let e of n)P(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)c(r,t,Ir(n,t))},Rr=e=>({execute:async t=>{let n=await j({remote:e},t.canvasId,t.baseVersion);Lr(t,n);let i=Dr(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Pr({canvasId:t.canvasId,nodeIds:t.nodeIds??[],...t.pageId!==void 0&&{pageId:t.pageId}},n,i.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=le.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:8,baseVersion:t.baseVersion,operations:i.operations});if(!a.success)throw new r(`BAD_REQUEST`,`The edit contains an invalid canvas operation.`,a.error.issues[0]?.message??`Check the edit’s node references and values.`);let o=g.parse(await A(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.`],...i.duplicatedNodes.length>0&&{duplicatedNodes:i.duplicatedNodes},...i.moves.length>0&&{moves:i.moves,affectedParents:i.affectedParents}}}}),zr=(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},R=(e,t,n,i=48e3)=>{if(t>e.length)throw new r(`BAD_REQUEST`,`The result page offset is out of range.`,`Restart pagination at offset 0.`);let a=[],o=2,s=e.slice(t,t+n);for(let e of s){let t=Buffer.byteLength(JSON.stringify(e))+1;if(a.length>0&&o+t>i)break;a.push(e),o+=t}let c=t+a.length;return{entries:a,total:e.length,offset:t,nextOffset:c<e.length?c:null,complete:c===e.length}},Br=e=>e.state===`succeeded`?[...e.result.insertedNodeIds.map(e=>({kind:`inserted`,nodeId:e})),...e.result.removedNodeIds.map(e=>({kind:`removed`,nodeId:e})),...Object.entries(e.result.idMap).map(([e,t])=>({kind:`identity`,temporaryId:e,nodeId:t})),...e.result.report.issues.map(e=>({kind:`issue`,issue:e}))]:[],Vr=e=>e.state===`succeeded`?{mutationId:e.result.mutationId,previousVersion:e.result.previousVersion,version:e.result.version,rootNodeId:e.result.rootNodeId,affectedBounds:e.result.affectedBounds,insertedCount:e.result.insertedNodeIds.length,removedCount:e.result.removedNodeIds.length,identityCount:Object.keys(e.result.idMap).length,issueCount:e.result.report.issues.length}:null,Hr=(e,t)=>({kind:`canvas-conversion`,operation:{kind:`canvas-conversion`,canvasId:e.canvasId,jobId:e.id},state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,destination:e.destination,result:Vr(e),failure:e.failure,details:R(Br(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),z=e=>new r(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Ur=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Wr=e=>{let t=e.failure;return new r(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 and correct the conversion source or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},Gr=async(e,t)=>{let n=ie.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw z(`conversion status`);if(n.data.job.id!==t)throw z(`conversion identity`);return n.data.job},Kr=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 Ur(250),i=await Gr(e,i.id)}if(i.state!==`succeeded`)throw Wr(i);return i},qr=(e,t)=>{let n=e.destination,r=t.request.destination;return n.kind===r.kind?n.kind===`adjacent`||r.kind===`adjacent`||n.targetNodeId===r.targetNodeId&&(n.kind!==`insert-children`||r.kind!==`insert-children`||n.pageId===r.pageId):!1},Jr=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!qr(e,t))throw z(`conversion destination or revision`);let r=e.source;if(r.kind!==n.source.kind||r.kind===`screen`&&n.source.kind===`screen`&&r.nodeId!==n.source.nodeId||r.kind===`html`&&n.source.kind===`html`&&r.label!==n.source.label)throw z(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw z(`conversion commitment`)},Yr=async(e,t)=>{let n=tt.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw z(`conversion creation`);Jr(n.data.job,t);let r=await Kr(e,n.data.job,t.waitMs);return Jr(r,t),r},Xr=async(e,t)=>{let n=vt.parse(t),r=h(n.canvasRef);return Hr(await Yr(e,{request:{canvasId:r.canvasId,expectedVersion:n.baseVersion,revisionPolicy:`strict`,scope:{pageId:r.pageId,nodeIds:[...r.nodeIds]},source:{kind:`screen`,nodeId:n.sourceNodeId},destination:n.placement},waitMs:n.waitMs}),{offset:0,limit:40})},Zr=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof r?{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.`]}),Qr=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 Zr(e,t,n.result.version)}},$r=async(e,t)=>{let n=await j({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??``}})},ei=(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}),ti=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:`canvas.render.getImport`,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),ni=e=>({waitMs:e.renderTimeoutMs,request:{canvasId:e.canvasId,expectedVersion:e.baseVersion,...e.revisionPolicy!==void 0&&{revisionPolicy:e.revisionPolicy},...(e.pageId!==void 0||(e.selectionNodeIds?.length??0)>0)&&{scope:{pageId:e.pageId,nodeIds:[...e.selectionNodeIds??[]]}},source:{kind:`html`,html:e.html,label:`Agent-authored HTML`,...e.idPrefix!==void 0&&{idPrefix:e.idPrefix}},destination:{kind:e.mode,targetNodeId:e.targetNodeId,...e.mode===`insert-children`&&e.pageId!==void 0&&{pageId:e.pageId}}}}),ri=(e,t)=>({execute:async n=>{let r=await Vn(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Yr(e,ni(n));if(n.responseMode===`bounded`)return Hr(i,{offset:0,limit:40});if(i.state!==`succeeded`)return ti(i);if(n.review===`none`)return ei(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await Qr(t,n,i),o=[];try{o=await $r(e,i)}catch{o=[]}return{...ei(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),ii=async(e,t)=>{let n=h(t.canvas),i=_.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=b.parse(i.document);l(n)&&x(n,a),t.nodeId!==void 0&&c(n,a,[t.nodeId]);let o=v(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new r(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link. Do not broaden the request.`);let s=Object.groupBy(Object.entries(a.relationships),([,e])=>e.parentId),u=Object.values(a.nodes).filter(e=>o.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:(s[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:i.version,pageId:o.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:o.rootNodeIds,nodeCount:u.length,nodes:u,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},ai=(e,t,n)=>{try{jt(e,t,{flag:n?`w`:`wx`,mode:384}),Et(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new r(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.`)}},oi=e=>({write:t=>{if(t.outputPath!==null){let e=T.resolve(t.outputPath);return ai(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=T.join(e,`sensitive`);At(n,{recursive:!0,mode:448}),Et(n,448);let r=T.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return ai(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),si=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],ci=(e,t)=>new r(e instanceof r?e.code:`INTERNAL`,e instanceof r?e.message:`The asset import did not return a confirmed result.`,e instanceof r?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof r&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),li=(e,t)=>{if(e.canvasId!==t.canvasId||e.clientToken!==t.clientToken||e.kind!==t.kind||e.contentType!==t.contentType||e.bytes!==t.bytes||e.sha256!==t.sha256)throw new r(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},ui=(e,t)=>({execute:async n=>{let i=h(n.canvasRef);if(l(i)){let t=_.parse(await e.query(si[2],{canvasId:i.canvasId}));x(i,b.parse(t.document))}let{body:a,...o}=await t.read(),s=Be.parse({...o,canvasId:i.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:i.canvasId,clientToken:n.clientToken};try{let t=$e.parse(await e.mutate(si[0],s));li(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let o=Le.parse(await e.mutate(si[1],{canvasId:i.canvasId,clientToken:n.clientToken}));if(li(o,s),o.assetId!==t.assetId||o.path!==t.path)throw new r(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return de.parse({operation:c,resource:o,placement:`not_requested`})}catch(e){throw ci(e,c)}}}),di=15e3,fi=async e=>new Promise(t=>setTimeout(t,e)),pi=new Set([`ready`,`failed`,`abandoned`]),B=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],V=e=>new r(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),mi=async(e,t,n,r)=>{let i=Te.safeParse(await e.mutate(B[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,...t.targetMode!==void 0&&{targetMode:t.targetMode},...t.canvasPageId!==void 0&&{canvasPageId:t.canvasPageId},title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw V(`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`){let n=nt.safeParse(await e.mutate(B[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw V(`artifact submission`)}return i.data},hi=async(e,t,n,r)=>{let i=Ce.safeParse(await e.query(B[0],{}));if(!i.success)throw V(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await mi(e,n,a,r)}finally{await a.dispose()}},gi=async(e,t,n)=>{let i=new AbortController,a=Promise.withResolvers(),o=setTimeout(()=>{i.abort(),a.reject(new r(`INTERNAL`,`The prototype status request timed out.`,`Check this deployment again; keep its existing client token.`,{reason:`STATUS_TIMEOUT`,deploymentId:t.deploymentId}))},n);try{let n=await Promise.race([e.query(B[3],t,{signal:i.signal}),a.promise]),r=De.safeParse(n);if(!r.success||r.data.deploymentId!==t.deploymentId)throw V(`status`);return r.data}finally{clearTimeout(o)}},_i=async(e,t,n)=>{let i=performance.now()+n,a=50,o=await gi(e,t,n>0?Math.min(di,n):di);for(;!pi.has(o.state);){let n=i-performance.now();if(n<=0)return o;await fi(Math.min(a,n)),a=Math.min(a*2,1e3);let s=i-performance.now();if(s<=0)return o;try{o=await gi(e,t,Math.min(di,s))}catch(e){if(e instanceof r&&e.fields?.reason===`STATUS_TIMEOUT`)return o;throw e}}return o},vi=[`BAD_ARTIFACT`,`ARTIFACT_INTEGRITY`,`FILE_INTEGRITY`,`FILE_TOO_LARGE`,`FILE_COUNT_`,`MANIFEST_`,`PATH_`,`ENTRY_`,`EXPANDED_`,`ZIP_INVALID`,`ZIP_ENCRYPTED`,`ZIP_PATH_ENCODING`,`ZIP_COMPRESSION`,`ZIP_ENTRY_TYPE`],yi=e=>{let t=e.failure,n=vi.some(e=>t.code.startsWith(e));return{isBuildFailure:n,nextAction:n?`fix_build`:`retry_new_publication`,failure:{code:t.code,message:t.message,remediation:n?`Correct the named build problem and publish a new artifact with a new clientToken.`:`This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure.`}}},bi=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],xi=[`prototype.getArtifactCapabilities`,`prototype.attach`],Si=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),Ci=async e=>{let t=Ce.safeParse(await e.query(xi[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new r(`BAD_REQUEST`,`This API does not advertise revision-checked prototype attachment.`,`Upgrade the API before publishing through the canvas profile. No artifact was created or attached.`)},wi=e=>e instanceof r?{code:e.code,message:e.message,remediation:e.remediation}:{code:`INTERNAL`,message:`The publication request did not return a confirmed outcome.`,remediation:`Retry the identical request with its original clientToken; do not assume the canvas is unchanged.`},Ti=async(e,t,n)=>{let r=h(t.canvasRef),i=a.safeParse(await e.mutate(xi[1],{canvasId:r.canvasId,deploymentId:n.deploymentId,baseVersion:t.baseVersion,...r.pageId!==void 0&&{canvasPageId:r.pageId},attachment:{clientToken:t.clientToken,scope:{...r.pageId!==void 0&&{pageId:r.pageId},nodeIds:r.nodeIds}}}));if(!i.success)throw Error(`Invalid prototype attachment response`);let o=i.data,s=o.attachment;if(s===void 0||o.canvasId!==r.canvasId||o.deploymentId!==n.deploymentId||o.prototypeId!==n.prototypeId||o.nodeId!==n.nodeId||o.version!==s.version||s.outcome===`committed`&&(s.mutationId!==t.clientToken||s.version!==s.previousVersion+1)||s.outcome===`no_op`&&s.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...o,attachment:s}},Ei=async(e,t,n,r)=>{try{let i=await Ti(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=wi(e),r=t.code===`CONFLICT`,i=Si.has(t.code);return{...n,attachmentStatus:r?`conflict`:i?`not_attempted`:`not_confirmed`,failure:t,nextAction:t.code===`UNAUTHORIZED`||t.code===`FORBIDDEN`?`restore_access`:r||i?`replan_attachment`:`retry_same_request`,warnings:[...n.warnings,`The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent.`]}}},Di=async(e,t,n,r)=>{let i={operation:{kind:`prototype-deployment`,canvasId:n,deploymentId:r.deploymentId},deploymentStatus:r.state,publication:r,attachmentStatus:`pending`,attachment:null,failure:null,nextAction:`check_status`,warnings:bi(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=yi(r);return{...i,attachmentStatus:`not_attempted`,nextAction:e,failure:t}}return r.state===`abandoned`?{...i,attachmentStatus:`not_attempted`,nextAction:`retry_new_publication`,failure:{code:`NOT_FOUND`,message:`The deployment was abandoned.`,remediation:`Publish the same build explicitly with a new clientToken if it is still needed.`}}:r.state===`ready`?Ei(e,t,i,r):i},Oi=(e,t)=>({execute:async n=>{let i=h(n.canvasRef);await Ci(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await hi(e,t,{...n.source,canvasId:i.canvasId,...i.pageId!==void 0&&{canvasPageId:i.pageId},clientToken:n.clientToken},e=>{a=e})).deploymentId),a===null)throw Error(`Publication has no deployment`);let r=await _i(e,{canvasId:i.canvasId,deploymentId:a},n.waitMs);return await Di(e,n,i.canvasId,r)}catch(e){if(a===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:i.canvasId,deploymentId:a},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:wi(e),nextAction:e instanceof r&&(e.code===`UNAUTHORIZED`||e.code===`FORBIDDEN`)?`restore_access`:`retry_same_request`,warnings:[`An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication.`]}}}}),ki=[`prototype.attach`],Ai=e=>new r(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),ji=e=>{if(e.state===`failed`){let t=yi(e);throw new r(t.isBuildFailure?`BAD_REQUEST`:`INTERNAL`,t.failure.message,t.failure.remediation,{reason:t.failure.code,deploymentId:e.deploymentId,nextAction:t.nextAction,...e.failure.path!==void 0&&{path:e.failure.path}})}if(e.state===`abandoned`)throw new r(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new r(`INTERNAL`,`Prototype ingestion is still processing.`,`Check this deployment status, then resume the same source and client token; do not reserve a second publication.`,{reason:`INGESTION_PENDING`,state:e.state,processedFiles:String(e.processedFiles),deploymentId:e.deploymentId})},Mi=async(e,t,n)=>{let i={deploymentId:null};try{let r=await hi(e,t,n,e=>{i.deploymentId=e}),o=await _i(e,{canvasId:n.canvasId,deploymentId:r.deploymentId},3e5);ji(o);let s=a.safeParse(await e.mutate(ki[0],{canvasId:n.canvasId,deploymentId:r.deploymentId,baseVersion:n.baseVersion}));if(!s.success)throw Ai(`attachment`);return{...s.data,fileCount:o.fileCount,totalBytes:o.totalBytes,alreadyExists:r.alreadyExists,warnings:bi(o),next:[s.data.canvasUrl??s.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${s.data.nodeId} --expected-version ${String(s.data.version)}`]}}catch(e){throw e instanceof r&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||i.deploymentId===null?e:new Ke(e instanceof r?e.message:`Prototype deployment ${i.deploymentId} has no confirmed completion.`,`${e instanceof r?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof r?e.code:`INTERNAL`,fields:{...e instanceof r&&e.fields,canvasId:n.canvasId,deploymentId:i.deploymentId,clientToken:n.clientToken}})}},Ni=(e,t)=>({execute:async n=>Mi(e,t,n)}),Pi=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new r(`NOT_FOUND`,`The preparation does not belong to this operation.`,`Use the complete operation reference returned by the original action.`);return{kind:`canvas-preparation`,operation:t,state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,failure:e.failure,outcome:`not_confirmed`,prepared:e.state===`succeeded`,warnings:[`Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit.`]}},Fi=async(e,t)=>{let{job:n}=f.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Pi(n,t)},H=(e,t)=>{let n=40,r=e=>{let t=e.slice(0,n);return n-=t.length,t},i=r(e.insertedNodeIds),a=r(e.changedNodeIds),o=r(e.removedNodeIds),s=e.insertedNodeIds.length+e.changedNodeIds.length+e.removedNodeIds.length;return{outcome:`committed`,canvasId:e.canvasId,mutationId:e.mutationId,previousVersion:e.previousVersion,version:e.version,operation:{kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.mutationId,fingerprint:t},affected:{insertedNodeIds:i,changedNodeIds:a,removedNodeIds:o,complete:s<=40,total:s},...e.copiedNodeIds!==void 0&&{identities:{entries:Object.entries(e.copiedNodeIds).toSorted(([e],[t])=>e.localeCompare(t,`en`)).slice(0,40).map(([e,t])=>({sourceNodeId:e,nodeId:t})),complete:Object.keys(e.copiedNodeIds).length<=40,total:Object.keys(e.copiedNodeIds).length}},verification:{rendered:!1},warnings:[]}},Ii=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=y.parse(await e.query(`canvas.render.get`,{jobId:n.operation.jobId}));return r.id!==n.operation.jobId||r.canvasId!==n.operation.canvasId||r.state!==`succeeded`?{...n,warnings:[`The stored result is unavailable for image delivery. Read this operation again.`]}:{status:n,localImage:await kn(e,t,r,{at:new Date,outputPath:null,overwrite:!1})}}catch{return{...n,warnings:[`The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference.`]}}},U=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],Li=(e,t)=>{if(e!==t)throw new r(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},Ri=e=>[...e.insertedNodeIds.map(e=>({nodeId:e,change:`inserted`})),...e.changedNodeIds.map(e=>({nodeId:e,change:`changed`})),...e.removedNodeIds.map(e=>({nodeId:e,change:`removed`})),...Object.entries(e.copiedNodeIds??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>({nodeId:t,sourceNodeId:e,change:`copied`}))],zi=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=bt.parse(await e.query(U[0],{canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}));return a.state===`not-found`?{kind:`canvas-mutation`,state:`not_found`,operation:n,outcome:`unknown`,warnings:[`No durable receipt was found. The original request may still be running.`]}:{kind:`canvas-mutation`,state:`committed`,receipt:H(a.result,n.fingerprint),affected:R(Ri(a.result),r,i)}},Bi=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=y.parse(await e.query(U[1],{jobId:n.jobId}));Li(a.canvasId,n.canvasId);let o=a.result===null?null:Vi(a.result);return{kind:`canvas-render`,operation:n,state:a.state,phase:a.phase,requestedVersion:a.requestedVersion,attempt:a.attempt,target:a.target,sourceState:a.sourceState??null,evidence:o,details:R(Hi(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Vi=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},Hi=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Ui=async(e,t)=>{let n=Le.parse(await e.query(U[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Li(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new r(`NOT_FOUND`,`The resource does not belong to this import.`,`Use the operation reference returned by the original import.`);return{kind:`canvas-asset`,operation:t,resource:n,placement:`not_checked`}},Wi=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return R([],r,i),Ui(e,n);case`canvas-mutation`:return zi(e,{...t,operation:n});case`canvas-preparation`:{let r=await zi(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:Fi(e,n)}case`canvas-render`:return Bi(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=ie.parse(await e.query(U[2],{jobId:n.jobId}));return Li(t.canvasId,n.canvasId),Hr(t,{offset:r,limit:i})}case`prototype-deployment`:return R([],r,i),{kind:`prototype-deployment`,operation:n,publication:De.parse(await e.query(U[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},Gi=(e,t)=>({execute:async n=>{let r=await Wi(e,n);return t!==void 0&&n.includeImage?Ii(e,t,r):r}}),Ki=[`transcript.get`],qi=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Ji=e=>({execute:async t=>{let n=Ge.safeParse(await e.query(Ki[0],t));if(!n.success)throw new r(`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:qi(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Yi=[`canvas.render.get`,`canvas.render.snapshot`],Xi=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Zi=e=>new r(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}),Qi=async(e,t)=>{let n=y.safeParse(await e.query(Yi[0],{jobId:t}));if(!n.success)throw new r(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},$i=async(e,t,n,i)=>{let a=Date.now()+n.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let u=Date.now(),d=`${s.state}:${s.phase}`;if((d!==l||u-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:u-o,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),c=u,l=d),u>=a){if(n.bounded===!0)return s;throw new r(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase})}await Xi();let f=await Qi(e,s.id);if(f.id!==t.id)throw ea();ta(f,n),s=f}return s},ea=()=>new r(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),ta=(e,t)=>{if(e.canvasId!==t.canvasId||e.purpose!==`snapshot`||e.sourceState?.recordingId!==t.recordingId||e.sourceState.atMs!==t.atMs||t.context!==void 0&&e.requestedVersion!==t.context.expectedVersion)throw ea();if(e.state!==`succeeded`)return;let n=e.result.snapshot,r=e.result.sourceState;if(e.result.canvasId!==t.canvasId||e.result.loadedVersion!==e.requestedVersion||e.result.requestedVersion!==e.requestedVersion||r?.recordingId!==t.recordingId||r.requestedAtMs!==t.atMs||r.settledAtMs!==t.atMs||n?.recordingId!==t.recordingId||n.atMs!==t.atMs||n.screenId!==e.id||n.screenNodeId!==`scr_${t.recordingId}_${String(t.atMs)}`||t.context!==void 0&&n.version!==t.context.expectedVersion+1)throw ea()},na=(e,t)=>({operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},state:e.state,requestedVersion:e.requestedVersion,source:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},attachment:e.state===`succeeded`?`committed`:e.state===`queued`||e.state===`running`?`pending`:`not_confirmed`,result:e.result?.snapshot??null,failure:e.failure,warningCount:e.result?.warnings.length??0,warnings:[e.state===`succeeded`?`The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings.`:`Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created.`]}),ra=async(e,t,n)=>{let r=yt.parse(t),i=h(r.canvasRef);return aa(e,()=>null).execute({canvasId:i.canvasId,recordingId:r.source.recordingId,atMs:r.source.atMs,retryClientToken:n,timeoutMs:r.waitMs,bounded:!0,context:{expectedVersion:r.baseVersion,request:{previewJobId:r.previewJobId,scope:{pageId:i.pageId,nodeIds:[...i.nodeIds]},placement:r.placement}}})},ia=async(e,t,n)=>{let i=ze.safeParse(await e.mutate(Yi[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");ta(i.data.job,n);let a=await $i(e,i.data.job,n,t);if(n.bounded===!0)return na(a,n);if(a.state!==`succeeded`||a.result.snapshot===void 0)throw Zi(a);let o={...a,result:{...a.result,snapshot:a.result.snapshot}},s=o.result.snapshot;return{jobId:o.id,canvasId:o.canvasId,...s,warnings:o.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${o.canvasId} --node-id ${s.screenNodeId}`,`enhance canvas render --canvas ${o.canvasId} --node-id ${s.screenNodeId} --expected-version ${String(s.version)}`]}},aa=(e,t)=>({execute:async n=>ia(e,t,n)}),oa={".avif":`image/avif`,".gif":`image/gif`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`,".ttf":`font/ttf`,".otf":`font/otf`,".woff":`font/woff`,".woff2":`font/woff2`},sa=()=>new r(`BAD_REQUEST`,`Choose one supported regular image or font file.`,`Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.`),ca=async e=>{let t=oa[T.extname(e).toLowerCase()];if(t===void 0)throw sa();let n=await zt(e,Dt.O_RDONLY|Dt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw sa();let i=Buffer.alloc(e.size+1),a=0;for(;a<i.byteLength;){let e=await n.read(i,a,i.byteLength-a,a);if(e.bytesRead===0)break;a+=e.bytesRead}if(a!==e.size)throw new r(`CONFLICT`,`The selected asset changed while it was being read.`,`Finish writing the file, then retry the unchanged import intent.`);let o=i.subarray(0,a);return{body:o,kind:t.startsWith(`image/`)?`image`:`font`,contentType:t,bytes:a,sha256:E(`sha256`).update(o).digest(`hex`)}}finally{await n.close()}},la=e=>({read:async()=>{try{return await ca(e)}catch(e){throw e instanceof r?e:new r(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),ua=[`canvas.list`,`organisation.list`],da=async(e,t)=>{let[n,r]=await Promise.all([e.query(ua[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(ua[1],{}):{items:[],truncated:!1}]),i=_t.parse(n),a=ve.parse(r),o=i.items.map(e=>({kind:`canvas`,canvasRef:e.id,title:e.title,organisationId:e.organisationId,accessState:e.accessState,viewerCan:e.viewerCan,openPath:`/c/${e.id}`}));return t.includeDestinations&&o.push({kind:`destination`,destination:{kind:`personal`},name:`Personal`},...a.items.filter(e=>t.collection===`everything`||t.collection===e.id).map(e=>({kind:`destination`,destination:{kind:`team`,organisationId:e.id},name:e.name}))),{items:o,sourceTruncated:{canvases:i.truncated,destinations:a.truncated}}},fa=e=>{let t=[],n=2;for(let r of e){let e=Buffer.byteLength(JSON.stringify(r))+1;if(n+e>48e3)break;t.push(r),n+=e}return t},pa=e=>({execute:async t=>{let{items:n,sourceTruncated:i}=await da(e,t),{cursor:a,...s}=t,c=S(s),l=S({items:n,sourceTruncated:i}),u=a===void 0?null:o(a,Ye);if(u!==null&&u.queryDigest!==c)throw new r(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(u!==null&&u.snapshotDigest!==l)throw new r(`CONFLICT`,`The accessible canvases or destinations changed between pages.`,`Restart discovery so results are not silently skipped or combined across permissions.`);let d=u?.offset??0;if(d>n.length)throw new r(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let f=fa(n.slice(d,d+t.limit)),p=d+f.length,m=p<n.length,ee=i.canvases||i.destinations;return{items:f,returnedCount:f.length,totalAvailable:n.length,complete:!m&&!ee,sourceTruncated:i,nextCursor:m?ft({protocol:`enhance-canvas-find/1`,queryDigest:c,snapshotDigest:l,offset:p}):null,warnings:ee?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),ma=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof r&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},ha=async(e,t,n)=>{let i=Date.now()+n,a=t;for(;a.state===`queued`||a.state===`running`;){let n=i-Date.now();if(n<=0)break;await Pt(Math.min(250,n));let o=await ma(e,t.id);if(o===null)return a;if(a=f.parse(o.value).job,a.id!==t.id)throw new r(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return a},ga=async(e,t,n)=>{let i=ge.parse(await e.mutate(`canvas.render.preparation.create`,t)),a=await ha(e,i.job,n);if(a.canvasId!==t.canvasId||a.requestedVersion!==t.expectedVersion||!qt(a.scope,t.scope)||!qt(a.request,t.request))throw new r(`CONFLICT`,`The native preparation does not match this request.`,`Read the canvas and prepare a new intent; do not apply this plan.`);if(a.state===`succeeded`&&a.result.loadedVersion!==t.expectedVersion)throw new r(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return a},_a=async(e,t)=>{try{return g.parse(await A(e).execute(t))}catch(e){throw new r(e instanceof r?e.code:`INTERNAL`,e instanceof r?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof r&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},va=async(e,t,n,i)=>{if(n.result.loadedVersion!==t.baseVersion)throw new r(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(n.result.operations.length===0)return{outcome:`no_op`,canvasId:n.canvasId,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let a=le.parse({canvasId:n.canvasId,mutationId:t.clientToken,documentFormatVersion:8,baseVersion:t.baseVersion,operations:n.result.operations,requestContext:{fingerprint:i,revisionPolicy:`strict`,...t.request.kind===`duplicate`&&{copiedNodeIds:n.result.idMap}}}),o=await _a(e,a);if(o.canvasId!==n.canvasId||o.mutationId!==t.clientToken||o.previousVersion!==t.baseVersion||o.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!qt(o.copiedNodeIds,n.result.idMap))throw new r(`INTERNAL`,`The canvas commit receipt could not be verified.`,`Check operation_status using the original mutation reference before retrying.`,{outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i})});return H(o,i)},ya=e=>({execute:async t=>{let n=h(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},i=S({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),a=bt.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i}));if(a.state===`committed`)return H(a.result,i);let o=await ga(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),s={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:o.id,mutationId:t.clientToken,fingerprint:i};return o.state===`succeeded`?va(e,t,o,i):Pi(o,s)}}),ba=new Set([`data-enhance-id`,`data-enhance-name`,`data-enhance-opaque`,`style`]),W=e=>{throw new r(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},G=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`),xa=e=>{let t=Yt(e,{context:`declarationList`,onParseError:e=>W(e.message)});if(t.type!==`DeclarationList`)return W(`Expected an inline CSS declaration list.`);let n=new Map;return t.children.forEach(e=>{if(e.type!==`Declaration`||e.important!==!1)return W(`Use ordinary inline CSS properties without !important or at-rules.`);let t=e.property.startsWith(`--`)?e.property:e.property.toLowerCase();if(n.has(t))return W(`Duplicate CSS property: ${t}.`);n.set(t,Jt(e.value))}),Object.fromEntries(n)},Sa=e=>{let t=Object.entries(e.styles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`),n=`data-enhance-id="${G(e.id)}" data-enhance-name="${G(e.label)}"${e.opaque?` data-enhance-opaque="true"`:``}${t===``?``:` style="${G(t)}"`}`;return`<${e.tag} ${n}>${G(e.text)}${e.children.map(e=>Sa(e)).join(``)}</${e.tag}>`},Ca=(e,t)=>{let n=new Set,r=[],i=N(e),a=t=>{if(n.has(t))return W(`The document contains repeated node identity.`);n.add(t);let o=P(e,t),s=i.get(t)??[],c=F(e,t)||o.component===`text`&&s.length>0||![`root`,`frame`,`group`,`text`].includes(o.component);c&&r.push(o.id);let l=c?{}:xa(Object.entries(Ze(o)).map(([e,t])=>`${e}:${ct(e,t)}`).join(`;`));return{id:o.id,tag:o.component===`text`?`span`:`div`,label:o.label,opaque:c,styles:l,text:c||o.component!==`text`?``:we(o)??``,children:c?[]:s.map(e=>a(e))}},o=a(t);return{projectionVersion:1,root:o,html:Sa(o),opaqueNodeIds:r}},wa=e=>e.flatMap(e=>`tagName`in e?[e]:e.nodeName===`#text`&&`value`in e&&e.value.trim()===``?[]:W(`Container content must contain identified elements; text belongs inside its retained span.`)),Ta=e=>{let t=Xt(e,{sourceCodeLocationInfo:!0,onParseError:e=>W(`Invalid HTML at line ${String(e.startLine)}: ${e.code}.`)}),n=[t];for(;n.length>0;){let e=n.pop();if(e===void 0)break;e.childNodes=e.childNodes.filter(e=>!(`tagName`in e)||hn(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>_n(e.name,e.value)),n.push(e)}return t},Ea=e=>{let t=Ta(e),n=new Set,r=e=>{if(e.tagName!==`div`&&e.tagName!==`span`)return W(`Unsupported retained element: ${e.tagName}.`);let t=Object.fromEntries(e.attrs.map(e=>!ba.has(e.name)||e.namespace!==void 0?W(`Unsupported attribute: ${e.name}.`):[e.name,e.value])),i=t[`data-enhance-id`],a=t[`data-enhance-name`];if(i===void 0||i===``||a===void 0)return W(`Every retained element requires its identity and name.`);if(n.has(i))return W(`Duplicate node identity: ${i}.`);n.add(i);let o=t[`data-enhance-opaque`];if(o!==void 0&&o!==`true`)return W(`Invalid opaque marker on ${i}.`);let s=e.tagName===`span`?e.childNodes.map(e=>`value`in e?e.value:W(`Retained text ${i} must contain text only; its existing rich formatting is preserved by the text owner.`)).join(``):``;return{id:i,tag:e.tagName,label:a,opaque:o===`true`,text:s,styles:xa(t.style??``),children:e.tagName===`span`?[]:wa(e.childNodes).map(e=>r(e))}},i=wa(t.childNodes),a=i[0];return a===void 0||i.length!==1?W(`An editable update must contain exactly its original root.`):r(a)},Da=(e,t,n)=>{if(e.rootNodeIds!==void 0)return e.rootNodeIds;if(t.nodeIds.length>0)return t.nodeIds;if(t.pageId===void 0)return[`root`];let i=v(t,n);if(i.ok)return i.rootNodeIds;throw x(t,n),new r(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},Oa=(e,t)=>{let n=new Set(t);for(let i of t){let t=new Set,a=e.relationships[i]?.parentId;for(;a!==void 0;){if(t.has(a)||n.has(a))throw new r(`BAD_REQUEST`,`Outline roots overlap or contain a parent cycle.`,`Choose disjoint roots so each depth and coverage statement has one meaning.`);t.add(a),a=e.relationships[a]?.parentId}}if(n.size!==t.length)throw new r(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},ka=(e,t,n,r)=>{let i=[],a=new Set,o=N(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=P(e,t),u=o.get(t)??[],d=F(e,t);if(i.push({id:t,label:l.label,kind:l.component,parentId:e.relationships[t]?.parentId??null,sortKey:e.relationships[t]?.sortKey??null,depth:c,childCount:u.length,childrenOmitted:c===n&&u.length>0,locked:d,visible:l.visible!==!1,editable:r&&!d&&[`root`,`frame`,`group`,`text`].includes(l.component),bounds:l.box??null}),c<n)for(let e of u)s(e,c+1)};for(let e of t)s(e,0);return i},Aa=(e,t,n)=>{if(e===void 0)return 0;let i=o(e,Pe);if(i.canvasId!==t.reference.canvasId||i.queryDigest!==n)throw new r(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(i.version!==t.version)throw new r(`CONFLICT`,`The canvas changed between outline pages.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(t.version),outcome:`not_committed`});return i.offset},ja=(e,t)=>{let{reference:n,scene:i,version:a,isCurrent:o}=t,s=Da(e,n,i);c(n,i,s),Oa(i,s);let l=S({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),u=Aa(e.cursor,t,l),d=ka(i,s,e.depth,o);if(u>d.length)throw new r(`BAD_REQUEST`,`The outline cursor is out of range.`,`Restart the outline read.`);let f=d.slice(u,u+e.limit),p=u+f.length,m=d.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:a,scope:{rootNodeIds:[...s]},view:`outline`,complete:p===d.length&&!m,returnedCount:f.length,total:d.length,nodes:f,omittedDescendants:m,nextCursor:p<d.length?ft({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:a,queryDigest:l,offset:p}):null,warnings:o?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},Ma=e=>{let t=He(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Je(e);if(n!==null)return{storage:`canvas-font`,reference:e,ownerId:n.canvasId,assetId:n.sha256};let r=/^\/v1\/recording-assets\/([a-f0-9-]{36})\/([a-f0-9]{32,64})$/u.exec(e);return r===null?{storage:e.startsWith(`data:`)?`inline`:/^https?:\/\//u.test(e)?`external`:`opaque`,reference:null,ownerId:null,assetId:null}:{storage:`recording-asset`,reference:e,ownerId:r[1]??null,assetId:r[2]??null}},Na=(e,t)=>typeof e[t]==`string`?e[t]:null,Pa=(e,t)=>{let n=new Map,r=[...t].toSorted((e,t)=>e.localeCompare(t));for(let t of r){let r=e.scene.nodes[t];if(r===void 0)continue;let i=(e,r,i)=>{let a={nodeId:t,kind:e,sourceDigest:S(r),...Ma(r),delivery:`not_checked`,metadata:i};return n.set(S(a),a),r};bn(r,e=>i(`image`,e,null)),te(r.props,(e,t)=>i(`font`,e,{family:Na(t,`family`),style:Na(t,`style`),weight:Na(t,`weight`)}))}return Array.from(n,([,e])=>e)},Fa=(e,t,n)=>{if(e.cursor===void 0)return 0;let i=o(e.cursor,Re);if(i.canvasId!==t.reference.canvasId||i.digest!==n)throw new r(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(i.version!==t.version)throw new r(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return i.offset},Ia=(e,t)=>{let n=v(t.reference,t.scene);if(!n.ok)throw new r(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let i=S({reference:t.reference,limit:e.limit}),a=Fa(e,t,i),o=Pa(t,n.nodeIds);if(a>o.length)throw new r(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let s=e=>{let r=a+e.length;return{view:`resources`,canvasId:t.reference.canvasId,version:t.version,scope:{rootNodeIds:[...n.rootNodeIds]},coverage:`authored-resource-slots`,resources:e,total:o.length,returnedCount:e.length,complete:r===o.length,nextCursor:r===o.length?null:ft({protocol:`enhance-canvas-resources/1`,canvasId:t.reference.canvasId,version:t.version,digest:i,offset:r}),warnings:[`Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.`,`Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.`,`Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope.`]}},c=48e3-Buffer.byteLength(JSON.stringify(s([])));return s(R(o,a,e.limit,c).entries)},La=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new r(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:i,...a}=t,s=S({scope:n,range:a,transcript:e}),c=i===void 0?null:o(i,lt);if(c!==null&&c.digest!==s)throw new r(`CONFLICT`,`The transcript cursor no longer matches this source, range or revision.`,`Restart the requested range; do not combine transcript revisions.`);let l=e.cues.filter(e=>e.endMs>=t.startMs&&(t.endMs===void 0||e.startMs<t.endMs)),u=c?.offset??0;if(u>l.length)throw new r(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let d=R(l,u,t.limit).entries,f=u+d.length;return{state:`ready`,languageCode:e.languageCode,integrity:e.integrity,isRefreshing:e.isRefreshing,requestedRange:{startMs:t.startMs,endMs:t.endMs??null},cues:d,returnedCount:d.length,totalInRange:l.length,omittedOutsideRange:e.cues.length-l.length,complete:f===l.length,nextCursor:f<l.length?ft({protocol:`enhance-canvas-transcript/1`,digest:s,offset:f}):null}},Ra=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],za=e=>{let t=s.safeParse(e.node.props?.capture).data;if(t===void 0)return null;let n=e.screens.find(e=>e.screenId===t.screenId);return{kind:`screen`,screenId:t.screenId,availability:n===void 0?t.html===void 0?`unavailable`:`inline-only`:n.download===null?`pending`:`available`,sourceUrl:n?.route??null,title:n?.title??null,viewport:n?.viewport??t.viewport,atMs:n?.atMs??t.atMs,recordingId:n===void 0?t.provenance?.recordingId??null:n.sourceRecordingId,missingAssetCount:n?.assetBundle?.missingAssetCount??null}},Ba=e=>{let t=pt.safeParse(e.props?.conversion).data;if(t===void 0)return{kind:`none`};let n=new Map,r=t.report?.issues??[];for(let e of r)n.set(e.code,(n.get(e.code)??0)+1);return{kind:`conversion`,recordingId:t.provenance?.recordingId??null,nodeCount:t.report?.nodeCount??null,issueCounts:Object.fromEntries(n)}},Va=async(e,t)=>{let{node:n,canvasId:i}=t;if(n.component===`recording`){let t=u.parse(n.props),r=w.uuid().parse(t.recordingId),a=ue.parse(await e.query(Ra[0],{canvasId:i,recordingId:r}));return{kind:`recording`,recordingId:r,durationMs:a.durationMs,viewport:a.viewport,sourceUrl:a.sourceUrl,interrupted:a.interrupted,integrity:a.integrity,chunkCount:a.chunks.length,missingChunkCount:a.chunks.filter(e=>e.state===`missing`).length,hasAudio:a.audio!==null,missingAssetCount:a.missingAssetCount}}if(n.component===`prototype`){let t=xe.parse(n.props),a=De.parse(await e.query(Ra[1],{canvasId:i,deploymentId:t.deploymentId}));if(a.prototypeId!==t.prototypeId)throw new r(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:a.state,fileCount:a.fileCount}}return za(t)??Ba(n)},Ha=e=>({execute:async t=>{let n=await Va(e,t),i=t.input.transcript,a=`recordingId`in n?n.recordingId:null;if(i!==void 0&&a===null)throw new r(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let o=i===void 0?null:La(Ge.parse(await e.query(Ra[2],{canvasId:t.canvasId,recordingId:w.uuid().parse(a)})),i,{canvasRef:t.input.canvasRef,nodeId:t.node.id,version:t.version}),s=n.kind===`screen`&&[`pending`,`unavailable`].includes(n.availability);return{canvasId:t.canvasId,version:t.version,scope:{rootNodeIds:[t.node.id]},view:`source`,nodeId:t.node.id,source:n,transcript:o,complete:!s&&(o===null||o.state===`empty`||o.state===`ready`&&o.complete),pixelsInspected:!1,warnings:[...s?[`The captured source bytes are not currently available.`]:[],...o===null?[]:[`Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments.`]]}}}),Ua=[`canvas.document.get`],Wa=e=>{throw new r(`CONFLICT`,`Canvas version ${String(e)} no longer matches this read.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(e),outcome:`not_committed`})},Ga=(e,t)=>{let{reference:n,scene:i,version:a}=t;if(!t.isCurrent)throw new r(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);c(n,i,[e.rootNodeId]);let o=Ca(i,e.rootNodeId);return{canvasId:n.canvasId,version:a,scope:{rootNodeIds:[e.rootNodeId]},view:`editable`,complete:!0,projectionVersion:o.projectionVersion,rootNodeId:e.rootNodeId,html:o.html,opaqueNodeIds:[...o.opaqueNodeIds],snapshotToken:ye({reference:n,version:a,rootNodeId:e.rootNodeId,html:o.html}),warnings:o.opaqueNodeIds.length>0?[`Preserve opaque placeholders unchanged; their authored content remains in the canvas.`]:[]}},Ka=e=>({execute:async t=>{let n=h(t.canvasRef),r=_.parse(await e.query(Ua[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return Wa(r.version);let i=We.safeParse(r.document),a=i.success?i.data:b.parse(r.document);return t.view===`resources`?Ia(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`outline`?ja(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`source`?(c(n,a,[t.nodeId]),Ha(e).execute({canvasId:n.canvasId,version:r.version,node:P(a,t.nodeId),screens:r.screens,input:t})):Ga(t,{reference:n,scene:a,version:r.version,isCurrent:i.success})}}),qa=[`canvas.mutation.get`],Ja=e=>({execute:async t=>{let n=t.reference.canvasId,i=bt.parse(await e.query(qa[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(i.state===`committed`)return H(i.result,t.fingerprint);let a=await j({remote:e},n,t.baseVersion),o=await t.plan(a);if(`outcome`in o)return o;if(Pr(t.reference,a,o),o.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let s=le.safeParse({canvasId:n,documentFormatVersion:8,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:o,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!s.success)throw new r(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,s.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return H(g.parse(await A(e).execute(s.data)),t.fingerprint)}}),Ya=(e,t)=>{let n=N(e),i=new Set(t),a=new Set,o=t=>{if(a.has(t))return;if(a.add(t),P(e,t),F(e,t))throw new r(`BAD_REQUEST`,`Removing this subtree would remove locked content: ${t}.`,`Keep the locked subtree, or explicitly unlock it before requesting removal.`);let i=n.get(t)??[];for(let e of i)o(e)};for(let e of i){if(e===`root`)throw new r(`BAD_REQUEST`,`The canvas root cannot be removed.`,`Name its children.`);o(e)}return[...i].filter(t=>{let n=e.relationships[t]?.parentId;for(;n!==void 0;){if(i.has(n))return!1;n=e.relationships[n]?.parentId}return!0}).map(e=>({op:`remove`,nodeId:e}))},Xa=e=>({execute:async({clientToken:t,...n})=>{let r=h(n.canvasRef);return Ja(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:S({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>Ya(e,n.rootNodeIds)})}}),Za=(e,t,n,i)=>{let a=e.parents.get(t),o=e.children.get(n)??[];if(a===n&&o.indexOf(t)===i)return;if(F(e.document,t)||F(e.document,n))throw new r(`BAD_REQUEST`,`Locked node ${t} cannot be rearranged through HTML.`,`Keep locked placeholders in place or unlock them in the editor before editing.`);a!==void 0&&e.children.set(a,(e.children.get(a)??[]).filter(e=>e!==t));let s=e.children.get(n)??[];s.splice(i,0,t),e.children.set(n,s),e.parents.set(t,n),e.moves.push({nodeId:t,parentId:n,index:i})},Qa=(e,t,n)=>{let r={...e,nodes:Object.fromEntries(Object.entries(e.nodes).filter(([e])=>!n.has(e))),relationships:Object.fromEntries(Object.entries(e.relationships).filter(([e])=>!n.has(e)))},i={document:r,parents:new Map(Object.entries(r.relationships).map(([e,t])=>[e,t.parentId])),children:new Map([...N(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())Za(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:dr(r,i.moves).operations},K=e=>{throw new r(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},$a=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return K(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return K(`Native compilation returned an incomplete insertion plan.`);let r={...e,nodes:{...e.nodes},relationships:{...e.relationships}};for(let[e,i]of n.fragments.entries()){let n=t.operations[e];if(n?.op!==`insertConvertedSubtree`||n.destination.kind!==`insert-children`||n.destination.targetNodeId!==i.parentNodeId||n.rootNodeId!==t.idMap[i.id])return K(`Native compilation returned a mismatched insertion plan.`);for(let e of Object.keys(n.nodes))if(r.nodes[e]!==void 0||Object.hasOwn(r.tombstones,e))return K(`New HTML identity ${e} already exists.`);let a=M(r,i.parentNodeId).at(-1),o=a===void 0?null:r.relationships[a]?.sortKey??null;Object.assign(r.nodes,n.nodes),Object.assign(r.relationships,n.relationships,{[n.rootNodeId]:{parentId:i.parentNodeId,sortKey:wt(o,null)}})}return r},eo=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>eo(e,t))}),to={operations:[],idMap:{},rootNodeIds:[]},no=(e,t,n=to)=>{let r=$a(e,n,t),i=eo(t.root,n.idMap);return[...t.operations,...n.operations,...Qa(r,i,t.removed)]},ro=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,io=e=>{throw new r(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},ao=e=>e.flatMap(e=>`tagName`in e?[e,...ao(e.childNodes)]:[]),oo=e=>{let t=Ta(e),n=ao(t.childNodes),r=new Set(n.map(e=>ro(e))),i=[],a=(e,t)=>{let n=ro(e);if(n!==void 0)return{...e,childNodes:e.childNodes.map(e=>`tagName`in e?a(e,n):e)};if(t===void 0)return io(`The submitted HTML must retain its original root identity.`);if([e,...ao(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return io(`A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.`);let o=`new_${String(i.length)}`;for(;r.has(o);)o=`_${o}`;return r.add(o),i.push({id:o,parentNodeId:t,html:Qt(e)}),{...e,tagName:`div`,nodeName:`div`,childNodes:[],attrs:[{name:`data-enhance-id`,value:o},{name:`data-enhance-name`,value:`New content`},{name:`data-enhance-opaque`,value:`true`}]}};return t.childNodes=t.childNodes.map(e=>`tagName`in e?a(e):e),{root:Ea(Zt(t)),fragments:i}},q=e=>{throw new r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},so=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},co=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),lo=(e,t,n,r)=>{let i=new Set,a=e=>{if(i.has(e.id))return q(`Overlapping removal roots include ${e.id}.`);if(t.has(e.id))return q(`Removed node ${e.id} is still present in the HTML.`);i.add(e.id);for(let t of e.children)a(t)};for(let t of n){let n=e.get(t);if(n===void 0||t===r)return q(`Invalid removal root: ${t}.`);a(n)}for(let n of e.keys())if(!t.has(n)&&!i.has(n))return q(`Missing retained node ${n}; declare intentional deletion in removeNodeIds.`);return i},uo=(e,t,n)=>{if(t.tag!==n.tag||t.opaque!==n.opaque)return q(`The kind or opaque marker of ${t.id} changed.`);let r=!co(t.styles,n.styles);if(t.opaque&&(r||t.label!==n.label||t.text!==n.text||n.children.length>0))return q(`Opaque node ${t.id} cannot be changed through HTML.`);let i=e.nodes[t.id];if(i===void 0)return q(`Node ${t.id} no longer exists.`);let a=[];if(t.label!==n.label&&a.push({op:`setLabel`,nodeId:t.id,label:n.label,labelOrigin:`user`}),t.text!==n.text&&a.push({op:`editText`,nodeId:t.id,change:Fe(i,{...i,props:mt(i,n.text)})}),r){let r=new Set([...Object.keys(t.styles),...Object.keys(n.styles)]),i=Object.fromEntries([...r].filter(e=>t.styles[e]!==n.styles[e]).map(e=>[e,n.styles[e]??null]));a.push(...yr(e,[{nodeIds:[t.id],styles:i}]))}return a},fo=(e,t,n,r)=>{let i=Ca(e,t).root,a=oo(n),o=a.root;if(o.id!==t)return q(`The submitted HTML must retain its original root identity.`);let s=new Set(a.fragments.map(e=>e.id)),c=so(i),l=so(o),u=lo(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Zn(e,t)])]);for(let t of d)if(F(e,t))return q(`Locked node ${t} cannot be removed through HTML.`);let f=r.map(e=>c.get(e)?.opaque===!0?q(`Use explicit canvas removal for opaque node ${e}.`):{op:`remove`,nodeId:e});for(let[t,n]of l){if(s.has(t))continue;let r=c.get(t);if(r===void 0)return q(`Unknown or outside-scope identity: ${t}.`);f.push(...uo(e,r,n))}for(let e of a.fragments){let t=c.get(e.parentNodeId);if(t===void 0||t.opaque||t.tag!==`div`)return q(`Node ${e.parentNodeId} cannot contain new HTML.`)}return{root:o,operations:f,removed:d,fragments:a.fragments}},po=(e,t,n)=>{let i=be(e.snapshotToken,t);c(t,n,[i.rootNodeId]);let a=Ca(n,i.rootNodeId);if(ye({reference:t,version:i.version,rootNodeId:i.rootNodeId,html:a.html})!==e.snapshotToken)throw new r(`CONFLICT`,`The editable snapshot no longer matches the complete source.`,`Read the requested subtree again and deliberately reapply the intended change.`,{outcome:`not_committed`});return fo(n,i.rootNodeId,e.html,e.removeNodeIds)},mo=async(e,t,n)=>{let r=po(t,n.reference,n.scene);if(r.fragments.length===0)return no(n.scene,r);let i=await ga(e,{canvasId:n.reference.canvasId,expectedVersion:n.version,scope:{nodeIds:[...n.reference.nodeIds],...n.reference.pageId!==void 0&&{pageId:n.reference.pageId}},request:{kind:`compile-html`,fragments:[...r.fragments],contextOperations:r.operations.filter(e=>e.op!==`remove`)}},t.waitMs);return i.state===`succeeded`?no(n.scene,r,i.result):Pi(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},ho=e=>({execute:async t=>{let n=qe.parse(t),r=h(n.canvasRef),i=be(n.snapshotToken,r),a=S({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return Ja(e).execute({reference:r,baseVersion:i.version,clientToken:n.clientToken,fingerprint:a,plan:async t=>mo(e,n,{reference:r,scene:t,fingerprint:a,version:i.version})})}}),go=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=pe.parse(t);return ya(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=d.parse(t);return ya(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>pa(e).execute(Ue.parse(t)),"canvas.remove":async()=>Xa(e).execute({...rt.parse(t),clientToken:n}),"canvas.read":async()=>{let n=Se.safeParse(t);return n.success?ii(e,n.data):Ka(e).execute(Qe.parse(t))},"canvas.updateHtml":async()=>ho(e).execute({...Ie.parse(t),clientToken:n})}),_o=(e,t)=>{let n=h(e.canvasRef),i=n.nodeIds;if(e.target.kind===`content`&&i.length>1)throw new r(`BAD_REQUEST`,`Choose an explicit node within this selection.`,`Render the selected screens separately; do not broaden to the whole canvas.`);let a=e.target.kind===`content`?i[0]===void 0?n.pageId===void 0?e.target:{kind:`page`,pageId:n.pageId}:{kind:`node`,nodeId:i[0]}:e.target;return{canvasId:n.canvasId,expectedVersion:e.expectedVersion,target:a,sourceState:e.sourceState,scale:e.scale,scope:{nodeIds:i,...n.pageId!==void 0&&{pageId:n.pageId}},outputPath:null,overwrite:!1,timeoutMs:e.waitMs,timeoutOutcome:`pending`,retryClientToken:t}},vo=(e,t)=>{let n=_e.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof r?e.fields?.jobId:void 0}),i=ke.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof r?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:i.success?i.data:`not_confirmed`,error:e instanceof r?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`This render outcome could not be confirmed.`,remediation:`Retry the identical batch and clientToken to recover its native render jobs.`}}},yo=(e,t)=>e.targets.map(({id:n,maxOutputPixels:r,...i})=>{let a=t.get(n);if(a===void 0)throw TypeError(`A batch target has no native render request key.`);return{id:n,maxOutputPixels:r,input:_o({...e,...i},a)}}),bo=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),i=Xe.safeParse(n);if(!i.success)return _e.parse(n);let a=i.data.width*i.data.height;if(!Number.isSafeInteger(a)||a<=0||t.maxOutputPixels!==void 0&&a>t.maxOutputPixels)throw new r(`INTERNAL`,`The render exceeded its allocated pixel budget.`,`Update the API and renderer together, then retry.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});return i.data}catch(e){return vo(e,t)}},xo=e=>({execute:async(t,n)=>{let r=Oe.parse(t),i=yo(r,n),a=[],o=0;for(let t of i){let n=await bo(e,t);`jobId`in n&&(o+=n.width*n.height),a.push({id:t.id,target:t.input.target,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},outcome:n})}let s=i[0];if(s===void 0)throw TypeError(`A render batch requires at least one target.`);return{kind:`canvas-render-batch`,canvasId:s.input.canvasId,requestedVersion:r.expectedVersion,complete:a.every(e=>`jobId`in e.outcome),renderedPixels:o,results:a,next:[`Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken.`]}}}),J=e=>Rn(e.remote,oi(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),So=async(e,t,n)=>{let r=Oe.safeParse(t);if(r.success){e.mutationKey.select(n,!0);let t=new Map(r.data.targets.map(t=>[t.id,e.mutationKey.current(`canvas.render.create`,{batch:{canvasRef:r.data.canvasRef,expectedVersion:r.data.expectedVersion,targets:r.data.targets},targetId:t.id})])),i=J(e);return xo({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=st.safeParse(t);if(i.success)return J(e).execute(_o(i.data,n));let a=Ee.parse(t);return J(e).execute({...a,retryClientToken:n})},Co=e=>({render:J(e),execute:async(t,n)=>So(e,t,n)}),wo=new Date(`1980-01-01T00:00:00.000Z`),To=33188,Eo=(e,t)=>new r(`BAD_REQUEST`,e,t),Do=(e,t)=>{let n=E(`sha256`),r=0;return new tn({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}try{t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}catch(e){i(e instanceof Error?e:Error(`prototype manifest failed`))}}})},Oo=e=>{let t=m.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(e.limits.manifestBytes!==void 0&&n.byteLength>e.limits.manifestBytes)throw Eo(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,xt,{mtime:wo,mode:To,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},ko=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:wo,mode:To,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Ot(r.absolutePath),a=Do(r,n);i.on(`error`,e=>a.destroy(e)),a.on(`error`,t=>e.emit(`error`,t)),a.on(`close`,()=>i.destroy()),t(null,i.pipe(a))});return}if(i.byteLength!==r.bytes)throw Error(`prototype file ${r.path} changed while it was packaged`);e.addBuffer(i,r.path,a),n({path:r.path,contentType:r.contentType,bytes:i.byteLength,sha256:E(`sha256`).update(i).digest(`hex`)})},Ao=(e,t,n)=>{let r=[];for(let i of t)i!==null&&(ko(e,i,n),r.push(i.source));return r},jo=async(e,t,n)=>{let r=[];for(let i=0;i<t.files.length;i+=32){let a=await Promise.all(t.files.slice(i,i+32).map(async e=>{try{let t=e.bytes<=128?await Bt(e.absolutePath):null;if(t===null&&await Ft(e.absolutePath,Dt.R_OK),t!==null&&t.byteLength!==e.bytes)throw Error(`prototype file ${e.path} changed while it was packaged`);return{source:e,content:t}}catch(n){if(e.path===t.entryPath)throw n;return null}}));r.push(...Ao(e,a,n))}return r},Mo=async e=>{let t=new rn,n=E(`sha256`),r=new tn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=nn(t.outputStream,r,kt(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=null,c=()=>{s!==null&&a.manifest===null&&i.size===s.length&&(a.manifest=Oo({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await jo(t,e,l),c()}catch(e){r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)),await o}if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let u=await Wt(e.artifactPath);if(u.size>e.limits.artifactBytes)throw Eo(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:u.size,sha256:n.digest(`hex`),unavailableFileCount:e.files.length-i.size}},No={".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`},Po=e=>No[T.extname(e).toLowerCase()]??`application/octet-stream`,Fo=async e=>{try{return await Wt(e)}catch{return null}},Io=e=>Buffer.byteLength(e,`utf8`),Y=(e,t)=>new r(`BAD_REQUEST`,e,t),Lo=(e,t)=>{if(!ce.safeParse(e).success)throw Y(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Io(e)>t.pathBytes)throw Y(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Ro=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await Vt(t);if(n.has(o))return a(),[];let s=new Set(n).add(o),{readdir:c}=await import(`node:fs/promises`),l=await c(t,{withFileTypes:!0}),u=[],d=l.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of d){let o=T.join(t,n.name),c=await Fo(o);if(c?.isDirectory()===!0){try{u.push(...await Ro(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=T.relative(e,o).split(T.sep).join(`/`).normalize(`NFC`);Lo(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:Po(o)})}return u},zo=(e,t,n)=>{if(e.length===0)throw Y(`The prototype build is empty.`,`Build the app before publishing it.`);if(n.fileCount!==void 0&&e.length>n.fileCount)throw Y(`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=ne(t.path);if(r.has(e))throw Y(`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 Y(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,n.expandedBytes!==void 0&&i>n.expandedBytes)throw Y(`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 Y(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw Y(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Bo=(e,t)=>{try{$t.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},Vo=async e=>{let t=T.resolve(e.directory),n=await Fo(t);if(n===null)throw new r(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw Y(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let i=e.entryPath.split(T.sep).join(`/`).normalize(`NFC`);Lo(i,e.limits);let a=0,o=await Ro(t,t,new Set,{limits:e.limits,unavailable:()=>{a+=1}});zo(o,i,e.limits);let s=await Rt(T.join(Ct(),`enhance-prototype-artifact-`)),c=T.join(s,`artifact.zip`);try{let t=await Mo({artifactPath:c,files:o,entryPath:i,limits:e.limits});return a+=t.unavailableFileCount,Bo(t.manifest.files.length,a),{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:()=>Ot(c),dispose:async()=>Ut(s,{recursive:!0})}}catch(e){throw await Ut(s,{recursive:!0}),e}},Ho=e=>({package:async t=>{if(e===void 0)throw Y(`No build directory was selected.`,`Select a build before publishing.`);return Vo({...t,directory:e})}}),Uo=async(e,t)=>{let n=ee.parse(t);return A(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Wo=async(e,t)=>{let n=p.parse(t);return ri(e.remote,Co(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Go=async(e,t,n)=>{let r=Ne.parse(t),i=h(r.canvasRef);return ri(e.remote,Co(e).render).execute({canvasId:i.canvasId,pageId:i.pageId,selectionNodeIds:i.nodeIds,targetNodeId:r.destination.parentNodeId,mode:`insert-children`,html:r.html,baseVersion:r.baseVersion,revisionPolicy:`strict`,responseMode:`bounded`,review:`none`,renderClientToken:n,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:r.waitMs})},Ko=async(e,t)=>{let n=oe.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},qo=async(e,t,n)=>{let r=et.parse(t);return Ni(e.remote,Ho(r.directory)).execute({...r,clientToken:n})},Jo=async(e,t,n)=>{let r=re.parse(t);return aa(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Yo=async(e,t)=>{let n=je.parse(t);return Ji(e.remote).execute(n)},Xo=async(e,t)=>{let n=ht.parse(t),r=h(n.canvas);return Rr(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Zo=async(e,t)=>Gi(e.remote,oi(e.configDirectory)).execute(me.parse(t)),Qo=async(e,n,r,i)=>{let a={...go(e.remote,r,i),"canvas.importAsset":async()=>{let n=t.parse(r);return ui(e.remote,la(n.source.path)).execute({canvasRef:n.canvasRef,clientToken:i})},"operation.status":async()=>Zo(e,r),"canvas.edit":async()=>Xo(e,r),"canvas.apply":async()=>Uo(e,r),"canvas.render":async()=>Co(e).execute(r,i),"canvas.writeHtml":async()=>Wo(e,r),"canvas.insertHtml":async()=>Go(e,r,i),"canvas.capture":async()=>ra(e.remote,r,i),"canvas.makeEditable":async()=>Xr(e.remote,r),"comment.attention":async()=>Ko(e,r),"prototype.publishCanvas":async()=>{let t=ut.parse(r);return Oi(e.remote,Ho(t.source.kind===`directory`?t.source.directory:void 0)).execute({...t,source:t.source.kind===`directory`?{...t.source,kind:`build`}:t.source,clientToken:i})},"prototype.publish":async()=>qo(e,r,i),"recording.snapshot":async()=>Jo(e,r,i),"transcript.read":async()=>Yo(e,r)}[n];if(a===void 0)throw TypeError(`${n} has no composite execution`);return a()},$o=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Nt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Qo(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),es=`/callback`,ts=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),ns=e=>{let t=C.platform===`darwin`?{executable:`open`,arguments:[e]}:C.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=sn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},rs=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==es){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)},is=e=>{let t=ts(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},as=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=cn((n,r)=>{rs({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)}${es}`,a=is({...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&&ns(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},os=e=>({authorize:async t=>{try{let n=Mt(32).toString(`base64url`),r=E(`sha256`).update(n).digest(`base64url`),i=Mt(32).toString(`base64url`),a=await as({...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 r(`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.`)}}}),ss=e=>e===void 0||e===``?void 0:e,cs=(e,t,n)=>{let r=ss(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=ss(e.ENHANCE3_API_URL),a=T.join(t,`.config`,n.configDirectoryName),o=ss(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&&T.resolve(o)!==T.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}},ls={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},us=()=>cs(C.env,St(),ls),ds=()=>{let e=w.enum([`legacy`,`canvas`]).default(`legacy`).parse(C.env.ENHANCE_MCP_PROFILE),t=w.enum([`true`,`false`]).default(`false`).parse(C.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...us(),profile:e,isReadOnly:t,workflowsDirectory:C.env.ENHANCE_WORKFLOWS_DIR}},fs=w.object({token:w.string().startsWith(`enh_`)}),ps=e=>{let t=T.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Bt(t,`utf8`));return fs.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Lt(e,{recursive:!0,mode:448}),await It(e,448);let r=T.join(e,`credentials.${String(C.pid)}.tmp`);await Kt(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ht(r,t),await It(t,384)},remove:async()=>{try{return await Gt(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},ms={path:`direct_cli`},hs=w.object({access_token:w.string().min(1)}),gs=w.object({code:w.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),X=`Check network access and proxy settings for this API, then run enhance doctor again.`,Z=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,_s=e=>{let t=gs.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?_s(e.cause):e instanceof Error?e.name:`Network request failed`},vs=(e,t)=>new r(`INTERNAL`,`${Z(e)} answered HTTP ${String(t)}.`,X),Q=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new r(`INTERNAL`,`Could not reach ${Z(e)}: ${_s(t)}.`,X)}},ys=async(e,t)=>{let n=await Q(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw vs(e,n.status);return n},bs=(e,t,n=null,r=ms)=>an({links:[on({url:`${e}/trpc`,fetch:async(e,t)=>ys(e,{...t,signal:t?.signal??null}),headers:{[fe]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),$=async e=>{try{return await e()}catch(e){throw it(e)}},xs=async e=>{let t=await fetch(e);if(!t.ok)throw new r(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())},Ss=async e=>{let t=await Q(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new r(`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 r(`INTERNAL`,`${Z(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,X);return t.json()},Cs=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Q(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw vs(e,n.status);return n.json()},ws=async e=>{let t=await Q(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 r(`INTERNAL`,`${Z(e.issuer)} token exchange answered HTTP ${String(t.status)}`,X);return hs.parse(await t.json()).access_token},Ts=async e=>{try{let t=await Q(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:vs(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Z(e)}.`}}},Es=async e=>{let t=!(e.body instanceof Uint8Array),n=t?en.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new r(`INTERNAL`,`Signed upload answered HTTP ${String(a.status)}.`,`Retry the fixture command with the same source file.`);let o=a.headers.get(`etag`);if(o===null||o===``)throw new r(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},Ds=(e,t,n,r=ms)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>Ss(i),oauthMetadata:Cs,exchangeOauthCode:ws,query:async(e,n,a)=>$(async()=>bs(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>$(async()=>bs(i,n,null,r).query(e,t)),mutate:async(e,a)=>$(async()=>bs(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>$(async()=>bs(i,n,null,r).mutation(e,t)),download:xs,upload:Es,health:async()=>Ts(i)}},Os=e=>Array.isArray(e)?e.map(e=>Os(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Os(t)])),ks=(e,t,n)=>E(`sha256`).update(`${e}\0${t}\0${JSON.stringify(Os(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),As=()=>{let e=Nt(),t=!1;return{current:(n,r)=>t?ks(e,n,r):e,select:(n,r)=>{e=n??Nt(),t=r}}};export{Vn as _,ds as a,oi as c,R as d,zr as f,A as g,j as h,us as i,ii as l,Pr as m,Ds as n,os as o,Rr as p,ps as r,$o as s,As as t,ri as u,Rn as v,Cn as y};