@enhance-eng/enhance-dev 0.1.26-dev.sha-e25164d9c5e2 → 0.1.27-dev.sha-3dce62542ab4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli-output-identity.lib-DHYR1EKD.mjs +32 -0
- package/dist/main.mjs +13 -13
- package/dist/mcp-main.mjs +42 -1
- package/dist/mcp-server.adapter-DMQEuPGm.mjs +4 -0
- package/dist/mcp.mjs +1 -1
- package/dist/mutation-key.adapter-BN-fQG_0.mjs +2 -0
- package/package.json +1 -1
- package/dist/cli-output-identity.lib-DImbm4C3.mjs +0 -73
- package/dist/mcp-server.adapter-0sYWDrrU.mjs +0 -4
- package/dist/mutation-key.adapter-CyZogRZp.mjs +0 -2
package/dist/main.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as e
|
|
3
|
-
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=
|
|
4
|
-
`)).action(async e=>{
|
|
2
|
+
import{$ as e,$t as t,An as n,At as r,Ct as i,Dt as a,Et as o,Ft as s,Gn as c,It as l,Mt as u,Nt as d,O as ee,Ot as f,Pt as te,Qn as ne,Rt as re,Sn as ie,St as ae,Tt as oe,Un as p,Wn as se,Zt as ce,_ as le,_r as ue,a as m,ar as h,cr as de,ct as fe,d as g,en as pe,f as me,g as _,ht as he,i as ge,jn as _e,kt as v,l as ve,lr as ye,m as be,n as xe,or as y,ot as Se,p as Ce,r as we,rr as Te,rt as Ee,sr as De,t as Oe,u as ke}from"./cli-output-identity.lib-DHYR1EKD.mjs";import{_ as Ae,c as je,f as b,g as Me,h as x,i as Ne,l as Pe,m as Fe,n as Ie,o as Le,p as Re,r as ze,s as Be,t as Ve,u as He,v as Ue,y as We}from"./mutation-key.adapter-BN-fQG_0.mjs";import{t as Ge}from"./capability-inventory.mapper-B_GMS9z3.mjs";import S from"node:process";import{Command as Ke}from"commander";import{createCli as qe,parseRouter as Je}from"trpc-cli";import{z as C}from"zod";import{hostname as Ye,tmpdir as Xe}from"node:os";import{createInterface as Ze}from"node:readline";import{chmodSync as Qe,existsSync as $e,lstatSync as et,mkdirSync as tt,readFileSync as nt,readdirSync as rt,statSync as it,unlinkSync as at,writeFileSync as w}from"node:fs";import T from"node:path";import{createHash as E,randomUUID as D}from"node:crypto";import{setTimeout as ot}from"node:timers/promises";import{mkdir as st,readFile as O,rename as ct,stat as lt,writeFile as ut}from"node:fs/promises";import{channel as dt}from"node:diagnostics_channel";import{proxify as ft}from"trpc-cli/dist/proxify.js";const pt=1e6,mt=e=>Math.round(e*255*pt)/pt,ht=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(mt(e))).join(` `);return n===1?`rgb(${t})`:`rgb(${t} / ${String(n)})`}let r=`${String(e.red)} ${String(e.green)} ${String(e.blue)}`;return`color(${e.space} ${r} / ${String(n)})`},gt=e=>e===void 0?{}:{...e!==`auto`&&{direction:e},"unicode-bidi":e===`auto`?`plaintext`:`isolate`},_t=/^-?[_a-z][-\w]*$/iu,vt=/^var\(--[-\w]+\)$/iu,yt=e=>_t.test(e)||vt.test(e)?e:JSON.stringify(e),bt=e=>[...new Set([e.family,...e.family===`Inter`?[`Inter Variable`]:[],...e.family===`JetBrains Mono`?[`JetBrains Mono Variable`]:[],...e.fallbackFamilies])].map(e=>yt(e)).join(`, `),xt=e=>Object.entries({...e.variations,...e.weight!==void 0&&{wght:e.weight},...e.opticalSize?.mode===`fixed`&&{opsz:e.opticalSize.value}}).toSorted(([e],[t])=>e.localeCompare(t,`en`,{caseFirst:`upper`})).map(([e,t])=>`${JSON.stringify(e)} ${String(t)}`).join(`, `),St=e=>{let t=Object.entries(e??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>`${JSON.stringify(e)} ${String(t)}`).join(`, `);return t===``?`normal`:t},Ct=e=>e.mode===`normal`?`normal`:e.mode===`percent`?String(e.value/100):e.value;function wt(e){return{...e.lineHeight!==void 0&&{"line-height":Ct(e.lineHeight)},...e.letterSpacing!==void 0&&{"letter-spacing":typeof e.letterSpacing==`number`?e.letterSpacing:`${String(e.letterSpacing.value/100)}em`}}}const Tt=e=>e===void 0?`auto`:typeof e==`number`?e:e.mode===`font-default`?`from-font`:`${String(e.value)}%`,Et=e=>({"text-decoration-line":e.line,"text-decoration-style":e.style,"text-decoration-color":e.color===void 0?`currentColor`:ht(e.color),"text-decoration-thickness":Tt(e.thickness),"text-underline-offset":Tt(e.offset),"text-decoration-skip-ink":e.skipInk??`auto`}),Dt=e=>`${JSON.stringify(e)}\n`,Ot=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
|
|
3
|
+
`),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=Dt(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},kt=(e,t)=>{let n=Ot(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},At=[`recording.start`,`recording.appendChunk`,`recording.complete`],jt=e=>async t=>{let n=re.parse(await e.mutate(At[0],{sourceUrl:t.sourceUrl,viewport:t.viewport,pageTitle:t.pageTitle,audio:null})),r=n.upload;try{let i=kt(t.entries,8388608);for(let[t,a]of i.entries()){let i=new TextEncoder().encode(a.body),o=await e.upload({url:r.url,headers:r.headers,body:i});r=s.parse(await e.mutate(At[1],{recordingId:n.recordingId,index:t,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:i.byteLength,etag:o})).upload}let a=Math.max(0,...t.entries.map(e=>e.atMs));return l.parse(await e.mutate(At[2],{recordingId:n.recordingId,durationMs:a,viewport:t.viewport,sourceUrl:t.sourceUrl,interrupted:!1,...t.canvasId!==void 0&&{canvasId:t.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new v(`Recording ${n.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${n.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},Mt=[`screen.create`,`screen.complete`],Nt=e=>async t=>{let n=te.parse(await e.mutate(Mt[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let r=await e.upload({url:n.upload.url,headers:n.upload.headers,body:t.body}),i=d.parse(await e.mutate(Mt[1],{screenId:n.screenId,etag:r}));return{screenId:i.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:i.storedBytes}}catch{throw new v(`Screen ${n.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},k=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],Pt=(e,n)=>async r=>{let i=ce.parse(await e.mutate(k[0],{name:r.organisationName})).organisation,a=ue.parse(await e.mutate(k[1],{title:r.canvasTitle,organisationId:i.id,sourceUrl:null}));try{let o=[];for(let e of r.screens)o.push(await n(e));let s=p.parse(await e.query(k[4],{canvasId:a.id})),c=t();for(let[e,t]of o.entries())c=pe(c,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:r.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=se.parse(await e.mutate(k[5],{canvasId:a.id,baseVersion:s.version,document:c,screenIds:o.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new v(`World canvas ${a.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${a.id}' before adding the screens.`);return{organisationId:i.id,canvasId:a.id,screenIds:o.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof v?e:new v(`Organisation ${i.id} and canvas ${a.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${a.id}' before retrying any missing steps.`)}},Ft=async(e,t)=>{if(e!==void 0&&e!==``)return e.trim();if(S.stdin.isTTY)throw new r(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${t}'.`);let n=Ze({input:S.stdin,crlfDelay:1/0});for await(let e of n){n.close();let t=e.trim();if(t!==``)return t;break}throw new r(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${t}'.`)},It=async e=>{if(e!==void 0)return e.trim();if(S.stdin.isTTY)return null;let t=Ze({input:S.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},Lt=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await It(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${Ye()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},Rt=C.coerce.number().int().positive(),zt=C.coerce.number().positive(),Bt=C.uuid(),Vt=C.union([C.string(),C.number(),C.null()]),Ht=C.record(C.string(),Vt),Ut=C.array(C.object({nodeId:C.string().min(1).max(200),textContent:C.string()})).min(1),Wt=C.array(C.object({nodeId:C.string().min(1).max(200),name:C.string()})).min(1),Gt=C.array(C.object({nodeIds:C.array(C.string().min(1).max(200)).min(1),styles:Ht})).min(1),Kt=C.array(C.object({id:C.string().min(1).max(200),parentId:C.string().min(1).max(200).optional()})).min(1),qt=C.array(C.union([C.object({nodeId:C.string().min(1).max(200),before:C.string().min(1).max(200)}),C.object({nodeId:C.string().min(1).max(200),after:C.string().min(1).max(200)}),C.object({nodeId:C.string().min(1).max(200),parentId:C.string().min(1).max(200),index:C.number().int().nonnegative().optional()})])).min(1),Jt=C.array(C.string().min(1).max(200)).min(1),Yt=C.coerce.number().int().min(0),Xt=C.uuid().nullable(),A=(e,t,n)=>{let i=e.safeParse(t);if(i.success)return i.data;throw new r(`BAD_REQUEST`,`${n} is invalid.`,`Run the command with --help.`)},j=e=>A(Rt,e,`--base-version`),M=(e,t,n)=>{let i=Xt.safeParse(t??null);if(!i.success)throw new r(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(i.data,n)},Zt=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),Qt=async(e,t,n,r)=>{M(e,t.clientToken,!1);let i=f(t.canvas),o=j(t.baseVersion);return a(i)&&Fe(i,await x(e,i.canvasId,o),r),Me(e.remote).execute({canvasId:i.canvasId,mutationId:Zt(e,n),baseVersion:o,operations:[...r]})},N=async(e,t,n,r)=>{M(e,t.clientToken,!1);let i=f(t.canvas);return Re(e.remote).execute({...i,baseVersion:j(t.baseVersion),mutationId:Zt(e,`canvas.edit`),edits:n,...r!==void 0&&{idPrefix:r}})},P=(e,t)=>{if(!e.startsWith(`@`))return e;let n=e.slice(1);if(n===``)throw new r(`BAD_REQUEST`,`${t} @ must name a file.`,`Pass ${t} @/absolute/path/to/file or an inline value.`);let i=T.resolve(n);try{if(!it(i).isFile())throw Error(`not a regular file`);return nt(i,`utf8`)}catch{throw new r(`BAD_REQUEST`,`Could not read the file at ${i}.`,`Use a readable regular UTF-8 file.`)}},$t=C.array(c).min(1),en=e=>{try{return JSON.parse(P(e,`--operations`))}catch(e){throw e instanceof r?e:new r(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},tn=e=>{let t=en(e),n=$t.safeParse(t);if(!n.success){let e=n.error.issues[0];throw new r(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return n.data},nn=C.coerce.number().int().positive(),rn=e=>{let t=nn.safeParse(e);if(t.success)return t.data;throw new r(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},an=(e,t)=>{let n=C.uuid().nullable().safeParse(t??null);if(!n.success)throw new r(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},on=(e,t)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).summary(`Apply edits and return affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, editText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.`,`Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
|
|
4
|
+
`)).action(async e=>{an(t,e.clientToken);let n=f(e.canvas),r=rn(e.baseVersion),i=tn(e.operations);a(n)&&Fe(n,await x(t,n.canvasId,r),i);let o=await t.invocation.invoke({capability:b(t.catalog(),`canvas.apply`),arguments:{canvasId:n.canvasId,baseVersion:r,operations:[...i]},clientToken:e.clientToken??null});t.output.result(o)})},sn=e=>{try{return JSON.parse(e)}catch{return}},cn=e=>{if(e===void 0)return null;let t=ne.safeParse(sn(e));if(t.success)return t.data;throw new r(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},ln=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),un=(e,t)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let i=_e.safeParse(e.phase);if(!i.success)throw new r(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let a=o(e.canvas),s=n.parse(await t.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:a,phase:i.data,nodeIds:ln(e.nodeIds),bounds:cn(e.bounds)}));t.output.result({...s,next:[`enhance canvas work update --canvas ${a} --activity-id ${s.activityId} --phase ${i.data}`,`enhance canvas finish-working-on-nodes --canvas ${a} --activity-id ${s.activityId}`]})})},dn=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(n.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:o(e.canvas),activityId:Bt.parse(e.activityId),phase:_e.parse(e.phase),nodeIds:ln(e.nodeIds),bounds:cn(e.bounds)})))})},fn=(e,t)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await Ae(t.remote).finish(o(e.canvas),Bt.parse(e.activityId)))throw new r(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);t.output.result({ended:!0,activityId:e.activityId})})},pn=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);un(n,t),dn(n,t),fn(e,t)},F=(e,t,n)=>{let i=(()=>{try{return JSON.parse(P(e,n))}catch(e){throw e instanceof r?e:new r(`BAD_REQUEST`,`${n} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),a=t.safeParse(i);if(a.success)return a.data;let o=a.error.issues[0];throw new r(`BAD_REQUEST`,`${n} is invalid${o===void 0||o.path.length===0?``:` at ${o.path.join(`.`)}`}.`,o?.message??`Correct the JSON shape and retry.`)},mn=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=F(e.updates,Ut,`--updates`).map(e=>({kind:`set_text`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await N(t,e,n))})},hn=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=F(e.updates,Wt,`--updates`).map(e=>({kind:`rename`,nodeId:e.nodeId,name:e.name}));t.output.result(await N(t,e,n))})},gn=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=F(e.nodeIds,Jt,`--node-ids`);t.output.result(await Qt(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},_n=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=F(e.updates,Gt,`--updates`);t.output.result(await N(t,e,n.map(e=>({kind:`set_styles`,...e}))))})},vn=(e,t)=>{e.command(`edit`).description(`Apply an atomic canvas edit batch.`).requiredOption(`--canvas <url-or-id>`,`Canvas or selection URL, or canvas UUID.`).requiredOption(`--base-version <integer>`,`Canvas version to edit; use the previous write result to continue.`).requiredOption(`--edits <json-or-@path>`,`Array of edits with kind set_text, set_styles, rename, duplicate or move.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).addHelpText(`after`,`
|
|
5
5
|
Edit shapes (combine related edits in one array):
|
|
6
6
|
{"kind":"set_text","nodeId":"title","text":"Your day"}
|
|
7
7
|
{"kind":"set_styles","nodeIds":["button"],"styles":{"background":"#0f766e"}}
|
|
@@ -10,16 +10,16 @@ Edit shapes (combine related edits in one array):
|
|
|
10
10
|
{"kind":"move","nodeId":"card","destination":{"kind":"before","nodeId":"other"}}
|
|
11
11
|
Move destinations also accept {"kind":"after","nodeId":"other"} or {"kind":"parent","parentId":"screen","index":0}.
|
|
12
12
|
Use input-version IDs. Duplicate mappings are returned for a subsequent call.
|
|
13
|
-
`).action(async e=>{let n=F(e.edits,ae,`--edits`);t.output.result(await P(t,e,n))})},xn=(e,t)=>{bn(e,t),gn(e,t),_n(e,t),vn(e,t),yn(e,t)},Sn=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),I=e=>e===`start`||e===`end`?`flex-${e}`:e,Cn=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},wn=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=Cn(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},Tn=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=wn(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},En=(e,t)=>{let n=e.box;if(n===void 0)return{};let r=h(e),i=e.layout?.position??m(e,`position`),a=i===void 0||[`absolute`,`fixed`].includes(i),o=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>r[e]!==void 0),s=n=>xe(e,n,t).some(t=>r[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...r[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...a&&r.position===void 0&&{position:`absolute`},...a&&!o(`horizontal`)&&{left:n.x},...a&&!o(`vertical`)&&{top:n.y},...a&&e.layout?.horizontal===void 0&&!s(`horizontal`)&&{width:n.width},...a&&e.layout?.vertical===void 0&&!s(`vertical`)&&{height:n.height}}},Dn=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},On=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=Dn(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...m(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":I(n.alignItems)},...n.alignContent!==void 0&&{"align-content":I(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":I(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},kn=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&m(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?Cn(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},An=e=>{let t=[...e.rotation===void 0||e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},jn=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:I(e.alignSelf),Mn=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||h(e)[r]!==void 0?{}:{[r]:0}},Nn=(e,t)=>{let n=e.layout;if(n===void 0)return{};let r=t?.relationships[e.id]?.parentId,i=_e(r===void 0?void 0:t?.nodes[r],t),a=n.position??m(e,`position`),o=a===`flow`||a!==`absolute`&&a!==`fixed`&&(a!==void 0||e.box===void 0),s=i===`horizontal`?n.horizontal:n.vertical,c=i===`horizontal`?n.vertical:n.horizontal,l=jn(n,c);return{...n.position!==void 0&&{position:o?`relative`:`absolute`},...Tn(`width`,n.horizontal,o&&(i===`horizontal`||l===`stretch`)),...Tn(`height`,n.vertical,o&&(i===`vertical`||l===`stretch`)),...o&&i!==void 0&&kn(e,s),...o&&l!==void 0&&{"align-self":l},...o&&Mn(e,i),...l===`stretch`&&c?.mode===`hug`&&i!==void 0&&{[i===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...An(n)}},Pn=(e,t)=>Object.fromEntries(Object.entries({...En(e,t),...fe(e,{...Nn(e,t),...On(e)})}).map(([e,t])=>[e,typeof t==`number`&&!Sn.has(e)?`${String(t)}px`:t])),L=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,R=e=>{if(!e.visible)return null;if(e.kind===`solid`)return L(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${L(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},Fn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},In=e=>e?.flatMap(e=>{let t=R(e);return t===null?[]:[t]})??[],Ln=e=>{if(e?.visible!==!0)return{};let t=R(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},Rn=e=>{if(e?.visible!==!0)return{};let t=R(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},zn=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${L(e.color)}`),n=e.filters?.filter(e=>e.visible).map(Fn),r=e.backdropFilters?.filter(e=>e.visible).map(Fn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},Bn=e=>{if(e===void 0)return{};let t=In(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...Ln(e.border),...Rn(e.outline),...zn(e)}},Vn=(e,t)=>{let n={},r=h(e),i=String(r[`font-family`]??`sans-serif`).split(`,`).map(e=>e.trim().replaceAll(/^(?:"|')|(?:"|')$/gu,``));if(t.family!==void 0||t.fallbackFamilies!==void 0){let[e=`sans-serif`,...r]=i;n[`font-family`]=xt({family:t.family??e,fallbackFamilies:t.fallbackFamilies??r})}return n},Hn=e=>{let t={};return e.size!==void 0&&(t[`font-size`]=`${String(e.size)}px`),e.weight!==void 0&&(t[`font-weight`]=e.weight),e.style!==void 0&&(t[`font-style`]=e.style),(e.variations!==void 0||e.opticalSize!==void 0)&&(t[`font-variation-settings`]=St({...e.weight!==void 0&&{weight:e.weight},...e.variations!==void 0&&{variations:e.variations},...e.opticalSize!==void 0&&{opticalSize:e.opticalSize}})),e.opticalSize!==void 0&&(t[`font-optical-sizing`]=e.opticalSize.mode===`auto`?`auto`:`none`),e.features!==void 0&&(t[`font-feature-settings`]=Ct(e.features)),Object.assign(t,Tt(e)),t},Un=e=>{let t={};return e.align!==void 0&&(t[`text-align`]=e.align),e.transform!==void 0&&(t[`text-transform`]=e.transform),Object.assign(t,_t(e.direction)),e.paragraphIndent!==void 0&&(t[`text-indent`]=`${String(e.paragraphIndent)}px each-line`),e.hangingPunctuation!==void 0&&(t[`hanging-punctuation`]=`none`),t},Wn=e=>{let t={};return e.verticalAlign!==void 0&&e.verticalAlign!==`top`&&(t.display=`flex`,t[`flex-direction`]=`column`,t[`justify-content`]=e.verticalAlign===`middle`?`center`:`flex-end`),e.verticalTrim!==void 0&&(t[`text-box-trim`]=e.verticalTrim===`cap-height`?`trim-both`:`none`,t[`text-box-edge`]=`cap alphabetic`),t},Gn=e=>{let t={};return e.decoration!==void 0&&Object.assign(t,Dt(e.decoration)),e.wrapping!==void 0&&(t[`white-space`]=e.wrapping===`wrap`?`normal`:e.wrapping),e.wrapStyle!==void 0&&(t[`text-wrap-style`]=e.wrapStyle),t},Kn=e=>{let t=e.typography??{};return{...Vn(e,t),...Hn(t),...Un(t),...Wn(t),...Gn(t)}},qn=(e,t)=>({...Object.fromEntries(Object.entries(h(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...Kn(e),...Bn(e.appearance),...Pn(e,t),...e.visible===!1&&{display:`none`}}),Jn=(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),Yn=(e,t)=>{let n=e.nodes[t];if(n===void 0)throw new d(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},Xn=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},Zn=e=>`{${JSON.stringify(e)}}`,z=(e,t)=>e===void 0?[]:[t(e)],Qn=(e,t)=>{let n=` `.repeat(t),r=`${n}${Zn(e.text)}`;return e.sourcePath===void 0?r:`${n}<span data-source-path=${JSON.stringify(e.sourcePath)}>${Zn(e.text)}</span>`},$n=(e,t)=>{let n=` `.repeat(t),r=z(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`).join(``);return`${n}<br data-text-break="${e.soft===!0?`line`:`paragraph`}"${r===``?``:` ${r}`} />`},er=(e,t)=>{let n=` `.repeat(t),r=[...z(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`),...z(e.href,e=>`href={${JSON.stringify(e)}}`),...z(e.href,()=>`rel="noreferrer" target="_blank"`),...z(Object.keys(e.styles).length===0?void 0:e.styles,e=>`style={${JSON.stringify(e)}}`),...z(e.textStyle,e=>`data-text-style={${JSON.stringify(e)}}`),...z(e.paragraph,e=>`data-text-paragraph={${JSON.stringify(e)}}`),...z(e.fills,e=>`data-text-fills={${JSON.stringify(e)}}`),...z(e.paragraphSpacing,e=>`data-paragraph-spacing=${JSON.stringify(e)}`),...z(e.paragraphIndent,e=>`data-paragraph-indent=${JSON.stringify(e)}`),...z(e.listSpacing,e=>`data-list-spacing=${JSON.stringify(e)}`),...z(e.hangingPunctuation,e=>`data-hanging-punctuation=${JSON.stringify(e)}`),...z(e.verticalTrim,e=>`data-vertical-trim=${JSON.stringify(e)}`),...z(e.wrapStyle,e=>`data-wrap-style=${JSON.stringify(e)}`)],i=e.href===void 0?`span`:`a`,a=e.children.map(e=>tr(e,t+1));return[`${n}<${i}${r.length===0?``:` ${r.join(` `)}`}>`,...a,`${n}</${i}>`].join(`
|
|
14
|
-
`)}
|
|
15
|
-
`),
|
|
16
|
-
`)},
|
|
13
|
+
`).action(async e=>{let n=F(e.edits,ae,`--edits`);t.output.result(await N(t,e,n))})},yn=(e,t)=>{vn(e,t),mn(e,t),hn(e,t),gn(e,t),_n(e,t)},bn=new Set([`flex-grow`,`flex-shrink`,`order`,`aspect-ratio`]),I=e=>e===`start`||e===`end`?`flex-${e}`:e,xn=e=>{let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},Sn=(e,t)=>{let n=e[t],r=e[t===`min`?`minParent`:`maxParent`];if(r===void 0)return n;let i=xn(r);return n===void 0?i:`${t===`min`?`max`:`min`}(${String(n)}px, ${i})`},Cn=(e,t,n)=>{if(t===void 0)return{};if(t.mode===`fixed`)return{[e]:t.value};let r={};for(let n of[`min`,`max`]){let i=Sn(t,n);i!==void 0&&(r[`${n}-${e}`]=i)}if(t.mode===`hug`)return{[e]:`max-content`,...r};let i=t.offset??0,a=i===0?`100%`:`calc(100% + ${String(i)}px)`;return{[e]:n&&i===0?`auto`:a,...r}},wn=(e,t)=>{let n=e.box;if(n===void 0)return{};let r=y(e),i=e.layout?.position??h(e,`position`),a=i===void 0||[`absolute`,`fixed`].includes(i),o=e=>(e===`horizontal`?[`left`,`right`,`inset`,`inset-inline`,`inset-inline-start`,`inset-inline-end`]:[`top`,`bottom`,`inset`,`inset-block`,`inset-block-start`,`inset-block-end`]).some(e=>r[e]!==void 0),s=n=>De(e,n,t).some(t=>r[t]!==void 0||e.additionalStyles?.declarations.some(e=>e.property.toLowerCase()===t)===!0);return{...r[`box-sizing`]===void 0&&{"box-sizing":`border-box`},...a&&r.position===void 0&&{position:`absolute`},...a&&!o(`horizontal`)&&{left:n.x},...a&&!o(`vertical`)&&{top:n.y},...a&&e.layout?.horizontal===void 0&&!s(`horizontal`)&&{width:n.width},...a&&e.layout?.vertical===void 0&&!s(`vertical`)&&{height:n.height}}},Tn=e=>{if(e.gridColumns!==void 0)return`repeat(${String(e.gridColumns)}, minmax(0, 1fr))`;if(e.gridAutoRepeat!==void 0)return`repeat(${e.gridAutoRepeat.mode}, minmax(${String(e.gridAutoRepeat.minimum)}px, 1fr))`},En=e=>{let t=e.layout,n=t?.container,r=t?.clipContent===void 0?{}:{overflow:t.clipContent?`hidden`:`visible`};if(n===void 0)return r;let i=Tn(n),a=n.rowGap??n.gap,o=n.columnGap??n.gap;return{...r,...h(e,`display`)===void 0&&{display:i===void 0?`flex`:`grid`},...i!==void 0&&{"grid-template-columns":i},...n.direction!==void 0&&{"flex-direction":n.direction},...n.wrap!==void 0&&{"flex-wrap":n.wrap},...n.alignItems!==void 0&&{"align-items":I(n.alignItems)},...n.alignContent!==void 0&&{"align-content":I(n.alignContent)},...n.justifyContent!==void 0&&{"justify-content":I(n.justifyContent)},...a!==void 0&&{"row-gap":a},...o!==void 0&&{"column-gap":o},...Object.fromEntries(Object.entries(n.padding??{}).map(([e,t])=>[`padding-${e}`,t]))}},Dn=(e,t)=>{let n=e.layout??{},r=n=>t!==void 0&&h(e,n)===void 0,i=n.flexBasis??(t?.mode===`fill`?0:`auto`);return{...(r(`flex-basis`)||n.flexBasis!==void 0)&&{"flex-basis":typeof i==`object`?xn(i):i},...(r(`flex-grow`)||n.flexGrow!==void 0)&&{"flex-grow":n.flexGrow??+(t?.mode===`fill`)},...(r(`flex-shrink`)||n.flexShrink!==void 0)&&{"flex-shrink":n.flexShrink??+(t?.mode===`fill`)},...n.flowOffset!==void 0&&{left:n.flowOffset.x,top:n.flowOffset.y},...n.order!==void 0&&{order:n.order},...Object.fromEntries(Object.entries(n.margin??{}).map(([e,t])=>[`margin-${e}`,t]))}},On=e=>{let t=[...e.rotation===void 0||e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},kn=(e,t)=>e.alignSelf===void 0||e.alignSelf===`auto`?t?.mode===`fill`?`stretch`:void 0:I(e.alignSelf),An=(e,t)=>{if(t===void 0)return{};let n=e.layout?.[t],r=t===`horizontal`?`min-width`:`min-height`;return n?.mode!==`fill`||n.min!==void 0||n.minParent!==void 0||y(e)[r]!==void 0?{}:{[r]:0}},jn=(e,t)=>{let n=e.layout;if(n===void 0)return{};let r=t?.relationships[e.id]?.parentId,i=de(r===void 0?void 0:t?.nodes[r],t),a=n.position??h(e,`position`),o=a===`flow`||a!==`absolute`&&a!==`fixed`&&(a!==void 0||e.box===void 0),s=i===`horizontal`?n.horizontal:n.vertical,c=i===`horizontal`?n.vertical:n.horizontal,l=kn(n,c);return{...n.position!==void 0&&{position:o?`relative`:`absolute`},...Cn(`width`,n.horizontal,o&&(i===`horizontal`||l===`stretch`)),...Cn(`height`,n.vertical,o&&(i===`vertical`||l===`stretch`)),...o&&i!==void 0&&Dn(e,s),...o&&l!==void 0&&{"align-self":l},...o&&An(e,i),...l===`stretch`&&c?.mode===`hug`&&i!==void 0&&{[i===`horizontal`?`height`:`width`]:`auto`},...n.aspectRatio!==void 0&&{"aspect-ratio":n.aspectRatio},...On(n)}},Mn=(e,t)=>Object.fromEntries(Object.entries({...wn(e,t),...ye(e,{...jn(e,t),...En(e)})}).map(([e,t])=>[e,typeof t==`number`&&!bn.has(e)?`${String(t)}px`:t])),L=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,R=e=>{if(!e.visible)return null;if(e.kind===`solid`)return L(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${L(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},Nn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},Pn=e=>e?.flatMap(e=>{let t=R(e);return t===null?[]:[t]})??[],Fn=e=>{if(e?.visible!==!0)return{};let t=R(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},In=e=>{if(e?.visible!==!0)return{};let t=R(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},Ln=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${L(e.color)}`),n=e.filters?.filter(e=>e.visible).map(Nn),r=e.backdropFilters?.filter(e=>e.visible).map(Nn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},Rn=e=>{if(e===void 0)return{};let t=Pn(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...Fn(e.border),...In(e.outline),...Ln(e)}},zn=(e,t)=>{let n={},r=y(e),i=String(r[`font-family`]??`sans-serif`).split(`,`).map(e=>e.trim().replaceAll(/^(?:"|')|(?:"|')$/gu,``));if(t.family!==void 0||t.fallbackFamilies!==void 0){let[e=`sans-serif`,...r]=i;n[`font-family`]=bt({family:t.family??e,fallbackFamilies:t.fallbackFamilies??r})}return n},Bn=e=>{let t={};return e.size!==void 0&&(t[`font-size`]=`${String(e.size)}px`),e.weight!==void 0&&(t[`font-weight`]=e.weight),e.style!==void 0&&(t[`font-style`]=e.style),(e.variations!==void 0||e.opticalSize!==void 0)&&(t[`font-variation-settings`]=xt({...e.weight!==void 0&&{weight:e.weight},...e.variations!==void 0&&{variations:e.variations},...e.opticalSize!==void 0&&{opticalSize:e.opticalSize}})),e.opticalSize!==void 0&&(t[`font-optical-sizing`]=e.opticalSize.mode===`auto`?`auto`:`none`),e.features!==void 0&&(t[`font-feature-settings`]=St(e.features)),Object.assign(t,wt(e)),t},Vn=e=>{let t={};return e.align!==void 0&&(t[`text-align`]=e.align),e.transform!==void 0&&(t[`text-transform`]=e.transform),Object.assign(t,gt(e.direction)),e.paragraphIndent!==void 0&&(t[`text-indent`]=`${String(e.paragraphIndent)}px each-line`),e.hangingPunctuation!==void 0&&(t[`hanging-punctuation`]=`none`),t},Hn=e=>{let t={};return e.verticalAlign!==void 0&&e.verticalAlign!==`top`&&(t.display=`flex`,t[`flex-direction`]=`column`,t[`justify-content`]=e.verticalAlign===`middle`?`center`:`flex-end`),e.verticalTrim!==void 0&&(t[`text-box-trim`]=e.verticalTrim===`cap-height`?`trim-both`:`none`,t[`text-box-edge`]=`cap alphabetic`),t},Un=e=>{let t={};return e.decoration!==void 0&&Object.assign(t,Et(e.decoration)),e.wrapping!==void 0&&(t[`white-space`]=e.wrapping===`wrap`?`normal`:e.wrapping),e.wrapStyle!==void 0&&(t[`text-wrap-style`]=e.wrapStyle),t},Wn=e=>{let t=e.typography??{};return{...zn(e,t),...Bn(t),...Vn(t),...Hn(t),...Un(t)}},Gn=(e,t)=>({...Object.fromEntries(Object.entries(y(e)).filter(([t])=>e.layout?.clipContent===void 0||![`overflow`,`overflow-x`,`overflow-y`].includes(t))),...Wn(e),...Rn(e.appearance),...Mn(e,t),...e.visible===!1&&{display:`none`}}),Kn=(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),qn=(e,t)=>{let n=e.nodes[t];if(n===void 0)throw new r(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`);return n},Jn=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},Yn=e=>`{${JSON.stringify(e)}}`,z=(e,t)=>e===void 0?[]:[t(e)],Xn=(e,t)=>{let n=` `.repeat(t),r=`${n}${Yn(e.text)}`;return e.sourcePath===void 0?r:`${n}<span data-source-path=${JSON.stringify(e.sourcePath)}>${Yn(e.text)}</span>`},Zn=(e,t)=>{let n=` `.repeat(t),r=z(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`).join(``);return`${n}<br data-text-break="${e.soft===!0?`line`:`paragraph`}"${r===``?``:` ${r}`} />`},Qn=(e,t)=>{let n=` `.repeat(t),r=[...z(e.sourcePath,e=>`data-source-path=${JSON.stringify(e)}`),...z(e.href,e=>`href={${JSON.stringify(e)}}`),...z(e.href,()=>`rel="noreferrer" target="_blank"`),...z(Object.keys(e.styles).length===0?void 0:e.styles,e=>`style={${JSON.stringify(e)}}`),...z(e.textStyle,e=>`data-text-style={${JSON.stringify(e)}}`),...z(e.paragraph,e=>`data-text-paragraph={${JSON.stringify(e)}}`),...z(e.fills,e=>`data-text-fills={${JSON.stringify(e)}}`),...z(e.paragraphSpacing,e=>`data-paragraph-spacing=${JSON.stringify(e)}`),...z(e.paragraphIndent,e=>`data-paragraph-indent=${JSON.stringify(e)}`),...z(e.listSpacing,e=>`data-list-spacing=${JSON.stringify(e)}`),...z(e.hangingPunctuation,e=>`data-hanging-punctuation=${JSON.stringify(e)}`),...z(e.verticalTrim,e=>`data-vertical-trim=${JSON.stringify(e)}`),...z(e.wrapStyle,e=>`data-wrap-style=${JSON.stringify(e)}`)],i=e.href===void 0?`span`:`a`,a=e.children.map(e=>$n(e,t+1));return[`${n}<${i}${r.length===0?``:` ${r.join(` `)}`}>`,...a,`${n}</${i}>`].join(`
|
|
14
|
+
`)},$n=(e,t)=>e.kind===`text`?Xn(e,t):e.kind===`break`?Zn(e,t):Qn(e,t),er=(e,t)=>ie(e).map(e=>$n(e,t)).join(`
|
|
15
|
+
`),tr=(e,t,n,r)=>{let i=qn(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(Gn(i,e))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(Jn(i,`alt`))} src=${JSON.stringify(Jn(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?er(i,n+1):``,l=(n>=r?[]:Kn(e,t)).map(t=>tr(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
|
|
16
|
+
`)},nr=(e,t,n)=>tr(e,t,0,n),rr=(e,t)=>t.map(t=>{let n=qn(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:Gn(n,e),layout:n.layout,appearance:n.appearance,typography:n.typography}}),ir={topic:`canvas-agent-authoring`,workflow:[`Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.`,`Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.`,`Multiple screens: publish each populated screen before authoring the next so users see progress. Prepare only what that screen needs; do not prepare the whole set before the first write.`,`Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.`,`Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.`,`Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.`,`Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.`,`Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.`,`Name meaningful groups with layer-name; include content and structure together.`,`Styled text controls become frames with editable text children.`,`Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected.`]},completion:[`Natural hierarchy with the fewest useful editable primitives.`,`The committed version and affected ids match the request.`,`Inspect the final PNG for hierarchy, alignment, clipping and overflow.`,`Keep text, layout and appearance editable in the ordinary inspector.`]},ar=async(e,t)=>{let n=p.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:Te.parse(n.document)}},or=(e,t)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{t.output.result(ir)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let n=f(e.canvas),r=n.canvasId,{held:a,document:o}=await ar(t,r);i(n,o,[e.nodeId]),t.output.result({canvasId:r,version:a.version,nodeId:e.nodeId,jsx:nr(o,e.nodeId,A(Yt,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let n=f(e.canvas),r=n.canvasId,{held:a,document:o}=await ar(t,r),s=F(e.nodeIds,Jt,`--node-ids`);i(n,o,s),t.output.result({canvasId:r,version:a.version,nodes:rr(o,s),warning:`These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority.`})})},sr=async(e,t)=>{if(t.input!==void 0){if([t.canvas,t.baseVersion,t.nodes,t.idPrefix].some(e=>e!==void 0))throw new r(`BAD_REQUEST`,`Choose --input or the individual duplicate options.`,`Use --input with --client-token for native measured duplication.`);let n=b(e.catalog(),`canvas.duplicateNodes`);e.output.result(await e.invocation.invoke({capability:n,arguments:F(t.input,n.inputSchema,`--input`),clientToken:C.uuid().parse(t.clientToken)}));return}if(t.canvas===void 0||t.baseVersion===void 0||t.nodes===void 0)throw new r(`BAD_REQUEST`,`Duplicate needs --canvas, --base-version and --nodes, or --input.`,`Run duplicate-nodes --help.`);let n=F(t.nodes,Kt,`--nodes`).map(e=>({kind:`duplicate`,nodeIds:[e.id],...e.parentId!==void 0&&{parentId:e.parentId}})),i=await N(e,{canvas:t.canvas,baseVersion:t.baseVersion,...t.clientToken!==void 0&&{clientToken:t.clientToken}},n,t.idPrefix),{duplicatedNodes:a,...o}=i;e.output.result({...i,duplicatedNodes:a,apply:o})},cr=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees; --input uses native measured layout and durable copy receipts.`).option(`--input <json-or-@path>`,`Scoped native duplication request; requires --client-token.`).option(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).option(`--base-version <integer>`,`Exact current canvas version.`).option(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>sr(t,e))},lr=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await N(t,e,F(e.moves,qt,`--moves`).map(e=>({kind:`move`,nodeId:e.nodeId,destination:`before`in e?{kind:`before`,nodeId:e.before}:`after`in e?{kind:`after`,nodeId:e.after}:{kind:`parent`,parentId:e.parentId,...e.index!==void 0&&{index:e.index}}}))),{moves:r,affectedParents:i,...a}=n;t.output.result({...n,moves:r,affectedParents:i,apply:a})})},ur=(e,t)=>{cr(e,t),lr(e,t)},dr=e=>P(e,`--html`),fr=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),pr=async(e,t)=>{if(![`insert-children`,`replace`].includes(t.mode))throw new r(`BAD_REQUEST`,`--mode must be insert-children or replace.`,`Choose one of the two documented modes.`);if(![`none`,`render`].includes(t.review))throw new r(`BAD_REQUEST`,`--review must be none or render.`,`Choose one of the documented review modes.`);M(e,t.clientToken,!0);let n=t.mode===`replace`?`replace`:`insert-children`,i=f(t.canvas),a=j(t.baseVersion);e.output.result(await e.invocation.invoke({capability:b(e.catalog(),`canvas.writeHtml`),arguments:{canvasId:i.canvasId,...i.pageId!==void 0&&{pageId:i.pageId},...i.nodeIds.length>0&&{selectionNodeIds:[...i.nodeIds]},targetNodeId:t.targetNodeId,mode:n,html:dr(t.html),...t.idPrefix!==void 0&&{idPrefix:t.idPrefix},baseVersion:a,review:t.review,renderOutputPath:t.output??null,overwriteRender:t.force===!0,renderScale:A(zt,t.scale,`--scale`),renderTimeoutMs:A(Rt,t.timeoutMs,`--timeout-ms`)},clientToken:t.clientToken??null}))},mr=(e,t)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--review <mode>`,`none to return after commitment; render to include review pixels.`,`render`).option(`--id-prefix <prefix>`,`Fresh namespace for a new import/replacement; reuse only for an identical retry.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
|
|
17
17
|
Write one visual group at a time. Use --review none for a committed receipt, then render its version and inspect the PNG. Use flex, padding and gap; use targeted commands for later edits.
|
|
18
|
-
`).action(async e=>gr(t,e))},vr=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),yr=(e,t)=>typeof t==`number`&&!hr.has(e)?`${String(t)}px`:String(t),br=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=vr(e);return`${n}:${yr(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),xr=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,Sr=(e,t)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let n=F(e.styles,Ht,`--styles`);if(n.width===void 0||n.height===void 0)throw new d(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);N(t,e.clientToken,!0);let r=v(e.canvas),i=M(e.baseVersion),a=await ze(t,r,i),o=Object.entries(a.relationships).flatMap(([e,t])=>{let n=a.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),s={display:`flex`,flexDirection:`column`,left:xr(o),top:0,...n,position:`absolute`},c=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);t.output.result(await Ke(t.remote,t.render).execute({canvasId:r,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${c}" data-enhance-kind="frame" style="${br(s)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:r})}`,baseVersion:i,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},Cr=(e,t)=>{_r(e,t),Sr(e,t)},wr=(e,t)=>{for(let n of[`canvas.insertHtml`,`canvas.makeEditable`,`canvas.capture`,`canvas.arrange`]){let r=b(t.catalog(),n),i=n===`canvas.insertHtml`?`insert-html`:n===`canvas.makeEditable`?`make-editable`:n.slice(7);e.command(i).description(r.guide.summary).requiredOption(`--input <json-or-@path>`,`Canvas reference, base version and explicit native authoring request.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:r,arguments:F(e.input,r.inputSchema,`--input`),clientToken:S.uuid().parse(e.clientToken)}))})}},Tr=(e,t)=>{e.command(`remove`).description(`Remove explicitly named canvas subtrees with scope, lock and revision checks.`).requiredOption(`--input <json-or-@path>`,`Request containing canvasRef, baseVersion and rootNodeIds.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.remove`),arguments:F(e.input,Te,`--input`),clientToken:S.uuid().parse(e.clientToken)}))})},Er=(e,t)=>{e.command(`read`).description(`Read complete editable content, bounded evidence, or the supplied reference.`).summary(`Read linked canvas content.`).option(`--input <json-or-@path>`,`Bounded read request containing canvasRef, view and target options.`).option(`--canvas <url-or-id>`,`Complete canvas, page or selection URL for comprehensive reads.`).option(`--node-id <id>`,`Subtree within --canvas; unavailable with --input.`).action(async e=>{if(e.input===void 0==(e.canvas===void 0)||e.input!==void 0&&e.nodeId!==void 0)throw new d(`BAD_REQUEST`,`Choose exactly one of --input or --canvas; --node-id requires --canvas.`,`Use --input for bounded views, or --canvas with an optional --node-id for comprehensive reads.`);let n=e.input===void 0?{canvas:e.canvas,...e.nodeId!==void 0&&{nodeId:e.nodeId}}:F(e.input,ye,`--input`);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.read`),arguments:n,clientToken:null}))})},Dr=(e,t)=>{e.command(`find`).description(`Find accessible canvases and existing creation destinations with bounded results.`).option(`--input <json-or-@path>`,`Search title, collection, limit and continuation cursor.`,`{}`).action(async e=>{t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.find`),arguments:F(e.input,pe,`--input`),clientToken:null}))}),Tr(e,t),Er(e,t),e.command(`update-html`).description(`Apply an identity-preserving edit from a complete HTML snapshot.`).requiredOption(`--input <json-or-@path>`,`Request containing canvasRef, snapshotToken, html and removeNodeIds.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{let n=F(e.input,le,`--input`);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.updateHtml`),arguments:n,clientToken:S.uuid().parse(e.clientToken)}))})},Or=(e,t)=>{let n=b(t.catalog(),`prototype.publishCanvas`);e.command(`publish-prototype`).description(n.guide.summary).requiredOption(`--input <json-or-@path>`,`Complete canvas reference, baseVersion, unpacked build directory or existing deployment, and bounded waitMs.`).requiredOption(`--client-token <uuid>`,`Stable attachment intent; reuse the same arguments after uncertainty, use a new token after replanning.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:n,arguments:F(e.input,n.inputSchema,`--input`),clientToken:S.uuid().parse(e.clientToken)}))})},kr=(e,t)=>{let n=b(t.catalog(),`canvas.importAsset`);e.command(`import-asset`).description(n.guide.summary).requiredOption(`--input <json-or-@path>`,`Canvas reference and selected local file source.`).requiredOption(`--client-token <uuid>`,`Stable import intent; reuse after uncertainty.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:n,arguments:F(e.input,n.inputSchema,`--input`),clientToken:S.uuid().parse(e.clientToken)}))})},Ar=(e,t)=>{Dr(e,t),Or(e,t),kr(e,t),wr(e,t),cr(e,t),Cr(e,t),xn(e,t),fr(e,t),mn(e,t)},jr=e=>{let t=e.getOptionValue(`canvas`),n=e.getOptionValue(`canvasId`);if(t!==void 0&&n!==void 0)throw new d(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let r=t??n;if(typeof r!=`string`)throw new d(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:_(r),url:r}},Mr=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new d(`BAD_REQUEST`,`--node-id or a single-node selection link is required.`,`Choose one node, or use canvas tree to inspect the linked selection.`);return n},Nr=async(e,t,n,r)=>{let i=e.name()===`node`?Mr(e,n):void 0,a=await Re(t.remote,{canvas:r,...i!==void 0&&{nodeId:i}});if(i===void 0)return a;let{nodes:o,...s}=a;return{...s,node:o.find(e=>e.id===i)}},Pr=(e,n)=>{for(let r of[`inspect`,`tree`,`node`,`selection`]){let i=e.commands.find(e=>e.name()===r),a=i?.options.find(e=>e.long===`--canvas-id`);i!==void 0&&a!==void 0&&(a.makeOptionMandatory(!1),i.options.find(e=>e.long===`--node-id`)?.makeOptionMandatory(!1),i.option(`--canvas <url-or-id>`,`Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.`),i.action(async()=>{let{reference:e,url:a}=jr(i),o=t(e)?await Nr(i,n,e,a):await n.remote.query(`canvas.${r}`,{canvasId:e.canvasId,...r===`node`&&{nodeId:Mr(i,e)}});n.output.result(o)}))}},Fr=t=>{if(t.input===void 0)return null;if(t.canvas!==void 0||t.nodeId!==void 0||t.bounds!==void 0||t.expectedVersion!==void 0||t.atMs!==void 0||t.output!==void 0||t.force===!0||t.scale!==`1`||t.timeoutMs!==`120000`)throw new d(`BAD_REQUEST`,`The bounded --input request cannot be combined with individual render options.`,`Put the entire scoped render request in --input.`);return{arguments:F(t.input,e,`--input`),clientToken:S.uuid().parse(t.clientToken)}},Ir=S.coerce.number().int().positive(),Lr=S.coerce.number().int().nonnegative(),Rr=S.coerce.number().min(Ee).max(4),B=(e,t,n,r=`canvas render`)=>{let i=e.safeParse(t);if(!i.success)throw new d(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${r} --help'.`);return i.data},zr=e=>{if(e===void 0)return null;try{let t=Oe.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new d(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},Br=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},Vr=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return S.uuid().safeParse(e.slice(4)).data},Hr=(e,t)=>{let n=S.uuid().nullable().safeParse(t??null);if(!n.success)throw new d(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},Ur=async(e,n)=>{let r=_(e.canvas??``),a=Br(e.nodeId,zr(e.bounds)),o=e.expectedVersion===void 0?null:B(Ir,e.expectedVersion,`--expected-version`);if(!t(r))return{target:a,expectedVersion:o};let s=i.parse(await n.remote.query(`canvas.document.get`,{canvasId:r.canvasId}));if(o!==null&&o!==s.version)throw new d(`CONFLICT`,`The canvas changed before rendering.`,`Read the linked page or selection and render its current version.`);return{target:te(r,ce.parse(s.document),a),expectedVersion:s.version}},Wr=async(e,t)=>{if(e.canvas===void 0)throw new d(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new d(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let n=await Ur(e,t),r=n.target.kind===`node`?n.target.nodeId:void 0;if(r===void 0&&e.atMs!==void 0)throw new d(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let i=e.atMs===void 0?null:Vr(r);if(i===void 0&&e.atMs!==void 0)throw new d(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");Hr(t,e.clientToken);let a=await t.invocation.invoke({capability:b(t.catalog(),`canvas.render`),arguments:{canvasId:_(e.canvas).canvasId,...n,sourceState:i==null?null:{kind:`recording`,recordingId:i,atMs:B(Lr,e.atMs??``,`--at-ms`)},scale:B(Rr,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:B(Ir,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});t.output.result(a)},Gr=(e,t)=>{e.option(`--input <json-or-@path>`,`Bounded scoped render request; requires --client-token.`).option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
18
|
+
`).action(async e=>pr(t,e))},hr=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),gr=(e,t)=>typeof t==`number`&&!fr.has(e)?`${String(t)}px`:String(t),_r=e=>Object.entries(e).filter(([,e])=>e!==null).map(([e,t])=>{let n=hr(e);return`${n}:${gr(n,t??``)}`}).join(`;`).replaceAll(`&`,`&`).replaceAll(`"`,`"`),vr=e=>e.length===0?0:Math.max(...e.map(e=>e.x+e.width))+80,yr=(e,t)=>{e.command(`create-artboard`).description(`Create a top-level frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--name <name>`,`Meaningful layer name.`).requiredOption(`--styles <json-or-@path>`,`CSSProperties with width and height.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact creation and review.`).option(`--output <path>`,`Review PNG path.`).option(`--force`,`Replace an existing review PNG.`,!1).action(async e=>{let n=F(e.styles,Ht,`--styles`);if(n.width===void 0||n.height===void 0)throw new r(`BAD_REQUEST`,`--styles must include width and height.`,`Use explicit whole-pixel dimensions such as 1440px and 900px.`);M(t,e.clientToken,!0);let i=o(e.canvas),a=j(e.baseVersion),s=await x(t,i,a),c=Object.entries(s.relationships).flatMap(([e,t])=>{let n=s.nodes[e]?.box;return n!==void 0&&t.parentId===`root`?[n]:[]}),l={display:`flex`,flexDirection:`column`,left:vr(c),top:0,...n,position:`absolute`},u=e.name.replaceAll(`&`,`&`).replaceAll(`"`,`"`);t.output.result(await He(t.remote,t.render).execute({canvasId:i,targetNodeId:`root`,mode:`insert-children`,html:`<div layer-name="${u}" data-enhance-kind="frame" style="${_r(l)}"></div>`,idPrefix:`artboard_${t.mutationKey.current(`canvas.render.importSource`,{canvasId:i})}`,baseVersion:a,renderClientToken:t.mutationKey.current(`canvas.render.create`,{purpose:`create-artboard-review`}),renderOutputPath:e.output??null,overwriteRender:e.force===!0,renderScale:1,renderTimeoutMs:12e4}))})},br=(e,t)=>{mr(e,t),yr(e,t)},xr=(e,t)=>{for(let n of[`canvas.insertHtml`,`canvas.makeEditable`,`canvas.capture`,`canvas.arrange`]){let r=b(t.catalog(),n),i=n===`canvas.insertHtml`?`insert-html`:n===`canvas.makeEditable`?`make-editable`:n.slice(7);e.command(i).description(r.guide.summary).requiredOption(`--input <json-or-@path>`,`Canvas reference, base version and explicit native authoring request.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:r,arguments:F(e.input,r.inputSchema,`--input`),clientToken:C.uuid().parse(e.clientToken)}))})}},Sr=(e,t)=>{e.command(`remove`).description(`Remove explicitly named canvas subtrees with scope, lock and revision checks.`).requiredOption(`--input <json-or-@path>`,`Request containing canvasRef, baseVersion and rootNodeIds.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.remove`),arguments:F(e.input,Ee,`--input`),clientToken:C.uuid().parse(e.clientToken)}))})},Cr=(e,t)=>{e.command(`read`).description(`Read complete editable content, bounded evidence, or the supplied reference.`).summary(`Read linked canvas content.`).option(`--input <json-or-@path>`,`Bounded read request containing canvasRef, view and target options.`).option(`--canvas <url-or-id>`,`Complete canvas, page or selection URL for comprehensive reads.`).option(`--node-id <id>`,`Subtree within --canvas; unavailable with --input.`).action(async e=>{if(e.input===void 0==(e.canvas===void 0)||e.input!==void 0&&e.nodeId!==void 0)throw new r(`BAD_REQUEST`,`Choose exactly one of --input or --canvas; --node-id requires --canvas.`,`Use --input for bounded views, or --canvas with an optional --node-id for comprehensive reads.`);let n=e.input===void 0?{canvas:e.canvas,...e.nodeId!==void 0&&{nodeId:e.nodeId}}:F(e.input,Se,`--input`);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.read`),arguments:n,clientToken:null}))})},wr=(e,t)=>{e.command(`find`).description(`Find accessible canvases and existing creation destinations with bounded results.`).option(`--input <json-or-@path>`,`Search title, collection, limit and continuation cursor.`,`{}`).action(async e=>{t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.find`),arguments:F(e.input,he,`--input`),clientToken:null}))}),Sr(e,t),Cr(e,t),e.command(`update-html`).description(`Apply an identity-preserving edit from a complete HTML snapshot.`).requiredOption(`--input <json-or-@path>`,`Request containing canvasRef, snapshotToken, html and removeNodeIds.`).requiredOption(`--client-token <uuid>`,`Stable intent ID; reuse unchanged after an uncertain outcome.`).action(async e=>{let n=F(e.input,fe,`--input`);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.updateHtml`),arguments:n,clientToken:C.uuid().parse(e.clientToken)}))})},Tr=(e,t)=>{let n=b(t.catalog(),`prototype.publishCanvas`);e.command(`publish-prototype`).description(n.guide.summary).requiredOption(`--input <json-or-@path>`,`Complete canvas reference, baseVersion, unpacked build directory or existing deployment, and bounded waitMs.`).requiredOption(`--client-token <uuid>`,`Stable attachment intent; reuse the same arguments after uncertainty, use a new token after replanning.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:n,arguments:F(e.input,n.inputSchema,`--input`),clientToken:C.uuid().parse(e.clientToken)}))})},Er=(e,t)=>{let n=b(t.catalog(),`canvas.importAsset`);e.command(`import-asset`).description(n.guide.summary).requiredOption(`--input <json-or-@path>`,`Canvas reference and selected local file source.`).requiredOption(`--client-token <uuid>`,`Stable import intent; reuse after uncertainty.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:n,arguments:F(e.input,n.inputSchema,`--input`),clientToken:C.uuid().parse(e.clientToken)}))})},Dr=(e,t)=>{wr(e,t),Tr(e,t),Er(e,t),xr(e,t),or(e,t),br(e,t),yn(e,t),ur(e,t),pn(e,t)},Or=e=>{let t=e.getOptionValue(`canvas`),n=e.getOptionValue(`canvasId`);if(t!==void 0&&n!==void 0)throw new r(`BAD_REQUEST`,`--canvas and --canvas-id cannot be combined.`,`Pass the pasted URL or UUID through --canvas.`);let i=t??n;if(typeof i!=`string`)throw new r(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);return{reference:f(i),url:i}},kr=(e,t)=>{let n=e.getOptionValue(`nodeId`)??(t.nodeIds.length===1?t.nodeIds[0]:void 0);if(typeof n!=`string`||n===``)throw new r(`BAD_REQUEST`,`--node-id or a single-node selection link is required.`,`Choose one node, or use canvas tree to inspect the linked selection.`);return n},Ar=async(e,t,n,r)=>{let i=e.name()===`node`?kr(e,n):void 0,a=await Pe(t.remote,{canvas:r,...i!==void 0&&{nodeId:i}});if(i===void 0)return a;let{nodes:o,...s}=a;return{...s,node:o.find(e=>e.id===i)}},jr=(e,t)=>{for(let n of[`inspect`,`tree`,`node`,`selection`]){let r=e.commands.find(e=>e.name()===n),i=r?.options.find(e=>e.long===`--canvas-id`);r!==void 0&&i!==void 0&&(i.makeOptionMandatory(!1),r.options.find(e=>e.long===`--node-id`)?.makeOptionMandatory(!1),r.option(`--canvas <url-or-id>`,`Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.`),r.action(async()=>{let{reference:e,url:i}=Or(r),o=a(e)?await Ar(r,t,e,i):await t.remote.query(`canvas.${n}`,{canvasId:e.canvasId,...n===`node`&&{nodeId:kr(r,e)}});t.output.result(o)}))}},Mr=t=>{if(t.input===void 0)return null;if(t.canvas!==void 0||t.nodeId!==void 0||t.bounds!==void 0||t.expectedVersion!==void 0||t.atMs!==void 0||t.output!==void 0||t.force===!0||t.scale!==`1`||t.timeoutMs!==`120000`)throw new r(`BAD_REQUEST`,`The bounded --input request cannot be combined with individual render options.`,`Put the entire scoped render request in --input.`);return{arguments:F(t.input,e,`--input`),clientToken:C.uuid().parse(t.clientToken)}},Nr=C.coerce.number().int().positive(),Pr=C.coerce.number().int().nonnegative(),Fr=C.coerce.number().positive(),B=(e,t,n,i=`canvas render`)=>{let a=e.safeParse(t);if(!a.success)throw new r(`BAD_REQUEST`,`${n} is invalid.`,`Run 'enhance ${i} --help'.`);return a.data},Ir=e=>{if(e===void 0)return null;try{let t=ne.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}throw new r(`BAD_REQUEST`,`--bounds must be a finite positive world rectangle.`,`Pass JSON such as '{"x":0,"y":0,"width":800,"height":600}'.`)},Lr=(e,t)=>e===void 0?t===null?{kind:`content`}:{kind:`bounds`,bounds:t}:{kind:`node`,nodeId:e},Rr=e=>{if(!(typeof e!=`string`||!e.startsWith(`rec_`)))return C.uuid().safeParse(e.slice(4)).data},zr=(e,t)=>{let n=C.uuid().nullable().safeParse(t??null);if(!n.success)throw new r(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact render.`);return e.mutationKey.select(n.data,!1),e.mutationKey.current(`canvas.render.create`,{})},Br=async(e,t)=>{let n=f(e.canvas??``),i=Lr(e.nodeId,Ir(e.bounds)),o=e.expectedVersion===void 0?null:B(Nr,e.expectedVersion,`--expected-version`);if(!a(n))return{target:i,expectedVersion:o};let s=p.parse(await t.remote.query(`canvas.document.get`,{canvasId:n.canvasId}));if(o!==null&&o!==s.version)throw new r(`CONFLICT`,`The canvas changed before rendering.`,`Read the linked page or selection and render its current version.`);return{target:oe(n,Te.parse(s.document),i),expectedVersion:s.version}},Vr=async(e,t)=>{if(e.canvas===void 0)throw new r(`BAD_REQUEST`,`--canvas is required.`,`Pass a pasted Enhance canvas URL or bare UUID through --canvas.`);if(e.nodeId!==void 0&&e.bounds!==void 0)throw new r(`BAD_REQUEST`,`--node-id and --bounds cannot be combined.`,`Choose one focused target, or omit both to render all authored content.`);let n=await Br(e,t),i=n.target.kind===`node`?n.target.nodeId:void 0;if(i===void 0&&e.atMs!==void 0)throw new r(`BAD_REQUEST`,`--at-ms requires --node-id.`,"Render the stable recording node returned by `enhance canvas tree`.");let a=e.atMs===void 0?null:Rr(i);if(a===void 0&&e.atMs!==void 0)throw new r(`BAD_REQUEST`,`--at-ms requires a stable recording node id such as rec_<recording-uuid>.`,"Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");zr(t,e.clientToken);let o=await t.invocation.invoke({capability:b(t.catalog(),`canvas.render`),arguments:{canvasId:f(e.canvas).canvasId,...n,sourceState:a==null?null:{kind:`recording`,recordingId:a,atMs:B(Pr,e.atMs??``,`--at-ms`)},scale:B(Fr,e.scale,`--scale`),outputPath:e.output??null,overwrite:e.force===!0,timeoutMs:B(Nr,e.timeoutMs,`--timeout-ms`)},clientToken:e.clientToken??null});t.output.result(o)},Hr=(e,t)=>{e.option(`--input <json-or-@path>`,`Bounded scoped render request; requires --client-token.`).option(`--canvas <url-or-id>`,`Canvas URL or UUID to render.`).option(`--node-id <id>`,`Render one stable canvas node instead of all authored content.`).option(`--bounds <json>`,`Render an explicit rectangle in canvas world coordinates.`).option(`--expected-version <integer>`,`Refuse pixels from any other document version.`).option(`--at-ms <integer>`,`Pause a recording node at this millisecond; inspect the PNG before snapshotting it.`).option(`--scale <number>`,`Output pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--output <path>`,`Write the PNG to this path instead of a protected temporary file.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this render request.`).addHelpText(`after`,`
|
|
19
19
|
For transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.
|
|
20
|
-
`).action(async e=>{let n=Fr(e);if(n===null)return Wr(e,t);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.render`),...n}))})},Kr=(e,t)=>{let n=e.commands.find(e=>e.name()===`canvas`);if(n===void 0)throw TypeError(`the API router did not supply canvas commands`);n.configureHelp({subcommandTerm:e=>e.name()});let r=n.commands.find(e=>e.name()===`render`);if(r===void 0)throw TypeError(`the API router did not supply canvas render`);let i=Me(t.remote,Ne(t.configDirectory),t.now,t.output.result);sn(n,t),Ar(n,{...t,render:i}),Pr(n,t),Gr(r,t)},qr=8192,V=S.string().trim().min(1).max(160),Jr=S.string().regex(/^[a-f0-9]{64}$/u),H=S.number().int().positive().max(32768),Yr=S.strictObject({source:V,journey:V,step:V,variant:V}),U=S.strictObject({sha256:Jr,bytes:S.number().int().positive().max(16777216),mediaType:S.string().min(1).max(200)}),Xr=S.strictObject({format:S.literal(`enhance-capture`),version:S.literal(1),key:Yr,label:V,journeyLabel:V,order:S.number().int().nonnegative().max(1e5),viewport:S.strictObject({width:H,height:H,deviceScaleFactor:S.number().positive().max(8)}),extent:S.enum([`viewport`,`full-page`]),source:S.strictObject({format:S.literal(`rrweb-screen`),version:S.literal(1),blob:U}),preview:S.strictObject({blob:U,width:H,height:H,pixelRatio:S.number().positive().max(8)}),assets:S.array(S.strictObject({url:S.url().max(qr),blob:U})).max(2e3),provenance:S.strictObject({adapter:V,sdkVersion:V,kernelVersion:V,browser:V,capturedAt:S.iso.datetime(),sourceUrl:S.url().max(qr).optional(),commit:S.string().min(1).max(200).optional()}),issues:S.array(S.strictObject({code:V,message:S.string().min(1).max(500)})).max(100)}).superRefine((e,t)=>{e.preview.width*e.preview.height>16e6&&t.addIssue({code:`custom`,path:[`preview`],message:`Capture previews are limited to 16 million pixels.`}),(e.preview.width/e.preview.pixelRatio!==e.viewport.width||e.preview.height/e.preview.pixelRatio!==e.viewport.height)&&t.addIssue({code:`custom`,path:[`preview`],message:`The preview and captured CSS extent must match.`}),e.source.blob.mediaType!==`application/json`&&t.addIssue({code:`custom`,path:[`source`,`blob`,`mediaType`],message:`Capture sources must be frozen JSON.`}),e.preview.blob.mediaType!==`image/png`&&t.addIssue({code:`custom`,path:[`preview`,`blob`,`mediaType`],message:`Capture previews must be PNG.`}),new Set(e.assets.map(e=>e.url)).size!==e.assets.length&&t.addIssue({code:`custom`,path:[`assets`],message:`Capture resource URLs must be unique.`})}),W=S.strictObject({id:S.uuid(),canvasId:S.uuid(),source:V,runKey:V,generation:S.number().int().nonnegative(),participants:S.array(V).min(1).max(128),expiresAt:S.iso.datetime(),formatVersion:S.literal(1)}),Zr=S.strictObject({participant:V,testId:V,project:V,retry:S.number().int().nonnegative().max(100),status:S.enum([`passed`,`failed`,`skipped`,`interrupted`,`timedOut`]),captures:S.array(Xr).max(64)}),G=S.strictObject({format:S.literal(`enhance-capture-run`),version:S.literal(1),run:W,participants:S.array(S.strictObject({id:V,status:S.enum([`passed`,`failed`,`interrupted`])})).min(1).max(128),attempts:S.array(Zr).max(1e4),ordering:S.enum([`partial`,`complete`])}),Qr=S.strictObject({runId:S.uuid(),canvasId:S.uuid(),canvasUrl:S.url(),version:S.number().int().positive(),manifestDigest:Jr,frames:S.array(S.strictObject({key:Yr,frameId:V,captureId:S.uuid()})).max(64),issues:S.array(S.strictObject({code:V,message:S.string().max(500)})).max(100)}),$r=S.strictObject({canvasId:S.uuid(),source:V.default(`default`),runKey:V,participants:S.array(V).min(1).max(128).default([`local`]),formatVersion:S.literal(1).default(1)}),ei=S.strictObject({run:W});S.strictObject({runId:S.uuid()});const ti=S.enum([`collecting`,`sealed`,`converting`,`committed`,`failed`,`cancelled`]),K=S.strictObject({run:W,state:ti,receipt:Qr.nullable(),failure:S.strictObject({code:V,message:S.string().max(1e3)}).nullable()});S.strictObject({runId:S.uuid(),blobs:S.array(U).min(1).max(400)});const ni=S.strictObject({uploads:S.array(S.strictObject({sha256:Jr,upload:S.strictObject({url:S.url(),headers:S.record(S.string(),S.string()),expiresAt:S.iso.datetime()}).nullable()})).max(400)});S.strictObject({manifest:G}),S.strictObject({canvasId:S.uuid(),frameId:S.string().min(1),captureId:S.uuid()});const ri=S.strictObject({captureId:S.uuid(),capturedAt:S.iso.datetime(),commit:S.string().max(200).optional(),url:S.string().min(1),width:S.number().positive(),height:S.number().positive(),pixelRatio:S.number().positive()});S.strictObject({frameId:S.string(),before:ri,after:ri});const ii=e=>JSON.stringify([e.source,e.journey,e.step,e.variant]),q=(e,t)=>e<t?-1:e===t?0:1,J=(e,t)=>{if(e===null||typeof e==`boolean`||typeof e==`string`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`||t.has(e)||t.size>=64)return null;let n=new Set(t);if(n.add(e),Array.isArray(e)){let t=e.map(e=>J(e,n));return t.includes(null)?null:`[${t.join(`,`)}]`}if(Object.getPrototypeOf(e)!==Object.prototype)return null;let r=Object.keys(e).toSorted(q).map(t=>{let r=J(Reflect.get(e,t),n);return r===null?null:`${JSON.stringify(t)}:${r}`});return r.includes(null)?null:`{${r.join(`,`)}}`},Y=e=>J(e,new Set),ai=e=>{let t=new Map,n=[],r=0;for(let i of e){let e=[i.source.blob,i.preview.blob,...i.assets.map(e=>e.blob)];for(let i of e){let e=t.get(i.sha256);if(e!==void 0&&Y(e)!==Y(i))return`The same capture digest has conflicting blob metadata.`;e===void 0&&(n.push(i),r+=i.bytes,t.set(i.sha256,i))}}return r>268435456?`Capture run exceeds the retained byte budget.`:n.toSorted((e,t)=>q(e.sha256,t.sha256))},oi=e=>{let t=new Set(e.run.participants);if(t.size!==e.run.participants.length||e.participants.length!==t.size||new Set(e.participants.map(e=>e.id)).size!==t.size||e.participants.some(e=>!t.has(e.id)||e.status!==`passed`))return`Every reserved participant must finish successfully exactly once.`;let n=new Map,r=new Map;for(let i of e.attempts){if(!t.has(i.participant))return`Capture attempt belongs to an unreserved participant.`;let e=JSON.stringify([i.participant,i.project,i.testId]),a=JSON.stringify([e,i.retry]),o=Y(i);if(o===null)return`Capture attempts must contain finite JSON values.`;let s=r.get(a);if(s!==void 0&&s!==o)return`Conflicting terminal records for the same test attempt.`;r.set(a,o);let c=n.get(e);(c===void 0||c.retry<i.retry)&&n.set(e,i)}return e.attempts.filter(e=>n.get(JSON.stringify([e.participant,e.project,e.testId]))===e)},si=(e,t)=>{let n=new Set,r=new Set;for(let i of t){if(i.key.source!==e)return`Capture source differs from its reserved run.`;let t=ii(i.key);if(n.has(t))return`Duplicate capture key: ${t}`;let a=JSON.stringify([i.key.journey,i.key.variant,i.order]);if(r.has(a))return`Duplicate step order in journey ${i.key.journey}.`;n.add(t),r.add(a)}return null},ci=(e,t)=>{let n=q(e.key.journey,t.key.journey);if(n!==0)return n;let r=q(e.key.variant,t.key.variant);return r===0?e.order-t.order:r},li=e=>{let t=G.safeParse(e);if(!t.success)return`Invalid capture manifest.`;let n=t.data,r=oi(n);if(typeof r==`string`)return r;let i=r.flatMap(e=>e.status===`passed`?e.captures:[]);if(i.length===0||i.length>64)return`A run must contain 1–64 successful captures.`;let a=si(n.run.source,i);if(a!==null)return a;let o=ai(i);return typeof o==`string`?o:i.toSorted(ci)},ui=e=>{let t=Y(e);return t===null?null:`enhance-capture-run:v1\0${t}`},X=(e,t,n)=>Object.assign(Error(t),{code:e,...n!==void 0&&{runId:n}}),di=e=>lt(`sha256`).update(e).digest(`hex`),fi=e=>{let t=ui(e);if(t===null)throw Error(`A capture manifest must contain only finite JSON values.`);return lt(`sha256`).update(t).digest(`hex`)},pi=(e,t)=>{if(!/^[a-f0-9]{64}$/u.test(t))throw X(`artifact`,`Invalid capture blob digest.`);return w.join(w.resolve(e),`blobs`,t)},Z=async(e,t)=>{let n=pi(e,t.sha256),r=await dt(n);if(!r.isFile()||r.size!==t.bytes||r.size>16777216)throw X(`artifact`,`Capture blob size does not match ${t.sha256}.`);let i=await D(n);if(di(i)!==t.sha256)throw X(`artifact`,`Capture blob checksum does not match ${t.sha256}.`);return i},mi=async(e,t)=>{let n=Xr.parse(t.artifact);await E(w.join(e,`blobs`),{recursive:!0});for(let n of t.blobs){if(n.description.bytes!==n.bytes.byteLength||n.bytes.byteLength>16777216||di(n.bytes)!==n.description.sha256)throw X(`artifact`,`Capture blob bytes do not match their descriptor.`);let t=pi(e,n.description.sha256),r=`${t}.${globalThis.crypto.randomUUID()}.tmp`;await ft(r,n.bytes,{flag:`wx`,mode:384}),await ut(r,t)}for(let t of[n.source.blob,n.preview.blob,...n.assets.map(e=>e.blob)])await Z(e,t);return n},Q=async(e,t)=>{let n=`${e}.${globalThis.crypto.randomUUID()}.tmp`;await ft(n,JSON.stringify(t),{mode:384}),await ut(n,e)},hi=async e=>{if((await dt(e)).size>16777216)throw X(`artifact`,`Capture manifest exceeds its byte budget.`);let t=JSON.parse(await D(e,`utf8`));return G.parse(t)},gi=async e=>{if(e.held===void 0)throw X(`transport`,`Enhance omitted a requested blob reservation.`,e.runId);let t=e.held.upload;if(t===null)return;let n=await Z(e.directory,e.blob);try{if(!(await fetch(t.url,{method:`PUT`,headers:t.headers,body:new Blob([Uint8Array.from(n)]),signal:AbortSignal.timeout(e.transport.timeoutMs),redirect:`error`})).ok)throw X(`transport`,`Upload refused.`,e.runId)}catch{throw X(`transport`,`Capture upload was not confirmed. Resume the same manifest.`,e.runId)}},_i=async(e,t,n,r)=>{for(let i=0;i<r.length;i+=400){let a=r.slice(i,i+400);for(let e of a)await Z(n,e);let o=await e.request(`captureRun.reserveAssets`,{runId:t.run.id,blobs:a},ni);for(let r of a)await gi({transport:e,runId:t.run.id,directory:n,blob:r,held:o.uploads.find(e=>e.sha256===r.sha256)})}},vi=async(e,t)=>{let n=await e.request(`captureRun.publish`,{runId:t},K),r=Date.now()+e.publicationTimeoutMs;for(;n.receipt===null&&n.failure===null&&![`cancelled`,`failed`].includes(n.state);){if(Date.now()>=r)throw X(`transport`,`Capture run ${t} is still processing. Resume the same manifest.`,t);await new Promise(e=>{setTimeout(e,250)}),n=await e.request(`captureRun.publish`,{runId:t},K)}if(n.receipt===null)throw X(n.failure?.code===`conflict`?`conflict`:`conversion`,n.failure?.message??`The capture run was cancelled.`,t);return n.receipt},yi=(e,t)=>{if(e.runId!==t.run.id||e.canvasId!==t.run.canvasId||e.manifestDigest!==fi(t))throw X(`conflict`,`This run committed a different manifest.`,t.run.id);return e},bi=async(e,t,n)=>{let r=li(t);if(typeof r==`string`)throw X(`artifact`,r);let i=ai(r);if(typeof i==`string`)throw X(`artifact`,i);let a=await e.request(`captureRun.get`,{runId:t.run.id},K,!0);if(a.receipt!==null){let e=yi(a.receipt,t);return await Q(w.join(n,`receipt.json`),e),e}a.state===`collecting`&&await _i(e,t,n,i),await e.request(`captureRun.seal`,{manifest:t},K);let o=yi(await vi(e,t.run.id),t);return await Q(w.join(n,`receipt.json`),o),o},xi=async(e,t,n)=>{try{return await bi(e,t,n)}catch(e){throw e instanceof Error?Object.assign(e,{runId:t.run.id}):X(`transport`,`Capture publication was not confirmed. Resume the same manifest.`,t.run.id)}},Si=new Map([[401,`authorization`],[403,`authorization`],[409,`conflict`],[400,`artifact`]]),Ci=async(e,t)=>{try{return await fetch(e,t)}catch{throw X(`transport`,`Enhance did not confirm the request. Resume the same run to recover its result.`)}},wi=async e=>{try{return await e.json()}catch{return null}},Ti=async(e,t,n,r)=>{let i=await Ci(e,t),a=await wi(i);if(!i.ok){let e=typeof a==`object`&&a?Reflect.get(a,`error`):null,t=typeof e==`object`&&e?Reflect.get(e,`message`):null;throw X(Si.get(i.status)??`transport`,typeof t==`string`?t.slice(0,1e3):`Enhance rejected ${r} (HTTP ${String(i.status)}).`)}let o=typeof a==`object`&&a?Reflect.get(a,`result`):null,s=typeof o==`object`&&o?Reflect.get(o,`data`):void 0,c=n.safeParse(s);if(!c.success)throw X(`transport`,`Enhance returned an incompatible ${r} response.`);return c.data},Ei=e=>{let t=URL.parse(e.apiUrl);if(t===null||![`http:`,`https:`].includes(t.protocol)||t.username!==``||t.password!==``||e.token.trim()===``)throw X(`configuration`,`Enhance needs an HTTP API URL and an explicit token.`);let n=e.timeoutMs??3e4,r=e.publicationTimeoutMs??6e5;if(!Number.isSafeInteger(r)||r<1||r>36e5)throw X(`configuration`,`Enhance publication timeout must be between 1 and 3600000 milliseconds.`);if(!Number.isSafeInteger(n)||n<1||n>3e5)throw X(`configuration`,`Enhance timeout must be between 1 and 300000 milliseconds.`);return{timeoutMs:n,publicationTimeoutMs:r,request:async(r,i,a,o=!1)=>{let s=new URL(`${t.pathname.replace(/\/$/u,``)}/trpc/${r}`,t.origin);return o&&s.searchParams.set(`input`,JSON.stringify(i)),Ti(s,{method:o?`GET`:`POST`,headers:{authorization:`Bearer ${e.token}`,"content-type":`application/json`},...!o&&{body:JSON.stringify(i)},signal:AbortSignal.timeout(n),redirect:`error`},a,r)}}},Di=(e,t)=>{let n=e.participants[0];if(n===void 0)throw X(`configuration`,`No capture participant was reserved.`);return{format:`enhance-capture-run`,version:1,run:e,ordering:`partial`,participants:[{id:n,status:`passed`}],attempts:[{participant:n,testId:`node`,project:`node`,retry:0,status:`passed`,captures:t}]}},Oi=(e,t,n)=>{let r=W.parse(t),i=[],a=!1;return{descriptor:r,directory:n,add:async e=>{if(a)throw X(`configuration`,`This run no longer accepts captures.`);let t=mi(n,e);i.push(t),await t},publish:async()=>{a=!0;let t=await Promise.all(i);if(r.participants.length!==1)throw X(`configuration`,`Multi-participant runs must publish a complete merged manifest.`);let o=Di(r,t),s=li(o);if(typeof s==`string`)throw X(`artifact`,s);return await E(n,{recursive:!0}),await Q(w.join(n,`manifest.json`),o),xi(e,o,n)},cancel:async()=>(a=!0,(await e.request(`captureRun.cancel`,{runId:r.id},K)).receipt)}},ki=e=>{let t=Ei(e);return{captures:{begin:async e=>{let n=$r.parse({canvasId:e.canvas,source:e.source,runKey:e.runKey,participants:e.participants}),{run:r}=await t.request(`captureRun.begin`,n,ei),i=e.directory??w.join(`.enhance`,`captures`,r.id);return await E(i,{recursive:!0}),await Q(w.join(i,`run.json`),r),Oi(t,r,i)},publishManifest:async e=>xi(t,await hi(e),w.dirname(e)),get:async e=>t.request(`captureRun.get`,{runId:e},K,!0)}}},Ai=(e,t)=>{let n=e instanceof Error?Reflect.get(e,`code`):void 0;return new d(n===`authorization`?`UNAUTHORIZED`:n===`conflict`?`CONFLICT`:[`configuration`,`artifact`].includes(String(n))?`BAD_REQUEST`:`INTERNAL`,e instanceof Error?e.message:`Capture publication was not confirmed.`,`Retry enhance captures publish with the same manifest: ${t}`)},ji=(e,t)=>{e.command(`captures`).description(`Publish SDK captures as editable canvas journeys.`).command(`publish <manifest>`).description(`Publish or resume a reserved capture manifest and print its durable receipt.`).action(async e=>{let n=await t.credentials.read();if(n===null)throw new d(`UNAUTHORIZED`,`Capture publication requires an agent token.`,`Run enhance auth login, then retry the same manifest.`);let r=ki({apiUrl:t.apiUrl,token:n});try{t.output.result(await r.captures.publishManifest(e))}catch(t){throw Ai(t,e)}})},Mi={"canvas chats":`Chat history.`,"canvas.createEditableFrame":`Make a screen editable.`,"canvas.create":`Create a canvas.`,"canvas.get":`Read a canvas and access.`,"canvas.setAccess":`Change canvas link access.`,"canvas.markViewed":`Mark a canvas as viewed.`,"canvas.list":`List canvases.`,"canvas.rename":`Rename a canvas.`,"canvas.setReviewState":`Set review state.`,"canvas.delete":`Bin a canvas.`,"canvas.move":`Move between shelves.`,"canvas.duplicate":`Copy a canvas.`,"canvas.deletePermanently":`Permanently delete a canvas.`,"canvas.restore":`Restore a binned canvas.`,"canvas.inspect":`Inspect a canvas.`,"canvas.tree":`Read the node hierarchy.`,"canvas.node":`Read a node and children.`,"canvas.selection":`Read the live selection.`,"canvas asset":`Manage uploaded assets.`,"canvas mutation":`Read mutation receipts.`,"canvas apply":`Apply canvas operations.`,"canvas find":`Find accessible canvases.`,"canvas remove":`Remove scoped subtrees.`,"canvas read":`Read linked content.`,"canvas update-html":`Update an HTML snapshot.`,"canvas publish-prototype":`Publish a static build.`,"canvas import-asset":`Import an image or font.`,"canvas insert-html":`Insert compiled HTML.`,"canvas make-editable":`Convert a captured screen.`,"canvas capture":`Capture a recording moment.`,"canvas arrange":`Arrange canvas objects.`,"canvas duplicate-nodes":`Duplicate node subtrees.`,"canvas text-style-library":`Manage text styles.`,"canvas realtime":`Canvas presence and activity.`,"canvas document":`Read or replace documents.`,"canvas version":`Retained canvas history.`,"canvas render":`Render canvas pixels.`,"canvas participants":`Manage participants.`,"canvas invites":`Invite people to a canvas.`},Ni=(e,t=!1)=>{let n=Symbol(`explicit-null`),r=e.parseArg;return r===void 0?()=>!1:(e.argParser((e,i)=>{if(t&&e===`null`)return n;try{return r(e,i)}catch(t){try{return r(JSON.stringify(e),i)}catch{throw t}}}),e=>e===n)},Pi=()=>({exit:e=>{throw new p(e)}}),Fi={"canvas text-style-library":`Find, read, and publish reusable text styles across canvases.`,"canvas chats":`Inspect and manage authorized canvas chat history.`,canvas:`Create, find, share and manage canvases.`,"canvas render":`Render production-faithful canvas pixels after inspecting exact structure and geometry.`,"canvas version":`Inspect and name retained canvas history.`,"canvas document":`Read or replace the opaque document stored on a canvas.`,"canvas invites":`Invite people to a canvas and manage pending invitations.`,"canvas participants":`List and change the people who can reach a canvas.`,comment:`Comment threads and replies anchored to canvas content.`,organisation:`Teams the authenticated person belongs to or creates.`,"organisation invites":`Invite people to a team and manage pending invitations.`,"organisation people":`Team roster membership and roles.`,person:`The current person, sharing recipients, and agent tokens.`,"person recipients":`People available when choosing sharing recipients.`,recording:`Recorded walkthroughs, chunks, recovery, and completion.`,"recording-asset":`External page assets mirrored for durable replay.`,screen:`Captured pages uploaded for placement on a canvas.`},Ii=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),Li=new Set([`canvas.create --organisation-id`,`canvas.create --source-url`,`recording.start --audio`,`recording.start --page-title`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`]),Ri=new Set([`comment.resolve --resolved`,`recording.start --page-title`,`recording.start --viewport`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`,`screen.create --viewport`]),zi=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Bi=e=>{let t=zi(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},Vi=(e,t,n,r)=>{let i=t.long,a=Bi(e)??r.join(` `),o=a===``||i===void 0?void 0:g[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&g[i]!==void 0)return g[i];let s=(n.split(/Any of:|One of:/u,1)[0]?.trim()??``).split(`;`).map(e=>e.trim()).filter(e=>e!==``&&[`Format:`,`Pattern:`,`Min length:`,`Max length:`].every(t=>!e.startsWith(t))).join(`; `);return s===``?`Value for ${i??t.attributeName()} on ${e.name()}.`:s},Hi=(e,t,n)=>{let r=Pi();e.exitOverride(e=>r.exit(e.exitCode)),e.configureOutput({writeOut:e=>t.output.logger.info?.(e),writeErr:e=>t.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let i=[],a=[];for(let t of e.options){let r=Bi(e)??n.join(` `);Ri.has(`${r} ${t.long??``}`)&&a.push({flag:t.long??``,name:t.attributeName()});let o=Li.has(`${r} ${t.long??``}`),s=Ni(t,o);o&&i.push({name:t.attributeName(),matches:s}),t.description=Vi(e,t,t.description,n)}i.length>0&&e.hook(`preAction`,e=>{for(let t of i)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),a.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let t=a.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(t!==void 0)throw new d(`BAD_REQUEST`,`${t.flag} is required unless --json supplies the complete input.`,`Pass ${t.flag} explicitly, including false or null when that is the intended value.`)})},Ui=(e,t,n,r)=>{(n!==null&&r.mutationPaths.has(n)||t[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,g[`--client-token`]),e.hook(`preAction`,e=>{let n=e.getOptionValue(`clientToken`),i=S.uuid().nullable().safeParse(n??null);if(!i.success)throw new d(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);r.mutationKey.select(i.data,t[0]===`fixture`)}))},Wi=(e,t,n)=>{n===null||!Ii.has(n)||(e.options.find(e=>e.long===`--token`)?.makeOptionMandatory(!1),e.hook(`preAction`,async e=>{let n=e.getOptionValue(`token`);if(n===void 0&&e.getOptionValue(`json`)!==void 0)return;let r=await Ft(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},Gi=(e,t,n,r)=>{let i=Fi[t.join(` `)];i===void 0?n!==null&&e.description(se[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=Mi[t.join(` `)]??(n===null?void 0:Mi[n]);a!==void 0&&e.summary(a)},Ki=(e,t,n=[])=>{Hi(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=Bi(r);Ui(r,e,i,t),Gi(r,e,i,t.descriptions),Wi(r,e,i),Ki(r,t,e)}},qi=ge().excludedProcedures,Ji=new Set([`canvas thumbnail`,`canvas font-catalog`,`telemetry`]),Yi=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},Xi=(e,t=[])=>{let n=e.commands.filter(e=>{let n=Yi(e),r=[...t,e.name()].join(` `);return!Ji.has(r)&&(n===null||!qi.has(n))});Reflect.set(e,`commands`,n);for(let e of n)Xi(e,[...t,e.name()])},Zi=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},Qi=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=Zi(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...Qi(e,n)]}),$i=(e,t,n)=>{e.command(`commands`).description(`Emit the command inventory as NDJSON without walking the help tree.`).option(`--namespace <path>`,`Keep commands at or below this space-separated path.`).option(`--capabilities`,`Emit the transport-neutral capability inventory.`,!1).option(`--reference`,`Emit complete shared capability contracts for documentation.`,!1).action(r=>{if(r.reference){let e=he(n()),r=ke(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:Je(n()),truncated:!1});return}let i=r.namespace?.trim(),a=Qi(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},ea=(e,t,n,r)=>{let i=e.commands.find(e=>e.name()===`comment`);if(i===void 0)throw TypeError(`derived comment namespace is missing`);i.command(`attention`).description(`List every open comment needing attention; source metadata is included when a capture has it.`).argument(`<canvas-url-or-id>`,`A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID.`).action(async e=>{r.result(await t.invoke({capability:b(n(),`comment.attention`),arguments:{canvasId:v(e)},clientToken:null}))})},ta=(e,t)=>{let{version:n,credentials:r,remote:i,output:a}=t;e.command(`doctor`).description(`Check the installed binary, API reachability, and credential file without changes.`).action(async()=>{let[e,t]=await Promise.all([i.health(),r.read()]);a.result({status:t!==null&&e.reachable?`ok`:`degraded`,binary:x.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},na=e=>S.coerce.number().int().positive().parse(e),ra=S.record(S.string(),S.unknown()),ia=(e,t)=>{let n=ra.safeParse(e);if(!n.success)return 0;let r=n.data.atMs;if(typeof r==`number`&&Number.isFinite(r))return Math.max(0,Math.round(r));let i=n.data.timestamp;return typeof i==`number`&&Number.isFinite(i)?Math.max(0,Math.round(i-t)):0},aa=async e=>{let t=(await D(e,`utf8`)).split(`
|
|
21
|
-
`).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>
|
|
20
|
+
`).action(async e=>{let n=Mr(e);if(n===null)return Vr(e,t);t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`canvas.render`),...n}))})},Ur=(e,t)=>{let n=e.commands.find(e=>e.name()===`canvas`);if(n===void 0)throw TypeError(`the API router did not supply canvas commands`);n.configureHelp({subcommandTerm:e=>e.name()});let r=n.commands.find(e=>e.name()===`render`);if(r===void 0)throw TypeError(`the API router did not supply canvas render`);let i=Ue(t.remote,je(t.configDirectory),t.now,t.output.result);on(n,t),Dr(n,{...t,render:i}),jr(n,t),Hr(r,t)},V=C.string().trim().min(1).max(160),H=C.string().regex(/^[a-f0-9]{64}$/u),U=C.number().int().positive(),Wr=C.strictObject({source:V,journey:V,step:V,variant:V}),W=C.strictObject({sha256:H,bytes:C.number().int().positive(),mediaType:C.string().min(1).max(200)}),Gr=C.strictObject({format:C.literal(`enhance-capture`),version:C.literal(1),key:Wr,label:V,journeyLabel:V,order:C.number().int().nonnegative(),viewport:C.strictObject({width:U,height:U,deviceScaleFactor:C.number().positive()}),extent:C.enum([`viewport`,`full-page`]),source:C.strictObject({format:C.literal(`rrweb-screen`),version:C.literal(1),blob:W}),preview:C.strictObject({blob:W,width:U,height:U,pixelRatio:C.number().positive()}),assets:C.array(C.strictObject({url:C.url(),blob:W})),provenance:C.strictObject({adapter:V,sdkVersion:V,kernelVersion:V,browser:V,capturedAt:C.iso.datetime(),sourceUrl:C.url().optional(),commit:C.string().min(1).max(200).optional()}),issues:C.array(C.strictObject({code:V,message:C.string().min(1).max(500)}))}).superRefine((e,t)=>{(e.preview.width/e.preview.pixelRatio!==e.viewport.width||e.preview.height/e.preview.pixelRatio!==e.viewport.height)&&t.addIssue({code:`custom`,path:[`preview`],message:`The preview and captured CSS extent must match.`}),e.source.blob.mediaType!==`application/json`&&t.addIssue({code:`custom`,path:[`source`,`blob`,`mediaType`],message:`Capture sources must be frozen JSON.`}),e.preview.blob.mediaType!==`image/png`&&t.addIssue({code:`custom`,path:[`preview`,`blob`,`mediaType`],message:`Capture previews must be PNG.`}),new Set(e.assets.map(e=>e.url)).size!==e.assets.length&&t.addIssue({code:`custom`,path:[`assets`],message:`Capture resource URLs must be unique.`})}),G=C.strictObject({id:C.uuid(),canvasId:C.uuid(),source:V,runKey:V,generation:C.number().int().nonnegative(),participants:C.array(V).min(1),expiresAt:C.iso.datetime(),formatVersion:C.literal(1)}),Kr=C.strictObject({participant:V,testId:V,project:V,retry:C.number().int().nonnegative(),status:C.enum([`passed`,`failed`,`skipped`,`interrupted`,`timedOut`]),captures:C.array(Gr)}),qr=C.strictObject({format:C.literal(`enhance-capture-run`),version:C.literal(1),run:G,participants:C.array(C.strictObject({id:V,status:C.enum([`passed`,`failed`,`interrupted`])})).min(1),attempts:C.array(Kr),ordering:C.enum([`partial`,`complete`])}),Jr=C.strictObject({runId:C.uuid(),canvasId:C.uuid(),canvasUrl:C.url(),version:C.number().int().positive(),manifestDigest:H,frames:C.array(C.strictObject({key:Wr,frameId:V,captureId:C.uuid()})),issues:C.array(C.strictObject({code:V,message:C.string().max(500)}))}),Yr=C.strictObject({canvasId:C.uuid(),source:V.default(`default`),runKey:V,participants:C.array(V).min(1).default([`local`]),formatVersion:C.literal(1).default(1)}),Xr=C.strictObject({run:G});C.strictObject({runId:C.uuid()});const Zr=C.enum([`collecting`,`sealed`,`converting`,`committed`,`failed`,`cancelled`]),K=C.strictObject({run:G,state:Zr,receipt:Jr.nullable(),failure:C.strictObject({code:V,message:C.string().max(1e3)}).nullable()});C.strictObject({runId:C.uuid(),blobs:C.array(W).min(1).max(400)});const Qr=C.strictObject({uploads:C.array(C.strictObject({sha256:H,upload:C.strictObject({url:C.url(),headers:C.record(C.string(),C.string()),expiresAt:C.iso.datetime()}).nullable()})).max(400)});C.strictObject({manifest:qr}),C.strictObject({canvasId:C.uuid(),frameId:C.string().min(1),captureId:C.uuid()});const $r=C.strictObject({captureId:C.uuid(),capturedAt:C.iso.datetime(),commit:C.string().max(200).optional(),url:C.string().min(1),width:C.number().positive(),height:C.number().positive(),pixelRatio:C.number().positive()});C.strictObject({frameId:C.string(),before:$r,after:$r});const ei=e=>JSON.stringify([e.source,e.journey,e.step,e.variant]),q=(e,t)=>e<t?-1:e===t?0:1,ti=(e,t)=>{let n=Object.keys(e).toSorted(q);t.output.push(`{`),t.pending.push({text:`}`});for(let r=n.length-1;r>=0;r--){let i=n[r];i!==void 0&&(t.pending.push({value:Reflect.get(e,i)},{text:`${JSON.stringify(i)}:`}),r>0&&t.pending.push({text:`,`}))}},ni=(e,t)=>{if(e===null||typeof e==`boolean`||typeof e==`string`||typeof e==`number`&&Number.isFinite(e))return t.output.push(JSON.stringify(e)),!0;if(typeof e!=`object`||t.active.has(e)||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype)return!1;if(t.active.add(e),t.pending.push({leave:e}),Array.isArray(e)){t.output.push(`[`),t.pending.push({text:`]`});for(let n=e.length-1;n>=0;n--)t.pending.push({value:e[n]}),n>0&&t.pending.push({text:`,`})}else ti(e,t);return!0},J=e=>{let t={pending:[{value:e}],active:new Set,output:[]};for(;t.pending.length>0;){let e=t.pending.pop();if(e===void 0)break;if(`text`in e)t.output.push(e.text);else if(`leave`in e)t.active.delete(e.leave);else if(!ni(e.value,t))return null}return t.output.join(``)},ri=e=>{let t=new Map,n=[];for(let r of e){let e=[r.source.blob,r.preview.blob,...r.assets.map(e=>e.blob)];for(let r of e){let e=t.get(r.sha256);if(e!==void 0&&J(e)!==J(r))return`The same capture digest has conflicting blob metadata.`;e===void 0&&(n.push(r),t.set(r.sha256,r))}}return n.toSorted((e,t)=>q(e.sha256,t.sha256))},ii=e=>{let t=new Set(e.run.participants);if(t.size!==e.run.participants.length||e.participants.length!==t.size||new Set(e.participants.map(e=>e.id)).size!==t.size||e.participants.some(e=>!t.has(e.id)||e.status!==`passed`))return`Every reserved participant must finish successfully exactly once.`;let n=new Map,r=new Map;for(let i of e.attempts){if(!t.has(i.participant))return`Capture attempt belongs to an unreserved participant.`;let e=JSON.stringify([i.participant,i.project,i.testId]),a=JSON.stringify([e,i.retry]),o=J(i);if(o===null)return`Capture attempts must contain finite JSON values.`;let s=r.get(a);if(s!==void 0&&s!==o)return`Conflicting terminal records for the same test attempt.`;r.set(a,o);let c=n.get(e);(c===void 0||c.retry<i.retry)&&n.set(e,i)}return e.attempts.filter(e=>n.get(JSON.stringify([e.participant,e.project,e.testId]))===e)},ai=(e,t)=>{let n=new Set,r=new Set;for(let i of t){if(i.key.source!==e)return`Capture source differs from its reserved run.`;let t=ei(i.key);if(n.has(t))return`Duplicate capture key: ${t}`;let a=JSON.stringify([i.key.journey,i.key.variant,i.order]);if(r.has(a))return`Duplicate step order in journey ${i.key.journey}.`;n.add(t),r.add(a)}return null},oi=(e,t)=>{let n=q(e.key.journey,t.key.journey);if(n!==0)return n;let r=q(e.key.variant,t.key.variant);return r===0?e.order-t.order:r},si=e=>{let t=qr.safeParse(e);if(!t.success)return`Invalid capture manifest.`;let n=t.data,r=ii(n);if(typeof r==`string`)return r;let i=r.flatMap(e=>e.status===`passed`?e.captures:[]);if(i.length===0)return`A run must contain at least one successful capture.`;let a=ai(n.run.source,i);if(a!==null)return a;let o=ri(i);return typeof o==`string`?o:i.toSorted(oi)},ci=e=>{let t=J(e);return t===null?null:`enhance-capture-run:v1\0${t}`},Y=(e,t,n)=>Object.assign(Error(t),{code:e,...n!==void 0&&{runId:n}}),li=e=>E(`sha256`).update(e).digest(`hex`),ui=e=>{let t=ci(e);if(t===null)throw Error(`A capture manifest must contain only finite JSON values.`);return E(`sha256`).update(t).digest(`hex`)},di=(e,t)=>{if(!/^[a-f0-9]{64}$/u.test(t))throw Y(`artifact`,`Invalid capture blob digest.`);return T.join(T.resolve(e),`blobs`,t)},X=async(e,t)=>{let n=di(e,t.sha256),r=await lt(n);if(!r.isFile()||r.size!==t.bytes)throw Y(`artifact`,`Capture blob size does not match ${t.sha256}.`);let i=await O(n);if(li(i)!==t.sha256)throw Y(`artifact`,`Capture blob checksum does not match ${t.sha256}.`);return i},fi=async(e,t)=>{let n=Gr.parse(t.artifact);await st(T.join(e,`blobs`),{recursive:!0});let r=0;for(let n of t.blobs)try{if(n.description.bytes!==n.bytes.byteLength||li(n.bytes)!==n.description.sha256)throw Y(`artifact`,`Capture blob bytes do not match their descriptor.`);let t=di(e,n.description.sha256),r=`${t}.${globalThis.crypto.randomUUID()}.tmp`;await ut(r,n.bytes,{flag:`wx`,mode:384}),await ct(r,t)}catch{r++}try{await X(e,n.source.blob)}catch{await X(e,n.preview.blob)}return r>0&&dt(`enhance.capture.resources`).publish({stage:`local-write`,unavailable:r}),n},Z=async(e,t)=>{let n=`${e}.${globalThis.crypto.randomUUID()}.tmp`;await ut(n,JSON.stringify(t),{mode:384}),await ct(n,e)},pi=async e=>{let t=JSON.parse(await O(e,`utf8`));return qr.parse(t)},mi=async e=>{if(e.held===void 0)throw Y(`transport`,`Enhance omitted a requested blob reservation.`,e.runId);let t=e.held.upload;if(t===null)return;let n=await X(e.directory,e.blob);try{if(!(await fetch(t.url,{method:`PUT`,headers:t.headers,body:new Blob([Uint8Array.from(n)]),signal:AbortSignal.timeout(e.transport.timeoutMs),redirect:`error`})).ok)throw Y(`transport`,`Upload refused.`,e.runId)}catch{throw Y(`transport`,`Capture upload was not confirmed. Resume the same manifest.`,e.runId)}},hi=async(e,t,n,r)=>{let i=0,a=[];for(let e of r)try{await X(n,e),a.push(e)}catch{i++}for(let r=0;r<a.length;r+=400){let o=a.slice(r,r+400),s=await e.request(`captureRun.reserveAssets`,{runId:t.run.id,blobs:o},Qr),c=new Map(s.uploads.map(e=>[e.sha256,e]));for(let r of o)try{await mi({transport:e,runId:t.run.id,directory:n,blob:r,held:c.get(r.sha256)})}catch{i++}}i>0&&dt(`enhance.capture.resources`).publish({stage:`upload`,runId:t.run.id,unavailable:i})},gi=async(e,t)=>{let n=await e.request(`captureRun.publish`,{runId:t},K),r=Date.now()+e.publicationTimeoutMs;for(;n.receipt===null&&n.failure===null&&![`cancelled`,`failed`].includes(n.state);){if(Date.now()>=r)throw Y(`transport`,`Capture run ${t} is still processing. Resume the same manifest.`,t);await new Promise(e=>{setTimeout(e,250)}),n=await e.request(`captureRun.publish`,{runId:t},K)}if(n.receipt===null)throw Y(n.failure?.code===`conflict`?`conflict`:`conversion`,n.failure?.message??`The capture run was cancelled.`,t);return n.receipt},_i=(e,t)=>{if(e.runId!==t.run.id||e.canvasId!==t.run.canvasId||e.manifestDigest!==ui(t))throw Y(`conflict`,`This run committed a different manifest.`,t.run.id);return e},vi=async(e,t,n)=>{let r=si(t);if(typeof r==`string`)throw Y(`artifact`,r);let i=ri(r);if(typeof i==`string`)throw Y(`artifact`,i);let a=await e.request(`captureRun.get`,{runId:t.run.id},K,!0);if(a.receipt!==null){let e=_i(a.receipt,t);return await Z(T.join(n,`receipt.json`),e),e}a.state===`collecting`&&await hi(e,t,n,i),await e.request(`captureRun.seal`,{manifest:t},K);let o=_i(await gi(e,t.run.id),t);return await Z(T.join(n,`receipt.json`),o),o},yi=async(e,t,n)=>{try{return await vi(e,t,n)}catch(e){throw e instanceof Error?Object.assign(e,{runId:t.run.id}):Y(`transport`,`Capture publication was not confirmed. Resume the same manifest.`,t.run.id)}},bi=new Map([[401,`authorization`],[403,`authorization`],[409,`conflict`],[400,`artifact`]]),xi=async(e,t,n,r)=>{try{for(;;){let i=await fetch(e,{...t,signal:AbortSignal.timeout(n)});if(i.status!==429)return i;let a=i.headers.get(`retry-after`);if(a===null)return i;let o=Number(a),s=Number.isFinite(o)?o*1e3:Date.parse(a)-Date.now();if(!Number.isFinite(s)||s<0||Date.now()+s>=r)return i;await i.body?.cancel(),await ot(s)}}catch{throw Y(`transport`,`Enhance did not confirm the request. Resume the same run to recover its result.`)}},Si=async e=>{try{return await e.json()}catch{return null}},Ci=async(e,t,n,r)=>{let{procedure:i,timeoutMs:a,publicationTimeoutMs:o}=r,s=await xi(e,t,a,Date.now()+o),c=await Si(s);if(!s.ok){let e=typeof c==`object`&&c?Reflect.get(c,`error`):null,t=typeof e==`object`&&e?Reflect.get(e,`message`):null;throw Y(bi.get(s.status)??`transport`,typeof t==`string`?t.slice(0,1e3):`Enhance rejected ${i} (HTTP ${String(s.status)}).`)}let l=typeof c==`object`&&c?Reflect.get(c,`result`):null,u=typeof l==`object`&&l?Reflect.get(l,`data`):void 0,d=n.safeParse(u);if(!d.success)throw Y(`transport`,`Enhance returned an incompatible ${i} response.`);return d.data},wi=e=>{let t=URL.parse(e.apiUrl);if(t===null||![`http:`,`https:`].includes(t.protocol)||t.username!==``||t.password!==``||e.token.trim()===``)throw Y(`configuration`,`Enhance needs an HTTP API URL and an explicit token.`);let n=e.timeoutMs??3e4,r=e.publicationTimeoutMs??6e5;if(!Number.isSafeInteger(r)||r<1)throw Y(`configuration`,`Enhance publication timeout must be a positive integer in milliseconds.`);if(!Number.isSafeInteger(n)||n<1||n>2147483647)throw Y(`configuration`,`Enhance timeout must fit the Node timer range of 1 to 2147483647 milliseconds.`);return{timeoutMs:n,publicationTimeoutMs:r,request:async(i,a,o,s=!1)=>{let c=new URL(`${t.pathname.replace(/\/$/u,``)}/trpc/${i}`,t.origin);return s&&c.searchParams.set(`input`,JSON.stringify(a)),Ci(c,{method:s?`GET`:`POST`,headers:{authorization:`Bearer ${e.token}`,"content-type":`application/json`},...!s&&{body:JSON.stringify(a)},redirect:`error`},o,{procedure:i,timeoutMs:n,publicationTimeoutMs:r})}}},Ti=(e,t)=>{let n=e.participants[0];if(n===void 0)throw Y(`configuration`,`No capture participant was reserved.`);return{format:`enhance-capture-run`,version:1,run:e,ordering:`partial`,participants:[{id:n,status:`passed`}],attempts:[{participant:n,testId:`node`,project:`node`,retry:0,status:`passed`,captures:t}]}},Ei=(e,t,n)=>{let r=G.parse(t),i=[],a=!1;return{descriptor:r,directory:n,add:async e=>{if(a)throw Y(`configuration`,`This run no longer accepts captures.`);let t=fi(n,e);i.push(t),await t},publish:async()=>{a=!0;let t=await Promise.all(i);if(r.participants.length!==1)throw Y(`configuration`,`Multi-participant runs must publish a complete merged manifest.`);let o=Ti(r,t),s=si(o);if(typeof s==`string`)throw Y(`artifact`,s);return await st(n,{recursive:!0}),await Z(T.join(n,`manifest.json`),o),yi(e,o,n)},cancel:async()=>(a=!0,(await e.request(`captureRun.cancel`,{runId:r.id},K)).receipt)}},Di=e=>{let t=wi(e);return{captures:{begin:async e=>{let n=Yr.parse({canvasId:e.canvas,source:e.source,runKey:e.runKey,participants:e.participants}),{run:r}=await t.request(`captureRun.begin`,n,Xr),i=e.directory??T.join(`.enhance`,`captures`,r.id);return await st(i,{recursive:!0}),await Z(T.join(i,`run.json`),r),Ei(t,r,i)},publishManifest:async e=>yi(t,await pi(e),T.dirname(e)),get:async e=>t.request(`captureRun.get`,{runId:e},K,!0)}}},Oi=(e,t)=>{let n=e instanceof Error?Reflect.get(e,`code`):void 0;return new r(n===`authorization`?`UNAUTHORIZED`:n===`conflict`?`CONFLICT`:[`configuration`,`artifact`].includes(String(n))?`BAD_REQUEST`:`INTERNAL`,e instanceof Error?e.message:`Capture publication was not confirmed.`,`Retry enhance captures publish with the same manifest: ${t}`)},ki=(e,t)=>{e.command(`captures`).description(`Publish SDK captures as editable canvas journeys.`).command(`publish <manifest>`).description(`Publish or resume a reserved capture manifest and print its durable receipt.`).action(async e=>{let n=await t.credentials.read();if(n===null)throw new r(`UNAUTHORIZED`,`Capture publication requires an agent token.`,`Run enhance auth login, then retry the same manifest.`);let i=Di({apiUrl:t.apiUrl,token:n});try{t.output.result(await i.captures.publishManifest(e))}catch(t){throw Oi(t,e)}})},Ai={"canvas chats":`Chat history.`,"canvas.createEditableFrame":`Make a screen editable.`,"canvas.create":`Create a canvas.`,"canvas.get":`Read a canvas and access.`,"canvas.setAccess":`Change canvas link access.`,"canvas.markViewed":`Mark a canvas as viewed.`,"canvas.list":`List canvases.`,"canvas.rename":`Rename a canvas.`,"canvas.setReviewState":`Set review state.`,"canvas.delete":`Bin a canvas.`,"canvas.move":`Move between shelves.`,"canvas.duplicate":`Copy a canvas.`,"canvas.deletePermanently":`Permanently delete a canvas.`,"canvas.restore":`Restore a binned canvas.`,"canvas.inspect":`Inspect a canvas.`,"canvas.tree":`Read the node hierarchy.`,"canvas.node":`Read a node and children.`,"canvas.selection":`Read the live selection.`,"canvas asset":`Manage uploaded assets.`,"canvas mutation":`Read mutation receipts.`,"canvas apply":`Apply canvas operations.`,"canvas find":`Find accessible canvases.`,"canvas remove":`Remove scoped subtrees.`,"canvas read":`Read linked content.`,"canvas update-html":`Update an HTML snapshot.`,"canvas publish-prototype":`Publish a static build.`,"canvas import-asset":`Import an image or font.`,"canvas insert-html":`Insert compiled HTML.`,"canvas make-editable":`Convert a captured screen.`,"canvas capture":`Capture a recording moment.`,"canvas arrange":`Arrange canvas objects.`,"canvas duplicate-nodes":`Duplicate node subtrees.`,"canvas text-style-library":`Manage text styles.`,"canvas realtime":`Canvas presence and activity.`,"canvas document":`Read or replace documents.`,"canvas version":`Retained canvas history.`,"canvas render":`Render canvas pixels.`,"canvas participants":`Manage participants.`,"canvas invites":`Invite people to a canvas.`},ji=(e,t=!1)=>{let n=Symbol(`explicit-null`),r=e.parseArg;return r===void 0?()=>!1:(e.argParser((e,i)=>{if(t&&e===`null`)return n;try{return r(e,i)}catch(t){try{return r(JSON.stringify(e),i)}catch{throw t}}}),e=>e===n)},Mi=()=>({exit:e=>{throw new g(e)}}),Ni={"canvas text-style-library":`Find, read, and publish reusable text styles across canvases.`,"canvas chats":`Inspect and manage authorized canvas chat history.`,canvas:`Create, find, share and manage canvases.`,"canvas render":`Render production-faithful canvas pixels after inspecting exact structure and geometry.`,"canvas version":`Inspect and name retained canvas history.`,"canvas document":`Read or replace the opaque document stored on a canvas.`,"canvas invites":`Invite people to a canvas and manage pending invitations.`,"canvas participants":`List and change the people who can reach a canvas.`,comment:`Comment threads and replies anchored to canvas content.`,organisation:`Teams the authenticated person belongs to or creates.`,"organisation invites":`Invite people to a team and manage pending invitations.`,"organisation people":`Team roster membership and roles.`,person:`The current person, sharing recipients, and agent tokens.`,"person recipients":`People available when choosing sharing recipients.`,recording:`Recorded walkthroughs, chunks, recovery, and completion.`,"recording-asset":`External page assets mirrored for durable replay.`,screen:`Captured pages uploaded for placement on a canvas.`},Pi=new Set([`canvas.invites.accept`,`canvas.invites.preview`,`organisation.invites.accept`,`organisation.invites.preview`]),Fi=new Set([`canvas.create --organisation-id`,`canvas.create --source-url`,`recording.start --audio`,`recording.start --page-title`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`]),Ii=new Set([`comment.resolve --resolved`,`recording.start --page-title`,`recording.start --viewport`,`screen.create --page-title`,`screen.create --provenance`,`screen.create --route`,`screen.create --viewport`]),Li=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Ri=e=>{let t=Li(Reflect.get(e,`__trpcCli`)),n=t===null?void 0:t.path;return typeof n==`string`?n:null},zi=(e,t,n,r)=>{let i=t.long,a=Ri(e)??r.join(` `),o=a===``||i===void 0?void 0:_[`${a} ${i}`];if(o!==void 0)return o;if(i!==void 0&&_[i]!==void 0)return _[i];let s=(n.split(/Any of:|One of:/u,1)[0]?.trim()??``).split(`;`).map(e=>e.trim()).filter(e=>e!==``&&[`Format:`,`Pattern:`,`Min length:`,`Max length:`].every(t=>!e.startsWith(t))).join(`; `);return s===``?`Value for ${i??t.attributeName()} on ${e.name()}.`:s},Bi=(e,t,n)=>{let i=Mi();e.exitOverride(e=>i.exit(e.exitCode)),e.configureOutput({writeOut:e=>t.output.logger.info?.(e),writeErr:e=>t.output.logger.error?.(e)}),e.showHelpAfterError(!1).showSuggestionAfterError(!1);let a=[],o=[];for(let t of e.options){let r=Ri(e)??n.join(` `);Ii.has(`${r} ${t.long??``}`)&&o.push({flag:t.long??``,name:t.attributeName()});let i=Fi.has(`${r} ${t.long??``}`),s=ji(t,i);i&&a.push({name:t.attributeName(),matches:s}),t.description=zi(e,t,t.description,n)}a.length>0&&e.hook(`preAction`,e=>{for(let t of a)t.matches(e.getOptionValue(t.name))&&e.setOptionValueWithSource(t.name,null,`cli`)}),o.length>0&&e.hook(`preAction`,e=>{if(e.getOptionValueSource(`json`)===`cli`)return;let t=o.find(({name:t})=>e.getOptionValueSource(t)!==`cli`);if(t!==void 0)throw new r(`BAD_REQUEST`,`${t.flag} is required unless --json supplies the complete input.`,`Pass ${t.flag} explicitly, including false or null when that is the intended value.`)})},Vi=(e,t,n,i)=>{(n!==null&&i.mutationPaths.has(n)||t[0]===`fixture`)&&(e.options.every(e=>e.long!==`--client-token`)&&e.option(`--client-token <uuid>`,_[`--client-token`]),e.hook(`preAction`,e=>{let n=e.getOptionValue(`clientToken`),a=C.uuid().nullable().safeParse(n??null);if(!a.success)throw new r(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact command.`);i.mutationKey.select(a.data,t[0]===`fixture`)}))},Hi=(e,t,n)=>{n===null||!Pi.has(n)||(e.options.find(e=>e.long===`--token`)?.makeOptionMandatory(!1),e.hook(`preAction`,async e=>{let n=e.getOptionValue(`token`);if(n===void 0&&e.getOptionValue(`json`)!==void 0)return;let r=await Ft(typeof n==`string`?n:void 0,`enhance ${t.join(` `)}`);e.setOptionValueWithSource(`token`,r,`cli`)}))},Ui=(e,t,n,r)=>{let i=Ni[t.join(` `)];i===void 0?n!==null&&e.description(le[n]??r.get(n)??`Run the ${n} API operation.`):e.description(i);let a=Ai[t.join(` `)]??(n===null?void 0:Ai[n]);a!==void 0&&e.summary(a)},Wi=(e,t,n=[])=>{Bi(e,t,n);for(let r of e.commands){let e=[...n,r.name()],i=Ri(r);Vi(r,e,i,t),Ui(r,e,i,t.descriptions),Hi(r,e,i),Wi(r,t,e)}},Gi=be().excludedProcedures,Ki=new Set([`canvas thumbnail`,`canvas font-catalog`,`telemetry`]),qi=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},Ji=(e,t=[])=>{let n=e.commands.filter(e=>{let n=qi(e),r=[...t,e.name()].join(` `);return!Ki.has(r)&&(n===null||!Gi.has(n))});Reflect.set(e,`commands`,n);for(let e of n)Ji(e,[...t,e.name()])},Yi=e=>{let t=Reflect.get(e,`__trpcCli`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,`path`);return typeof n==`string`?n:null},Xi=(e,t=[])=>e.commands.filter(e=>e.name()!==`help`).flatMap(e=>{let n=[...t,e.name()],r=Yi(e);return[{path:n.join(` `),procedure:r,description:e.description(),kind:r===null?e.commands.length>0?`namespace`:`utility`:`derived`,helpCharacters:e.helpInformation().length},...Xi(e,n)]}),Zi=(e,t,n)=>{e.command(`commands`).description(`Emit the command inventory as NDJSON without walking the help tree.`).option(`--namespace <path>`,`Keep commands at or below this space-separated path.`).option(`--capabilities`,`Emit the transport-neutral capability inventory.`,!1).option(`--reference`,`Emit complete shared capability contracts for documentation.`,!1).action(r=>{if(r.reference){let e=ve(n()),r=ke(e);t.result({items:e.map(e=>r.describe(e.id)),truncated:!1});return}if(r.capabilities){t.result({items:Ge(n()),truncated:!1});return}let i=r.namespace?.trim(),a=Xi(e).filter(e=>i===void 0||e.path===i||e.path.startsWith(`${i} `));t.result({items:a,truncated:!1})})},Qi=(e,t,n,r)=>{let i=e.commands.find(e=>e.name()===`comment`);if(i===void 0)throw TypeError(`derived comment namespace is missing`);i.command(`attention`).description(`List every open comment needing attention; source metadata is included when a capture has it.`).argument(`<canvas-url-or-id>`,`A pasted Enhance canvas URL shaped /c/<UUID>, or a bare canvas UUID.`).action(async e=>{r.result(await t.invoke({capability:b(n(),`comment.attention`),arguments:{canvasId:o(e)},clientToken:null}))})},$i=(e,t)=>{let{version:n,credentials:r,remote:i,output:a}=t;e.command(`doctor`).description(`Check the installed binary, API reachability, and credential file without changes.`).action(async()=>{let[e,t]=await Promise.all([i.health(),r.read()]);a.result({status:t!==null&&e.reachable?`ok`:`degraded`,binary:S.argv[1]??`enhance`,version:n,api:e,credential:{path:r.path,present:t!==null}})})},ea=e=>C.coerce.number().int().positive().parse(e),ta=C.record(C.string(),C.unknown()),na=(e,t)=>{let n=ta.safeParse(e);if(!n.success)return 0;let r=n.data.atMs;if(typeof r==`number`&&Number.isFinite(r))return Math.max(0,Math.round(r));let i=n.data.timestamp;return typeof i==`number`&&Number.isFinite(i)?Math.max(0,Math.round(i-t)):0},ra=async e=>{let t=(await O(e,`utf8`)).split(`
|
|
21
|
+
`).filter(e=>e.trim()!==``).map(e=>JSON.parse(e)),n=t.map(e=>ta.safeParse(e).data?.timestamp).find(e=>typeof e==`number`&&Number.isFinite(e));return t.map(e=>({atMs:na(e,n??0),event:e}))},ia=async e=>({clientToken:e.clientToken??D(),body:await O(e.file),route:e.route??null,pageTitle:e.pageTitle??T.basename(e.file),viewport:{width:e.width,height:e.height},provenance:null}),aa=e=>e.option(`--width <pixels>`,`Captured viewport width.`,ea,1440).option(`--height <pixels>`,`Captured viewport height.`,ea,900),oa=(e,t,n)=>{aa(e.command(`screen`).description(`Upload one captured page and return its reusable screen id.`).requiredOption(`--file <path>`,`File containing the captured HTML bytes.`).option(`--client-token <uuid>`,`Stable UUID to reuse when retrying the same upload.`).option(`--route <url>`,`Original browser route, when it is safe to retain.`).option(`--page-title <title>`,`Captured page title.`)).action(async e=>{n.result(await t(await ia(e)))})},sa=(e,t,n)=>{aa(e.command(`recording`).description(`Upload NDJSON rrweb events as a walkthrough; chunk offsets start at the first event.`).requiredOption(`--file <path>`,'NDJSON with one rrweb event per line; minimum example: `{"type":2,"timestamp":1000}`.').requiredOption(`--source-url <url>`,`Required route the recording represents.`).option(`--page-title <title>`,`Title for a newly created walkthrough canvas.`).option(`--canvas-id <uuid>`,`Existing canvas to receive the walkthrough.`)).action(async e=>{n.result(await t({entries:await ra(e.file),sourceUrl:e.sourceUrl,pageTitle:e.pageTitle??null,viewport:{width:e.width,height:e.height},...e.canvasId!==void 0&&{canvasId:e.canvasId}}))})},ca=(e,t,n)=>{aa(e.command(`world`).description(`Create a team, a canvas, and zero or more attached screen fixtures.`).requiredOption(`--organisation-name <name>`,`Name of the team to create.`).requiredOption(`--canvas-title <title>`,`Title of the canvas to create.`).option(`--screen <path...>`,`Captured HTML files to upload and attach.`)).action(async e=>{let r=[],i=e.screen??[];for(let t of i)r.push(await ia({file:t,width:e.width,height:e.height}));n.result(await t({organisationName:e.organisationName,canvasTitle:e.canvasTitle,screens:r}))})},la=(e,t,n)=>{let r=e.command(`fixture`).description(`Build deterministic product fixtures.`);oa(r,t.screen,n),sa(r,t.recording,n),ca(r,t.world,n)},ua=(e,t)=>{e.command(`operation`).description(`Read existing domain-owned operation outcomes.`).command(`status`).description(`Recover an existing outcome without creating or resuming work.`).requiredOption(`--input <json-or-@path>`,`Operation reference and optional detail offset/limit.`).action(async e=>{t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`operation.status`),arguments:F(e.input,ee,`--input`),clientToken:null}))})},da=e=>C.coerce.number().parse(e),fa=e=>C.coerce.number().positive().parse(e),pa=e=>C.coerce.number().int().positive().parse(e),ma=(e,t,n,r)=>{(e.commands.find(e=>e.name()===`prototype`)??e.command(`prototype`).description(`Publish static frontend prototypes.`)).command(`publish`).description(`Package and publish an unpacked static build directory. The CLI creates the upload artifact.`).requiredOption(`--canvas-id <uuid>`,`Canvas that receives the prototype.`).requiredOption(`--directory <path>`,`Unpacked static build directory; do not pass a ZIP file.`).requiredOption(`--title <title>`,`Label above the prototype frame.`).requiredOption(`--base-version <number>`,`Current canvas document version.`,pa).option(`--prototype-id <uuid>`,`Existing prototype identity to publish a new deployment.`).option(`--client-token <uuid>`,`Stable retry token for this exact build.`).option(`--node-id <id>`,`Stable canvas node id for a new prototype.`).option(`--entry <path>`,`HTML entry relative to the uploaded directory.`,`index.html`).option(`--x <pixels>`,`Canvas x coordinate.`,da,48).option(`--y <pixels>`,`Canvas y coordinate.`,da,48).option(`--width <pixels>`,`Prototype viewport width.`,fa,1440).option(`--height <pixels>`,`Prototype viewport height.`,fa,900).action(async e=>{let i=e.clientToken??D();r.result(await t.invoke({capability:b(n(),`prototype.publish`),arguments:{canvasId:e.canvasId,prototypeId:e.prototypeId??null,nodeId:e.nodeId??`proto_${i.replaceAll(`-`,``)}`,title:e.title,directory:e.directory,entryPath:e.entry,baseVersion:e.baseVersion,box:{x:e.x,y:e.y,width:e.width,height:e.height}},clientToken:i}))})},ha=(e,t,n)=>{let i=(n?C.coerce.number().int().positive():C.coerce.number().int().nonnegative()).safeParse(e);if(!i.success)throw new r(`BAD_REQUEST`,`${t} is invalid.`,`Run 'enhance recording snapshot --help'.`);return i.data},ga=(e,t)=>{let n=e.commands.find(e=>e.name()===`recording`);if(n===void 0)throw TypeError(`the API router did not supply recording commands`);n.command(`snapshot`).description(`Persist one visually accepted recording moment as an ordinary screen and frame.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).requiredOption(`--at-ms <integer>`,`Accepted recording timestamp in milliseconds.`).option(`--timeout-ms <integer>`,`Local polling deadline in milliseconds.`,`120000`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact snapshot.`).addHelpText(`after`,`
|
|
22
22
|
Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
|
|
23
|
-
`).action(async e=>{let n=
|
|
24
|
-
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){
|
|
25
|
-
`)}\n`;
|
|
23
|
+
`).action(async e=>{let n=C.uuid().nullable().safeParse(e.clientToken??null),i=C.uuid().safeParse(e.recordingId);if(!n.success||!i.success)throw new r(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`recording.snapshot`),arguments:{canvasId:o(e.canvas),recordingId:i.data,atMs:ha(e.atMs,`--at-ms`,!1),timeoutMs:ha(e.timeoutMs,`--timeout-ms`,!0)},clientToken:n.data}))})},_a=(e,t,n)=>{if(e!==`canvas.document.save`||typeof n!=`object`||!n||!(`outcome`in n)||n.outcome!==`conflict`)return n;throw new r(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof t==`object`&&t&&`canvasId`in t&&typeof t.canvasId==`string`?t.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},va=(e,t)=>ft(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>_a(e,n,await t.mutate(e,n))}})),ya=(e,t)=>{let n=e.commands.find(e=>e.name()===`transcript`);if(n===void 0)throw TypeError(`the API router did not supply transcript commands`);n.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let n=C.uuid().safeParse(e.recordingId);if(!n.success)throw new r(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");t.output.result(await t.invocation.invoke({capability:b(t.catalog(),`transcript.read`),arguments:{canvasId:o(e.canvas),recordingId:n.data},clientToken:null}))})},ba={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},xa=e=>{let t=e.state;return{logger:e.output.logger,prompts:ba.prompts,process:Mi(),formatError:e=>{let n=m(e,t.pendingParserMessage);return t.exitCode=ge(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},Sa=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,Ca=e=>{let t=Sa(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},wa=e=>({descriptions:new Map(e.flatMap(([e,t])=>{let n=Ca(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(e.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}),Ta=()=>{let e=null;return()=>(e??=me(),e)},Ea=(e,t,n)=>{let r=Nt(t.remote),i=Be({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});Lt(e,We(t.credentials,t.remote,Le(t.remote)),t.output),Qi(e,i,n,t.output),ki(e,t),ua(e,{invocation:i,catalog:n,output:t.output}),$i(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),la(e,{screen:r,recording:jt(t.remote),world:Pt(t.remote,r)},t.output),Zi(e,t.output,n),Ur(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),ga(e,{invocation:i,catalog:n,output:t.output}),ma(e,i,n,t.output),ya(e,{invocation:i,catalog:n,output:t.output})},Da=e=>{let t=Je({router:Ce()}),n=Ta(),{descriptions:r,mutationPaths:i}=wa(t),a=qe({router:va(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:ba.jsonInput}),o=xa(e),s=a.buildProgram(o);if(!(s instanceof Ke))throw TypeError(`trpc-cli did not return a Commander program`);Ji(s),Ea(s,e,n),Wi(s,{descriptions:r,mutationPaths:i,mutationKey:e.mutationKey,output:e.output}),s.description(`Operate Enhance as the authenticated person.`);let c=e.state;return{program:s,run:async()=>{try{await a.run(o,s)}catch(t){if(!(t instanceof g))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=m(t,c.pendingParserMessage);c.exitCode=ge(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},Oa=e=>S.exit(e),ka=36e5,Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Aa=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!Q(e)||!Array.isArray(e.items)||`nextCursor`in e)return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(Q(e)?{...e,truncated:n}:{value:e,truncated:n}))},ja=e=>{let t=`${e.join(`
|
|
24
|
+
`)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){S.stdout.write(t);return}let n=E(`sha256`).update(t).digest(`hex`).slice(0,16),r=T.join(Xe(),`enhance-${n}.ndjson`);w(r,t,{mode:384}),S.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},Ma=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},Na=e=>typeof e==`string`?Ma(e):Array.isArray(e)?e.some(e=>Na(e)):Q(e)?Object.values(e).some(e=>Na(e)):!1,Pa=e=>{tt(e,{recursive:!0,mode:448}),Qe(e,448)},Fa=e=>{if(!$e(e))return;let t=Date.now()-ka,n=rt(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=T.join(e,r.name);et(n).mtimeMs<t&&at(n)}},$=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+ka).toISOString()}),Ia=(e,t)=>{let n=Aa(e),r=`${n.join(`
|
|
25
|
+
`)}\n`;Pa(t);let i=T.join(t,`result-${D()}.ndjson`);w(i,r,{mode:384,flag:`wx`}),S.stdout.write(`${JSON.stringify($({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},La=e=>Q(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,Ra=(e,t,n)=>{let r=`${t.value}\n`;Pa(n);let i=T.join(n,`result-${D()}.token`);w(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));S.stdout.write(`${JSON.stringify({...a,secret:$({path:i,field:t.field,characters:r.length})})}\n`)},za=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),Ba=u.omit({fields:!0}).extend({remediation:C.string(),fields:C.array(C.object({path:C.string(),message:C.string()})).optional()}),Va=e=>{try{let t=JSON.parse(e),n=Ba.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},Ha=(e,t)=>{if(typeof e==`string`&&za(e)){S.stdout.write(e);return}let n=La(e);if(n!==null&&Q(e)){Ra(e,n,t);return}if(Na(e)){Ia(e,t);return}let r=we(e);if(r!==null){let e=null;if(r.detail!==null){Pa(t);let n=T.join(t,`result-${D()}.ndjson`),i=`${JSON.stringify(r.detail)}\n`;w(n,i,{mode:384,flag:`wx`}),e=$({path:n,characters:i.length,records:1})}S.stdout.write(`${JSON.stringify({...r.value,...e!==null&&{detail:e}})}\n`);return}ja(Aa(e))},Ua=e=>{S.stderr.write(`${JSON.stringify(e)}\n`)},Wa=(e,t,n=`enhance`)=>{let r=e,i=T.join(t,`sensitive`);return Fa(i),{result:e=>{Ha(xe(e,n),i)},failure:e=>{Ua(Oe(e,n))},logger:{info:(...e)=>{Ha(xe(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(xe(e.map(String).join(``),n)),i=Va(t);i===null?r.pendingParserMessage=t:Ua(i)}}}};(async()=>{let e=Ne(),t={exitCode:1,pendingParserMessage:null},n=Wa(t,e.configDirectory,e.commandName),r=ze(e.configDirectory),i=Ve(),a=Ie(e.apiUrl,r,i),o=Da({apiUrl:e.apiUrl,version:`0.1.27-dev.sha-3dce62542ab4`,credentials:r,remote:a,mutationKey:i,output:n,state:t,configDirectory:e.configDirectory,commandName:e.commandName});try{await o.run()}catch(e){e instanceof g&&Oa(e.requestedCode===0?0:t.exitCode),n.failure(m(e,null)),Oa(1)}})().catch(e=>{S.stderr.write(`${e instanceof Error?e.message:`CLI startup failed.`}\n`),S.exitCode=1});export{};
|