agent-canvas 0.9.0-dev.14 → 0.9.0-dev.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,89 +1,89 @@
1
- var Y8=Object.defineProperty;var X8=($)=>$;function G8($,Q){this[$]=X8.bind(null,Q)}var _8=($,Q)=>{for(var J in Q)Y8($,J,{get:Q[J],enumerable:!0,configurable:!0,set:G8.bind(Q,J)})};import{ActiveViewCtx as Kq,SessionContext as e6}from"#canvas/runtime";import{AnnotationCtx as VX,AnnotationHostContext as CX,SessionContext as RX,useAnnotationHost as DX,useAnnotations as IX}from"@fabrika/annotations/runtime";function A1($,Q){let J=[],Y=j3($);for(let q of Y){let G=document.createRange();if(G.selectNodeContents(q),q===$.startContainer)G.setStart(q,$.startOffset);if(q===$.endContainer)G.setEnd(q,$.endOffset);let X=G.toString();if(!X||!X.trim())continue;let W=document.createElement("mark");W.setAttribute("data-annotation-id",Q);try{G.surroundContents(W)}catch{let _=G.extractContents();W.appendChild(_),G.insertNode(W)}J.push(W)}return J}function E0($){let Q=$.parentElement;if(Q?.classList.contains("select-none"))return!1;if(Q?.closest("[data-annotation-id]"))return!1;return!0}function j3($){let Q=[],J=$.commonAncestorContainer;if(J.nodeType===Node.TEXT_NODE)return Q.push(J),Q;let Y=document.createTreeWalker(J,NodeFilter.SHOW_TEXT),q;while(q=Y.nextNode()){if(!E0(q))continue;if($.intersectsNode(q))Q.push(q)}return Q}function W8($,Q){let J=document.createRange();if(J.selectNodeContents($),$===Q.startContainer)J.setStart($,Q.startOffset);if($===Q.endContainer)J.setEnd($,Q.endOffset);return J.toString()}function b3($){let Q="";for(let J of j3($))Q+=W8(J,$);return Q}function q0($,Q){let J=document.querySelectorAll(`[data-annotation-id="${$}"]`);for(let Y of J)Y.classList.toggle("mark-active",Q)}function v0($,Q){if(Q!=null&&Q!==$)q0(Q,!1);if($!=null)q0($,!0)}function g0($,Q){let J=document.querySelectorAll(`[data-annotation-id="${$}"]`);for(let Y of J)Y.setAttribute("data-annotation-id",Q)}function m0($,Q){for(let J of Q){if($.querySelector(`[data-annotation-id="${J.id}"]`))continue;let Y=J.snippet;if(!Y)continue;let{fullText:q,textNodes:G}=H8($),X=[],W=0;while(!0){let M=q.indexOf(Y,W);if(M===-1)break;X.push(M),W=M+1}let[_]=X;if(_===void 0)continue;let H=_;if(X.length>1&&J.context){let M=-1;for(let L of X){let F=0;if(J.context.before){let w=q.slice(Math.max(0,L-80),L);if(w.includes(J.context.before))F+=2;else if(J.context.before.length>10&&w.includes(J.context.before.slice(-10)))F+=1}if(J.context.after){let w=q.slice(L+Y.length,L+Y.length+80);if(w.includes(J.context.after))F+=2;else if(J.context.after.length>10&&w.includes(J.context.after.slice(0,10)))F+=1}if(F>M)M=F,H=L}}let U=H,K=H+Y.length,N=T3(G,U),O=T3(G,K);if(!N||!O)continue;try{let M=document.createRange();M.setStart(N.node,N.offset),M.setEnd(O.node,O.offset),A1(M,J.id)}catch{}}}function H8($){let Q=[],J="",Y=document.createTreeWalker($,NodeFilter.SHOW_TEXT),q;while(q=Y.nextNode()){if(!E0(q))continue;Q.push({node:q,start:J.length}),J+=q.textContent||""}return{fullText:J,textNodes:Q}}function T3($,Q){for(let J=$.length-1;J>=0;J--){let Y=$[J];if(!Y||Y.start>Q)continue;let q=Q-Y.start,G=Y.node.textContent?.length??0;if(q<=G)return{node:Y.node,offset:q}}return null}function x0($){let Q=document.querySelectorAll(`[data-annotation-id="${$}"]`);for(let J of Q){let Y=J.parentNode;if(!Y)continue;if(J.tagName!=="MARK"){Y.removeChild(J);continue}while(J.firstChild)Y.insertBefore(J.firstChild,J);Y.removeChild(J),Y.normalize()}}function P1($,Q){let J=Z3($,"before",60),Y=Z3($,"after",60),q=K8($.startContainer,Q);return{before:J,after:Y,hierarchy:q}}function Z3($,Q,J){let Y=U8(Q==="before"?$.startContainer:$.endContainer);if(!Y)return"";let q="";if(Q==="before"){let G=document.createTreeWalker(Y,NodeFilter.SHOW_TEXT),X;while(X=G.nextNode()){if(X===$.startContainer){q+=(X.textContent||"").slice(0,$.startOffset);break}if(!E0(X))continue;q+=X.textContent||""}if(q.length>J){q=q.slice(-J);let W=q.indexOf(" ");if(W>0)q=q.slice(W+1)}}else{let G=document.createTreeWalker(Y,NodeFilter.SHOW_TEXT),X=!1,W;while(W=G.nextNode()){if(W===$.endContainer){q+=(W.textContent||"").slice($.endOffset),X=!0;continue}if(X){if(!E0(W))continue;q+=W.textContent||""}}if(q.length>J){q=q.slice(0,J);let _=q.lastIndexOf(" ");if(_>0)q=q.slice(0,_)}}return q.trim()}function U8($){let Q=new Set(["DIV","P","LI","PRE","BLOCKQUOTE","SECTION","ARTICLE"]),J=$.parentElement;while(J){if(Q.has(J.tagName))return J;J=J.parentElement}return null}function K8($,Q){let J=[],Y=$ instanceof Element?$:$.parentElement;while(Y&&Y!==Q){let q=Y.getAttribute?.("data-task-id");if(q){let X=Y.querySelector(".font-semibold");if(X)J.unshift(X.textContent?.trim()||q)}let G=B8(Y);if(G)J.unshift(G);Y=Y.parentElement}return J}function B8($){if($.getAttribute("data-md")==="section"){let J=$.getAttribute("data-md-title");if(J)return J}if($.tagName!=="DIV")return null;return $.querySelector(":scope > button > .font-heading, :scope > div > .font-heading")?.textContent?.trim()||null}function A2($){let Q=$.snippet.trim(),J=$.context,Y=Q.length<30;if(J&&Y&&(J.before||J.after)){let q=[];if(J.before)q.push(`...${J.before} `);if(q.push(`**${Q}**`),J.after)q.push(` ${J.after}...`);return q.join("")}return Q}function h0($){return{kind:$.kind,owns:(Q)=>$.parse(Q)!==null,find:(Q,J)=>{let Y=$.parse(Q);return Y===null?null:$.find(Y,J)},restore:(Q,J)=>{let Y=$.parse(J.snippet);if(Y===null)return;$.restore?.(Y,Q,J)},describe:(Q)=>{let J=$.parse(Q);if(J===null||!$.describe)return null;return $.describe(J)}}}function V3($){let Q=document.createTreeWalker($,NodeFilter.SHOW_TEXT),J="";for(let Y=Q.nextNode();Y;Y=Q.nextNode()){let q=Y.parentElement?.closest("[aria-hidden='true']");if(q&&$.contains(q))continue;J+=Y.textContent??""}return J.trim()}function P2($,Q,J){return{selector:$,snippet:(Y)=>{let q=Y.getAttribute(J);return q?`${Q} ${q}`:null}}}var H4=[P2("[data-md='item']","[Item]","data-md-label"),P2("[data-md='section']","[Section]","data-md-title"),P2("[data-md='checklist-item']","[Checklist]","data-md-label"),P2("[data-md='image']","[Image]","data-md-src"),{selector:"[data-md='callout']",snippet:($)=>{return`[Callout:${$.getAttribute("data-md-type")||"info"}] ${V3($).slice(0,60)||"Callout"}`}},{selector:"[data-md='note']",snippet:($)=>`[Note] ${V3($).slice(0,60)||"Note"}`},{selector:"[data-md='table'] tbody tr",snippet:($)=>{let Q=Array.from($.querySelectorAll("td")).map((J)=>J.textContent?.trim()).filter(Boolean);return Q.length?`[Row] ${Q.join(" | ")}`:null}}],N8=["[data-md='choice-option']","[data-md='multichoice-option']","[data-md='userinput']","[data-md='rangeinput']"],S1=H4.map(($)=>$.selector).join(", "),Y0=[...H4.map(($)=>$.selector),...N8].join(", ");function s$($){for(let Q of H4)if($.matches(Q.selector))return Q.snippet($);return null}var U4={kind:"block",parse:($)=>$.startsWith("[")?{snippet:$}:null,format:($)=>$.snippet,find:($,Q)=>{for(let J of Q.querySelectorAll(S1)){if(!(J instanceof HTMLElement))continue;if(s$(J)===$.snippet)return J}return null}};var B4="data-annotation-image",O8=/^\[Region:(rect|ellipse)\] ([\s\S]+) @(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*)$/;function z8($){if($==="rect")return"rect";if($==="ellipse")return"ellipse";return null}function S2($){if($===void 0)return null;let Q=Number($);if(!Number.isInteger(Q)||Q<0||Q>1e4)return null;return Q}function C3($){return Math.min(1e4,Math.max(0,$))}function N4($,Q,J){if(!($.width>0)||!($.height>0))return null;return{x:C3(Math.round(Q/$.width*1e4)),y:C3(Math.round(J/$.height*1e4))}}function T2($,Q){let J=Math.min($.x,Q.x),Y=Math.min($.y,Q.y);return{x:J,y:Y,w:Math.min(1e4-J,Math.abs($.x-Q.x)),h:Math.min(1e4-Y,Math.abs($.y-Q.y))}}function O4($){return $.w>=30&&$.h>=30}function R3($){return{left:`${$.x/100}%`,top:`${$.y/100}%`,width:`${$.w/100}%`,height:`${$.h/100}%`}}function w2($){return`${($/100).toFixed(1).replace(/\.0$/,"")}%`}function j2($){let Q=`${w2($.x)}-${w2($.x+$.w)}`,J=`${w2($.y)}-${w2($.y+$.h)}`;return`[Region] ${$.src} — ${$.shape} x ${Q}, y ${J} of the image`}function K4($,Q){for(let J of Q.querySelectorAll("[data-md='image']")){if(!(J instanceof HTMLElement))continue;if(J.getAttribute("data-md-src")!==$)continue;let Y=J.querySelector("[data-annotation-image]");if(Y instanceof HTMLElement)return Y}return null}function b2($,Q){let J=R3(Q);$.style.left=J.left,$.style.top=J.top,$.style.width=J.width,$.style.height=J.height}function Z2($,Q,J){let Y=document.createElement("div");return Y.className="ann-region",Y.setAttribute("data-annotation-id",J),Y.setAttribute("data-annotation-region",Q),b2(Y,$),Y}var u0={kind:"region",parse:($)=>{let Q=O8.exec($);if(!Q)return null;let J=z8(Q[1]),Y=Q[2],q=S2(Q[3]),G=S2(Q[4]),X=S2(Q[5]),W=S2(Q[6]);if(J===null||Y===void 0)return null;if(q===null||G===null||X===null||W===null)return null;if(X<1||W<1)return null;return{src:Y,shape:J,x:q,y:G,w:X,h:W}},format:($)=>`[Region:${$.shape}] ${$.src} @${$.x},${$.y},${$.w},${$.h}`,find:($,Q)=>K4($.src,Q),restore:($,Q,J)=>{if(Q.querySelector(`[data-annotation-id="${J.id}"]`))return;let Y=K4($.src,Q);if(!Y)return;Y.appendChild(Z2($,$.shape,J.id))},describe:j2};var z4={kind:"text",parse:($)=>$?{text:$}:null,format:($)=>$.text,find:()=>null,restore:($,Q,J)=>{m0(Q,[J])}};var V2=[h0(u0),h0(U4),h0(z4)];function M4($,Q){for(let J of V2){let Y=J.find($,Q);if(Y)return Y}return null}function F4($,Q){for(let J of Q){if(!J.snippet)continue;for(let Y of V2)Y.restore($,J)}}function p0($){for(let Q of V2){let J=Q.describe($);if(J!==null)return J}return $}import{AnnotationCtx as NY,SessionContext as OY,useAnnotationHost as zY}from"@fabrika/annotations/runtime";import{useEffect as LY,useRef as AY,useState as PY}from"react";var B={};_8(B,{void:()=>e8,util:()=>q$,unknown:()=>s8,union:()=>q9,undefined:()=>o8,tuple:()=>G9,transformer:()=>M9,symbol:()=>i8,string:()=>m3,strictObject:()=>J9,setErrorMap:()=>L8,set:()=>H9,record:()=>_9,quotelessJson:()=>M8,promise:()=>z9,preprocess:()=>A9,pipeline:()=>P9,ostring:()=>S9,optional:()=>F9,onumber:()=>w9,oboolean:()=>T9,objectUtil:()=>L4,object:()=>Q9,number:()=>x3,nullable:()=>L9,null:()=>a8,never:()=>t8,nativeEnum:()=>O9,nan:()=>l8,map:()=>W9,makeIssue:()=>c0,literal:()=>B9,lazy:()=>K9,late:()=>p8,isValid:()=>w1,isDirty:()=>R2,isAsync:()=>G0,isAborted:()=>C2,intersection:()=>X9,instanceof:()=>c8,getParsedType:()=>t$,getErrorMap:()=>X0,function:()=>U9,enum:()=>N9,effect:()=>M9,discriminatedUnion:()=>Y9,defaultErrorMap:()=>H1,datetimeRegex:()=>E3,date:()=>r8,custom:()=>g3,coerce:()=>j9,boolean:()=>h3,bigint:()=>d8,array:()=>$9,any:()=>n8,addIssueToContext:()=>k,ZodVoid:()=>d0,ZodUnknown:()=>T1,ZodUnion:()=>B0,ZodUndefined:()=>U0,ZodType:()=>$$,ZodTuple:()=>$1,ZodTransformer:()=>r$,ZodSymbol:()=>l0,ZodString:()=>p$,ZodSet:()=>u1,ZodSchema:()=>$$,ZodRecord:()=>r0,ZodReadonly:()=>A0,ZodPromise:()=>p1,ZodPipeline:()=>a0,ZodParsedType:()=>R,ZodOptional:()=>l$,ZodObject:()=>A$,ZodNumber:()=>j1,ZodNullable:()=>K1,ZodNull:()=>K0,ZodNever:()=>e$,ZodNativeEnum:()=>M0,ZodNaN:()=>o0,ZodMap:()=>i0,ZodLiteral:()=>z0,ZodLazy:()=>O0,ZodIssueCode:()=>b,ZodIntersection:()=>N0,ZodFunction:()=>W0,ZodFirstPartyTypeKind:()=>l,ZodError:()=>E$,ZodEnum:()=>Z1,ZodEffects:()=>r$,ZodDiscriminatedUnion:()=>D2,ZodDefault:()=>F0,ZodDate:()=>x1,ZodCatch:()=>L0,ZodBranded:()=>I2,ZodBoolean:()=>H0,ZodBigInt:()=>b1,ZodArray:()=>c$,ZodAny:()=>h1,Schema:()=>$$,ParseStatus:()=>V$,OK:()=>R$,NEVER:()=>b9,INVALID:()=>p,EMPTY_PATH:()=>A8,DIRTY:()=>m1,BRAND:()=>u8});var q$;(function($){$.assertEqual=(q)=>{};function Q(q){}$.assertIs=Q;function J(q){throw Error()}$.assertNever=J,$.arrayToEnum=(q)=>{let G={};for(let X of q)G[X]=X;return G},$.getValidEnumValues=(q)=>{let G=$.objectKeys(q).filter((W)=>typeof q[q[W]]!=="number"),X={};for(let W of G)X[W]=q[W];return $.objectValues(X)},$.objectValues=(q)=>{return $.objectKeys(q).map(function(G){return q[G]})},$.objectKeys=typeof Object.keys==="function"?(q)=>Object.keys(q):(q)=>{let G=[];for(let X in q)if(Object.prototype.hasOwnProperty.call(q,X))G.push(X);return G},$.find=(q,G)=>{for(let X of q)if(G(X))return X;return},$.isInteger=typeof Number.isInteger==="function"?(q)=>Number.isInteger(q):(q)=>typeof q==="number"&&Number.isFinite(q)&&Math.floor(q)===q;function Y(q,G=" | "){return q.map((X)=>typeof X==="string"?`'${X}'`:X).join(G)}$.joinValues=Y,$.jsonStringifyReplacer=(q,G)=>{if(typeof G==="bigint")return G.toString();return G}})(q$||(q$={}));var L4;(function($){$.mergeShapes=(Q,J)=>{return{...Q,...J}}})(L4||(L4={}));var R=q$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),t$=($)=>{switch(typeof $){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN($)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":if(Array.isArray($))return R.array;if($===null)return R.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return R.promise;if(typeof Map<"u"&&$ instanceof Map)return R.map;if(typeof Set<"u"&&$ instanceof Set)return R.set;if(typeof Date<"u"&&$ instanceof Date)return R.date;return R.object;default:return R.unknown}};var b=q$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),M8=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class E$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let Q=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Q);else this.__proto__=Q;this.name="ZodError",this.issues=$}format($){let Q=$||function(q){return q.message},J={_errors:[]},Y=(q)=>{for(let G of q.issues)if(G.code==="invalid_union")G.unionErrors.map(Y);else if(G.code==="invalid_return_type")Y(G.returnTypeError);else if(G.code==="invalid_arguments")Y(G.argumentsError);else if(G.path.length===0)J._errors.push(Q(G));else{let X=J,W=0;while(W<G.path.length){let _=G.path[W];if(W!==G.path.length-1)X[_]=X[_]||{_errors:[]};else X[_]=X[_]||{_errors:[]},X[_]._errors.push(Q(G));X=X[_],W++}}};return Y(this),J}static assert($){if(!($ instanceof E$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,q$.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(Q)=>Q.message){let Q={},J=[];for(let Y of this.issues)if(Y.path.length>0){let q=Y.path[0];Q[q]=Q[q]||[],Q[q].push($(Y))}else J.push($(Y));return{formErrors:J,fieldErrors:Q}}get formErrors(){return this.flatten()}}E$.create=($)=>{return new E$($)};var F8=($,Q)=>{let J;switch($.code){case b.invalid_type:if($.received===R.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case b.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,q$.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:J=`Unrecognized key(s) in object: ${q$.joinValues($.keys,", ")}`;break;case b.invalid_union:J="Invalid input";break;case b.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${q$.joinValues($.options)}`;break;case b.invalid_enum_value:J=`Invalid enum value. Expected ${q$.joinValues($.options)}, received '${$.received}'`;break;case b.invalid_arguments:J="Invalid function arguments";break;case b.invalid_return_type:J="Invalid function return type";break;case b.invalid_date:J="Invalid date";break;case b.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else q$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case b.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case b.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case b.custom:J="Invalid input";break;case b.invalid_intersection_types:J="Intersection results could not be merged";break;case b.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case b.not_finite:J="Number must be finite";break;default:J=Q.defaultError,q$.assertNever($)}return{message:J}},H1=F8;var D3=H1;function L8($){D3=$}function X0(){return D3}var c0=($)=>{let{data:Q,path:J,errorMaps:Y,issueData:q}=$,G=[...J,...q.path||[]],X={...q,path:G};if(q.message!==void 0)return{...q,path:G,message:q.message};let W="",_=Y.filter((H)=>!!H).slice().reverse();for(let H of _)W=H(X,{data:Q,defaultError:W}).message;return{...q,path:G,message:W}},A8=[];function k($,Q){let J=X0(),Y=c0({issueData:Q,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===H1?void 0:H1].filter((q)=>!!q)});$.common.issues.push(Y)}class V${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,Q){let J=[];for(let Y of Q){if(Y.status==="aborted")return p;if(Y.status==="dirty")$.dirty();J.push(Y.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,Q){let J=[];for(let Y of Q){let q=await Y.key,G=await Y.value;J.push({key:q,value:G})}return V$.mergeObjectSync($,J)}static mergeObjectSync($,Q){let J={};for(let Y of Q){let{key:q,value:G}=Y;if(q.status==="aborted")return p;if(G.status==="aborted")return p;if(q.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(q.value!=="__proto__"&&(typeof G.value<"u"||Y.alwaysSet))J[q.value]=G.value}return{status:$.value,value:J}}}var p=Object.freeze({status:"aborted"}),m1=($)=>({status:"dirty",value:$}),R$=($)=>({status:"valid",value:$}),C2=($)=>$.status==="aborted",R2=($)=>$.status==="dirty",w1=($)=>$.status==="valid",G0=($)=>typeof Promise<"u"&&$ instanceof Promise;var m;(function($){$.errToObj=(Q)=>typeof Q==="string"?{message:Q}:Q||{},$.toString=(Q)=>typeof Q==="string"?Q:Q?.message})(m||(m={}));class d${constructor($,Q,J,Y){this._cachedPath=[],this.parent=$,this.data=Q,this._path=J,this._key=Y}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var I3=($,Q)=>{if(w1(Q))return{success:!0,data:Q.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new E$($.common.issues);return this._error=J,this._error}}}};function t($){if(!$)return{};let{errorMap:Q,invalid_type_error:J,required_error:Y,description:q}=$;if(Q&&(J||Y))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Q)return{errorMap:Q,description:q};return{errorMap:(X,W)=>{let{message:_}=$;if(X.code==="invalid_enum_value")return{message:_??W.defaultError};if(typeof W.data>"u")return{message:_??Y??W.defaultError};if(X.code!=="invalid_type")return{message:W.defaultError};return{message:_??J??W.defaultError}},description:q}}class $${get description(){return this._def.description}_getType($){return t$($.data)}_getOrReturnCtx($,Q){return Q||{common:$.parent.common,data:$.data,parsedType:t$($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new V$,ctx:{common:$.parent.common,data:$.data,parsedType:t$($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let Q=this._parse($);if(G0(Q))throw Error("Synchronous parse encountered promise.");return Q}_parseAsync($){let Q=this._parse($);return Promise.resolve(Q)}parse($,Q){let J=this.safeParse($,Q);if(J.success)return J.data;throw J.error}safeParse($,Q){let J={common:{issues:[],async:Q?.async??!1,contextualErrorMap:Q?.errorMap},path:Q?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t$($)},Y=this._parseSync({data:$,path:J.path,parent:J});return I3(J,Y)}"~validate"($){let Q={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t$($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:Q});return w1(J)?{value:J.value}:{issues:Q.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Q.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:Q}).then((J)=>w1(J)?{value:J.value}:{issues:Q.common.issues})}async parseAsync($,Q){let J=await this.safeParseAsync($,Q);if(J.success)return J.data;throw J.error}async safeParseAsync($,Q){let J={common:{issues:[],contextualErrorMap:Q?.errorMap,async:!0},path:Q?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:t$($)},Y=this._parse({data:$,path:J.path,parent:J}),q=await(G0(Y)?Y:Promise.resolve(Y));return I3(J,q)}refine($,Q){let J=(Y)=>{if(typeof Q==="string"||typeof Q>"u")return{message:Q};else if(typeof Q==="function")return Q(Y);else return Q};return this._refinement((Y,q)=>{let G=$(Y),X=()=>q.addIssue({code:b.custom,...J(Y)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((W)=>{if(!W)return X(),!1;else return!0});if(!G)return X(),!1;else return!0})}refinement($,Q){return this._refinement((J,Y)=>{if(!$(J))return Y.addIssue(typeof Q==="function"?Q(J,Y):Q),!1;else return!0})}_refinement($){return new r$({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(Q)=>this["~validate"](Q)}}optional(){return l$.create(this,this._def)}nullable(){return K1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return c$.create(this)}promise(){return p1.create(this,this._def)}or($){return B0.create([this,$],this._def)}and($){return N0.create(this,$,this._def)}transform($){return new r$({...t(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:$}})}default($){let Q=typeof $==="function"?$:()=>$;return new F0({...t(this._def),innerType:this,defaultValue:Q,typeName:l.ZodDefault})}brand(){return new I2({typeName:l.ZodBranded,type:this,...t(this._def)})}catch($){let Q=typeof $==="function"?$:()=>$;return new L0({...t(this._def),innerType:this,catchValue:Q,typeName:l.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return a0.create(this,$)}readonly(){return A0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var P8=/^c[^\s-]{8,}$/i,S8=/^[0-9a-z]+$/,w8=/^[0-9A-HJKMNP-TV-Z]{26}$/i,T8=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,j8=/^[a-z0-9_-]{21}$/i,b8=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Z8=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,V8=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,C8="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",A4,R8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,D8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,I8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,k8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,y8=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,f8=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,y3="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",E8=new RegExp(`^${y3}$`);function f3($){let Q="[0-5]\\d";if($.precision)Q=`${Q}\\.\\d{${$.precision}}`;else if($.precision==null)Q=`${Q}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Q})${J}`}function v8($){return new RegExp(`^${f3($)}$`)}function E3($){let Q=`${y3}T${f3($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return Q=`${Q}(${J.join("|")})`,new RegExp(`^${Q}$`)}function g8($,Q){if((Q==="v4"||!Q)&&R8.test($))return!0;if((Q==="v6"||!Q)&&I8.test($))return!0;return!1}function m8($,Q){if(!b8.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let Y=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),q=JSON.parse(atob(Y));if(typeof q!=="object"||q===null)return!1;if("typ"in q&&q?.typ!=="JWT")return!1;if(!q.alg)return!1;if(Q&&q.alg!==Q)return!1;return!0}catch{return!1}}function x8($,Q){if((Q==="v4"||!Q)&&D8.test($))return!0;if((Q==="v6"||!Q)&&k8.test($))return!0;return!1}class p$ extends $${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==R.string){let q=this._getOrReturnCtx($);return k(q,{code:b.invalid_type,expected:R.string,received:q.parsedType}),p}let J=new V$,Y=void 0;for(let q of this._def.checks)if(q.kind==="min"){if($.data.length<q.value)Y=this._getOrReturnCtx($,Y),k(Y,{code:b.too_small,minimum:q.value,type:"string",inclusive:!0,exact:!1,message:q.message}),J.dirty()}else if(q.kind==="max"){if($.data.length>q.value)Y=this._getOrReturnCtx($,Y),k(Y,{code:b.too_big,maximum:q.value,type:"string",inclusive:!0,exact:!1,message:q.message}),J.dirty()}else if(q.kind==="length"){let G=$.data.length>q.value,X=$.data.length<q.value;if(G||X){if(Y=this._getOrReturnCtx($,Y),G)k(Y,{code:b.too_big,maximum:q.value,type:"string",inclusive:!0,exact:!0,message:q.message});else if(X)k(Y,{code:b.too_small,minimum:q.value,type:"string",inclusive:!0,exact:!0,message:q.message});J.dirty()}}else if(q.kind==="email"){if(!V8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"email",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="emoji"){if(!A4)A4=new RegExp(C8,"u");if(!A4.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"emoji",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="uuid"){if(!T8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"uuid",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="nanoid"){if(!j8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"nanoid",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="cuid"){if(!P8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"cuid",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="cuid2"){if(!S8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"cuid2",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="ulid"){if(!w8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"ulid",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="url")try{new URL($.data)}catch{Y=this._getOrReturnCtx($,Y),k(Y,{validation:"url",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="regex"){if(q.regex.lastIndex=0,!q.regex.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"regex",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="trim")$.data=$.data.trim();else if(q.kind==="includes"){if(!$.data.includes(q.value,q.position))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:{includes:q.value,position:q.position},message:q.message}),J.dirty()}else if(q.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(q.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(q.kind==="startsWith"){if(!$.data.startsWith(q.value))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:{startsWith:q.value},message:q.message}),J.dirty()}else if(q.kind==="endsWith"){if(!$.data.endsWith(q.value))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:{endsWith:q.value},message:q.message}),J.dirty()}else if(q.kind==="datetime"){if(!E3(q).test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:"datetime",message:q.message}),J.dirty()}else if(q.kind==="date"){if(!E8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:"date",message:q.message}),J.dirty()}else if(q.kind==="time"){if(!v8(q).test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{code:b.invalid_string,validation:"time",message:q.message}),J.dirty()}else if(q.kind==="duration"){if(!Z8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"duration",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="ip"){if(!g8($.data,q.version))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"ip",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="jwt"){if(!m8($.data,q.alg))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"jwt",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="cidr"){if(!x8($.data,q.version))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"cidr",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="base64"){if(!y8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"base64",code:b.invalid_string,message:q.message}),J.dirty()}else if(q.kind==="base64url"){if(!f8.test($.data))Y=this._getOrReturnCtx($,Y),k(Y,{validation:"base64url",code:b.invalid_string,message:q.message}),J.dirty()}else q$.assertNever(q);return{status:J.value,value:$.data}}_regex($,Q,J){return this.refinement((Y)=>$.test(Y),{validation:Q,code:b.invalid_string,...m.errToObj(J)})}_addCheck($){return new p$({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...m.errToObj($)})}url($){return this._addCheck({kind:"url",...m.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...m.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...m.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...m.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...m.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...m.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...m.errToObj($)})}base64($){return this._addCheck({kind:"base64",...m.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...m.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...m.errToObj($)})}ip($){return this._addCheck({kind:"ip",...m.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...m.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...m.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...m.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...m.errToObj($)})}regex($,Q){return this._addCheck({kind:"regex",regex:$,...m.errToObj(Q)})}includes($,Q){return this._addCheck({kind:"includes",value:$,position:Q?.position,...m.errToObj(Q?.message)})}startsWith($,Q){return this._addCheck({kind:"startsWith",value:$,...m.errToObj(Q)})}endsWith($,Q){return this._addCheck({kind:"endsWith",value:$,...m.errToObj(Q)})}min($,Q){return this._addCheck({kind:"min",value:$,...m.errToObj(Q)})}max($,Q){return this._addCheck({kind:"max",value:$,...m.errToObj(Q)})}length($,Q){return this._addCheck({kind:"length",value:$,...m.errToObj(Q)})}nonempty($){return this.min(1,m.errToObj($))}trim(){return new p$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p$({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxLength(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}}p$.create=($)=>{return new p$({checks:[],typeName:l.ZodString,coerce:$?.coerce??!1,...t($)})};function h8($,Q){let J=($.toString().split(".")[1]||"").length,Y=(Q.toString().split(".")[1]||"").length,q=J>Y?J:Y,G=Number.parseInt($.toFixed(q).replace(".","")),X=Number.parseInt(Q.toFixed(q).replace(".",""));return G%X/10**q}class j1 extends $${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==R.number){let q=this._getOrReturnCtx($);return k(q,{code:b.invalid_type,expected:R.number,received:q.parsedType}),p}let J=void 0,Y=new V$;for(let q of this._def.checks)if(q.kind==="int"){if(!q$.isInteger($.data))J=this._getOrReturnCtx($,J),k(J,{code:b.invalid_type,expected:"integer",received:"float",message:q.message}),Y.dirty()}else if(q.kind==="min"){if(q.inclusive?$.data<q.value:$.data<=q.value)J=this._getOrReturnCtx($,J),k(J,{code:b.too_small,minimum:q.value,type:"number",inclusive:q.inclusive,exact:!1,message:q.message}),Y.dirty()}else if(q.kind==="max"){if(q.inclusive?$.data>q.value:$.data>=q.value)J=this._getOrReturnCtx($,J),k(J,{code:b.too_big,maximum:q.value,type:"number",inclusive:q.inclusive,exact:!1,message:q.message}),Y.dirty()}else if(q.kind==="multipleOf"){if(h8($.data,q.value)!==0)J=this._getOrReturnCtx($,J),k(J,{code:b.not_multiple_of,multipleOf:q.value,message:q.message}),Y.dirty()}else if(q.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),k(J,{code:b.not_finite,message:q.message}),Y.dirty()}else q$.assertNever(q);return{status:Y.value,value:$.data}}gte($,Q){return this.setLimit("min",$,!0,m.toString(Q))}gt($,Q){return this.setLimit("min",$,!1,m.toString(Q))}lte($,Q){return this.setLimit("max",$,!0,m.toString(Q))}lt($,Q){return this.setLimit("max",$,!1,m.toString(Q))}setLimit($,Q,J,Y){return new j1({...this._def,checks:[...this._def.checks,{kind:$,value:Q,inclusive:J,message:m.toString(Y)}]})}_addCheck($){return new j1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:m.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString($)})}multipleOf($,Q){return this._addCheck({kind:"multipleOf",value:$,message:m.toString(Q)})}finite($){return this._addCheck({kind:"finite",message:m.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString($)})}get minValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&q$.isInteger($.value))}get isFinite(){let $=null,Q=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(Q===null||J.value>Q)Q=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(Q)&&Number.isFinite($)}}j1.create=($)=>{return new j1({checks:[],typeName:l.ZodNumber,coerce:$?.coerce||!1,...t($)})};class b1 extends $${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==R.bigint)return this._getInvalidInput($);let J=void 0,Y=new V$;for(let q of this._def.checks)if(q.kind==="min"){if(q.inclusive?$.data<q.value:$.data<=q.value)J=this._getOrReturnCtx($,J),k(J,{code:b.too_small,type:"bigint",minimum:q.value,inclusive:q.inclusive,message:q.message}),Y.dirty()}else if(q.kind==="max"){if(q.inclusive?$.data>q.value:$.data>=q.value)J=this._getOrReturnCtx($,J),k(J,{code:b.too_big,type:"bigint",maximum:q.value,inclusive:q.inclusive,message:q.message}),Y.dirty()}else if(q.kind==="multipleOf"){if($.data%q.value!==BigInt(0))J=this._getOrReturnCtx($,J),k(J,{code:b.not_multiple_of,multipleOf:q.value,message:q.message}),Y.dirty()}else q$.assertNever(q);return{status:Y.value,value:$.data}}_getInvalidInput($){let Q=this._getOrReturnCtx($);return k(Q,{code:b.invalid_type,expected:R.bigint,received:Q.parsedType}),p}gte($,Q){return this.setLimit("min",$,!0,m.toString(Q))}gt($,Q){return this.setLimit("min",$,!1,m.toString(Q))}lte($,Q){return this.setLimit("max",$,!0,m.toString(Q))}lt($,Q){return this.setLimit("max",$,!1,m.toString(Q))}setLimit($,Q,J,Y){return new b1({...this._def,checks:[...this._def.checks,{kind:$,value:Q,inclusive:J,message:m.toString(Y)}]})}_addCheck($){return new b1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString($)})}multipleOf($,Q){return this._addCheck({kind:"multipleOf",value:$,message:m.toString(Q)})}get minValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}}b1.create=($)=>{return new b1({checks:[],typeName:l.ZodBigInt,coerce:$?.coerce??!1,...t($)})};class H0 extends $${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==R.boolean){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.boolean,received:J.parsedType}),p}return R$($.data)}}H0.create=($)=>{return new H0({typeName:l.ZodBoolean,coerce:$?.coerce||!1,...t($)})};class x1 extends $${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==R.date){let q=this._getOrReturnCtx($);return k(q,{code:b.invalid_type,expected:R.date,received:q.parsedType}),p}if(Number.isNaN($.data.getTime())){let q=this._getOrReturnCtx($);return k(q,{code:b.invalid_date}),p}let J=new V$,Y=void 0;for(let q of this._def.checks)if(q.kind==="min"){if($.data.getTime()<q.value)Y=this._getOrReturnCtx($,Y),k(Y,{code:b.too_small,message:q.message,inclusive:!0,exact:!1,minimum:q.value,type:"date"}),J.dirty()}else if(q.kind==="max"){if($.data.getTime()>q.value)Y=this._getOrReturnCtx($,Y),k(Y,{code:b.too_big,message:q.message,inclusive:!0,exact:!1,maximum:q.value,type:"date"}),J.dirty()}else q$.assertNever(q);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new x1({...this._def,checks:[...this._def.checks,$]})}min($,Q){return this._addCheck({kind:"min",value:$.getTime(),message:m.toString(Q)})}max($,Q){return this._addCheck({kind:"max",value:$.getTime(),message:m.toString(Q)})}get minDate(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $!=null?new Date($):null}}x1.create=($)=>{return new x1({checks:[],coerce:$?.coerce||!1,typeName:l.ZodDate,...t($)})};class l0 extends $${_parse($){if(this._getType($)!==R.symbol){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.symbol,received:J.parsedType}),p}return R$($.data)}}l0.create=($)=>{return new l0({typeName:l.ZodSymbol,...t($)})};class U0 extends $${_parse($){if(this._getType($)!==R.undefined){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.undefined,received:J.parsedType}),p}return R$($.data)}}U0.create=($)=>{return new U0({typeName:l.ZodUndefined,...t($)})};class K0 extends $${_parse($){if(this._getType($)!==R.null){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.null,received:J.parsedType}),p}return R$($.data)}}K0.create=($)=>{return new K0({typeName:l.ZodNull,...t($)})};class h1 extends $${constructor(){super(...arguments);this._any=!0}_parse($){return R$($.data)}}h1.create=($)=>{return new h1({typeName:l.ZodAny,...t($)})};class T1 extends $${constructor(){super(...arguments);this._unknown=!0}_parse($){return R$($.data)}}T1.create=($)=>{return new T1({typeName:l.ZodUnknown,...t($)})};class e$ extends $${_parse($){let Q=this._getOrReturnCtx($);return k(Q,{code:b.invalid_type,expected:R.never,received:Q.parsedType}),p}}e$.create=($)=>{return new e$({typeName:l.ZodNever,...t($)})};class d0 extends $${_parse($){if(this._getType($)!==R.undefined){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.void,received:J.parsedType}),p}return R$($.data)}}d0.create=($)=>{return new d0({typeName:l.ZodVoid,...t($)})};class c$ extends $${_parse($){let{ctx:Q,status:J}=this._processInputParams($),Y=this._def;if(Q.parsedType!==R.array)return k(Q,{code:b.invalid_type,expected:R.array,received:Q.parsedType}),p;if(Y.exactLength!==null){let G=Q.data.length>Y.exactLength.value,X=Q.data.length<Y.exactLength.value;if(G||X)k(Q,{code:G?b.too_big:b.too_small,minimum:X?Y.exactLength.value:void 0,maximum:G?Y.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Y.exactLength.message}),J.dirty()}if(Y.minLength!==null){if(Q.data.length<Y.minLength.value)k(Q,{code:b.too_small,minimum:Y.minLength.value,type:"array",inclusive:!0,exact:!1,message:Y.minLength.message}),J.dirty()}if(Y.maxLength!==null){if(Q.data.length>Y.maxLength.value)k(Q,{code:b.too_big,maximum:Y.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Y.maxLength.message}),J.dirty()}if(Q.common.async)return Promise.all([...Q.data].map((G,X)=>{return Y.type._parseAsync(new d$(Q,G,Q.path,X))})).then((G)=>{return V$.mergeArray(J,G)});let q=[...Q.data].map((G,X)=>{return Y.type._parseSync(new d$(Q,G,Q.path,X))});return V$.mergeArray(J,q)}get element(){return this._def.type}min($,Q){return new c$({...this._def,minLength:{value:$,message:m.toString(Q)}})}max($,Q){return new c$({...this._def,maxLength:{value:$,message:m.toString(Q)}})}length($,Q){return new c$({...this._def,exactLength:{value:$,message:m.toString(Q)}})}nonempty($){return this.min(1,$)}}c$.create=($,Q)=>{return new c$({type:$,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...t(Q)})};function _0($){if($ instanceof A$){let Q={};for(let J in $.shape){let Y=$.shape[J];Q[J]=l$.create(_0(Y))}return new A$({...$._def,shape:()=>Q})}else if($ instanceof c$)return new c$({...$._def,type:_0($.element)});else if($ instanceof l$)return l$.create(_0($.unwrap()));else if($ instanceof K1)return K1.create(_0($.unwrap()));else if($ instanceof $1)return $1.create($.items.map((Q)=>_0(Q)));else return $}class A$ extends $${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),Q=q$.objectKeys($);return this._cached={shape:$,keys:Q},this._cached}_parse($){if(this._getType($)!==R.object){let _=this._getOrReturnCtx($);return k(_,{code:b.invalid_type,expected:R.object,received:_.parsedType}),p}let{status:J,ctx:Y}=this._processInputParams($),{shape:q,keys:G}=this._getCached(),X=[];if(!(this._def.catchall instanceof e$&&this._def.unknownKeys==="strip")){for(let _ in Y.data)if(!G.includes(_))X.push(_)}let W=[];for(let _ of G){let H=q[_],U=Y.data[_];W.push({key:{status:"valid",value:_},value:H._parse(new d$(Y,U,Y.path,_)),alwaysSet:_ in Y.data})}if(this._def.catchall instanceof e$){let _=this._def.unknownKeys;if(_==="passthrough")for(let H of X)W.push({key:{status:"valid",value:H},value:{status:"valid",value:Y.data[H]}});else if(_==="strict"){if(X.length>0)k(Y,{code:b.unrecognized_keys,keys:X}),J.dirty()}else if(_==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let _=this._def.catchall;for(let H of X){let U=Y.data[H];W.push({key:{status:"valid",value:H},value:_._parse(new d$(Y,U,Y.path,H)),alwaysSet:H in Y.data})}}if(Y.common.async)return Promise.resolve().then(async()=>{let _=[];for(let H of W){let U=await H.key,K=await H.value;_.push({key:U,value:K,alwaysSet:H.alwaysSet})}return _}).then((_)=>{return V$.mergeObjectSync(J,_)});else return V$.mergeObjectSync(J,W)}get shape(){return this._def.shape()}strict($){return m.errToObj,new A$({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(Q,J)=>{let Y=this._def.errorMap?.(Q,J).message??J.defaultError;if(Q.code==="unrecognized_keys")return{message:m.errToObj($).message??Y};return{message:Y}}}:{}})}strip(){return new A$({...this._def,unknownKeys:"strip"})}passthrough(){return new A$({...this._def,unknownKeys:"passthrough"})}extend($){return new A$({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new A$({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:l.ZodObject})}setKey($,Q){return this.augment({[$]:Q})}catchall($){return new A$({...this._def,catchall:$})}pick($){let Q={};for(let J of q$.objectKeys($))if($[J]&&this.shape[J])Q[J]=this.shape[J];return new A$({...this._def,shape:()=>Q})}omit($){let Q={};for(let J of q$.objectKeys(this.shape))if(!$[J])Q[J]=this.shape[J];return new A$({...this._def,shape:()=>Q})}deepPartial(){return _0(this)}partial($){let Q={};for(let J of q$.objectKeys(this.shape)){let Y=this.shape[J];if($&&!$[J])Q[J]=Y;else Q[J]=Y.optional()}return new A$({...this._def,shape:()=>Q})}required($){let Q={};for(let J of q$.objectKeys(this.shape))if($&&!$[J])Q[J]=this.shape[J];else{let q=this.shape[J];while(q instanceof l$)q=q._def.innerType;Q[J]=q}return new A$({...this._def,shape:()=>Q})}keyof(){return v3(q$.objectKeys(this.shape))}}A$.create=($,Q)=>{return new A$({shape:()=>$,unknownKeys:"strip",catchall:e$.create(),typeName:l.ZodObject,...t(Q)})};A$.strictCreate=($,Q)=>{return new A$({shape:()=>$,unknownKeys:"strict",catchall:e$.create(),typeName:l.ZodObject,...t(Q)})};A$.lazycreate=($,Q)=>{return new A$({shape:$,unknownKeys:"strip",catchall:e$.create(),typeName:l.ZodObject,...t(Q)})};class B0 extends $${_parse($){let{ctx:Q}=this._processInputParams($),J=this._def.options;function Y(q){for(let X of q)if(X.result.status==="valid")return X.result;for(let X of q)if(X.result.status==="dirty")return Q.common.issues.push(...X.ctx.common.issues),X.result;let G=q.map((X)=>new E$(X.ctx.common.issues));return k(Q,{code:b.invalid_union,unionErrors:G}),p}if(Q.common.async)return Promise.all(J.map(async(q)=>{let G={...Q,common:{...Q.common,issues:[]},parent:null};return{result:await q._parseAsync({data:Q.data,path:Q.path,parent:G}),ctx:G}})).then(Y);else{let q=void 0,G=[];for(let W of J){let _={...Q,common:{...Q.common,issues:[]},parent:null},H=W._parseSync({data:Q.data,path:Q.path,parent:_});if(H.status==="valid")return H;else if(H.status==="dirty"&&!q)q={result:H,ctx:_};if(_.common.issues.length)G.push(_.common.issues)}if(q)return Q.common.issues.push(...q.ctx.common.issues),q.result;let X=G.map((W)=>new E$(W));return k(Q,{code:b.invalid_union,unionErrors:X}),p}}get options(){return this._def.options}}B0.create=($,Q)=>{return new B0({options:$,typeName:l.ZodUnion,...t(Q)})};var U1=($)=>{if($ instanceof O0)return U1($.schema);else if($ instanceof r$)return U1($.innerType());else if($ instanceof z0)return[$.value];else if($ instanceof Z1)return $.options;else if($ instanceof M0)return q$.objectValues($.enum);else if($ instanceof F0)return U1($._def.innerType);else if($ instanceof U0)return[void 0];else if($ instanceof K0)return[null];else if($ instanceof l$)return[void 0,...U1($.unwrap())];else if($ instanceof K1)return[null,...U1($.unwrap())];else if($ instanceof I2)return U1($.unwrap());else if($ instanceof A0)return U1($.unwrap());else if($ instanceof L0)return U1($._def.innerType);else return[]};class D2 extends $${_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==R.object)return k(Q,{code:b.invalid_type,expected:R.object,received:Q.parsedType}),p;let J=this.discriminator,Y=Q.data[J],q=this.optionsMap.get(Y);if(!q)return k(Q,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),p;if(Q.common.async)return q._parseAsync({data:Q.data,path:Q.path,parent:Q});else return q._parseSync({data:Q.data,path:Q.path,parent:Q})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,Q,J){let Y=new Map;for(let q of Q){let G=U1(q.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let X of G){if(Y.has(X))throw Error(`Discriminator property ${String($)} has duplicate value ${String(X)}`);Y.set(X,q)}}return new D2({typeName:l.ZodDiscriminatedUnion,discriminator:$,options:Q,optionsMap:Y,...t(J)})}}function P4($,Q){let J=t$($),Y=t$(Q);if($===Q)return{valid:!0,data:$};else if(J===R.object&&Y===R.object){let q=q$.objectKeys(Q),G=q$.objectKeys($).filter((W)=>q.indexOf(W)!==-1),X={...$,...Q};for(let W of G){let _=P4($[W],Q[W]);if(!_.valid)return{valid:!1};X[W]=_.data}return{valid:!0,data:X}}else if(J===R.array&&Y===R.array){if($.length!==Q.length)return{valid:!1};let q=[];for(let G=0;G<$.length;G++){let X=$[G],W=Q[G],_=P4(X,W);if(!_.valid)return{valid:!1};q.push(_.data)}return{valid:!0,data:q}}else if(J===R.date&&Y===R.date&&+$===+Q)return{valid:!0,data:$};else return{valid:!1}}class N0 extends $${_parse($){let{status:Q,ctx:J}=this._processInputParams($),Y=(q,G)=>{if(C2(q)||C2(G))return p;let X=P4(q.value,G.value);if(!X.valid)return k(J,{code:b.invalid_intersection_types}),p;if(R2(q)||R2(G))Q.dirty();return{status:Q.value,value:X.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([q,G])=>Y(q,G));else return Y(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}N0.create=($,Q,J)=>{return new N0({left:$,right:Q,typeName:l.ZodIntersection,...t(J)})};class $1 extends $${_parse($){let{status:Q,ctx:J}=this._processInputParams($);if(J.parsedType!==R.array)return k(J,{code:b.invalid_type,expected:R.array,received:J.parsedType}),p;if(J.data.length<this._def.items.length)return k(J,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;if(!this._def.rest&&J.data.length>this._def.items.length)k(J,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q.dirty();let q=[...J.data].map((G,X)=>{let W=this._def.items[X]||this._def.rest;if(!W)return null;return W._parse(new d$(J,G,J.path,X))}).filter((G)=>!!G);if(J.common.async)return Promise.all(q).then((G)=>{return V$.mergeArray(Q,G)});else return V$.mergeArray(Q,q)}get items(){return this._def.items}rest($){return new $1({...this._def,rest:$})}}$1.create=($,Q)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new $1({items:$,typeName:l.ZodTuple,rest:null,...t(Q)})};class r0 extends $${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:Q,ctx:J}=this._processInputParams($);if(J.parsedType!==R.object)return k(J,{code:b.invalid_type,expected:R.object,received:J.parsedType}),p;let Y=[],q=this._def.keyType,G=this._def.valueType;for(let X in J.data)Y.push({key:q._parse(new d$(J,X,J.path,X)),value:G._parse(new d$(J,J.data[X],J.path,X)),alwaysSet:X in J.data});if(J.common.async)return V$.mergeObjectAsync(Q,Y);else return V$.mergeObjectSync(Q,Y)}get element(){return this._def.valueType}static create($,Q,J){if(Q instanceof $$)return new r0({keyType:$,valueType:Q,typeName:l.ZodRecord,...t(J)});return new r0({keyType:p$.create(),valueType:$,typeName:l.ZodRecord,...t(Q)})}}class i0 extends $${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:Q,ctx:J}=this._processInputParams($);if(J.parsedType!==R.map)return k(J,{code:b.invalid_type,expected:R.map,received:J.parsedType}),p;let Y=this._def.keyType,q=this._def.valueType,G=[...J.data.entries()].map(([X,W],_)=>{return{key:Y._parse(new d$(J,X,J.path,[_,"key"])),value:q._parse(new d$(J,W,J.path,[_,"value"]))}});if(J.common.async){let X=new Map;return Promise.resolve().then(async()=>{for(let W of G){let _=await W.key,H=await W.value;if(_.status==="aborted"||H.status==="aborted")return p;if(_.status==="dirty"||H.status==="dirty")Q.dirty();X.set(_.value,H.value)}return{status:Q.value,value:X}})}else{let X=new Map;for(let W of G){let{key:_,value:H}=W;if(_.status==="aborted"||H.status==="aborted")return p;if(_.status==="dirty"||H.status==="dirty")Q.dirty();X.set(_.value,H.value)}return{status:Q.value,value:X}}}}i0.create=($,Q,J)=>{return new i0({valueType:Q,keyType:$,typeName:l.ZodMap,...t(J)})};class u1 extends $${_parse($){let{status:Q,ctx:J}=this._processInputParams($);if(J.parsedType!==R.set)return k(J,{code:b.invalid_type,expected:R.set,received:J.parsedType}),p;let Y=this._def;if(Y.minSize!==null){if(J.data.size<Y.minSize.value)k(J,{code:b.too_small,minimum:Y.minSize.value,type:"set",inclusive:!0,exact:!1,message:Y.minSize.message}),Q.dirty()}if(Y.maxSize!==null){if(J.data.size>Y.maxSize.value)k(J,{code:b.too_big,maximum:Y.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Y.maxSize.message}),Q.dirty()}let q=this._def.valueType;function G(W){let _=new Set;for(let H of W){if(H.status==="aborted")return p;if(H.status==="dirty")Q.dirty();_.add(H.value)}return{status:Q.value,value:_}}let X=[...J.data.values()].map((W,_)=>q._parse(new d$(J,W,J.path,_)));if(J.common.async)return Promise.all(X).then((W)=>G(W));else return G(X)}min($,Q){return new u1({...this._def,minSize:{value:$,message:m.toString(Q)}})}max($,Q){return new u1({...this._def,maxSize:{value:$,message:m.toString(Q)}})}size($,Q){return this.min($,Q).max($,Q)}nonempty($){return this.min(1,$)}}u1.create=($,Q)=>{return new u1({valueType:$,minSize:null,maxSize:null,typeName:l.ZodSet,...t(Q)})};class W0 extends $${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==R.function)return k(Q,{code:b.invalid_type,expected:R.function,received:Q.parsedType}),p;function J(X,W){return c0({data:X,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,X0(),H1].filter((_)=>!!_),issueData:{code:b.invalid_arguments,argumentsError:W}})}function Y(X,W){return c0({data:X,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,X0(),H1].filter((_)=>!!_),issueData:{code:b.invalid_return_type,returnTypeError:W}})}let q={errorMap:Q.common.contextualErrorMap},G=Q.data;if(this._def.returns instanceof p1){let X=this;return R$(async function(...W){let _=new E$([]),H=await X._def.args.parseAsync(W,q).catch((N)=>{throw _.addIssue(J(W,N)),_}),U=await Reflect.apply(G,this,H);return await X._def.returns._def.type.parseAsync(U,q).catch((N)=>{throw _.addIssue(Y(U,N)),_})})}else{let X=this;return R$(function(...W){let _=X._def.args.safeParse(W,q);if(!_.success)throw new E$([J(W,_.error)]);let H=Reflect.apply(G,this,_.data),U=X._def.returns.safeParse(H,q);if(!U.success)throw new E$([Y(H,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new W0({...this._def,args:$1.create($).rest(T1.create())})}returns($){return new W0({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,Q,J){return new W0({args:$?$:$1.create([]).rest(T1.create()),returns:Q||T1.create(),typeName:l.ZodFunction,...t(J)})}}class O0 extends $${get schema(){return this._def.getter()}_parse($){let{ctx:Q}=this._processInputParams($);return this._def.getter()._parse({data:Q.data,path:Q.path,parent:Q})}}O0.create=($,Q)=>{return new O0({getter:$,typeName:l.ZodLazy,...t(Q)})};class z0 extends $${_parse($){if($.data!==this._def.value){let Q=this._getOrReturnCtx($);return k(Q,{received:Q.data,code:b.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:$.data}}get value(){return this._def.value}}z0.create=($,Q)=>{return new z0({value:$,typeName:l.ZodLiteral,...t(Q)})};function v3($,Q){return new Z1({values:$,typeName:l.ZodEnum,...t(Q)})}class Z1 extends $${_parse($){if(typeof $.data!=="string"){let Q=this._getOrReturnCtx($),J=this._def.values;return k(Q,{expected:q$.joinValues(J),received:Q.parsedType,code:b.invalid_type}),p}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let Q=this._getOrReturnCtx($),J=this._def.values;return k(Q,{received:Q.data,code:b.invalid_enum_value,options:J}),p}return R$($.data)}get options(){return this._def.values}get enum(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}get Values(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}get Enum(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}extract($,Q=this._def){return Z1.create($,{...this._def,...Q})}exclude($,Q=this._def){return Z1.create(this.options.filter((J)=>!$.includes(J)),{...this._def,...Q})}}Z1.create=v3;class M0 extends $${_parse($){let Q=q$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==R.string&&J.parsedType!==R.number){let Y=q$.objectValues(Q);return k(J,{expected:q$.joinValues(Y),received:J.parsedType,code:b.invalid_type}),p}if(!this._cache)this._cache=new Set(q$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let Y=q$.objectValues(Q);return k(J,{received:J.data,code:b.invalid_enum_value,options:Y}),p}return R$($.data)}get enum(){return this._def.values}}M0.create=($,Q)=>{return new M0({values:$,typeName:l.ZodNativeEnum,...t(Q)})};class p1 extends $${unwrap(){return this._def.type}_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==R.promise&&Q.common.async===!1)return k(Q,{code:b.invalid_type,expected:R.promise,received:Q.parsedType}),p;let J=Q.parsedType===R.promise?Q.data:Promise.resolve(Q.data);return R$(J.then((Y)=>{return this._def.type.parseAsync(Y,{path:Q.path,errorMap:Q.common.contextualErrorMap})}))}}p1.create=($,Q)=>{return new p1({type:$,typeName:l.ZodPromise,...t(Q)})};class r$ extends $${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:Q,ctx:J}=this._processInputParams($),Y=this._def.effect||null,q={addIssue:(G)=>{if(k(J,G),G.fatal)Q.abort();else Q.dirty()},get path(){return J.path}};if(q.addIssue=q.addIssue.bind(q),Y.type==="preprocess"){let G=Y.transform(J.data,q);if(J.common.async)return Promise.resolve(G).then(async(X)=>{if(Q.value==="aborted")return p;let W=await this._def.schema._parseAsync({data:X,path:J.path,parent:J});if(W.status==="aborted")return p;if(W.status==="dirty")return m1(W.value);if(Q.value==="dirty")return m1(W.value);return W});else{if(Q.value==="aborted")return p;let X=this._def.schema._parseSync({data:G,path:J.path,parent:J});if(X.status==="aborted")return p;if(X.status==="dirty")return m1(X.value);if(Q.value==="dirty")return m1(X.value);return X}}if(Y.type==="refinement"){let G=(X)=>{let W=Y.refinement(X,q);if(J.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return X};if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(X.status==="aborted")return p;if(X.status==="dirty")Q.dirty();return G(X.value),{status:Q.value,value:X.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(X.status==="aborted")return p;if(X.status==="dirty")Q.dirty();return G(X.value).then(()=>{return{status:Q.value,value:X.value}})})}if(Y.type==="transform")if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!w1(G))return p;let X=Y.transform(G.value,q);if(X instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Q.value,value:X}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(!w1(G))return p;return Promise.resolve(Y.transform(G.value,q)).then((X)=>({status:Q.value,value:X}))});q$.assertNever(Y)}}r$.create=($,Q,J)=>{return new r$({schema:$,typeName:l.ZodEffects,effect:Q,...t(J)})};r$.createWithPreprocess=($,Q,J)=>{return new r$({schema:Q,effect:{type:"preprocess",transform:$},typeName:l.ZodEffects,...t(J)})};class l$ extends $${_parse($){if(this._getType($)===R.undefined)return R$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}l$.create=($,Q)=>{return new l$({innerType:$,typeName:l.ZodOptional,...t(Q)})};class K1 extends $${_parse($){if(this._getType($)===R.null)return R$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}K1.create=($,Q)=>{return new K1({innerType:$,typeName:l.ZodNullable,...t(Q)})};class F0 extends $${_parse($){let{ctx:Q}=this._processInputParams($),J=Q.data;if(Q.parsedType===R.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:Q.path,parent:Q})}removeDefault(){return this._def.innerType}}F0.create=($,Q)=>{return new F0({innerType:$,typeName:l.ZodDefault,defaultValue:typeof Q.default==="function"?Q.default:()=>Q.default,...t(Q)})};class L0 extends $${_parse($){let{ctx:Q}=this._processInputParams($),J={...Q,common:{...Q.common,issues:[]}},Y=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(G0(Y))return Y.then((q)=>{return{status:"valid",value:q.status==="valid"?q.value:this._def.catchValue({get error(){return new E$(J.common.issues)},input:J.data})}});else return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new E$(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}L0.create=($,Q)=>{return new L0({innerType:$,typeName:l.ZodCatch,catchValue:typeof Q.catch==="function"?Q.catch:()=>Q.catch,...t(Q)})};class o0 extends $${_parse($){if(this._getType($)!==R.nan){let J=this._getOrReturnCtx($);return k(J,{code:b.invalid_type,expected:R.nan,received:J.parsedType}),p}return{status:"valid",value:$.data}}}o0.create=($)=>{return new o0({typeName:l.ZodNaN,...t($)})};var u8=Symbol("zod_brand");class I2 extends $${_parse($){let{ctx:Q}=this._processInputParams($),J=Q.data;return this._def.type._parse({data:J,path:Q.path,parent:Q})}unwrap(){return this._def.type}}class a0 extends $${_parse($){let{status:Q,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let q=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(q.status==="aborted")return p;if(q.status==="dirty")return Q.dirty(),m1(q.value);else return this._def.out._parseAsync({data:q.value,path:J.path,parent:J})})();else{let Y=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(Y.status==="aborted")return p;if(Y.status==="dirty")return Q.dirty(),{status:"dirty",value:Y.value};else return this._def.out._parseSync({data:Y.value,path:J.path,parent:J})}}static create($,Q){return new a0({in:$,out:Q,typeName:l.ZodPipeline})}}class A0 extends $${_parse($){let Q=this._def.innerType._parse($),J=(Y)=>{if(w1(Y))Y.value=Object.freeze(Y.value);return Y};return G0(Q)?Q.then((Y)=>J(Y)):J(Q)}unwrap(){return this._def.innerType}}A0.create=($,Q)=>{return new A0({innerType:$,typeName:l.ZodReadonly,...t(Q)})};function k3($,Q){let J=typeof $==="function"?$(Q):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function g3($,Q={},J){if($)return h1.create().superRefine((Y,q)=>{let G=$(Y);if(G instanceof Promise)return G.then((X)=>{if(!X){let W=k3(Q,Y),_=W.fatal??J??!0;q.addIssue({code:"custom",...W,fatal:_})}});if(!G){let X=k3(Q,Y),W=X.fatal??J??!0;q.addIssue({code:"custom",...X,fatal:W})}return});return h1.create()}var p8={object:A$.lazycreate},l;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(l||(l={}));var c8=($,Q={message:`Input not instance of ${$.name}`})=>g3((J)=>J instanceof $,Q),m3=p$.create,x3=j1.create,l8=o0.create,d8=b1.create,h3=H0.create,r8=x1.create,i8=l0.create,o8=U0.create,a8=K0.create,n8=h1.create,s8=T1.create,t8=e$.create,e8=d0.create,$9=c$.create,Q9=A$.create,J9=A$.strictCreate,q9=B0.create,Y9=D2.create,X9=N0.create,G9=$1.create,_9=r0.create,W9=i0.create,H9=u1.create,U9=W0.create,K9=O0.create,B9=z0.create,N9=Z1.create,O9=M0.create,z9=p1.create,M9=r$.create,F9=l$.create,L9=K1.create,A9=r$.createWithPreprocess,P9=a0.create,S9=()=>m3().optional(),w9=()=>x3().optional(),T9=()=>h3().optional(),j9={string:($)=>p$.create({...$,coerce:!0}),number:($)=>j1.create({...$,coerce:!0}),boolean:($)=>H0.create({...$,coerce:!0}),bigint:($)=>b1.create({...$,coerce:!0}),date:($)=>x1.create({...$,coerce:!0})};var b9=p;var Z9=B.object({before:B.string(),after:B.string(),hierarchy:B.array(B.string()),lineStart:B.number().optional(),lineEnd:B.number().optional()}).passthrough(),S4=B.object({id:B.string(),name:B.string()}).passthrough(),V9=B.object({url:B.string(),mime:B.string().optional()}).passthrough(),w4=B.object({id:B.string(),snippet:B.string(),note:B.string(),createdAt:B.string(),filePath:B.string().optional(),canvasFile:B.string().optional(),context:Z9.optional(),images:B.array(B.string()).optional(),attachments:B.array(V9).optional(),source:B.enum(["local","remote"]).optional(),author:S4.optional()}).passthrough(),C9=B.array(w4.optional().catch(void 0)).transform(($)=>$.filter((Q)=>Q!==void 0)).catch([]),T4=B.object({annotations:C9,generalNote:B.string().catch("")}).passthrough(),u3=B.object({path:B.string()}),p3=B.object({url:B.string()}),c3=B.object({error:B.string()});import{useCallback as l1,useMemo as R9,useState as D9}from"react";var g$="__agent-response__";function c1($){return $.filePath&&$.filePath!=="__agent-response__"?$.filePath:void 0}function n0($){return $.uploadUrl!==null}var j4=["image/png","image/jpeg","image/gif","image/webp"],l3="Only PNG, JPEG, GIF and WebP images can be attached";function x$(){return`ann-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function V1($,Q){$.style.height="auto",$.style.height=(Q?Math.max(Q,$.scrollHeight):$.scrollHeight)+"px"}function d3($){let Q=$?`[data-annotation-id="${CSS.escape($)}"]`:"[data-annotation-id]";for(let J of document.querySelectorAll(Q))if(J.tagName==="MARK"){let Y=J.parentNode;J.replaceWith(document.createTextNode(J.textContent||"")),Y?.normalize()}else J.remove()}function k2({annotations:$,setAnnotations:Q,generalNote:J,setGeneralNote:Y,remoteAnnotations:q,isReadOnly:G,onClear:X}){let[W,_]=D9(null),H=R9(()=>{if(!q?.length)return $;let w=new Set($.map((A)=>A.id)),z=q.filter((A)=>!w.has(A.id));return[...$,...z.map((A)=>({...A,source:"remote"}))]},[$,q]),U=l1((w,z,A,T,S,j,Z)=>{Q((y)=>[...y,{id:w,snippet:z,note:A,createdAt:new Date().toISOString(),filePath:T,context:S,...j?.length?{images:j}:{},...Z?{canvasFile:Z}:{}}])},[Q]),K=l1((w,z,A)=>{U(x$(),w,z,A)},[U]),N=l1((w,z)=>{Q((A)=>A.map((T)=>T.id===w?{...T,note:z}:T))},[Q]),O=l1((w)=>{if(!$.some((z)=>z.id===w))return;d3(w),Q((z)=>z.filter((A)=>A.id!==w)),_((z)=>z===w?null:z)},[$,Q]),M=l1((w,z)=>{Q((A)=>A.map((T)=>T.id===w?{...T,images:[...T.images||[],z]}:T))},[Q]),L=l1((w,z)=>{Q((A)=>A.map((T)=>T.id===w?{...T,images:(T.images||[]).filter((S)=>S!==z)}:T))},[Q]),F=l1(()=>{d3(),Q([]),Y(""),_(null),X?.()},[Q,Y,X]);return{annotations:H,generalNote:J,setGeneralNote:Y,activeAnnotationId:W,setActiveAnnotationId:_,addAnnotation:K,addAnnotationWithId:U,updateAnnotation:N,removeAnnotation:O,addAnnotationImage:M,removeAnnotationImage:L,clearAll:F,isReadOnly:G}}import{useAnnotations as C1}from"@fabrika/annotations/runtime";import{jsxDEV as bY}from"react/jsx-dev-runtime";import{jsxDEV as d1,Fragment as I9}from"react/jsx-dev-runtime";function b4({hasContent:$,onSubmit:Q,onSubmitEmpty:J,notice:Y,secondaryAction:q,placeholder:G="General notes...",submitLabel:X="Submit",emptyLabel:W="Submit without feedback"}){let{generalNote:_,setGeneralNote:H}=C1();return d1(I9,{children:[d1("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:d1("textarea",{value:_,onChange:(U)=>H(U.currentTarget.value),className:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none leading-relaxed p-0 border-none ring-0 shadow-none outline-none focus:outline-none focus:ring-0 focus:border-none placeholder:text-text-disabled min-h-[40px]",placeholder:G,onInput:(U)=>V1(U.currentTarget,40),ref:(U)=>{if(U)V1(U,40)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),Y,d1("div",{className:"px-4 py-3 border-t border-border-subtle flex-shrink-0",children:$?d1("div",{className:"flex gap-2",children:[q,d1("button",{onClick:Q,className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-btn-primary text-btn-primary-text hover:opacity-90 hover:-translate-y-px shadow-sm",children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this):d1("button",{onClick:J,className:"w-full py-2 rounded-lg font-body text-[13px] font-medium border border-border-medium text-text-secondary hover:text-text-primary hover:border-border-hover hover:bg-bg-input transition-all",children:W},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useAnnotationHost as k9}from"@fabrika/annotations/runtime";import{useCallback as B1,useEffect as y9,useRef as Z4,useState as y2}from"react";import{jsxDEV as j$}from"react/jsx-dev-runtime";function V4($){if($.startsWith("/s/")||$.startsWith("http://")||$.startsWith("https://"))return $;return`/api/uploads/${$.split("/").pop()}`}async function f9($,Q){let J=$.uploadUrl;if(!J)return{error:"Uploads are not available here"};let Y=new FormData;Y.append("image",Q);try{let q=await fetch(J(),{method:"POST",body:Y}),G=await q.json();if(!q.ok){let X=c3.safeParse(G);return{error:X.success?X.data.error:`Upload failed (HTTP ${q.status})`}}return{path:$.isShared?p3.parse(G).url:u3.parse(G).path}}catch{return{error:"Upload failed"}}}function s0({note:$,onNoteChange:Q,images:J,onAddImage:Y,onRemoveImage:q,sessionId:G,placeholder:X="Add your note...",autoFocus:W=!1,autoResize:_=!1,readOnly:H=!1,onKeyDown:U,onTextareaClick:K,textareaRef:N,textareaClassName:O,textareaStyle:M,minHeight:L,attachButton:F="always",openFilePickerRef:w}){let z=k9(),A=!H&&n0(z),[T,S]=y2(!1),[j,Z]=y2(!1),[y,V]=y2(null),[C,v]=y2(!1),h=Z4(0),o=Z4(null),B$=Z4(null),a=B1(()=>B$.current?.click(),[]);if(w)w.current=a;let U$=B1((f)=>{if(o.current=f,N)N.current=f;if(f&&_)V1(f,L)},[N,_,L]);y9(()=>{if(W&&o.current){let f=o.current;if(f.focus(),f.value)f.setSelectionRange(f.value.length,f.value.length)}},[W]);let Y$=B1(async(f)=>{if(!j4.includes(f.type)){V(l3);return}V(null),Z(!0);try{let D=await f9(z,f);if("path"in D)Y(D.path);else V(D.error)}finally{Z(!1)}},[z,Y]),N$=B1((f)=>{for(let D of f.clipboardData?.items??[])if(D.type.startsWith("image/")){f.preventDefault();let x=D.getAsFile();if(x)Y$(x);return}},[Y$]),Q$=B1((f)=>{if(f.preventDefault(),h.current++,h.current===1)S(!0)},[]),_$=B1((f)=>{f.preventDefault()},[]),F$=B1((f)=>{if(f.preventDefault(),h.current--,h.current===0)S(!1)},[]),n=B1((f)=>{f.preventDefault(),h.current=0,S(!1);for(let D of f.dataTransfer?.files??[])if(D.type.startsWith("image/"))Y$(D)},[Y$]),d=B1((f)=>{if(Q(f.currentTarget.value),_)f.currentTarget.style.height="auto",f.currentTarget.style.height=(L?Math.max(L,f.currentTarget.scrollHeight):f.currentTarget.scrollHeight)+"px"},[Q,_,L]),X$="w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none",g={width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",outline:"none",..._?{resize:"none",overflow:"hidden"}:{resize:"vertical"}},c=A&&(F==="always"||F==="on-focus"&&C);return j$("div",{style:{position:"relative"},onDragEnter:A?Q$:void 0,onDragOver:A?_$:void 0,onDragLeave:A?F$:void 0,onDrop:A?n:void 0,children:[j$("textarea",{ref:U$,value:$,onChange:H?void 0:d,onPaste:A?N$:void 0,onKeyDown:U,onClick:K,onFocus:()=>v(!0),onBlur:()=>{setTimeout(()=>v(!1),150)},readOnly:H,placeholder:X,className:O??X$,style:M??g,rows:_?1:void 0},void 0,!1,void 0,this),A&&j$("input",{ref:B$,type:"file",accept:j4.join(","),multiple:!0,style:{display:"none"},onChange:(f)=>{let D=f.currentTarget.files;if(D)for(let x of D)Y$(x);f.currentTarget.value=""}},void 0,!1,void 0,this),(J.length>0||c)&&j$("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px",alignItems:"center"},children:[J.map((f)=>j$("div",{style:{position:"relative",width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:[j$("img",{src:V4(f),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this),!H&&j$("button",{onClick:(D)=>{D.stopPropagation(),q(f)},style:{position:"absolute",top:"2px",right:"2px",width:"16px",height:"16px",borderRadius:"50%",background:"rgba(0,0,0,0.6)",color:"white",border:"none",cursor:"pointer",fontSize:"11px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,padding:0},title:"Remove image",children:"×"},void 0,!1,void 0,this)]},f,!0,void 0,this)),c&&j$(f2,{onClick:a},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j&&j$("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:"Uploading..."},void 0,!1,void 0,this),y&&j$("div",{role:"alert",style:{fontSize:"11px",color:"var(--color-accent-red)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:y},void 0,!1,void 0,this),T&&j$("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--color-highlight-bg)",opacity:0.9,border:"2px dashed var(--color-highlight-border)",borderRadius:"6px",zIndex:10,pointerEvents:"none",fontSize:"12px",fontFamily:"'Inter', sans-serif",color:"var(--color-text-secondary)"},children:"Drop image"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function f2({onClick:$,size:Q=16}){return j$("button",{onClick:(J)=>{J.stopPropagation(),$()},style:{width:`${Q*2}px`,height:`${Q*2}px`,borderRadius:"6px",border:"none",background:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--color-text-tertiary)",flexShrink:0,transition:"color 0.15s"},title:"Attach image",onMouseEnter:(J)=>{J.currentTarget.style.color="var(--color-text-secondary)"},onMouseLeave:(J)=>{J.currentTarget.style.color="var(--color-text-tertiary)"},children:j$("svg",{width:Q,height:Q,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[j$("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},void 0,!1,void 0,this),j$("circle",{cx:"8.5",cy:"8.5",r:"1.5"},void 0,!1,void 0,this),j$("polyline",{points:"21 15 16 10 5 21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function C4({images:$}){if(!$.length)return null;return j$("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px"},children:$.map((Q)=>j$("div",{style:{width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:j$("img",{src:V4(Q),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this)},Q,!1,void 0,this))},void 0,!1,void 0,this)}import{SessionContext as E9}from"@fabrika/annotations/runtime";import{useContext as v9,useEffect as g9,useRef as m9}from"react";import{jsxDEV as P$,Fragment as r3}from"react/jsx-dev-runtime";function x9($){let Q=p0($);return Q.length>80?Q.slice(0,80)+"...":Q}function t0({annotations:$,readOnly:Q=!1,onSelect:J,onReveal:Y,includedRemoteIds:q,onToggleRemoteId:G}){let{updateAnnotation:X,removeAnnotation:W,addAnnotationImage:_,removeAnnotationImage:H,activeAnnotationId:U,setActiveAnnotationId:K}=C1(),N=v9(E9),O=m9(new Map);g9(()=>{if(Q||!U)return;let A=O.current.get(U);if(A)A.scrollIntoView({behavior:"smooth",block:"nearest"})},[U,Q]);let M=(A)=>{K(A),q0(A,!0)},L=(A)=>{K(null),q0(A,!1)},F=(A)=>{if(A.id===U){K(null);return}K(A.id),J?.(A)},w=!!q&&!!G,z=(A)=>{let T=w&&A.source==="remote";return P$("div",{ref:(S)=>{if(S)O.current.set(A.id,S);else O.current.delete(A.id)},className:`group/ann relative px-3 py-2.5 transition-colors duration-150 ${Q?"cursor-pointer ":""}${U===A.id?"bg-highlight-selected":T?"bg-accent-purple-muted/30 hover:bg-accent-purple-muted/50":"odd:bg-bg-elevated-half hover:bg-bg-input"}`,onMouseEnter:()=>M(A.id),onMouseLeave:()=>L(A.id),onClick:()=>F(A),children:[T&&A.author&&P$("div",{className:"flex items-center gap-1.5 mb-1.5",children:[P$("input",{type:"checkbox",checked:q.has(A.id),onChange:(S)=>{S.stopPropagation(),G(A.id)},onClick:(S)=>S.stopPropagation(),className:"accent-accent-purple flex-shrink-0",title:"Include in submission"},void 0,!1,void 0,this),P$("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-accent-purple text-white text-[9px] font-medium uppercase",children:A.author.name.charAt(0)},void 0,!1,void 0,this),P$("span",{className:"text-[11px] font-medium text-accent-purple font-body",children:A.author.name},void 0,!1,void 0,this),P$("span",{className:"text-[10px] text-text-tertiary font-body uppercase tracking-widest",children:"Remote"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P$("div",{className:"text-[11px] text-text-tertiary italic line-clamp-2 mb-1.5 leading-snug font-body border-l-2 border-border-medium pl-2",children:x9(A.snippet)},void 0,!1,void 0,this),Q?P$(r3,{children:[A.note.trim()&&P$("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:A.note},void 0,!1,void 0,this),P$(C4,{images:A.images||[]},void 0,!1,void 0,this)]},void 0,!0,void 0,this):T?P$("div",{className:"text-[13px] font-body text-text-primary leading-relaxed whitespace-pre-wrap",children:A.note},void 0,!1,void 0,this):P$("div",{onClick:(S)=>S.stopPropagation(),children:P$(s0,{note:A.note,onNoteChange:(S)=>X(A.id,S),images:A.images||[],onAddImage:(S)=>_(A.id,S),onRemoveImage:(S)=>H(A.id,S),sessionId:N,autoResize:!0,minHeight:20,textareaClassName:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none min-h-[20px]",textareaStyle:{height:"auto",overflow:"hidden"},placeholder:"Add your note...",attachButton:"on-focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P$("div",{className:"absolute top-1.5 right-1.5 opacity-0 group-hover/ann:opacity-100 transition-opacity duration-100 flex items-center gap-0.5",children:[Y&&P$("button",{onClick:(S)=>{S.stopPropagation(),Y(A)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-input transition-colors",title:"Scroll to annotation",children:P$("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P$("circle",{cx:"12",cy:"12",r:"3"},void 0,!1,void 0,this),P$("path",{d:"M12 2v4M12 18v4M2 12h4M18 12h4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!Q&&!T&&P$("button",{onClick:(S)=>{S.stopPropagation(),W(A.id)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-accent-red hover:bg-accent-red-muted transition-colors",title:"Delete annotation",children:P$("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P$("polyline",{points:"3 6 5 6 21 6"},void 0,!1,void 0,this),P$("path",{d:"M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},A.id,!0,void 0,this)};return P$(r3,{children:$.map(z)},void 0,!1,void 0,this)}function E2($){let Q=[],J=$.snippet.trim(),Y=$.context,q=p0(J);if(q!==J)Q.push(`> ${q}`);else if($.filePath&&Y&&Y.lineStart!=null){let W=Y.lineStart,_=Y.lineEnd??W,H=J.split(`
2
- `);if(J.length<30&&W===_&&(Y.before||Y.after)){let K=A2($);Q.push(`> L${W}: ${K}`)}else if(H.length<=6)for(let K=0;K<H.length;K++)Q.push(`> ${W+K} | ${H[K]}`);else{for(let K=0;K<3;K++)Q.push(`> ${W+K} | ${H[K]}`);Q.push(`> ... (${H.length} lines)`);for(let K=H.length-3;K<H.length;K++)Q.push(`> ${W+K} | ${H[K]}`)}}else{let W=A2($);if(J.split(`
3
- `).length<=3)Q.push(`> ${W.split(`
1
+ import{ActiveViewCtx as Cp,SessionContext as sl}from"#canvas/runtime";import{AnnotationCtx as ih,AnnotationHostContext as lh,SessionContext as ch,useAnnotationHost as dh,useAnnotations as uh}from"@fabrika/annotations/runtime";function St(e,t){let n=[],o=Hs(e);for(let r of o){let a=document.createRange();if(a.selectNodeContents(r),r===e.startContainer)a.setStart(r,e.startOffset);if(r===e.endContainer)a.setEnd(r,e.endOffset);let s=a.toString();if(!s||!s.trim())continue;let l=document.createElement("mark");l.setAttribute("data-annotation-id",t);try{a.surroundContents(l)}catch{let i=a.extractContents();l.appendChild(i),a.insertNode(l)}n.push(l)}return n}function Nn(e){let t=e.parentElement;if(t?.classList.contains("select-none"))return!1;if(t?.closest("[data-annotation-id]"))return!1;return!0}function Hs(e){let t=[],n=e.commonAncestorContainer;if(n.nodeType===Node.TEXT_NODE)return t.push(n),t;let o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT),r;while(r=o.nextNode()){if(!Nn(r))continue;if(e.intersectsNode(r))t.push(r)}return t}function dl(e,t){let n=document.createRange();if(n.selectNodeContents(e),e===t.startContainer)n.setStart(e,t.startOffset);if(e===t.endContainer)n.setEnd(e,t.endOffset);return n.toString()}function Os(e){let t="";for(let n of Hs(e))t+=dl(n,e);return t}function rn(e,t){let n=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let o of n)o.classList.toggle("mark-active",t)}function _n(e,t){if(t!=null&&t!==e)rn(t,!1);if(e!=null)rn(e,!0)}function Mn(e,t){let n=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let o of n)o.setAttribute("data-annotation-id",t)}function Ln(e,t){for(let n of t){if(e.querySelector(`[data-annotation-id="${n.id}"]`))continue;let o=n.snippet;if(!o)continue;let{fullText:r,textNodes:a}=ul(e),s=[],l=0;while(!0){let h=r.indexOf(o,l);if(h===-1)break;s.push(h),l=h+1}let[i]=s;if(i===void 0)continue;let c=i;if(s.length>1&&n.context){let h=-1;for(let x of s){let g=0;if(n.context.before){let k=r.slice(Math.max(0,x-80),x);if(k.includes(n.context.before))g+=2;else if(n.context.before.length>10&&k.includes(n.context.before.slice(-10)))g+=1}if(n.context.after){let k=r.slice(x+o.length,x+o.length+80);if(k.includes(n.context.after))g+=2;else if(n.context.after.length>10&&k.includes(n.context.after.slice(0,10)))g+=1}if(g>h)h=g,c=x}}let d=c,u=c+o.length,p=$s(a,d),f=$s(a,u);if(!p||!f)continue;try{let h=document.createRange();h.setStart(p.node,p.offset),h.setEnd(f.node,f.offset),St(h,n.id)}catch{}}}function ul(e){let t=[],n="",o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r;while(r=o.nextNode()){if(!Nn(r))continue;t.push({node:r,start:n.length}),n+=r.textContent||""}return{fullText:n,textNodes:t}}function $s(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.start>t)continue;let r=t-o.start,a=o.node.textContent?.length??0;if(r<=a)return{node:o.node,offset:r}}return null}function In(e){let t=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let n of t){let o=n.parentNode;if(!o)continue;if(n.tagName!=="MARK"){o.removeChild(n);continue}while(n.firstChild)o.insertBefore(n.firstChild,n);o.removeChild(n),o.normalize()}}function At(e,t){let n=Ds(e,"before",60),o=Ds(e,"after",60),r=fl(e.startContainer,t);return{before:n,after:o,hierarchy:r}}function Ds(e,t,n){let o=pl(t==="before"?e.startContainer:e.endContainer);if(!o)return"";let r="";if(t==="before"){let a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT),s;while(s=a.nextNode()){if(s===e.startContainer){r+=(s.textContent||"").slice(0,e.startOffset);break}if(!Nn(s))continue;r+=s.textContent||""}if(r.length>n){r=r.slice(-n);let l=r.indexOf(" ");if(l>0)r=r.slice(l+1)}}else{let a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT),s=!1,l;while(l=a.nextNode()){if(l===e.endContainer){r+=(l.textContent||"").slice(e.endOffset),s=!0;continue}if(s){if(!Nn(l))continue;r+=l.textContent||""}}if(r.length>n){r=r.slice(0,n);let i=r.lastIndexOf(" ");if(i>0)r=r.slice(0,i)}}return r.trim()}function pl(e){let t=new Set(["DIV","P","LI","PRE","BLOCKQUOTE","SECTION","ARTICLE"]),n=e.parentElement;while(n){if(t.has(n.tagName))return n;n=n.parentElement}return null}function fl(e,t){let n=[],o=e instanceof Element?e:e.parentElement;while(o&&o!==t){let r=o.getAttribute?.("data-task-id");if(r){let s=o.querySelector(".font-semibold");if(s)n.unshift(s.textContent?.trim()||r)}let a=ml(o);if(a)n.unshift(a);o=o.parentElement}return n}function ml(e){if(e.getAttribute("data-md")==="section"){let n=e.getAttribute("data-md-title");if(n)return n}if(e.tagName!=="DIV")return null;return e.querySelector(":scope > button > .font-heading, :scope > div > .font-heading")?.textContent?.trim()||null}function yr(e){let t=e.snippet.trim(),n=e.context,o=t.length<30;if(n&&o&&(n.before||n.after)){let r=[];if(n.before)r.push(`...${n.before} `);if(r.push(`**${t}**`),n.after)r.push(` ${n.after}...`);return r.join("")}return t}function Pn(e){return{kind:e.kind,owns:(t)=>e.parse(t)!==null,find:(t,n)=>{let o=e.parse(t);return o===null?null:e.find(o,n)},restore:(t,n)=>{let o=e.parse(n.snippet);if(o===null)return;e.restore?.(o,t,n)},describe:(t)=>{let n=e.parse(t);if(n===null||!e.describe)return null;return e.describe(n)}}}function js(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n="";for(let o=t.nextNode();o;o=t.nextNode()){let r=o.parentElement?.closest("[aria-hidden='true']");if(r&&e.contains(r))continue;n+=o.textContent??""}return n.trim()}function kr(e,t,n){return{selector:e,snippet:(o)=>{let r=o.getAttribute(n);return r?`${t} ${r}`:null}}}var xo=[kr("[data-md='item']","[Item]","data-md-label"),kr("[data-md='section']","[Section]","data-md-title"),kr("[data-md='checklist-item']","[Checklist]","data-md-label"),kr("[data-md='image']","[Image]","data-md-src"),{selector:"[data-md='callout']",snippet:(e)=>`[Callout:${e.getAttribute("data-md-type")||"info"}] ${js(e).slice(0,60)||"Callout"}`},{selector:"[data-md='note']",snippet:(e)=>`[Note] ${js(e).slice(0,60)||"Note"}`},{selector:"[data-md='table'] tbody tr",snippet:(e)=>{let t=Array.from(e.querySelectorAll("td")).map((n)=>n.textContent?.trim()).filter(Boolean);return t.length?`[Row] ${t.join(" | ")}`:null}}],hl=["[data-md='choice-option']","[data-md='multichoice-option']","[data-md='userinput']","[data-md='rangeinput']"],Tt=xo.map((e)=>e.selector).join(", "),on=[...xo.map((e)=>e.selector),...hl].join(", ");function Xe(e){for(let t of xo)if(e.matches(t.selector))return t.snippet(e);return null}var bo={kind:"block",parse:(e)=>e.startsWith("[")?{snippet:e}:null,format:(e)=>e.snippet,find:(e,t)=>{for(let n of t.querySelectorAll(Tt)){if(!(n instanceof HTMLElement))continue;if(Xe(n)===e.snippet)return n}return null}};var yo="data-annotation-image",gl=/^\[Region:(rect|ellipse)\] ([\s\S]+) @(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*)$/;function xl(e){if(e==="rect")return"rect";if(e==="ellipse")return"ellipse";return null}function wr(e){if(e===void 0)return null;let t=Number(e);if(!Number.isInteger(t)||t<0||t>1e4)return null;return t}function Fs(e){return Math.min(1e4,Math.max(0,e))}function ko(e,t,n){if(!(e.width>0)||!(e.height>0))return null;return{x:Fs(Math.round(t/e.width*1e4)),y:Fs(Math.round(n/e.height*1e4))}}function Ar(e,t){let n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.min(1e4-n,Math.abs(e.x-t.x)),h:Math.min(1e4-o,Math.abs(e.y-t.y))}}function wo(e){return e.w>=30&&e.h>=30}function Bs(e){return{left:`${e.x/100}%`,top:`${e.y/100}%`,width:`${e.w/100}%`,height:`${e.h/100}%`}}function Sr(e){return`${(e/100).toFixed(1).replace(/\.0$/,"")}%`}function Tr(e){let t=`${Sr(e.x)}-${Sr(e.x+e.w)}`,n=`${Sr(e.y)}-${Sr(e.y+e.h)}`;return`[Region] ${e.src} — ${e.shape} x ${t}, y ${n} of the image`}function vo(e,t){for(let n of t.querySelectorAll("[data-md='image']")){if(!(n instanceof HTMLElement))continue;if(n.getAttribute("data-md-src")!==e)continue;let o=n.querySelector("[data-annotation-image]");if(o instanceof HTMLElement)return o}return null}function Er(e,t){let n=Bs(t);e.style.left=n.left,e.style.top=n.top,e.style.width=n.width,e.style.height=n.height}function Rr(e,t,n){let o=document.createElement("div");return o.className="ann-region",o.setAttribute("data-annotation-id",n),o.setAttribute("data-annotation-region",t),Er(o,e),o}var $n={kind:"region",parse:(e)=>{let t=gl.exec(e);if(!t)return null;let n=xl(t[1]),o=t[2],r=wr(t[3]),a=wr(t[4]),s=wr(t[5]),l=wr(t[6]);if(n===null||o===void 0)return null;if(r===null||a===null||s===null||l===null)return null;if(s<1||l<1)return null;return{src:o,shape:n,x:r,y:a,w:s,h:l}},format:(e)=>`[Region:${e.shape}] ${e.src} @${e.x},${e.y},${e.w},${e.h}`,find:(e,t)=>vo(e.src,t),restore:(e,t,n)=>{if(t.querySelector(`[data-annotation-id="${n.id}"]`))return;let o=vo(e.src,t);if(!o)return;o.appendChild(Rr(e,e.shape,n.id))},describe:Tr};var So={kind:"text",parse:(e)=>e?{text:e}:null,format:(e)=>e.text,find:()=>null,restore:(e,t,n)=>{Ln(t,[n])}};var Cr=[Pn($n),Pn(bo),Pn(So)];function Ao(e,t){for(let n of Cr){let o=n.find(e,t);if(o)return o}return null}function To(e,t){for(let n of t){if(!n.snippet)continue;for(let o of Cr)o.restore(e,n)}}function Hn(e){for(let t of Cr){let n=t.describe(e);if(n!==null)return n}return e}import{AnnotationCtx as Jf,SessionContext as Yf,useAnnotationHost as Xf}from"@fabrika/annotations/runtime";import{useEffect as em,useRef as tm,useState as nm}from"react";var ie;(function(e){e.assertEqual=(r)=>{};function t(r){}e.assertIs=t;function n(r){throw Error()}e.assertNever=n,e.arrayToEnum=(r)=>{let a={};for(let s of r)a[s]=s;return a},e.getValidEnumValues=(r)=>{let a=e.objectKeys(r).filter((l)=>typeof r[r[l]]!=="number"),s={};for(let l of a)s[l]=r[l];return e.objectValues(s)},e.objectValues=(r)=>e.objectKeys(r).map(function(a){return r[a]}),e.objectKeys=typeof Object.keys==="function"?(r)=>Object.keys(r):(r)=>{let a=[];for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s))a.push(s);return a},e.find=(r,a)=>{for(let s of r)if(a(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function o(r,a=" | "){return r.map((s)=>typeof s==="string"?`'${s}'`:s).join(a)}e.joinValues=o,e.jsonStringifyReplacer=(r,a)=>{if(typeof a==="bigint")return a.toString();return a}})(ie||(ie={}));var zs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(zs||(zs={}));var I=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dt=(e)=>{switch(typeof e){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(e)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":if(Array.isArray(e))return I.array;if(e===null)return I.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return I.promise;if(typeof Map<"u"&&e instanceof Map)return I.map;if(typeof Set<"u"&&e instanceof Set)return I.set;if(typeof Date<"u"&&e instanceof Date)return I.date;return I.object;default:return I.unknown}};var A=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Fe extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(r){return r.message},n={_errors:[]},o=(r)=>{for(let a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let s=n,l=0;while(l<a.path.length){let i=a.path[l];if(l!==a.path.length-1)s[i]=s[i]||{_errors:[]};else s[i]=s[i]||{_errors:[]},s[i]._errors.push(t(a));s=s[i],l++}}};return o(this),n}static assert(e){if(!(e instanceof Fe))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let o of this.issues)if(o.path.length>0){let r=o.path[0];t[r]=t[r]||[],t[r].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Fe.create=(e)=>new Fe(e);var bl=(e,t)=>{let n;switch(e.code){case A.invalid_type:if(e.received===I.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ie.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${ie.joinValues(e.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ie.joinValues(e.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${ie.joinValues(e.options)}, received '${e.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else ie.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case A.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case A.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=t.defaultError,ie.assertNever(e)}return{message:n}},Et=bl;var vl=Et;function On(){return vl}var Nr=(e)=>{let{data:t,path:n,errorMaps:o,issueData:r}=e,a=[...n,...r.path||[]],s={...r,path:a};if(r.message!==void 0)return{...r,path:a,message:r.message};let l="",i=o.filter((c)=>!!c).slice().reverse();for(let c of i)l=c(s,{data:t,defaultError:l}).message;return{...r,path:a,message:l}};function L(e,t){let n=On(),o=Nr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Et?void 0:Et].filter((r)=>!!r)});e.common.issues.push(o)}class Le{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let o of t){if(o.status==="aborted")return U;if(o.status==="dirty")e.dirty();n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let o of t){let r=await o.key,a=await o.value;n.push({key:r,value:a})}return Le.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let o of t){let{key:r,value:a}=o;if(r.status==="aborted")return U;if(a.status==="aborted")return U;if(r.status==="dirty")e.dirty();if(a.status==="dirty")e.dirty();if(r.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet))n[r.value]=a.value}return{status:e.value,value:n}}}var U=Object.freeze({status:"aborted"}),sn=(e)=>({status:"dirty",value:e}),$e=(e)=>({status:"valid",value:e}),Eo=(e)=>e.status==="aborted",Ro=(e)=>e.status==="dirty",jt=(e)=>e.status==="valid",Dn=(e)=>typeof Promise<"u"&&e instanceof Promise;var j;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(j||(j={}));class We{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=o}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var qs=(e,t)=>{if(jt(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Fe(e.common.issues);return this._error=n,this._error}}}};function ee(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:o,description:r}=e;if(t&&(n||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:r};return{errorMap:(s,l)=>{let{message:i}=e;if(s.code==="invalid_enum_value")return{message:i??l.defaultError};if(typeof l.data>"u")return{message:i??o??l.defaultError};if(s.code!=="invalid_type")return{message:l.defaultError};return{message:i??n??l.defaultError}},description:r}}class re{get description(){return this._def.description}_getType(e){return dt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Le,ctx:{common:e.parent.common,data:e.data,parsedType:dt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Dn(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return qs(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return jt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>jt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dt(e)},o=this._parse({data:e,path:n.path,parent:n}),r=await(Dn(o)?o:Promise.resolve(o));return qs(n,r)}refine(e,t){let n=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,r)=>{let a=e(o),s=()=>r.addIssue({code:A.custom,...n(o)});if(typeof Promise<"u"&&a instanceof Promise)return a.then((l)=>{if(!l)return s(),!1;else return!0});if(!a)return s(),!1;else return!0})}refinement(e,t){return this._refinement((n,o)=>{if(!e(n))return o.addIssue(typeof t==="function"?t(n,o):t),!1;else return!0})}_refinement(e){return new et({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Ze.create(this,this._def)}nullable(){return Rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qe.create(this)}promise(){return un.create(this,this._def)}or(e){return qn.create([this,e],this._def)}and(e){return Vn.create(this,e,this._def)}transform(e){return new et({...ee(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new Kn({...ee(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new Mo({typeName:G.ZodBranded,type:this,...ee(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new Jn({...ee(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Or.create(this,e)}readonly(){return Yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var yl=/^c[^\s-]{8,}$/i,kl=/^[0-9a-z]+$/,wl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Sl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Al=/^[a-z0-9_-]{21}$/i,Tl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,El=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Cl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Co,Nl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_l=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ml=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ll=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Il=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Pl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vs="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$l=new RegExp(`^${Vs}$`);function Us(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Hl(e){return new RegExp(`^${Us(e)}$`)}function Ol(e){let t=`${Vs}T${Us(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Dl(e,t){if((t==="v4"||!t)&&Nl.test(e))return!0;if((t==="v6"||!t)&&Ml.test(e))return!0;return!1}function jl(e,t){if(!Tl.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let o=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(o));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&r.alg!==t)return!1;return!0}catch{return!1}}function Fl(e,t){if((t==="v4"||!t)&&_l.test(e))return!0;if((t==="v6"||!t)&&Ll.test(e))return!0;return!1}class pt extends re{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==I.string){let r=this._getOrReturnCtx(e);return L(r,{code:A.invalid_type,expected:I.string,received:r.parsedType}),U}let n=new Le,o=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(e.data.length<r.value)o=this._getOrReturnCtx(e,o),L(o,{code:A.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty()}else if(r.kind==="max"){if(e.data.length>r.value)o=this._getOrReturnCtx(e,o),L(o,{code:A.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty()}else if(r.kind==="length"){let a=e.data.length>r.value,s=e.data.length<r.value;if(a||s){if(o=this._getOrReturnCtx(e,o),a)L(o,{code:A.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(s)L(o,{code:A.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});n.dirty()}}else if(r.kind==="email"){if(!Rl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"email",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="emoji"){if(!Co)Co=new RegExp(Cl,"u");if(!Co.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"emoji",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="uuid"){if(!Sl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"uuid",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="nanoid"){if(!Al.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"nanoid",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cuid"){if(!yl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"cuid",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cuid2"){if(!kl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"cuid2",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="ulid"){if(!wl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"ulid",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),L(o,{validation:"url",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"regex",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="trim")e.data=e.data.trim();else if(r.kind==="includes"){if(!e.data.includes(r.value,r.position))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),n.dirty()}else if(r.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(r.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(r.kind==="startsWith"){if(!e.data.startsWith(r.value))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:{startsWith:r.value},message:r.message}),n.dirty()}else if(r.kind==="endsWith"){if(!e.data.endsWith(r.value))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:{endsWith:r.value},message:r.message}),n.dirty()}else if(r.kind==="datetime"){if(!Ol(r).test(e.data))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:"datetime",message:r.message}),n.dirty()}else if(r.kind==="date"){if(!$l.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:"date",message:r.message}),n.dirty()}else if(r.kind==="time"){if(!Hl(r).test(e.data))o=this._getOrReturnCtx(e,o),L(o,{code:A.invalid_string,validation:"time",message:r.message}),n.dirty()}else if(r.kind==="duration"){if(!El.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"duration",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="ip"){if(!Dl(e.data,r.version))o=this._getOrReturnCtx(e,o),L(o,{validation:"ip",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="jwt"){if(!jl(e.data,r.alg))o=this._getOrReturnCtx(e,o),L(o,{validation:"jwt",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cidr"){if(!Fl(e.data,r.version))o=this._getOrReturnCtx(e,o),L(o,{validation:"cidr",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="base64"){if(!Il.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"base64",code:A.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="base64url"){if(!Pl.test(e.data))o=this._getOrReturnCtx(e,o),L(o,{validation:"base64url",code:A.invalid_string,message:r.message}),n.dirty()}else ie.assertNever(r);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((o)=>e.test(o),{validation:t,code:A.invalid_string,...j.errToObj(n)})}_addCheck(e){return new pt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...j.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...j.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new pt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}pt.create=(e)=>new pt({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...ee(e)});function Bl(e,t){let n=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,r=n>o?n:o,a=Number.parseInt(e.toFixed(r).replace(".","")),s=Number.parseInt(t.toFixed(r).replace(".",""));return a%s/10**r}class ln extends re{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==I.number){let r=this._getOrReturnCtx(e);return L(r,{code:A.invalid_type,expected:I.number,received:r.parsedType}),U}let n=void 0,o=new Le;for(let r of this._def.checks)if(r.kind==="int"){if(!ie.isInteger(e.data))n=this._getOrReturnCtx(e,n),L(n,{code:A.invalid_type,expected:"integer",received:"float",message:r.message}),o.dirty()}else if(r.kind==="min"){if(r.inclusive?e.data<r.value:e.data<=r.value)n=this._getOrReturnCtx(e,n),L(n,{code:A.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()}else if(r.kind==="max"){if(r.inclusive?e.data>r.value:e.data>=r.value)n=this._getOrReturnCtx(e,n),L(n,{code:A.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()}else if(r.kind==="multipleOf"){if(Bl(e.data,r.value)!==0)n=this._getOrReturnCtx(e,n),L(n,{code:A.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),L(n,{code:A.not_finite,message:r.message}),o.dirty()}else ie.assertNever(r);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,o){return new ln({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new ln({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}ln.create=(e)=>new ln({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...ee(e)});class cn extends re{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==I.bigint)return this._getInvalidInput(e);let n=void 0,o=new Le;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?e.data<r.value:e.data<=r.value)n=this._getOrReturnCtx(e,n),L(n,{code:A.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()}else if(r.kind==="max"){if(r.inclusive?e.data>r.value:e.data>=r.value)n=this._getOrReturnCtx(e,n),L(n,{code:A.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()}else if(r.kind==="multipleOf"){if(e.data%r.value!==BigInt(0))n=this._getOrReturnCtx(e,n),L(n,{code:A.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()}else ie.assertNever(r);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return L(t,{code:A.invalid_type,expected:I.bigint,received:t.parsedType}),U}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,o){return new cn({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new cn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}cn.create=(e)=>new cn({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...ee(e)});class _r extends re{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==I.boolean){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.boolean,received:n.parsedType}),U}return $e(e.data)}}_r.create=(e)=>new _r({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...ee(e)});class Fn extends re{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==I.date){let r=this._getOrReturnCtx(e);return L(r,{code:A.invalid_type,expected:I.date,received:r.parsedType}),U}if(Number.isNaN(e.data.getTime())){let r=this._getOrReturnCtx(e);return L(r,{code:A.invalid_date}),U}let n=new Le,o=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(e.data.getTime()<r.value)o=this._getOrReturnCtx(e,o),L(o,{code:A.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),n.dirty()}else if(r.kind==="max"){if(e.data.getTime()>r.value)o=this._getOrReturnCtx(e,o),L(o,{code:A.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),n.dirty()}else ie.assertNever(r);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Fn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}Fn.create=(e)=>new Fn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...ee(e)});class Mr extends re{_parse(e){if(this._getType(e)!==I.symbol){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.symbol,received:n.parsedType}),U}return $e(e.data)}}Mr.create=(e)=>new Mr({typeName:G.ZodSymbol,...ee(e)});class Bn extends re{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.undefined,received:n.parsedType}),U}return $e(e.data)}}Bn.create=(e)=>new Bn({typeName:G.ZodUndefined,...ee(e)});class zn extends re{_parse(e){if(this._getType(e)!==I.null){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.null,received:n.parsedType}),U}return $e(e.data)}}zn.create=(e)=>new zn({typeName:G.ZodNull,...ee(e)});class Lr extends re{constructor(){super(...arguments);this._any=!0}_parse(e){return $e(e.data)}}Lr.create=(e)=>new Lr({typeName:G.ZodAny,...ee(e)});class Ft extends re{constructor(){super(...arguments);this._unknown=!0}_parse(e){return $e(e.data)}}Ft.create=(e)=>new Ft({typeName:G.ZodUnknown,...ee(e)});class ft extends re{_parse(e){let t=this._getOrReturnCtx(e);return L(t,{code:A.invalid_type,expected:I.never,received:t.parsedType}),U}}ft.create=(e)=>new ft({typeName:G.ZodNever,...ee(e)});class Ir extends re{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.void,received:n.parsedType}),U}return $e(e.data)}}Ir.create=(e)=>new Ir({typeName:G.ZodVoid,...ee(e)});class Qe extends re{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==I.array)return L(t,{code:A.invalid_type,expected:I.array,received:t.parsedType}),U;if(o.exactLength!==null){let a=t.data.length>o.exactLength.value,s=t.data.length<o.exactLength.value;if(a||s)L(t,{code:a?A.too_big:A.too_small,minimum:s?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)L(t,{code:A.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)L(t,{code:A.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((a,s)=>o.type._parseAsync(new We(t,a,t.path,s)))).then((a)=>Le.mergeArray(n,a));let r=[...t.data].map((a,s)=>o.type._parseSync(new We(t,a,t.path,s)));return Le.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Qe({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new Qe({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new Qe({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}}Qe.create=(e,t)=>new Qe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...ee(t)});function an(e){if(e instanceof Ae){let t={};for(let n in e.shape){let o=e.shape[n];t[n]=Ze.create(an(o))}return new Ae({...e._def,shape:()=>t})}else if(e instanceof Qe)return new Qe({...e._def,type:an(e.element)});else if(e instanceof Ze)return Ze.create(an(e.unwrap()));else if(e instanceof Rt)return Rt.create(an(e.unwrap()));else if(e instanceof mt)return mt.create(e.items.map((t)=>an(t)));else return e}class Ae extends re{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=ie.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==I.object){let i=this._getOrReturnCtx(e);return L(i,{code:A.invalid_type,expected:I.object,received:i.parsedType}),U}let{status:n,ctx:o}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof ft&&this._def.unknownKeys==="strip")){for(let i in o.data)if(!a.includes(i))s.push(i)}let l=[];for(let i of a){let c=r[i],d=o.data[i];l.push({key:{status:"valid",value:i},value:c._parse(new We(o,d,o.path,i)),alwaysSet:i in o.data})}if(this._def.catchall instanceof ft){let i=this._def.unknownKeys;if(i==="passthrough")for(let c of s)l.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(i==="strict"){if(s.length>0)L(o,{code:A.unrecognized_keys,keys:s}),n.dirty()}else if(i==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let i=this._def.catchall;for(let c of s){let d=o.data[c];l.push({key:{status:"valid",value:c},value:i._parse(new We(o,d,o.path,c)),alwaysSet:c in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let i=[];for(let c of l){let d=await c.key,u=await c.value;i.push({key:d,value:u,alwaysSet:c.alwaysSet})}return i}).then((i)=>Le.mergeObjectSync(n,i));else return Le.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new Ae({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let o=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:j.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ae({...this._def,catchall:e})}pick(e){let t={};for(let n of ie.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new Ae({...this._def,shape:()=>t})}omit(e){let t={};for(let n of ie.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new Ae({...this._def,shape:()=>t})}deepPartial(){return an(this)}partial(e){let t={};for(let n of ie.objectKeys(this.shape)){let o=this.shape[n];if(e&&!e[n])t[n]=o;else t[n]=o.optional()}return new Ae({...this._def,shape:()=>t})}required(e){let t={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let r=this.shape[n];while(r instanceof Ze)r=r._def.innerType;t[n]=r}return new Ae({...this._def,shape:()=>t})}keyof(){return Ws(ie.objectKeys(this.shape))}}Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:ft.create(),typeName:G.ZodObject,...ee(t)});Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:ft.create(),typeName:G.ZodObject,...ee(t)});Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:ft.create(),typeName:G.ZodObject,...ee(t)});class qn extends re{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function o(r){for(let s of r)if(s.result.status==="valid")return s.result;for(let s of r)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let a=r.map((s)=>new Fe(s.ctx.common.issues));return L(t,{code:A.invalid_union,unionErrors:a}),U}if(t.common.async)return Promise.all(n.map(async(r)=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(o);else{let r=void 0,a=[];for(let l of n){let i={...t,common:{...t.common,issues:[]},parent:null},c=l._parseSync({data:t.data,path:t.path,parent:i});if(c.status==="valid")return c;else if(c.status==="dirty"&&!r)r={result:c,ctx:i};if(i.common.issues.length)a.push(i.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;let s=a.map((l)=>new Fe(l));return L(t,{code:A.invalid_union,unionErrors:s}),U}}get options(){return this._def.options}}qn.create=(e,t)=>new qn({options:e,typeName:G.ZodUnion,...ee(t)});var ut=(e)=>{if(e instanceof Un)return ut(e.schema);else if(e instanceof et)return ut(e.innerType());else if(e instanceof Wn)return[e.value];else if(e instanceof Bt)return e.options;else if(e instanceof Gn)return ie.objectValues(e.enum);else if(e instanceof Kn)return ut(e._def.innerType);else if(e instanceof Bn)return[void 0];else if(e instanceof zn)return[null];else if(e instanceof Ze)return[void 0,...ut(e.unwrap())];else if(e instanceof Rt)return[null,...ut(e.unwrap())];else if(e instanceof Mo)return ut(e.unwrap());else if(e instanceof Yn)return ut(e.unwrap());else if(e instanceof Jn)return ut(e._def.innerType);else return[]};class _o extends re{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.object)return L(t,{code:A.invalid_type,expected:I.object,received:t.parsedType}),U;let n=this.discriminator,o=t.data[n],r=this.optionsMap.get(o);if(!r)return L(t,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U;if(t.common.async)return r._parseAsync({data:t.data,path:t.path,parent:t});else return r._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let o=new Map;for(let r of t){let a=ut(r.shape[e]);if(!a.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of a){if(o.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);o.set(s,r)}}return new _o({typeName:G.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...ee(n)})}}function No(e,t){let n=dt(e),o=dt(t);if(e===t)return{valid:!0,data:e};else if(n===I.object&&o===I.object){let r=ie.objectKeys(t),a=ie.objectKeys(e).filter((l)=>r.indexOf(l)!==-1),s={...e,...t};for(let l of a){let i=No(e[l],t[l]);if(!i.valid)return{valid:!1};s[l]=i.data}return{valid:!0,data:s}}else if(n===I.array&&o===I.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let a=0;a<e.length;a++){let s=e[a],l=t[a],i=No(s,l);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}else if(n===I.date&&o===I.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class Vn extends re{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=(r,a)=>{if(Eo(r)||Eo(a))return U;let s=No(r.value,a.value);if(!s.valid)return L(n,{code:A.invalid_intersection_types}),U;if(Ro(r)||Ro(a))t.dirty();return{status:t.value,value:s.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([r,a])=>o(r,a));else return o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Vn.create=(e,t,n)=>new Vn({left:e,right:t,typeName:G.ZodIntersection,...ee(n)});class mt extends re{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.array)return L(n,{code:A.invalid_type,expected:I.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return L(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;if(!this._def.rest&&n.data.length>this._def.items.length)L(n,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let r=[...n.data].map((a,s)=>{let l=this._def.items[s]||this._def.rest;if(!l)return null;return l._parse(new We(n,a,n.path,s))}).filter((a)=>!!a);if(n.common.async)return Promise.all(r).then((a)=>Le.mergeArray(t,a));else return Le.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:e,typeName:G.ZodTuple,rest:null,...ee(t)})};class Pr extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return L(n,{code:A.invalid_type,expected:I.object,received:n.parsedType}),U;let o=[],r=this._def.keyType,a=this._def.valueType;for(let s in n.data)o.push({key:r._parse(new We(n,s,n.path,s)),value:a._parse(new We(n,n.data[s],n.path,s)),alwaysSet:s in n.data});if(n.common.async)return Le.mergeObjectAsync(t,o);else return Le.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof re)return new Pr({keyType:e,valueType:t,typeName:G.ZodRecord,...ee(n)});return new Pr({keyType:pt.create(),valueType:e,typeName:G.ZodRecord,...ee(t)})}}class $r extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.map)return L(n,{code:A.invalid_type,expected:I.map,received:n.parsedType}),U;let o=this._def.keyType,r=this._def.valueType,a=[...n.data.entries()].map(([s,l],i)=>({key:o._parse(new We(n,s,n.path,[i,"key"])),value:r._parse(new We(n,l,n.path,[i,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of a){let i=await l.key,c=await l.value;if(i.status==="aborted"||c.status==="aborted")return U;if(i.status==="dirty"||c.status==="dirty")t.dirty();s.set(i.value,c.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let l of a){let{key:i,value:c}=l;if(i.status==="aborted"||c.status==="aborted")return U;if(i.status==="dirty"||c.status==="dirty")t.dirty();s.set(i.value,c.value)}return{status:t.value,value:s}}}}$r.create=(e,t,n)=>new $r({valueType:t,keyType:e,typeName:G.ZodMap,...ee(n)});class dn extends re{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.set)return L(n,{code:A.invalid_type,expected:I.set,received:n.parsedType}),U;let o=this._def;if(o.minSize!==null){if(n.data.size<o.minSize.value)L(n,{code:A.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(n.data.size>o.maxSize.value)L(n,{code:A.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let r=this._def.valueType;function a(l){let i=new Set;for(let c of l){if(c.status==="aborted")return U;if(c.status==="dirty")t.dirty();i.add(c.value)}return{status:t.value,value:i}}let s=[...n.data.values()].map((l,i)=>r._parse(new We(n,l,n.path,i)));if(n.common.async)return Promise.all(s).then((l)=>a(l));else return a(s)}min(e,t){return new dn({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new dn({...this._def,maxSize:{value:e,message:j.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}dn.create=(e,t)=>new dn({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...ee(t)});class jn extends re{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.function)return L(t,{code:A.invalid_type,expected:I.function,received:t.parsedType}),U;function n(s,l){return Nr({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,On(),Et].filter((i)=>!!i),issueData:{code:A.invalid_arguments,argumentsError:l}})}function o(s,l){return Nr({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,On(),Et].filter((i)=>!!i),issueData:{code:A.invalid_return_type,returnTypeError:l}})}let r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof un){let s=this;return $e(async function(...l){let i=new Fe([]),c=await s._def.args.parseAsync(l,r).catch((p)=>{throw i.addIssue(n(l,p)),i}),d=await Reflect.apply(a,this,c);return await s._def.returns._def.type.parseAsync(d,r).catch((p)=>{throw i.addIssue(o(d,p)),i})})}else{let s=this;return $e(function(...l){let i=s._def.args.safeParse(l,r);if(!i.success)throw new Fe([n(l,i.error)]);let c=Reflect.apply(a,this,i.data),d=s._def.returns.safeParse(c,r);if(!d.success)throw new Fe([o(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new jn({...this._def,args:mt.create(e).rest(Ft.create())})}returns(e){return new jn({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new jn({args:e?e:mt.create([]).rest(Ft.create()),returns:t||Ft.create(),typeName:G.ZodFunction,...ee(n)})}}class Un extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Un.create=(e,t)=>new Un({getter:e,typeName:G.ZodLazy,...ee(t)});class Wn extends re{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return L(t,{received:t.data,code:A.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Wn.create=(e,t)=>new Wn({value:e,typeName:G.ZodLiteral,...ee(t)});function Ws(e,t){return new Bt({values:e,typeName:G.ZodEnum,...ee(t)})}class Bt extends re{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{expected:ie.joinValues(n),received:t.parsedType,code:A.invalid_type}),U}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return L(t,{received:t.data,code:A.invalid_enum_value,options:n}),U}return $e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Bt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Bt.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}Bt.create=Ws;class Gn extends re{_parse(e){let t=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.string&&n.parsedType!==I.number){let o=ie.objectValues(t);return L(n,{expected:ie.joinValues(o),received:n.parsedType,code:A.invalid_type}),U}if(!this._cache)this._cache=new Set(ie.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=ie.objectValues(t);return L(n,{received:n.data,code:A.invalid_enum_value,options:o}),U}return $e(e.data)}get enum(){return this._def.values}}Gn.create=(e,t)=>new Gn({values:e,typeName:G.ZodNativeEnum,...ee(t)});class un extends re{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.promise&&t.common.async===!1)return L(t,{code:A.invalid_type,expected:I.promise,received:t.parsedType}),U;let n=t.parsedType===I.promise?t.data:Promise.resolve(t.data);return $e(n.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}un.create=(e,t)=>new un({type:e,typeName:G.ZodPromise,...ee(t)});class et extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,r={addIssue:(a)=>{if(L(n,a),a.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),o.type==="preprocess"){let a=o.transform(n.data,r);if(n.common.async)return Promise.resolve(a).then(async(s)=>{if(t.value==="aborted")return U;let l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});if(l.status==="aborted")return U;if(l.status==="dirty")return sn(l.value);if(t.value==="dirty")return sn(l.value);return l});else{if(t.value==="aborted")return U;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});if(s.status==="aborted")return U;if(s.status==="dirty")return sn(s.value);if(t.value==="dirty")return sn(s.value);return s}}if(o.type==="refinement"){let a=(s)=>{let l=o.refinement(s,r);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return U;if(s.status==="dirty")t.dirty();return a(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(s.status==="aborted")return U;if(s.status==="dirty")t.dirty();return a(s.value).then(()=>({status:t.value,value:s.value}))})}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jt(a))return U;let s=o.transform(a.value,r);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((a)=>{if(!jt(a))return U;return Promise.resolve(o.transform(a.value,r)).then((s)=>({status:t.value,value:s}))});ie.assertNever(o)}}et.create=(e,t,n)=>new et({schema:e,typeName:G.ZodEffects,effect:t,...ee(n)});et.createWithPreprocess=(e,t,n)=>new et({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...ee(n)});class Ze extends re{_parse(e){if(this._getType(e)===I.undefined)return $e(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ze.create=(e,t)=>new Ze({innerType:e,typeName:G.ZodOptional,...ee(t)});class Rt extends re{_parse(e){if(this._getType(e)===I.null)return $e(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Rt.create=(e,t)=>new Rt({innerType:e,typeName:G.ZodNullable,...ee(t)});class Kn extends re{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===I.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Kn.create=(e,t)=>new Kn({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...ee(t)});class Jn extends re{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(Dn(o))return o.then((r)=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Fe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Jn.create=(e,t)=>new Jn({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...ee(t)});class Hr extends re{_parse(e){if(this._getType(e)!==I.nan){let n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:I.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}Hr.create=(e)=>new Hr({typeName:G.ZodNaN,...ee(e)});var mf=Symbol("zod_brand");class Mo extends re{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Or extends re{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return U;if(r.status==="dirty")return t.dirty(),sn(r.value);else return this._def.out._parseAsync({data:r.value,path:n.path,parent:n})})();else{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return U;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new Or({in:e,out:t,typeName:G.ZodPipeline})}}class Yn extends re{_parse(e){let t=this._def.innerType._parse(e),n=(o)=>{if(jt(o))o.value=Object.freeze(o.value);return o};return Dn(t)?t.then((o)=>n(o)):n(t)}unwrap(){return this._def.innerType}}Yn.create=(e,t)=>new Yn({innerType:e,typeName:G.ZodReadonly,...ee(t)});var hf={object:Ae.lazycreate},G;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(G||(G={}));var R=pt.create,Ce=ln.create,gf=Hr.create,xf=cn.create,tt=_r.create,bf=Fn.create,vf=Mr.create,yf=Bn.create,zl=zn.create,kf=Lr.create,pn=Ft.create,wf=ft.create,Sf=Ir.create,ye=Qe.create,{create:z,strictCreate:Af}=Ae,Dr=qn.create,Tf=_o.create,Ef=Vn.create,Lo=mt.create,Rf=Pr.create,Cf=$r.create,Nf=dn.create,_f=jn.create,Mf=Un.create,fn=Wn.create,zt=Bt.create,Lf=Gn.create,If=un.create,Pf=et.create,$f=Ze.create,Hf=Rt.create,Of=et.createWithPreprocess,Df=Or.create;var ql=z({before:R(),after:R(),hierarchy:ye(R()),lineStart:Ce().optional(),lineEnd:Ce().optional()}).passthrough(),Io=z({id:R(),name:R()}).passthrough(),Vl=z({url:R(),mime:R().optional()}).passthrough(),Po=z({id:R(),snippet:R(),note:R(),createdAt:R(),filePath:R().optional(),canvasFile:R().optional(),context:ql.optional(),images:ye(R()).optional(),attachments:ye(Vl).optional(),source:zt(["local","remote"]).optional(),author:Io.optional()}).passthrough(),Ul=ye(Po.optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).catch([]),$o=z({annotations:Ul,generalNote:R().catch("")}).passthrough(),Gs=z({path:R()}),Ks=z({url:R()}),Js=z({error:R()});import{useCallback as Vt,useMemo as Wl,useState as Gl}from"react";var Be="__agent-response__";function qt(e){return e.filePath&&e.filePath!=="__agent-response__"?e.filePath:void 0}function Xn(e){return e.uploadUrl!==null}var Ho=["image/png","image/jpeg","image/gif","image/webp"],Ys="Only PNG, JPEG, GIF and WebP images can be attached";function qe(){return`ann-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function Ct(e,t){e.style.height="auto",e.style.height=(t?Math.max(t,e.scrollHeight):e.scrollHeight)+"px"}function Xs(e){let t=e?`[data-annotation-id="${CSS.escape(e)}"]`:"[data-annotation-id]";for(let n of document.querySelectorAll(t))if(n.tagName==="MARK"){let o=n.parentNode;n.replaceWith(document.createTextNode(n.textContent||"")),o?.normalize()}else n.remove()}function jr({annotations:e,setAnnotations:t,generalNote:n,setGeneralNote:o,remoteAnnotations:r,isReadOnly:a,onClear:s}){let[l,i]=Gl(null),c=Wl(()=>{if(!r?.length)return e;let k=new Set(e.map((b)=>b.id)),m=r.filter((b)=>!k.has(b.id));return[...e,...m.map((b)=>({...b,source:"remote"}))]},[e,r]),d=Vt((k,m,b,w,y,S,T)=>{t((M)=>[...M,{id:k,snippet:m,note:b,createdAt:new Date().toISOString(),filePath:w,context:y,...S?.length?{images:S}:{},...T?{canvasFile:T}:{}}])},[t]),u=Vt((k,m,b)=>{d(qe(),k,m,b)},[d]),p=Vt((k,m)=>{t((b)=>b.map((w)=>w.id===k?{...w,note:m}:w))},[t]),f=Vt((k)=>{if(!e.some((m)=>m.id===k))return;Xs(k),t((m)=>m.filter((b)=>b.id!==k)),i((m)=>m===k?null:m)},[e,t]),h=Vt((k,m)=>{t((b)=>b.map((w)=>w.id===k?{...w,images:[...w.images||[],m]}:w))},[t]),x=Vt((k,m)=>{t((b)=>b.map((w)=>w.id===k?{...w,images:(w.images||[]).filter((y)=>y!==m)}:w))},[t]),g=Vt(()=>{Xs(),t([]),o(""),i(null),s?.()},[t,o,s]);return{annotations:c,generalNote:n,setGeneralNote:o,activeAnnotationId:l,setActiveAnnotationId:i,addAnnotation:u,addAnnotationWithId:d,updateAnnotation:p,removeAnnotation:f,addAnnotationImage:h,removeAnnotationImage:x,clearAll:g,isReadOnly:a}}import{useAnnotations as Nt}from"@fabrika/annotations/runtime";import{jsxDEV as Ut,Fragment as Kl}from"react/jsx-dev-runtime";function Oo({hasContent:e,onSubmit:t,onSubmitEmpty:n,notice:o,secondaryAction:r,placeholder:a="General notes...",submitLabel:s="Submit",emptyLabel:l="Submit without feedback"}){let{generalNote:i,setGeneralNote:c}=Nt();return Ut(Kl,{children:[Ut("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:Ut("textarea",{value:i,onChange:(d)=>c(d.currentTarget.value),className:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none leading-relaxed p-0 border-none ring-0 shadow-none outline-none focus:outline-none focus:ring-0 focus:border-none placeholder:text-text-disabled min-h-[40px]",placeholder:a,onInput:(d)=>Ct(d.currentTarget,40),ref:(d)=>{if(d)Ct(d,40)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),o,Ut("div",{className:"px-4 py-3 border-t border-border-subtle flex-shrink-0",children:e?Ut("div",{className:"flex gap-2",children:[r,Ut("button",{onClick:t,className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-btn-primary text-btn-primary-text hover:opacity-90 hover:-translate-y-px shadow-sm",children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this):Ut("button",{onClick:n,className:"w-full py-2 rounded-lg font-body text-[13px] font-medium border border-border-medium text-text-secondary hover:text-text-primary hover:border-border-hover hover:bg-bg-input transition-all",children:l},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useAnnotationHost as Jl}from"@fabrika/annotations/runtime";import{useCallback as gt,useEffect as Yl,useRef as Do,useState as Fr}from"react";import{jsxDEV as Re}from"react/jsx-dev-runtime";function jo(e){if(e.startsWith("/s/")||e.startsWith("http://")||e.startsWith("https://"))return e;return`/api/uploads/${e.split("/").pop()}`}async function Xl(e,t){let n=e.uploadUrl;if(!n)return{error:"Uploads are not available here"};let o=new FormData;o.append("image",t);try{let r=await fetch(n(),{method:"POST",body:o}),a=await r.json();if(!r.ok){let s=Js.safeParse(a);return{error:s.success?s.data.error:`Upload failed (HTTP ${r.status})`}}return{path:e.isShared?Ks.parse(a).url:Gs.parse(a).path}}catch{return{error:"Upload failed"}}}function Qn({note:e,onNoteChange:t,images:n,onAddImage:o,onRemoveImage:r,sessionId:a,placeholder:s="Add your note...",autoFocus:l=!1,autoResize:i=!1,readOnly:c=!1,onKeyDown:d,onTextareaClick:u,textareaRef:p,textareaClassName:f,textareaStyle:h,minHeight:x,attachButton:g="always",openFilePickerRef:k}){let m=Jl(),b=!c&&Xn(m),[w,y]=Fr(!1),[S,T]=Fr(!1),[M,E]=Fr(null),[C,O]=Fr(!1),B=Do(0),Y=Do(null),me=Do(null),X=gt(()=>me.current?.click(),[]);if(k)k.current=X;let pe=gt((P)=>{if(Y.current=P,p)p.current=P;if(P&&i)Ct(P,x)},[p,i,x]);Yl(()=>{if(l&&Y.current){let P=Y.current;if(P.focus(),P.value)P.setSelectionRange(P.value.length,P.value.length)}},[l]);let se=gt(async(P)=>{if(!Ho.includes(P.type)){E(Ys);return}E(null),T(!0);try{let N=await Xl(m,P);if("path"in N)o(N.path);else E(N.error)}finally{T(!1)}},[m,o]),he=gt((P)=>{for(let N of P.clipboardData?.items??[])if(N.type.startsWith("image/")){P.preventDefault();let F=N.getAsFile();if(F)se(F);return}},[se]),ne=gt((P)=>{if(P.preventDefault(),B.current++,B.current===1)y(!0)},[]),ce=gt((P)=>{P.preventDefault()},[]),ve=gt((P)=>{if(P.preventDefault(),B.current--,B.current===0)y(!1)},[]),Q=gt((P)=>{P.preventDefault(),B.current=0,y(!1);for(let N of P.dataTransfer?.files??[])if(N.type.startsWith("image/"))se(N)},[se]),W=gt((P)=>{if(t(P.currentTarget.value),i)P.currentTarget.style.height="auto",P.currentTarget.style.height=(x?Math.max(x,P.currentTarget.scrollHeight):P.currentTarget.scrollHeight)+"px"},[t,i,x]),ae="w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none",D={width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",outline:"none",...i?{resize:"none",overflow:"hidden"}:{resize:"vertical"}},V=b&&(g==="always"||g==="on-focus"&&C);return Re("div",{style:{position:"relative"},onDragEnter:b?ne:void 0,onDragOver:b?ce:void 0,onDragLeave:b?ve:void 0,onDrop:b?Q:void 0,children:[Re("textarea",{ref:pe,value:e,onChange:c?void 0:W,onPaste:b?he:void 0,onKeyDown:d,onClick:u,onFocus:()=>O(!0),onBlur:()=>{setTimeout(()=>O(!1),150)},readOnly:c,placeholder:s,className:f??ae,style:h??D,rows:i?1:void 0},void 0,!1,void 0,this),b&&Re("input",{ref:me,type:"file",accept:Ho.join(","),multiple:!0,style:{display:"none"},onChange:(P)=>{let N=P.currentTarget.files;if(N)for(let F of N)se(F);P.currentTarget.value=""}},void 0,!1,void 0,this),(n.length>0||V)&&Re("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px",alignItems:"center"},children:[n.map((P)=>Re("div",{style:{position:"relative",width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:[Re("img",{src:jo(P),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this),!c&&Re("button",{onClick:(N)=>{N.stopPropagation(),r(P)},style:{position:"absolute",top:"2px",right:"2px",width:"16px",height:"16px",borderRadius:"50%",background:"rgba(0,0,0,0.6)",color:"white",border:"none",cursor:"pointer",fontSize:"11px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,padding:0},title:"Remove image",children:"×"},void 0,!1,void 0,this)]},P,!0,void 0,this)),V&&Re(Br,{onClick:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this),S&&Re("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:"Uploading..."},void 0,!1,void 0,this),M&&Re("div",{role:"alert",style:{fontSize:"11px",color:"var(--color-accent-red)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:M},void 0,!1,void 0,this),w&&Re("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--color-highlight-bg)",opacity:0.9,border:"2px dashed var(--color-highlight-border)",borderRadius:"6px",zIndex:10,pointerEvents:"none",fontSize:"12px",fontFamily:"'Inter', sans-serif",color:"var(--color-text-secondary)"},children:"Drop image"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Br({onClick:e,size:t=16}){return Re("button",{onClick:(n)=>{n.stopPropagation(),e()},style:{width:`${t*2}px`,height:`${t*2}px`,borderRadius:"6px",border:"none",background:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--color-text-tertiary)",flexShrink:0,transition:"color 0.15s"},title:"Attach image",onMouseEnter:(n)=>{n.currentTarget.style.color="var(--color-text-secondary)"},onMouseLeave:(n)=>{n.currentTarget.style.color="var(--color-text-tertiary)"},children:Re("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[Re("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},void 0,!1,void 0,this),Re("circle",{cx:"8.5",cy:"8.5",r:"1.5"},void 0,!1,void 0,this),Re("polyline",{points:"21 15 16 10 5 21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Fo({images:e}){if(!e.length)return null;return Re("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px"},children:e.map((t)=>Re("div",{style:{width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:Re("img",{src:jo(t),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this)},t,!1,void 0,this))},void 0,!1,void 0,this)}import{SessionContext as Ql}from"@fabrika/annotations/runtime";import{useContext as Zl,useEffect as ec,useRef as tc}from"react";import{jsxDEV as we,Fragment as Qs}from"react/jsx-dev-runtime";function nc(e){let t=Hn(e);return t.length>80?t.slice(0,80)+"...":t}function Zn({annotations:e,readOnly:t=!1,onSelect:n,onReveal:o,includedRemoteIds:r,onToggleRemoteId:a}){let{updateAnnotation:s,removeAnnotation:l,addAnnotationImage:i,removeAnnotationImage:c,activeAnnotationId:d,setActiveAnnotationId:u}=Nt(),p=Zl(Ql),f=tc(new Map);ec(()=>{if(t||!d)return;let b=f.current.get(d);if(b)b.scrollIntoView({behavior:"smooth",block:"nearest"})},[d,t]);let h=(b)=>{u(b),rn(b,!0)},x=(b)=>{u(null),rn(b,!1)},g=(b)=>{if(b.id===d){u(null);return}u(b.id),n?.(b)},k=!!r&&!!a,m=(b)=>{let w=k&&b.source==="remote";return we("div",{ref:(y)=>{if(y)f.current.set(b.id,y);else f.current.delete(b.id)},className:`group/ann relative px-3 py-2.5 transition-colors duration-150 ${t?"cursor-pointer ":""}${d===b.id?"bg-highlight-selected":w?"bg-accent-purple-muted/30 hover:bg-accent-purple-muted/50":"odd:bg-bg-elevated-half hover:bg-bg-input"}`,onMouseEnter:()=>h(b.id),onMouseLeave:()=>x(b.id),onClick:()=>g(b),children:[w&&b.author&&we("div",{className:"flex items-center gap-1.5 mb-1.5",children:[we("input",{type:"checkbox",checked:r.has(b.id),onChange:(y)=>{y.stopPropagation(),a(b.id)},onClick:(y)=>y.stopPropagation(),className:"accent-accent-purple flex-shrink-0",title:"Include in submission"},void 0,!1,void 0,this),we("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-accent-purple text-white text-[9px] font-medium uppercase",children:b.author.name.charAt(0)},void 0,!1,void 0,this),we("span",{className:"text-[11px] font-medium text-accent-purple font-body",children:b.author.name},void 0,!1,void 0,this),we("span",{className:"text-[10px] text-text-tertiary font-body uppercase tracking-widest",children:"Remote"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),we("div",{className:"text-[11px] text-text-tertiary italic line-clamp-2 mb-1.5 leading-snug font-body border-l-2 border-border-medium pl-2",children:nc(b.snippet)},void 0,!1,void 0,this),t?we(Qs,{children:[b.note.trim()&&we("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:b.note},void 0,!1,void 0,this),we(Fo,{images:b.images||[]},void 0,!1,void 0,this)]},void 0,!0,void 0,this):w?we("div",{className:"text-[13px] font-body text-text-primary leading-relaxed whitespace-pre-wrap",children:b.note},void 0,!1,void 0,this):we("div",{onClick:(y)=>y.stopPropagation(),children:we(Qn,{note:b.note,onNoteChange:(y)=>s(b.id,y),images:b.images||[],onAddImage:(y)=>i(b.id,y),onRemoveImage:(y)=>c(b.id,y),sessionId:p,autoResize:!0,minHeight:20,textareaClassName:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none min-h-[20px]",textareaStyle:{height:"auto",overflow:"hidden"},placeholder:"Add your note...",attachButton:"on-focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this),we("div",{className:"absolute top-1.5 right-1.5 opacity-0 group-hover/ann:opacity-100 transition-opacity duration-100 flex items-center gap-0.5",children:[o&&we("button",{onClick:(y)=>{y.stopPropagation(),o(b)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-input transition-colors",title:"Scroll to annotation",children:we("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[we("circle",{cx:"12",cy:"12",r:"3"},void 0,!1,void 0,this),we("path",{d:"M12 2v4M12 18v4M2 12h4M18 12h4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!t&&!w&&we("button",{onClick:(y)=>{y.stopPropagation(),l(b.id)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-accent-red hover:bg-accent-red-muted transition-colors",title:"Delete annotation",children:we("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[we("polyline",{points:"3 6 5 6 21 6"},void 0,!1,void 0,this),we("path",{d:"M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},b.id,!0,void 0,this)};return we(Qs,{children:e.map(m)},void 0,!1,void 0,this)}function zr(e){let t=[],n=e.snippet.trim(),o=e.context,r=Hn(n);if(r!==n)t.push(`> ${r}`);else if(e.filePath&&o&&o.lineStart!=null){let l=o.lineStart,i=o.lineEnd??l,c=n.split(`
2
+ `);if(n.length<30&&l===i&&(o.before||o.after)){let u=yr(e);t.push(`> L${l}: ${u}`)}else if(c.length<=6)for(let u=0;u<c.length;u++)t.push(`> ${l+u} | ${c[u]}`);else{for(let u=0;u<3;u++)t.push(`> ${l+u} | ${c[u]}`);t.push(`> ... (${c.length} lines)`);for(let u=c.length-3;u<c.length;u++)t.push(`> ${l+u} | ${c[u]}`)}}else{let l=yr(e);if(n.split(`
3
+ `).length<=3)t.push(`> ${l.split(`
4
4
  `).join(`
5
- > `)}`);else{let _=J.split(`
6
- `);Q.push(`> ${_[0]}`),Q.push(`> ... (${_.length} lines)`),Q.push(`> ${_[_.length-1]}`)}}if($.note.trim())Q.push(""),Q.push($.note.trim());let G=[...$.images??[]],X=new Set(G);for(let W of $.attachments??[]){if(X.has(W.url))continue;X.add(W.url),G.push(W.url)}if(G.length){Q.push("");for(let W of G)Q.push(`![screenshot](${W})`)}return Q.push(""),Q.join(`
7
- `)}import{SessionContext as h9,useAnnotationHost as u9}from"@fabrika/annotations/runtime";import{useCallback as v2,useContext as p9,useEffect as c9,useMemo as a3,useRef as g2,useState as P0}from"react";import{createPortal as l9}from"react-dom";function i3($){let Q=/^(\d+(?:\.\d+)?)px$/.exec($.trim());return Q?Number(Q[1]):void 0}function o3($,Q,J=280){let q=Q||document.body,G=$.getBoundingClientRect(),X=q.getBoundingClientRect(),W=q===document.body?0:q.scrollTop,_=G.bottom-X.top+W+8,H=Math.max(0,Math.min(G.left-X.left,X.width-J-12));return q.style.position="relative",{style:{position:"absolute",top:`${_}px`,left:`${H}px`},parent:q}}import{jsxDEV as b$,Fragment as d9}from"react/jsx-dev-runtime";function s3({anchorEl:$,scrollContainer:Q,onClose:J,ignoreSelector:Y,zIndex:q="50",padding:G="12px",width:X="280px",children:W}){let _=g2(null),H=g2(J);H.current=J;let{style:U,parent:K}=o3($,Q,i3(X));return c9(()=>{let N=setTimeout(()=>{let O=(M)=>{if(_.current&&!_.current.contains(M.target)){if(Y&&M.target.closest?.(Y))return;H.current(),document.removeEventListener("mousedown",O)}};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},0);return()=>clearTimeout(N)},[Y]),l9(b$("div",{ref:_,style:{...U,zIndex:q,width:X,background:"var(--color-bg-elevated)",border:"1px solid var(--color-border-hover)",borderRadius:"8px",boxShadow:"0 4px 12px var(--color-shadow)",padding:G,fontFamily:"'Inter', sans-serif"},children:W},void 0,!1,void 0,this),K)}var t3=[{label:"Clarity",items:["Unclear","Why?","Needs example","Missing context"]},{label:"Scope",items:["Overkill","Out of scope","Important","Risky"]},{label:"Action",items:["Simplify","Rethink","Expand on this","Skip this"]}],n3=t3.flatMap(($)=>$.items);function R4({anchorEl:$,scrollContainer:Q,snippet:J,truncateAt:Y=100,header:q,initialNote:G="",initialImages:X,onConfirm:W,onCancel:_,onDelete:H}){let U=p9(h9),K=u9(),N=n0(K),O=G!==""||!!H,[M,L]=P0(G),[F,w]=P0(X||[]),[z,A]=P0(null),[T,S]=P0(O),[j,Z]=P0(!1),y=g2(null),V=g2(null),C=v2(()=>{if(M.trim()||F.length>0)W(M.trim(),F);else if(O&&H)H();else _()},[M,F,W,_,O,H]),v=v2(()=>{if(O){if(!M.trim()&&F.length===0&&H){H(),_();return}W(M,F);return}_()},[M,F,O,W,_,H]),h=!O,o=M.trim().length>0?n3.filter((D)=>D.toLowerCase().startsWith(M.trim().toLowerCase())):n3,B$=!h||T?[]:o.length===1&&o[0]?.toLowerCase()===M.trim().toLowerCase()?[]:o,a=new Set(B$),U$=t3.map((D)=>({label:D.label,items:D.items.filter((x)=>a.has(x))})).filter((D)=>D.items.length>0),Y$=U$.map((D)=>D.items),N$=(D)=>Y$[D]?.length??0,Q$=Y$.flat(),_$=a3(()=>{if(z===null)return 0;let D=0;for(let x=0;x<Y$.length;x++){if(z<D+N$(x))return x;D+=N$(x)}return 0},[z,Y$]),F$=a3(()=>{if(z===null)return 0;let D=0;for(let x=0;x<_$;x++)D+=N$(x);return z-D},[z,_$,Y$]),n=(D,x)=>{let r=0;for(let z$=0;z$<D;z$++)r+=N$(z$);return r+x},[d,X$]=P0(M);if(M!==d)X$(M),A(null),S(O);let g=v2((D)=>{L(D)},[]),c=J.length>Y?J.slice(0,Y)+"...":J,f=v2((D)=>{if(Q$.length>0&&(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="ArrowLeft"||D.key==="ArrowRight")){if(D.preventDefault(),z===null){A(0);return}if(D.key==="ArrowDown"){let r=Math.min(F$+1,N$(_$)-1);A(n(_$,r))}else if(D.key==="ArrowUp"){let r=Math.max(F$-1,0);A(n(_$,r))}else if(D.key==="ArrowRight"){let r=Math.min(_$+1,Y$.length-1),z$=Math.min(F$,N$(r)-1);A(n(r,z$))}else if(D.key==="ArrowLeft"){let r=Math.max(_$-1,0),z$=Math.min(F$,N$(r)-1);A(n(r,z$))}return}let x=z===null?void 0:Q$[z];if(x!==void 0){if(D.key==="Tab"){D.preventDefault(),g(x);return}if(D.key==="Enter"&&!D.shiftKey){D.preventDefault(),W(x,F);return}}if(D.key==="Enter"&&!D.shiftKey){D.preventDefault(),C();return}if(D.key==="Escape")if(Q$.length>0&&!T)S(!0);else if(O)v();else _()},[Q$,z,F$,_$,Y$,n,g,W,F,C,T,O,v,_]);return b$(s3,{anchorEl:$,scrollContainer:Q,onClose:O?v:_,ignoreSelector:O?"[data-annotation-id]":void 0,zIndex:O?"60":"50",padding:O?"10px 12px":"12px",width:"420px",children:[!O&&(q??b$("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontStyle:"italic",marginBottom:"8px",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:["“",c,"”"]},void 0,!0,void 0,this)),b$(s0,{note:M,onNoteChange:L,images:F,onAddImage:(D)=>w((x)=>[...x,D]),onRemoveImage:(D)=>w((x)=>x.filter((r)=>r!==D)),sessionId:U,autoFocus:!0,autoResize:O,textareaRef:y,onKeyDown:f,attachButton:"none",openFilePickerRef:V,textareaStyle:O?{width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"none",outline:"none",overflow:"hidden"}:{width:"100%",minHeight:"60px",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"vertical",outline:"none"},placeholder:"Add your note..."},void 0,!1,void 0,this),b$("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:O?"6px":"8px"},children:[N&&b$(f2,{onClick:()=>V.current?.(),size:14},void 0,!1,void 0,this),b$("div",{style:{flex:1}},void 0,!1,void 0,this),O?b$("button",{onClick:()=>{if(H)H();_()},onMouseEnter:()=>Z(!0),onMouseLeave:()=>Z(!1),style:{fontSize:"11px",color:j?"var(--color-accent-red)":"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"2px 0",fontFamily:"'Inter', sans-serif"},children:"Delete"},void 0,!1,void 0,this):b$(d9,{children:[b$("button",{onClick:_,style:{fontSize:"11px",color:"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"4px 12px",fontFamily:"'Inter', sans-serif"},children:"Cancel"},void 0,!1,void 0,this),b$("button",{onClick:C,style:{fontSize:"11px",fontWeight:500,padding:"4px 12px",borderRadius:"6px",background:"var(--color-highlight-bg)",color:"var(--color-text-primary)",border:"1px solid var(--color-highlight-border)",cursor:"pointer",fontFamily:"'Inter', sans-serif"},children:"Add"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q$.length>0&&b$("div",{style:{marginTop:"6px",borderTop:"1px solid var(--color-border-subtle)",paddingTop:"8px",display:"flex",gap:"4px"},children:U$.map((D)=>b$("div",{style:{flex:1},children:[b$("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--color-text-disabled)",textTransform:"uppercase",letterSpacing:"0.05em",padding:"2px 6px",marginBottom:"2px",fontFamily:"'Inter', sans-serif"},children:D.label},void 0,!1,void 0,this),D.items.map((x)=>{let r=Q$.indexOf(x);return b$("div",{onMouseDown:(z$)=>{z$.preventDefault(),z$.stopPropagation(),g(x)},onMouseEnter:()=>A(r),style:{padding:"3px 6px",fontSize:"12px",borderRadius:"4px",fontFamily:"'Inter', sans-serif",color:r===z?"var(--color-text-primary)":"var(--color-text-secondary)",background:r===z?"var(--color-highlight-selected)":"transparent",cursor:"pointer"},children:[b$("span",{style:{fontWeight:500},children:x.slice(0,M.trim().length)},void 0,!1,void 0,this),x.slice(M.trim().length)]},x,!0,void 0,this)})]},D.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Q1({anchorEl:$,scrollContainer:Q,snippet:J,truncateAt:Y,header:q,onAdd:G,onCancel:X}){return b$(R4,{anchorEl:$,scrollContainer:Q,snippet:J,truncateAt:Y,header:q,onConfirm:(W,_)=>G(W,_),onCancel:X},void 0,!1,void 0,this)}function r1({anchorEl:$,scrollContainer:Q,initialNote:J,initialImages:Y,onUpdate:q,onDelete:G,onClose:X}){return b$(R4,{anchorEl:$,scrollContainer:Q,snippet:"",initialNote:J,initialImages:Y,onConfirm:(W,_)=>{q(W,_),X()},onDelete:G,onCancel:X},void 0,!1,void 0,this)}import{useEffect as r9,useRef as D4,useState as e3}from"react";import{jsxDEV as i9}from"react/jsx-dev-runtime";function I4($){let{containerRef:Q,restoreKey:J,shape:Y="rect",canvasFile:q,scrollContainer:G}=$,{addAnnotationWithId:X}=C1(),[W,_]=e3(null),[H,U]=e3(!1),K=D4(X);K.current=X;let N=D4(q);N.current=q;let O=D4(Y);return O.current=Y,r9(()=>{let L=Q.current;if(!L)return;let F=null;function w(Z,y){let V=Z.getBoundingClientRect();return N4(V,y.clientX-V.left,y.clientY-V.top)}function z(){if(!F)return;let{host:Z,pointerId:y}=F;if(Z.hasPointerCapture(y))Z.releasePointerCapture(y);Z.removeEventListener("pointermove",T),Z.removeEventListener("pointerup",S),Z.removeEventListener("pointercancel",j),F=null,U(!1)}function A(Z){if(F||Z.button!==0)return;let y=Z.target;if(!(y instanceof Element))return;if(y.closest("[data-block-comment-btn]"))return;if(y.closest("[data-annotation-id]"))return;let V=y.closest(`[${B4}]`);if(!(V instanceof HTMLElement)||!L?.contains(V))return;let C=V.closest("[data-md='image']")?.getAttribute("data-md-src");if(!C)return;let v=w(V,Z);if(!v)return;Z.preventDefault(),V.setPointerCapture(Z.pointerId);let h=x$(),o=Z2({...v,w:0,h:0},O.current,h);o.classList.add("ann-region-draft"),V.appendChild(o),F={pointerId:Z.pointerId,host:V,src:C,start:v,shape:O.current,overlay:o,id:h},V.addEventListener("pointermove",T),V.addEventListener("pointerup",S),V.addEventListener("pointercancel",j),U(!0)}function T(Z){if(!F||F.pointerId!==Z.pointerId)return;let y=w(F.host,Z);if(!y)return;b2(F.overlay,T2(F.start,y))}function S(Z){if(!F||F.pointerId!==Z.pointerId)return;let{overlay:y,id:V,src:C,shape:v}=F,h=w(F.host,Z)??F.start,o=T2(F.start,h);if(z(),!O4(o)){y.remove();return}b2(y,o);let B$={src:C,shape:v,...o};_({overlay:y,id:V,snippet:u0.format(B$),label:j2(B$)})}function j(Z){if(!F||F.pointerId!==Z.pointerId)return;F.overlay.remove(),z()}return L.addEventListener("pointerdown",A),()=>{if(L.removeEventListener("pointerdown",A),F)F.overlay.remove(),z()}},[J]),{popovers:W?i9(Q1,{anchorEl:W.overlay,scrollContainer:G,snippet:W.label,truncateAt:80,onAdd:(L,F)=>{W.overlay.classList.remove("ann-region-draft"),K.current(W.id,W.snippet,L,void 0,void 0,F,N.current),_(null)},onCancel:()=>{W.overlay.remove(),_(null)}},void 0,!1,void 0,this):null,isDrawing:H,isPopoverOpen:!!W}}import{useCallback as $5,useEffect as m2,useRef as i1,useState as Q5}from"react";import{jsxDEV as k4,Fragment as o9}from"react/jsx-dev-runtime";function R1($){let{containerRef:Q,restoreKey:J,restoreAnnotations:Y,extractContext:q,filePath:G,canvasFile:X,scrollContainer:W}=$,{annotations:_,addAnnotationWithId:H,removeAnnotation:U,updateAnnotation:K,addAnnotationImage:N,removeAnnotationImage:O,activeAnnotationId:M,setActiveAnnotationId:L}=C1(),[F,w]=Q5(null),[z,A]=Q5(null),T=i1(q);T.current=q;let S=i1(G);S.current=G;let j=i1(X);j.current=X;let Z=i1(H);Z.current=H;let y=i1(M);y.current=M;let V=i1(L);V.current=L;let C=Y.length;m2(()=>{if(!Q.current)return;let a=setTimeout(()=>{if(Q.current)F4(Q.current,Y)},50);return()=>clearTimeout(a)},[J,C]);let v=i1(null);m2(()=>{v0(M,v.current),v.current=M},[M]),m2(()=>{let a=Q.current;if(!a)return;let U$=(Q$)=>{let _$=Q$.target.closest("[data-annotation-id]");if(!_$)return;Q$.stopPropagation();let F$=_$.getAttribute("data-annotation-id");if(F$===y.current)w({anchorEl:_$,annId:F$});else V.current(F$)},Y$=(Q$)=>{let _$=Q$.target.closest("[data-annotation-id]");if(_$)V.current(_$.getAttribute("data-annotation-id"))},N$=(Q$)=>{let _$=Q$.target.closest("[data-annotation-id]"),F$=Q$.relatedTarget?.closest?.("[data-annotation-id]");if(_$&&!F$&&!document.getElementById("ann-inline-popover"))V.current(null)};return a.addEventListener("click",U$),a.addEventListener("mouseover",Y$),a.addEventListener("mouseout",N$),()=>{a.removeEventListener("click",U$),a.removeEventListener("mouseover",Y$),a.removeEventListener("mouseout",N$)}},[J]),m2(()=>{let a=()=>h();return document.addEventListener("mouseup",a),()=>document.removeEventListener("mouseup",a)},[]);let h=$5(()=>{let a=window.getSelection();if(!a||a.isCollapsed||!a.toString().trim())return;if(!Q.current)return;let U$=a.getRangeAt(0);if(!Q.current.contains(U$.startContainer))return;if(U$.startContainer.parentElement?.closest?.("[data-annotation-id]"))return;let Y$=b3(U$).trim();if(Y$.length<2)return;let N$=T.current(U$),Q$=U$.cloneRange(),_$=`__pending_${Date.now()}`;try{A1(Q$,_$)}catch{}window.getSelection()?.removeAllRanges();let F$=document.querySelectorAll(`[data-annotation-id="${_$}"]`),n=F$[F$.length-1];if(!n)return;A({anchorEl:n,tempId:_$,snippet:Y$,ctx:N$})},[]),o=$5((a,U$,Y$,N$)=>{A({anchorEl:a,tempId:U$,snippet:Y$,ctx:N$})},[]);return{popovers:k4(o9,{children:[F&&(()=>{let a=_.find((U$)=>U$.id===F.annId);if(!a)return null;return k4(r1,{anchorEl:F.anchorEl,scrollContainer:W,initialNote:a.note,initialImages:a.images,onUpdate:(U$,Y$)=>{K(F.annId,U$);let N$=a.images||[];for(let Q$ of Y$)if(!N$.includes(Q$))N(F.annId,Q$);for(let Q$ of N$)if(!Y$.includes(Q$))O(F.annId,Q$)},onDelete:()=>{U(F.annId),L(null)},onClose:()=>w(null)},void 0,!1,void 0,this)})(),z&&k4(Q1,{anchorEl:z.anchorEl,scrollContainer:W,snippet:z.snippet,truncateAt:80,onAdd:(a,U$)=>{let Y$=x$();g0(z.tempId,Y$),Z.current(Y$,z.snippet,a,S.current,z.ctx,U$,j.current),A(null)},onCancel:()=>{x0(z.tempId),A(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),openCreatePopover:o,isPopoverOpen:!!(F||z)}}import{AnnotationCtx as YQ}from"#canvas/runtime";import{AnnotationCtx as XQ,AnnotationHostContext as GQ}from"@fabrika/annotations/runtime";import{useCallback as T0,useEffect as B5,useMemo as _Q,useRef as g4,useState as j0}from"react";var a9=B.object({}).passthrough(),n9=B.object({annotations:B.array(B.unknown()).catch([]),generalNote:B.string().catch(""),responses:B.array(B.unknown()).catch([])}),s9=B.tuple([B.unknown(),B.object({note:B.unknown(),value:B.unknown()})]);function J1($,Q,J="current"){let Y=`canvas:${$}:rev:${Q}`;return J==="next"?`${Y}:next-draft`:Y}function S0($,Q){return`${J1($,Q)}:draft-handled`}function o1($,Q,J){try{$.removeItem(J1(Q,J)),$.removeItem(S0(Q,J))}catch{}}function y4($){if(!$)return null;try{let Q=JSON.parse($),J=a9.safeParse(Q);return J.success?J.data:null}catch{return null}}function t9($){let Q=s9.safeParse($);if(!Q.success)return!1;let{note:J,value:Y}=Q.data[1];if(typeof J==="string"&&J.trim().length>0)return!0;if(typeof Y==="string")return Y.trim().length>0;if(Array.isArray(Y))return Y.length>0;return Y!==null&&Y!==void 0}function f4($){if(!$)return!1;let{annotations:Q,generalNote:J,responses:Y}=n9.parse($);return Q.length>0||J.trim().length>0||Y.some(t9)}function x2($,Q,J,Y){try{let q=J1(Q,J);if(f4(y4($.getItem(q))))return $.setItem(S0(Q,J),"1"),null;if($.getItem(S0(Q,J))!==null)return null;let G=Y.filter((X)=>X.revision<J).sort((X,W)=>W.revision-X.revision);for(let X of G){if(X.hasFeedback){let _=J1(Q,X.revision,"next"),H=y4($.getItem(_));if(!f4(H))return null;return $.setItem(q,JSON.stringify({...H,feedbackEntries:[]})),$.setItem(S0(Q,J),"1"),$.removeItem(_),X.revision}let W=y4($.getItem(J1(Q,X.revision)));if(!f4(W)){if($.getItem(S0(Q,X.revision))!==null)return null;continue}return $.setItem(q,JSON.stringify({...W,feedbackEntries:[]})),$.setItem(S0(Q,J),"1"),X.revision}}catch{}return null}function E4($,Q){let J=new Map;for(let[Y,q]of $)if(Q.has(Y))J.set(Y,q);return J}function v4($,Q){if(!$||$.length===0)return!1;return $.every((J)=>Q.has(J))}function e9($,Q){return $.filter((J)=>J.source!=="remote"||Q&&Q.has(J.id))}function e0($,Q,J,Y,q,G={}){let X=[],W=e9($,q),_=(L)=>G.annotationIds&&L.source!=="remote"?`Annotation \`${L.id}\`
8
- ${E2(L)}`:E2(L),H=W.filter((L)=>L.filePath===g$),U=W.filter((L)=>!L.filePath),K=W.filter((L)=>L.filePath&&L.filePath!==g$),N=J?Array.from(J.values()).filter((L)=>$2(L)):[],O=Y?Array.from(Y.values()).filter((L)=>L.markdown.trim()):[];if(N.length>0||O.length>0){X.push("## Responses"),X.push("");for(let L of N)X.push($Q(L));for(let L of O)X.push(L.markdown.trim()),X.push("")}if(H.length>0){X.push("## Annotations on agent response"),X.push("");for(let L of H)X.push(_(L))}if(U.length>0){X.push("## Canvas annotations"),X.push("");let L=new Map;for(let z of U){let A=z.canvasFile||"";if(!L.has(A))L.set(A,[]);L.get(A).push(z)}let F=[...L.keys()].sort(),w=F.length>1||F.length===1&&F[0]!=="";for(let z of F){let A=L.get(z);if(w&&z)X.push(`### ${z.replace(/\.jsx$/,"")}`),X.push("");let T=QQ(A);X.push(X5(T,_))}}if(K.length>0){let L={};for(let F of K){let w=F.filePath;if(!L[w])L[w]=[];L[w].push(F)}X.push("## File annotations"),X.push("");for(let[F,w]of Object.entries(L)){X.push(`### ${F}`),X.push("");for(let z of w)X.push(_(z))}}if(Q.trim())X.push("## General notes"),X.push(""),X.push(Q.trim()),X.push("");return X.join(`
5
+ > `)}`);else{let i=n.split(`
6
+ `);t.push(`> ${i[0]}`),t.push(`> ... (${i.length} lines)`),t.push(`> ${i[i.length-1]}`)}}if(e.note.trim())t.push(""),t.push(e.note.trim());let a=[...e.images??[]],s=new Set(a);for(let l of e.attachments??[]){if(s.has(l.url))continue;s.add(l.url),a.push(l.url)}if(a.length){t.push("");for(let l of a)t.push(`![screenshot](${l})`)}return t.push(""),t.join(`
7
+ `)}import{SessionContext as rc,useAnnotationHost as oc}from"@fabrika/annotations/runtime";import{useCallback as qr,useContext as sc,useEffect as ac,useMemo as ta,useRef as Vr,useState as mn}from"react";import{createPortal as ic}from"react-dom";function Zs(e){let t=/^(\d+(?:\.\d+)?)px$/.exec(e.trim());return t?Number(t[1]):void 0}function ea(e,t,n=280){let r=t||document.body,a=e.getBoundingClientRect(),s=r.getBoundingClientRect(),l=r===document.body?0:r.scrollTop,i=a.bottom-s.top+l+8,c=Math.max(0,Math.min(a.left-s.left,s.width-n-12));return r.style.position="relative",{style:{position:"absolute",top:`${i}px`,left:`${c}px`},parent:r}}import{jsxDEV as Ne,Fragment as lc}from"react/jsx-dev-runtime";function ra({anchorEl:e,scrollContainer:t,onClose:n,ignoreSelector:o,zIndex:r="50",padding:a="12px",width:s="280px",children:l}){let i=Vr(null),c=Vr(n);c.current=n;let{style:d,parent:u}=ea(e,t,Zs(s));return ac(()=>{let p=setTimeout(()=>{let f=(h)=>{if(i.current&&!i.current.contains(h.target)){if(o&&h.target.closest?.(o))return;c.current(),document.removeEventListener("mousedown",f)}};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},0);return()=>clearTimeout(p)},[o]),ic(Ne("div",{ref:i,style:{...d,zIndex:r,width:s,background:"var(--color-bg-elevated)",border:"1px solid var(--color-border-hover)",borderRadius:"8px",boxShadow:"0 4px 12px var(--color-shadow)",padding:a,fontFamily:"'Inter', sans-serif"},children:l},void 0,!1,void 0,this),u)}var oa=[{label:"Clarity",items:["Unclear","Why?","Needs example","Missing context"]},{label:"Scope",items:["Overkill","Out of scope","Important","Risky"]},{label:"Action",items:["Simplify","Rethink","Expand on this","Skip this"]}],na=oa.flatMap((e)=>e.items);function Bo({anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o=100,header:r,initialNote:a="",initialImages:s,onConfirm:l,onCancel:i,onDelete:c}){let d=sc(rc),u=oc(),p=Xn(u),f=a!==""||!!c,[h,x]=mn(a),[g,k]=mn(s||[]),[m,b]=mn(null),[w,y]=mn(f),[S,T]=mn(!1),M=Vr(null),E=Vr(null),C=qr(()=>{if(h.trim()||g.length>0)l(h.trim(),g);else if(f&&c)c();else i()},[h,g,l,i,f,c]),O=qr(()=>{if(f){if(!h.trim()&&g.length===0&&c){c(),i();return}l(h,g);return}i()},[h,g,f,l,i,c]),B=!f,Y=h.trim().length>0?na.filter((N)=>N.toLowerCase().startsWith(h.trim().toLowerCase())):na,me=!B||w?[]:Y.length===1&&Y[0]?.toLowerCase()===h.trim().toLowerCase()?[]:Y,X=new Set(me),pe=oa.map((N)=>({label:N.label,items:N.items.filter((F)=>X.has(F))})).filter((N)=>N.items.length>0),se=pe.map((N)=>N.items),he=(N)=>se[N]?.length??0,ne=se.flat(),ce=ta(()=>{if(m===null)return 0;let N=0;for(let F=0;F<se.length;F++){if(m<N+he(F))return F;N+=he(F)}return 0},[m,se]),ve=ta(()=>{if(m===null)return 0;let N=0;for(let F=0;F<ce;F++)N+=he(F);return m-N},[m,ce,se]),Q=(N,F)=>{let K=0;for(let xe=0;xe<N;xe++)K+=he(xe);return K+F},[W,ae]=mn(h);if(h!==W)ae(h),b(null),y(f);let D=qr((N)=>{x(N)},[]),V=n.length>o?n.slice(0,o)+"...":n,P=qr((N)=>{if(ne.length>0&&(N.key==="ArrowDown"||N.key==="ArrowUp"||N.key==="ArrowLeft"||N.key==="ArrowRight")){if(N.preventDefault(),m===null){b(0);return}if(N.key==="ArrowDown"){let K=Math.min(ve+1,he(ce)-1);b(Q(ce,K))}else if(N.key==="ArrowUp"){let K=Math.max(ve-1,0);b(Q(ce,K))}else if(N.key==="ArrowRight"){let K=Math.min(ce+1,se.length-1),xe=Math.min(ve,he(K)-1);b(Q(K,xe))}else if(N.key==="ArrowLeft"){let K=Math.max(ce-1,0),xe=Math.min(ve,he(K)-1);b(Q(K,xe))}return}let F=m===null?void 0:ne[m];if(F!==void 0){if(N.key==="Tab"){N.preventDefault(),D(F);return}if(N.key==="Enter"&&!N.shiftKey){N.preventDefault(),l(F,g);return}}if(N.key==="Enter"&&!N.shiftKey){N.preventDefault(),C();return}if(N.key==="Escape")if(ne.length>0&&!w)y(!0);else if(f)O();else i()},[ne,m,ve,ce,se,Q,D,l,g,C,w,f,O,i]);return Ne(ra,{anchorEl:e,scrollContainer:t,onClose:f?O:i,ignoreSelector:f?"[data-annotation-id]":void 0,zIndex:f?"60":"50",padding:f?"10px 12px":"12px",width:"420px",children:[!f&&(r??Ne("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontStyle:"italic",marginBottom:"8px",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:["“",V,"”"]},void 0,!0,void 0,this)),Ne(Qn,{note:h,onNoteChange:x,images:g,onAddImage:(N)=>k((F)=>[...F,N]),onRemoveImage:(N)=>k((F)=>F.filter((K)=>K!==N)),sessionId:d,autoFocus:!0,autoResize:f,textareaRef:M,onKeyDown:P,attachButton:"none",openFilePickerRef:E,textareaStyle:f?{width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"none",outline:"none",overflow:"hidden"}:{width:"100%",minHeight:"60px",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"vertical",outline:"none"},placeholder:"Add your note..."},void 0,!1,void 0,this),Ne("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:f?"6px":"8px"},children:[p&&Ne(Br,{onClick:()=>E.current?.(),size:14},void 0,!1,void 0,this),Ne("div",{style:{flex:1}},void 0,!1,void 0,this),f?Ne("button",{onClick:()=>{if(c)c();i()},onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{fontSize:"11px",color:S?"var(--color-accent-red)":"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"2px 0",fontFamily:"'Inter', sans-serif"},children:"Delete"},void 0,!1,void 0,this):Ne(lc,{children:[Ne("button",{onClick:i,style:{fontSize:"11px",color:"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"4px 12px",fontFamily:"'Inter', sans-serif"},children:"Cancel"},void 0,!1,void 0,this),Ne("button",{onClick:C,style:{fontSize:"11px",fontWeight:500,padding:"4px 12px",borderRadius:"6px",background:"var(--color-highlight-bg)",color:"var(--color-text-primary)",border:"1px solid var(--color-highlight-border)",cursor:"pointer",fontFamily:"'Inter', sans-serif"},children:"Add"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),ne.length>0&&Ne("div",{style:{marginTop:"6px",borderTop:"1px solid var(--color-border-subtle)",paddingTop:"8px",display:"flex",gap:"4px"},children:pe.map((N)=>Ne("div",{style:{flex:1},children:[Ne("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--color-text-disabled)",textTransform:"uppercase",letterSpacing:"0.05em",padding:"2px 6px",marginBottom:"2px",fontFamily:"'Inter', sans-serif"},children:N.label},void 0,!1,void 0,this),N.items.map((F)=>{let K=ne.indexOf(F);return Ne("div",{onMouseDown:(xe)=>{xe.preventDefault(),xe.stopPropagation(),D(F)},onMouseEnter:()=>b(K),style:{padding:"3px 6px",fontSize:"12px",borderRadius:"4px",fontFamily:"'Inter', sans-serif",color:K===m?"var(--color-text-primary)":"var(--color-text-secondary)",background:K===m?"var(--color-highlight-selected)":"transparent",cursor:"pointer"},children:[Ne("span",{style:{fontWeight:500},children:F.slice(0,h.trim().length)},void 0,!1,void 0,this),F.slice(h.trim().length)]},F,!0,void 0,this)})]},N.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nt({anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o,header:r,onAdd:a,onCancel:s}){return Ne(Bo,{anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o,header:r,onConfirm:(l,i)=>a(l,i),onCancel:s},void 0,!1,void 0,this)}function Wt({anchorEl:e,scrollContainer:t,initialNote:n,initialImages:o,onUpdate:r,onDelete:a,onClose:s}){return Ne(Bo,{anchorEl:e,scrollContainer:t,snippet:"",initialNote:n,initialImages:o,onConfirm:(l,i)=>{r(l,i),s()},onDelete:a,onCancel:s},void 0,!1,void 0,this)}import{useEffect as cc,useRef as zo,useState as sa}from"react";import{jsxDEV as dc}from"react/jsx-dev-runtime";function qo(e){let{containerRef:t,restoreKey:n,shape:o="rect",canvasFile:r,scrollContainer:a}=e,{addAnnotationWithId:s}=Nt(),[l,i]=sa(null),[c,d]=sa(!1),u=zo(s);u.current=s;let p=zo(r);p.current=r;let f=zo(o);return f.current=o,cc(()=>{let x=t.current;if(!x)return;let g=null;function k(T,M){let E=T.getBoundingClientRect();return ko(E,M.clientX-E.left,M.clientY-E.top)}function m(){if(!g)return;let{host:T,pointerId:M}=g;if(T.hasPointerCapture(M))T.releasePointerCapture(M);T.removeEventListener("pointermove",w),T.removeEventListener("pointerup",y),T.removeEventListener("pointercancel",S),g=null,d(!1)}function b(T){if(g||T.button!==0)return;let M=T.target;if(!(M instanceof Element))return;if(M.closest("[data-block-comment-btn]"))return;if(M.closest("[data-annotation-id]"))return;let E=M.closest(`[${yo}]`);if(!(E instanceof HTMLElement)||!x?.contains(E))return;let C=E.closest("[data-md='image']")?.getAttribute("data-md-src");if(!C)return;let O=k(E,T);if(!O)return;T.preventDefault(),E.setPointerCapture(T.pointerId);let B=qe(),Y=Rr({...O,w:0,h:0},f.current,B);Y.classList.add("ann-region-draft"),E.appendChild(Y),g={pointerId:T.pointerId,host:E,src:C,start:O,shape:f.current,overlay:Y,id:B},E.addEventListener("pointermove",w),E.addEventListener("pointerup",y),E.addEventListener("pointercancel",S),d(!0)}function w(T){if(!g||g.pointerId!==T.pointerId)return;let M=k(g.host,T);if(!M)return;Er(g.overlay,Ar(g.start,M))}function y(T){if(!g||g.pointerId!==T.pointerId)return;let{overlay:M,id:E,src:C,shape:O}=g,B=k(g.host,T)??g.start,Y=Ar(g.start,B);if(m(),!wo(Y)){M.remove();return}Er(M,Y);let me={src:C,shape:O,...Y};i({overlay:M,id:E,snippet:$n.format(me),label:Tr(me)})}function S(T){if(!g||g.pointerId!==T.pointerId)return;g.overlay.remove(),m()}return x.addEventListener("pointerdown",b),()=>{if(x.removeEventListener("pointerdown",b),g)g.overlay.remove(),m()}},[n]),{popovers:l?dc(nt,{anchorEl:l.overlay,scrollContainer:a,snippet:l.label,truncateAt:80,onAdd:(x,g)=>{l.overlay.classList.remove("ann-region-draft"),u.current(l.id,l.snippet,x,void 0,void 0,g,p.current),i(null)},onCancel:()=>{l.overlay.remove(),i(null)}},void 0,!1,void 0,this):null,isDrawing:c,isPopoverOpen:!!l}}import{useCallback as aa,useEffect as Ur,useRef as Gt,useState as ia}from"react";import{jsxDEV as Vo,Fragment as uc}from"react/jsx-dev-runtime";function _t(e){let{containerRef:t,restoreKey:n,restoreAnnotations:o,extractContext:r,filePath:a,canvasFile:s,scrollContainer:l}=e,{annotations:i,addAnnotationWithId:c,removeAnnotation:d,updateAnnotation:u,addAnnotationImage:p,removeAnnotationImage:f,activeAnnotationId:h,setActiveAnnotationId:x}=Nt(),[g,k]=ia(null),[m,b]=ia(null),w=Gt(r);w.current=r;let y=Gt(a);y.current=a;let S=Gt(s);S.current=s;let T=Gt(c);T.current=c;let M=Gt(h);M.current=h;let E=Gt(x);E.current=x;let C=o.length;Ur(()=>{if(!t.current)return;let X=setTimeout(()=>{if(t.current)To(t.current,o)},50);return()=>clearTimeout(X)},[n,C]);let O=Gt(null);Ur(()=>{_n(h,O.current),O.current=h},[h]),Ur(()=>{let X=t.current;if(!X)return;let pe=(ne)=>{let ce=ne.target.closest("[data-annotation-id]");if(!ce)return;ne.stopPropagation();let ve=ce.getAttribute("data-annotation-id");if(ve===M.current)k({anchorEl:ce,annId:ve});else E.current(ve)},se=(ne)=>{let ce=ne.target.closest("[data-annotation-id]");if(ce)E.current(ce.getAttribute("data-annotation-id"))},he=(ne)=>{let ce=ne.target.closest("[data-annotation-id]"),ve=ne.relatedTarget?.closest?.("[data-annotation-id]");if(ce&&!ve&&!document.getElementById("ann-inline-popover"))E.current(null)};return X.addEventListener("click",pe),X.addEventListener("mouseover",se),X.addEventListener("mouseout",he),()=>{X.removeEventListener("click",pe),X.removeEventListener("mouseover",se),X.removeEventListener("mouseout",he)}},[n]),Ur(()=>{let X=()=>B();return document.addEventListener("mouseup",X),()=>document.removeEventListener("mouseup",X)},[]);let B=aa(()=>{let X=window.getSelection();if(!X||X.isCollapsed||!X.toString().trim())return;if(!t.current)return;let pe=X.getRangeAt(0);if(!t.current.contains(pe.startContainer))return;if(pe.startContainer.parentElement?.closest?.("[data-annotation-id]"))return;let se=Os(pe).trim();if(se.length<2)return;let he=w.current(pe),ne=pe.cloneRange(),ce=`__pending_${Date.now()}`;try{St(ne,ce)}catch{}window.getSelection()?.removeAllRanges();let ve=document.querySelectorAll(`[data-annotation-id="${ce}"]`),Q=ve[ve.length-1];if(!Q)return;b({anchorEl:Q,tempId:ce,snippet:se,ctx:he})},[]),Y=aa((X,pe,se,he)=>{b({anchorEl:X,tempId:pe,snippet:se,ctx:he})},[]);return{popovers:Vo(uc,{children:[g&&(()=>{let X=i.find((pe)=>pe.id===g.annId);if(!X)return null;return Vo(Wt,{anchorEl:g.anchorEl,scrollContainer:l,initialNote:X.note,initialImages:X.images,onUpdate:(pe,se)=>{u(g.annId,pe);let he=X.images||[];for(let ne of se)if(!he.includes(ne))p(g.annId,ne);for(let ne of he)if(!se.includes(ne))f(g.annId,ne)},onDelete:()=>{d(g.annId),x(null)},onClose:()=>k(null)},void 0,!1,void 0,this)})(),m&&Vo(nt,{anchorEl:m.anchorEl,scrollContainer:l,snippet:m.snippet,truncateAt:80,onAdd:(X,pe)=>{let se=qe();Mn(m.tempId,se),T.current(se,m.snippet,X,y.current,m.ctx,pe,S.current),b(null)},onCancel:()=>{In(m.tempId),b(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),openCreatePopover:Y,isPopoverOpen:!!(g||m)}}import{AnnotationCtx as kc}from"#canvas/runtime";import{AnnotationCtx as wc,AnnotationHostContext as Sc}from"@fabrika/annotations/runtime";import{useCallback as xn,useEffect as ba,useMemo as Ac,useRef as Jo,useState as bn}from"react";var pc=z({}).passthrough(),fc=z({annotations:ye(pn()).catch([]),generalNote:R().catch(""),responses:ye(pn()).catch([])}),mc=Lo([pn(),z({note:pn(),value:pn()})]);function rt(e,t,n="current"){let o=`canvas:${e}:rev:${t}`;return n==="next"?`${o}:next-draft`:o}function hn(e,t){return`${rt(e,t)}:draft-handled`}function Kt(e,t,n){try{e.removeItem(rt(t,n)),e.removeItem(hn(t,n))}catch{}}function Uo(e){if(!e)return null;try{let t=JSON.parse(e),n=pc.safeParse(t);return n.success?n.data:null}catch{return null}}function hc(e){let t=mc.safeParse(e);if(!t.success)return!1;let{note:n,value:o}=t.data[1];if(typeof n==="string"&&n.trim().length>0)return!0;if(typeof o==="string")return o.trim().length>0;if(Array.isArray(o))return o.length>0;return o!==null&&o!==void 0}function Wo(e){if(!e)return!1;let{annotations:t,generalNote:n,responses:o}=fc.parse(e);return t.length>0||n.trim().length>0||o.some(hc)}function Wr(e,t,n,o){try{let r=rt(t,n);if(Wo(Uo(e.getItem(r))))return e.setItem(hn(t,n),"1"),null;if(e.getItem(hn(t,n))!==null)return null;let a=o.filter((s)=>s.revision<n).sort((s,l)=>l.revision-s.revision);for(let s of a){if(s.hasFeedback){let i=rt(t,s.revision,"next"),c=Uo(e.getItem(i));if(!Wo(c))return null;return e.setItem(r,JSON.stringify({...c,feedbackEntries:[]})),e.setItem(hn(t,n),"1"),e.removeItem(i),s.revision}let l=Uo(e.getItem(rt(t,s.revision)));if(!Wo(l)){if(e.getItem(hn(t,s.revision))!==null)return null;continue}return e.setItem(r,JSON.stringify({...l,feedbackEntries:[]})),e.setItem(hn(t,n),"1"),s.revision}}catch{}return null}function Go(e,t){let n=new Map;for(let[o,r]of e)if(t.has(o))n.set(o,r);return n}function Ko(e,t){if(!e||e.length===0)return!1;return e.every((n)=>t.has(n))}function gc(e,t){return e.filter((n)=>n.source!=="remote"||t&&t.has(n.id))}function er(e,t,n,o,r,a={}){let s=[],l=gc(e,r),i=(x)=>a.annotationIds&&x.source!=="remote"?`Annotation \`${x.id}\`
8
+ ${zr(x)}`:zr(x),c=l.filter((x)=>x.filePath===Be),d=l.filter((x)=>!x.filePath),u=l.filter((x)=>x.filePath&&x.filePath!==Be),p=n?Array.from(n.values()).filter((x)=>tr(x)):[],f=o?Array.from(o.values()).filter((x)=>x.markdown.trim()):[];if(p.length>0||f.length>0){s.push("## Responses"),s.push("");for(let x of p)s.push(xc(x));for(let x of f)s.push(x.markdown.trim()),s.push("")}if(c.length>0){s.push("## Annotations on agent response"),s.push("");for(let x of c)s.push(i(x))}if(d.length>0){s.push("## Canvas annotations"),s.push("");let x=new Map;for(let m of d){let b=m.canvasFile||"";if(!x.has(b))x.set(b,[]);x.get(b).push(m)}let g=[...x.keys()].sort(),k=g.length>1||g.length===1&&g[0]!=="";for(let m of g){let b=x.get(m);if(k&&m)s.push(`### ${m.replace(/\.jsx$/,"")}`),s.push("");let w=bc(b);s.push(ua(w,i))}}if(u.length>0){let x={};for(let g of u){let k=g.filePath;if(!x[k])x[k]=[];x[k].push(g)}s.push("## File annotations"),s.push("");for(let[g,k]of Object.entries(x)){s.push(`### ${g}`),s.push("");for(let m of k)s.push(i(m))}}if(t.trim())s.push("## General notes"),s.push(""),s.push(t.trim()),s.push("");return s.join(`
9
9
  `).trim()+`
10
- `}function J5($){return Array.from($.values()).filter($2).map(({id:Q,value:J})=>({id:Q,value:J}))}function $2($){if($.note?.trim())return!0;if($.value===null||$.value===void 0)return!1;if($.type==="text"&&!$.value.trim())return!1;if($.type==="checkbox"&&$.value.length===0)return!1;return!0}function q5($){let Q=[];for(let J of $.values()){if(!J.required)continue;if(J.value===null||J.value===void 0){Q.push(J);continue}if(J.type==="text"&&!J.value.trim()){Q.push(J);continue}if(J.type==="checkbox"&&J.value.length===0){Q.push(J);continue}}return Q}function Y5($){let Q=[];for(let J of $.values())if(J.required&&!J.markdown.trim())Q.push(J);return Q}function Q2($,Q){let J=q5($),Y=Y5(Q);return[...J.map((q)=>q.label),...Y.map((q)=>q.label||q.id)]}function $Q($){let Q=[];switch(Q.push(`**${$.label}**`),$.type){case"radio":case"select":Q.push(`Answer: ${$.value}`);break;case"checkbox":for(let J of $.value)Q.push(`- [x] ${J}`);break;case"text":Q.push(""),Q.push($.value.trim());break;case"range":Q.push(`Answer: ${$.value}`);break}if($.note?.trim())Q.push(""),Q.push(`Note: ${$.note.trim()}`);return Q.push(""),Q.join(`
11
- `)}function QQ($){let Q={label:"",annotations:[],children:new Map};for(let J of $){let Y=J.context?.hierarchy||[],q=Q;for(let G of Y){if(!q.children.has(G))q.children.set(G,{label:G,annotations:[],children:new Map});q=q.children.get(G)}q.annotations.push(J)}return Q}function X5($,Q,J=0){let Y=[];for(let q of $.annotations)Y.push(Q(q));for(let[,q]of $.children){let G=J===0?"###":"####";Y.push(`${G} ${q.label}`),Y.push(""),Y.push(X5(q,Q,J+1))}return Y.join(`
12
- `)}import{createContext as JQ,useContext as qQ}from"react";function G5(){if(typeof window>"u")return"";return window.location.pathname.replace("/s/","")}var _5={get sessionId(){return G5()},isShared:!1,fsAvailable:!0,uploadUrl:null,loadCanvasModule:($,Q)=>{let J=$.replace(/\.jsx$/,".js"),Y=Q?`?rev=${Q}&t=${Date.now()}`:`?t=${Date.now()}`;return import(`/api/session/${G5()}/canvas/${encodeURIComponent(J)}${Y}`)},threads:null},h2=JQ(_5);function v$(){return qQ(h2)}var W5=B.object({id:B.string(),type:B.enum(["select","radio","checkbox","text","range"]),label:B.string(),value:B.unknown(),options:B.array(B.string()).optional(),required:B.boolean().optional(),note:B.string().optional()}).passthrough().transform(($)=>({...$,value:$.value})),H5=B.object({id:B.string(),markdown:B.string(),label:B.string().optional(),required:B.boolean().optional()}).passthrough(),U5=T4.extend({responses:B.array(B.tuple([B.string(),W5]).optional().catch(void 0)).transform(($)=>$.filter((Q)=>Q!==void 0)).catch([]),feedbackEntries:B.array(B.tuple([B.string(),H5]).optional().catch(void 0)).transform(($)=>$.filter((Q)=>Q!==void 0)).optional().catch([])});function w0($){let Q=U5.safeParse($);return Q.success?Q.data:null}var K5=B.object({feedback:B.string().nullish()}),D1=B.union([B.object({error:B.string().min(1)}),B.object({content:B.string(),language:B.string().nullish()})]);import{useAnnotations as a1}from"#canvas/runtime";import{jsxDEV as x4}from"react/jsx-dev-runtime";function N5($,Q,J){try{let Y=localStorage.getItem(J1($,Q,J));if(!Y)return null;return w0(JSON.parse(Y))}catch{return null}}function WQ($,Q,J,Y){try{localStorage.setItem(J1($,Q,J),JSON.stringify(Y))}catch{}}function m4($){return{draft:$,responseIds:new Set,canvases:new Set}}function h4({sessionId:$,revision:Q,isReadOnly:J,draftPhase:Y,remoteAnnotations:q,canvasFiles:G,loadState:X,saveState:W,children:_}){let H=!!X,U=H?null:N5($,Q,Y),K=g4(U),[N,O]=j0(()=>(U?.annotations??[]).map((n)=>({...n,source:n.source??"local"}))),[M,L]=j0(()=>U?.generalNote??""),[F,w]=j0(()=>U?.responses?new Map(U.responses):new Map),z=`${$}:${Q}:${Y}`,A=g4(z);A.current=z;let[T,S]=j0(()=>m4(z)),[j,Z]=j0(()=>U?.feedbackEntries?new Map(U.feedbackEntries):new Map),[y,V]=j0(!H);B5(()=>{let n=(d)=>{K.current=d,O((d?.annotations??[]).map((X$)=>({...X$,source:X$.source??"local"}))),L(d?.generalNote??""),w(d?.responses?new Map(d.responses):new Map),Z(d?.feedbackEntries?new Map(d.feedbackEntries):new Map),_$(null)};if(H){let d=!1;return V(!1),X($,Q,Y).then((X$)=>{if(d)return;n(w0(X$)),V(!0)}),()=>{d=!0}}n(N5($,Q,Y)),V(!0);return},[$,Q,Y,H,X]);let C=g4(null);B5(()=>{if(J&&Y!=="next")return;if(!y)return;if(C.current)clearTimeout(C.current);let n={...K.current,annotations:N,generalNote:M,responses:Array.from(F.entries()),feedbackEntries:Array.from(j.entries())},d=()=>{if(W)W($,Q,n,Y);else WQ($,Q,Y,n)};if(Y==="next"){d();return}return C.current=setTimeout(d,300),()=>{if(C.current)clearTimeout(C.current)}},[N,M,F,j,$,Q,J,Y,y,W]);let v=T0((n,d)=>{w((X$)=>{let g=new Map(X$);return g.set(n,d),g})},[]),h=T0((n)=>{S((d)=>{let X$=d.draft===A.current?d:m4(A.current);if(X$.responseIds.has(n))return X$;return{...X$,responseIds:new Set(X$.responseIds).add(n)}})},[]),o=T0((n)=>{S((d)=>{let X$=d.draft===A.current?d:m4(A.current);if(X$.canvases.has(n))return X$;return{...X$,canvases:new Set(X$.canvases).add(n)}})},[]),B$=T.draft===z?T:null,a=_Q(()=>{if(!B$||!v4(G,B$.canvases))return F;return E4(F,B$.responseIds)},[B$,G,F]),U$=T0((n,d)=>{Z((X$)=>{let g=X$.get(n);if(g&&g.markdown===d.markdown&&g.label===d.label&&g.required===d.required)return X$;let c=new Map(X$);return c.set(n,d),c})},[]),Y$=T0((n)=>{Z((d)=>{if(!d.has(n))return d;let X$=new Map(d);return X$.delete(n),X$})},[]),N$=T0(()=>{if(w(new Map),Z(new Map),W)W($,Q,{annotations:[],generalNote:"",responses:[],feedbackEntries:[]},Y);else if(Y==="next")localStorage.removeItem(J1($,Q,Y));else o1(localStorage,$,Q)},[$,Q,Y,W]),Q$=k2({annotations:N,setAnnotations:O,generalNote:M,setGeneralNote:L,remoteAnnotations:q,isReadOnly:J,onClear:N$}),{setActiveAnnotationId:_$}=Q$,F$=v$();return x4(GQ.Provider,{value:F$,children:x4(XQ.Provider,{value:Q$,children:x4(YQ.Provider,{value:{...Q$,responses:F,setResponse:v,submittableResponses:a,registerResponse:h,registerCanvasRendered:o,feedbackEntries:j,setFeedbackEntry:U$,removeFeedbackEntry:Y$},children:_},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}import{ActiveViewCtx as PU,AnnotationCtx as SU,CanvasFileCtx as wU,SessionContext as TU,useAnnotations as G1,useCanvasFile as jU,useFeedback as bU,useResponseRegistration as ZU}from"#canvas/runtime";function J2($){let Q=document.querySelector(`[data-annotation-id="${$.id}"]`);if(Q instanceof HTMLElement)return Q;let J=$.canvasFile?document.querySelector(`[data-canvas-file="${$.canvasFile}"]`):document;if(!J)return null;return M4($.snippet,J)}function O5($){$.classList.remove("ann-flash"),$.offsetWidth,$.classList.add("ann-flash"),$.addEventListener("animationend",()=>{$.classList.remove("ann-flash")},{once:!0})}function u4($,Q){let J=c1($);if(J)Q({type:"file",path:J}),setTimeout(()=>{let Y=J2($);if(Y)Y.scrollIntoView({behavior:"smooth",block:"center"}),O5(Y)},150);else{let Y=J2($);if(Y)Y.scrollIntoView({behavior:"smooth",block:"center"}),O5(Y)}}import{SessionContext as HJ}from"#canvas/runtime";import{useCallback as q3,useContext as Y3,useEffect as m5,useMemo as UJ,useState as C0}from"react";import{createContext as z5}from"react";var q1=z5({activeView:{type:"overview"},setActiveView:()=>{},openFiles:[],closeFile:()=>{},canvasFiles:[]}),h$=z5({currentRevision:1,selectedRevision:1,revisions:[],setSelectedRevision:()=>{},isReadOnly:!1,compareRevision:null,setCompareRevision:()=>{},agentWatching:!1});import{jsxDEV as n1}from"react/jsx-dev-runtime";var HQ={ts:"#3178c6",tsx:"#3178c6",js:"#e8a32e",jsx:"#4ba0c8",html:"#e34c26",css:"#264de4",scss:"#c69",json:"#7a7568",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",rs:"#dea584",go:"#00add8",c:"#6a6a6a",cpp:"#f34b7d",h:"#6a6a6a",py:"#3572a5",rb:"#cc342d",sh:"#5a8c3c",bash:"#5a8c3c",md:"#3573b5",txt:"#6b6560",lock:"#6b6560",gitignore:"#6b6560",svg:"#d9952e",png:"#6a9c2e",jpg:"#6a9c2e",gif:"#6a9c2e"},UQ={ts:"TS",tsx:"TX",js:"JS",jsx:"JX",py:"PY",rs:"RS",go:"GO",rb:"RB",json:"{}",yaml:"YM",yml:"YM",toml:"TM",html:"<>",css:"#",scss:"#",md:"M↓",sh:"$",bash:"$",c:"C",cpp:"C+",h:"H",svg:"◇",png:"▣",jpg:"▣"};function I1({name:$,type:Q,expanded:J,className:Y=""}){if(Q==="dir")return n1("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:`flex-shrink-0 ${Y}`,children:J?n1("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill-active)",stroke:"var(--color-folder-stroke-active)"},strokeWidth:"1"},void 0,!1,void 0,this):n1("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill)",stroke:"var(--color-folder-stroke)"},strokeWidth:"1"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let q=$.includes(".")?$.split(".").pop().toLowerCase():"",G=HQ[q]||"#6b6560",X=UQ[q];return n1("svg",{width:"14",height:"14",viewBox:"0 0 16 16",className:`flex-shrink-0 ${Y}`,children:[n1("path",{d:"M2 1.5h8l3.5 3.5v9.5a1 1 0 01-1 1H3a1 1 0 01-1-1v-12a1 1 0 011-1z",fill:G,opacity:"0.85"},void 0,!1,void 0,this),n1("path",{d:"M10 1.5v2.5a1 1 0 001 1h2.5",fill:"none",stroke:"white",strokeWidth:"0.5",opacity:"0.5"},void 0,!1,void 0,this),X&&n1("text",{x:"8",y:"11.5",textAnchor:"middle",fill:"white",fontSize:"5.5",fontFamily:"monospace",fontWeight:"600",children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function c4(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var e1=c4();function w5($){e1=$}var s1={exec:()=>null};function H$($,Q=""){let J=typeof $=="string"?$:$.source,Y={replace:(q,G)=>{let X=typeof G=="string"?G:G.source;return X=X.replace(k$.caret,"$1"),J=J.replace(q,X),Y},getRegex:()=>new RegExp(J,Q)};return Y}var KQ=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),k$={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:($)=>new RegExp(`^( {0,3}${$})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}#`),htmlBeginRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:($)=>new RegExp(`^ {0,${Math.min(3,$-1)}}>`)},BQ=/^(?:[ \t]*(?:\n|$))+/,NQ=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,OQ=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,G2=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,zQ=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,l4=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,T5=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,j5=H$(T5).replace(/bull/g,l4).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),MQ=H$(T5).replace(/bull/g,l4).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),d4=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,FQ=/^[^\n]+/,r4=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,LQ=H$(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",r4).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),AQ=H$(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,l4).getRegex(),d2="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",i4=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,PQ=H$("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",i4).replace("tag",d2).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),b5=H$(d4).replace("hr",G2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",d2).getRegex(),SQ=H$(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",b5).getRegex(),o4={blockquote:SQ,code:NQ,def:LQ,fences:OQ,heading:zQ,hr:G2,html:PQ,lheading:j5,list:AQ,newline:BQ,paragraph:b5,table:s1,text:FQ},M5=H$("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",G2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",d2).getRegex(),wQ={...o4,lheading:MQ,table:M5,paragraph:H$(d4).replace("hr",G2).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",M5).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",d2).getRegex()},TQ={...o4,html:H$(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",i4).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:s1,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:H$(d4).replace("hr",G2).replace("heading",` *#{1,6} *[^
13
- ]`).replace("lheading",j5).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jQ=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,bQ=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Z5=/^( {2,}|\\)\n(?!\s*$)/,ZQ=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,b0=/[\p{P}\p{S}]/u,r2=/[\s\p{P}\p{S}]/u,a4=/[^\s\p{P}\p{S}]/u,VQ=H$(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,r2).getRegex(),V5=/(?!~)[\p{P}\p{S}]/u,CQ=/(?!~)[\s\p{P}\p{S}]/u,RQ=/(?:[^\s\p{P}\p{S}]|~)/u,DQ=H$(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",KQ?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),C5=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,IQ=H$(C5,"u").replace(/punct/g,b0).getRegex(),kQ=H$(C5,"u").replace(/punct/g,V5).getRegex(),R5="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",yQ=H$(R5,"gu").replace(/notPunctSpace/g,a4).replace(/punctSpace/g,r2).replace(/punct/g,b0).getRegex(),fQ=H$(R5,"gu").replace(/notPunctSpace/g,RQ).replace(/punctSpace/g,CQ).replace(/punct/g,V5).getRegex(),EQ=H$("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,a4).replace(/punctSpace/g,r2).replace(/punct/g,b0).getRegex(),vQ=H$(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,b0).getRegex(),gQ="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",mQ=H$(gQ,"gu").replace(/notPunctSpace/g,a4).replace(/punctSpace/g,r2).replace(/punct/g,b0).getRegex(),xQ=H$(/\\(punct)/,"gu").replace(/punct/g,b0).getRegex(),hQ=H$(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),uQ=H$(i4).replace("(?:-->|$)","-->").getRegex(),pQ=H$("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",uQ).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),p2=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,cQ=H$(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",p2).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),D5=H$(/^!?\[(label)\]\[(ref)\]/).replace("label",p2).replace("ref",r4).getRegex(),I5=H$(/^!?\[(ref)\](?:\[\])?/).replace("ref",r4).getRegex(),lQ=H$("reflink|nolink(?!\\()","g").replace("reflink",D5).replace("nolink",I5).getRegex(),F5=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,n4={_backpedal:s1,anyPunctuation:xQ,autolink:hQ,blockSkip:DQ,br:Z5,code:bQ,del:s1,delLDelim:s1,delRDelim:s1,emStrongLDelim:IQ,emStrongRDelimAst:yQ,emStrongRDelimUnd:EQ,escape:jQ,link:cQ,nolink:I5,punctuation:VQ,reflink:D5,reflinkSearch:lQ,tag:pQ,text:ZQ,url:s1},dQ={...n4,link:H$(/^!?\[(label)\]\((.*?)\)/).replace("label",p2).getRegex(),reflink:H$(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",p2).getRegex()},p4={...n4,emStrongRDelimAst:fQ,emStrongLDelim:kQ,delLDelim:vQ,delRDelim:mQ,url:H$(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",F5).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:H$(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",F5).getRegex()},rQ={...p4,br:H$(Z5).replace("{2,}","*").getRegex(),text:H$(p4.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},u2={normal:o4,gfm:wQ,pedantic:TQ},q2={normal:n4,gfm:p4,breaks:rQ,pedantic:dQ},iQ={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},L5=($)=>iQ[$];function Y1($,Q){if(Q){if(k$.escapeTest.test($))return $.replace(k$.escapeReplace,L5)}else if(k$.escapeTestNoEncode.test($))return $.replace(k$.escapeReplaceNoEncode,L5);return $}function A5($){try{$=encodeURI($).replace(k$.percentDecode,"%")}catch{return null}return $}function P5($,Q){let J=$.replace(k$.findPipe,(G,X,W)=>{let _=!1,H=X;for(;--H>=0&&W[H]==="\\";)_=!_;return _?"|":" |"}),Y=J.split(k$.splitPipe),q=0;if(Y[0].trim()||Y.shift(),Y.length>0&&!Y.at(-1)?.trim()&&Y.pop(),Q)if(Y.length>Q)Y.splice(Q);else for(;Y.length<Q;)Y.push("");for(;q<Y.length;q++)Y[q]=Y[q].trim().replace(k$.slashPipe,"|");return Y}function Y2($,Q,J){let Y=$.length;if(Y===0)return"";let q=0;for(;q<Y;){let G=$.charAt(Y-q-1);if(G===Q&&!J)q++;else if(G!==Q&&J)q++;else break}return $.slice(0,Y-q)}function oQ($,Q){if($.indexOf(Q[1])===-1)return-1;let J=0;for(let Y=0;Y<$.length;Y++)if($[Y]==="\\")Y++;else if($[Y]===Q[0])J++;else if($[Y]===Q[1]&&(J--,J<0))return Y;return J>0?-2:-1}function aQ($,Q=0){let J=Q,Y="";for(let q of $)if(q==="\t"){let G=4-J%4;Y+=" ".repeat(G),J+=G}else Y+=q,J++;return Y}function S5($,Q,J,Y,q){let G=Q.href,X=Q.title||null,W=$[1].replace(q.other.outputLinkReplace,"$1");Y.state.inLink=!0;let _={type:$[0].charAt(0)==="!"?"image":"link",raw:J,href:G,title:X,text:W,tokens:Y.inlineTokens(W)};return Y.state.inLink=!1,_}function nQ($,Q,J){let Y=$.match(J.other.indentCodeCompensation);if(Y===null)return Q;let q=Y[1];return Q.split(`
14
- `).map((G)=>{let X=G.match(J.other.beginningSpace);if(X===null)return G;let[W]=X;return W.length>=q.length?G.slice(q.length):G}).join(`
15
- `)}var c2=class{options;rules;lexer;constructor($){this.options=$||e1}space($){let Q=this.rules.block.newline.exec($);if(Q&&Q[0].length>0)return{type:"space",raw:Q[0]}}code($){let Q=this.rules.block.code.exec($);if(Q){let J=Q[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:Q[0],codeBlockStyle:"indented",text:this.options.pedantic?J:Y2(J,`
16
- `)}}}fences($){let Q=this.rules.block.fences.exec($);if(Q){let J=Q[0],Y=nQ(J,Q[3]||"",this.rules);return{type:"code",raw:J,lang:Q[2]?Q[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):Q[2],text:Y}}}heading($){let Q=this.rules.block.heading.exec($);if(Q){let J=Q[2].trim();if(this.rules.other.endingHash.test(J)){let Y=Y2(J,"#");(this.options.pedantic||!Y||this.rules.other.endingSpaceChar.test(Y))&&(J=Y.trim())}return{type:"heading",raw:Q[0],depth:Q[1].length,text:J,tokens:this.lexer.inline(J)}}}hr($){let Q=this.rules.block.hr.exec($);if(Q)return{type:"hr",raw:Y2(Q[0],`
17
- `)}}blockquote($){let Q=this.rules.block.blockquote.exec($);if(Q){let J=Y2(Q[0],`
10
+ `}function la(e){return Array.from(e.values()).filter(tr).map(({id:t,value:n})=>({id:t,value:n}))}function tr(e){if(e.note?.trim())return!0;if(e.value===null||e.value===void 0)return!1;if(e.type==="text"&&!e.value.trim())return!1;if(e.type==="checkbox"&&e.value.length===0)return!1;return!0}function ca(e){let t=[];for(let n of e.values()){if(!n.required)continue;if(n.value===null||n.value===void 0){t.push(n);continue}if(n.type==="text"&&!n.value.trim()){t.push(n);continue}if(n.type==="checkbox"&&n.value.length===0){t.push(n);continue}}return t}function da(e){let t=[];for(let n of e.values())if(n.required&&!n.markdown.trim())t.push(n);return t}function nr(e,t){let n=ca(e),o=da(t);return[...n.map((r)=>r.label),...o.map((r)=>r.label||r.id)]}function xc(e){let t=[];switch(t.push(`**${e.label}**`),e.type){case"radio":case"select":t.push(`Answer: ${e.value}`);break;case"checkbox":for(let n of e.value)t.push(`- [x] ${n}`);break;case"text":t.push(""),t.push(e.value.trim());break;case"range":t.push(`Answer: ${e.value}`);break}if(e.note?.trim())t.push(""),t.push(`Note: ${e.note.trim()}`);return t.push(""),t.join(`
11
+ `)}function bc(e){let t={label:"",annotations:[],children:new Map};for(let n of e){let o=n.context?.hierarchy||[],r=t;for(let a of o){if(!r.children.has(a))r.children.set(a,{label:a,annotations:[],children:new Map});r=r.children.get(a)}r.annotations.push(n)}return t}function ua(e,t,n=0){let o=[];for(let r of e.annotations)o.push(t(r));for(let[,r]of e.children){let a=n===0?"###":"####";o.push(`${a} ${r.label}`),o.push(""),o.push(ua(r,t,n+1))}return o.join(`
12
+ `)}import{createContext as vc,useContext as yc}from"react";function pa(){if(typeof window>"u")return"";return window.location.pathname.replace("/s/","")}var fa={get sessionId(){return pa()},isShared:!1,fsAvailable:!0,uploadUrl:null,loadCanvasModule:(e,t)=>{let n=e.replace(/\.jsx$/,".js"),o=t?`?rev=${t}&t=${Date.now()}`:`?t=${Date.now()}`;return import(`/api/session/${pa()}/canvas/${encodeURIComponent(n)}${o}`)},threads:null},Gr=vc(fa);function je(){return yc(Gr)}var ma=z({id:R(),type:zt(["select","radio","checkbox","text","range"]),label:R(),value:pn(),options:ye(R()).optional(),required:tt().optional(),note:R().optional()}).passthrough().transform((e)=>({...e,value:e.value})),ha=z({id:R(),markdown:R(),label:R().optional(),required:tt().optional()}).passthrough(),ga=$o.extend({responses:ye(Lo([R(),ma]).optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).catch([]),feedbackEntries:ye(Lo([R(),ha]).optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).optional().catch([])});function gn(e){let t=ga.safeParse(e);return t.success?t.data:null}var xa=z({feedback:R().nullish()}),Mt=Dr([z({error:R().min(1)}),z({content:R(),language:R().nullish()})]);import{useAnnotations as Jt}from"#canvas/runtime";import{jsxDEV as Xo}from"react/jsx-dev-runtime";function va(e,t,n){try{let o=localStorage.getItem(rt(e,t,n));if(!o)return null;return gn(JSON.parse(o))}catch{return null}}function Tc(e,t,n,o){try{localStorage.setItem(rt(e,t,n),JSON.stringify(o))}catch{}}function Yo(e){return{draft:e,responseIds:new Set,canvases:new Set}}function Qo({sessionId:e,revision:t,isReadOnly:n,draftPhase:o,remoteAnnotations:r,canvasFiles:a,loadState:s,saveState:l,children:i}){let c=!!s,d=c?null:va(e,t,o),u=Jo(d),[p,f]=bn(()=>(d?.annotations??[]).map((Q)=>({...Q,source:Q.source??"local"}))),[h,x]=bn(()=>d?.generalNote??""),[g,k]=bn(()=>d?.responses?new Map(d.responses):new Map),m=`${e}:${t}:${o}`,b=Jo(m);b.current=m;let[w,y]=bn(()=>Yo(m)),[S,T]=bn(()=>d?.feedbackEntries?new Map(d.feedbackEntries):new Map),[M,E]=bn(!c);ba(()=>{let Q=(W)=>{u.current=W,f((W?.annotations??[]).map((ae)=>({...ae,source:ae.source??"local"}))),x(W?.generalNote??""),k(W?.responses?new Map(W.responses):new Map),T(W?.feedbackEntries?new Map(W.feedbackEntries):new Map),ce(null)};if(c){let W=!1;return E(!1),s(e,t,o).then((ae)=>{if(W)return;Q(gn(ae)),E(!0)}),()=>{W=!0}}Q(va(e,t,o)),E(!0);return},[e,t,o,c,s]);let C=Jo(null);ba(()=>{if(n&&o!=="next")return;if(!M)return;if(C.current)clearTimeout(C.current);let Q={...u.current,annotations:p,generalNote:h,responses:Array.from(g.entries()),feedbackEntries:Array.from(S.entries())},W=()=>{if(l)l(e,t,Q,o);else Tc(e,t,o,Q)};if(o==="next"){W();return}return C.current=setTimeout(W,300),()=>{if(C.current)clearTimeout(C.current)}},[p,h,g,S,e,t,n,o,M,l]);let O=xn((Q,W)=>{k((ae)=>{let D=new Map(ae);return D.set(Q,W),D})},[]),B=xn((Q)=>{y((W)=>{let ae=W.draft===b.current?W:Yo(b.current);if(ae.responseIds.has(Q))return ae;return{...ae,responseIds:new Set(ae.responseIds).add(Q)}})},[]),Y=xn((Q)=>{y((W)=>{let ae=W.draft===b.current?W:Yo(b.current);if(ae.canvases.has(Q))return ae;return{...ae,canvases:new Set(ae.canvases).add(Q)}})},[]),me=w.draft===m?w:null,X=Ac(()=>{if(!me||!Ko(a,me.canvases))return g;return Go(g,me.responseIds)},[me,a,g]),pe=xn((Q,W)=>{T((ae)=>{let D=ae.get(Q);if(D&&D.markdown===W.markdown&&D.label===W.label&&D.required===W.required)return ae;let V=new Map(ae);return V.set(Q,W),V})},[]),se=xn((Q)=>{T((W)=>{if(!W.has(Q))return W;let ae=new Map(W);return ae.delete(Q),ae})},[]),he=xn(()=>{if(k(new Map),T(new Map),l)l(e,t,{annotations:[],generalNote:"",responses:[],feedbackEntries:[]},o);else if(o==="next")localStorage.removeItem(rt(e,t,o));else Kt(localStorage,e,t)},[e,t,o,l]),ne=jr({annotations:p,setAnnotations:f,generalNote:h,setGeneralNote:x,remoteAnnotations:r,isReadOnly:n,onClear:he}),{setActiveAnnotationId:ce}=ne,ve=je();return Xo(Sc.Provider,{value:ve,children:Xo(wc.Provider,{value:ne,children:Xo(kc.Provider,{value:{...ne,responses:g,setResponse:O,submittableResponses:X,registerResponse:B,registerCanvasRendered:Y,feedbackEntries:S,setFeedbackEntry:pe,removeFeedbackEntry:se},children:i},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}import{ActiveViewCtx as vv,AnnotationCtx as yv,CanvasFileCtx as kv,SessionContext as wv,useAnnotations as it,useCanvasFile as Sv,useFeedback as Av,useResponseRegistration as Tv}from"#canvas/runtime";function rr(e){let t=document.querySelector(`[data-annotation-id="${e.id}"]`);if(t instanceof HTMLElement)return t;let n=e.canvasFile?document.querySelector(`[data-canvas-file="${e.canvasFile}"]`):document;if(!n)return null;return Ao(e.snippet,n)}function ya(e){e.classList.remove("ann-flash"),e.offsetWidth,e.classList.add("ann-flash"),e.addEventListener("animationend",()=>{e.classList.remove("ann-flash")},{once:!0})}function Zo(e,t){let n=qt(e);if(n)t({type:"file",path:n}),setTimeout(()=>{let o=rr(e);if(o)o.scrollIntoView({behavior:"smooth",block:"center"}),ya(o)},150);else{let o=rr(e);if(o)o.scrollIntoView({behavior:"smooth",block:"center"}),ya(o)}}import{SessionContext as Ed}from"#canvas/runtime";import{useCallback as hs,useContext as gs,useEffect as Va,useMemo as Rd,useState as wn}from"react";import{createContext as ka}from"react";var ot=ka({activeView:{type:"overview"},setActiveView:()=>{},openFiles:[],closeFile:()=>{},canvasFiles:[]}),Ve=ka({currentRevision:1,selectedRevision:1,revisions:[],setSelectedRevision:()=>{},isReadOnly:!1,compareRevision:null,setCompareRevision:()=>{},agentWatching:!1});import{jsxDEV as Yt}from"react/jsx-dev-runtime";var Ec={ts:"#3178c6",tsx:"#3178c6",js:"#e8a32e",jsx:"#4ba0c8",html:"#e34c26",css:"#264de4",scss:"#c69",json:"#7a7568",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",rs:"#dea584",go:"#00add8",c:"#6a6a6a",cpp:"#f34b7d",h:"#6a6a6a",py:"#3572a5",rb:"#cc342d",sh:"#5a8c3c",bash:"#5a8c3c",md:"#3573b5",txt:"#6b6560",lock:"#6b6560",gitignore:"#6b6560",svg:"#d9952e",png:"#6a9c2e",jpg:"#6a9c2e",gif:"#6a9c2e"},Rc={ts:"TS",tsx:"TX",js:"JS",jsx:"JX",py:"PY",rs:"RS",go:"GO",rb:"RB",json:"{}",yaml:"YM",yml:"YM",toml:"TM",html:"<>",css:"#",scss:"#",md:"M↓",sh:"$",bash:"$",c:"C",cpp:"C+",h:"H",svg:"◇",png:"▣",jpg:"▣"};function Lt({name:e,type:t,expanded:n,className:o=""}){if(t==="dir")return Yt("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:`flex-shrink-0 ${o}`,children:n?Yt("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill-active)",stroke:"var(--color-folder-stroke-active)"},strokeWidth:"1"},void 0,!1,void 0,this):Yt("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill)",stroke:"var(--color-folder-stroke)"},strokeWidth:"1"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let r=e.includes(".")?e.split(".").pop().toLowerCase():"",a=Ec[r]||"#6b6560",s=Rc[r];return Yt("svg",{width:"14",height:"14",viewBox:"0 0 16 16",className:`flex-shrink-0 ${o}`,children:[Yt("path",{d:"M2 1.5h8l3.5 3.5v9.5a1 1 0 01-1 1H3a1 1 0 01-1-1v-12a1 1 0 011-1z",fill:a,opacity:"0.85"},void 0,!1,void 0,this),Yt("path",{d:"M10 1.5v2.5a1 1 0 001 1h2.5",fill:"none",stroke:"white",strokeWidth:"0.5",opacity:"0.5"},void 0,!1,void 0,this),s&&Yt("text",{x:"8",y:"11.5",textAnchor:"middle",fill:"white",fontSize:"5.5",fontFamily:"monospace",fontWeight:"600",children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ts(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Zt=ts();function Ca(e){Zt=e}var Xt={exec:()=>null};function ue(e,t=""){let n=typeof e=="string"?e:e.source,o={replace:(r,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(He.caret,"$1"),n=n.replace(r,s),o},getRegex:()=>new RegExp(n,t)};return o}var Cc=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),He={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:(e)=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Nc=/^(?:[ \t]*(?:\n|$))+/,_c=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Mc=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ir=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Lc=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ns=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Na=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_a=ue(Na).replace(/bull/g,ns).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ic=ue(Na).replace(/bull/g,ns).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),rs=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pc=/^[^\n]+/,os=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$c=ue(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",os).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Hc=ue(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ns).getRegex(),Qr="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ss=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Oc=ue("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",ss).replace("tag",Qr).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ma=ue(rs).replace("hr",ir).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qr).getRegex(),Dc=ue(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ma).getRegex(),as={blockquote:Dc,code:_c,def:$c,fences:Mc,heading:Lc,hr:ir,html:Oc,lheading:_a,list:Hc,newline:Nc,paragraph:Ma,table:Xt,text:Pc},wa=ue("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ir).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qr).getRegex(),jc={...as,lheading:Ic,table:wa,paragraph:ue(rs).replace("hr",ir).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",wa).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qr).getRegex()},Fc={...as,html:ue(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ss).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Xt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ue(rs).replace("hr",ir).replace("heading",` *#{1,6} *[^
13
+ ]`).replace("lheading",_a).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Bc=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,zc=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,La=/^( {2,}|\\)\n(?!\s*$)/,qc=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vn=/[\p{P}\p{S}]/u,Zr=/[\s\p{P}\p{S}]/u,is=/[^\s\p{P}\p{S}]/u,Vc=ue(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Zr).getRegex(),Ia=/(?!~)[\p{P}\p{S}]/u,Uc=/(?!~)[\s\p{P}\p{S}]/u,Wc=/(?:[^\s\p{P}\p{S}]|~)/u,Gc=ue(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Cc?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Pa=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Kc=ue(Pa,"u").replace(/punct/g,vn).getRegex(),Jc=ue(Pa,"u").replace(/punct/g,Ia).getRegex(),$a="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Yc=ue($a,"gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,Zr).replace(/punct/g,vn).getRegex(),Xc=ue($a,"gu").replace(/notPunctSpace/g,Wc).replace(/punctSpace/g,Uc).replace(/punct/g,Ia).getRegex(),Qc=ue("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,Zr).replace(/punct/g,vn).getRegex(),Zc=ue(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vn).getRegex(),ed="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",td=ue(ed,"gu").replace(/notPunctSpace/g,is).replace(/punctSpace/g,Zr).replace(/punct/g,vn).getRegex(),nd=ue(/\\(punct)/,"gu").replace(/punct/g,vn).getRegex(),rd=ue(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),od=ue(ss).replace("(?:-->|$)","-->").getRegex(),sd=ue("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",od).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Jr=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ad=ue(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Jr).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ha=ue(/^!?\[(label)\]\[(ref)\]/).replace("label",Jr).replace("ref",os).getRegex(),Oa=ue(/^!?\[(ref)\](?:\[\])?/).replace("ref",os).getRegex(),id=ue("reflink|nolink(?!\\()","g").replace("reflink",Ha).replace("nolink",Oa).getRegex(),Sa=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ls={_backpedal:Xt,anyPunctuation:nd,autolink:rd,blockSkip:Gc,br:La,code:zc,del:Xt,delLDelim:Xt,delRDelim:Xt,emStrongLDelim:Kc,emStrongRDelimAst:Yc,emStrongRDelimUnd:Qc,escape:Bc,link:ad,nolink:Oa,punctuation:Vc,reflink:Ha,reflinkSearch:id,tag:sd,text:qc,url:Xt},ld={...ls,link:ue(/^!?\[(label)\]\((.*?)\)/).replace("label",Jr).getRegex(),reflink:ue(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Jr).getRegex()},es={...ls,emStrongRDelimAst:Xc,emStrongLDelim:Jc,delLDelim:Zc,delRDelim:td,url:ue(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Sa).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ue(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Sa).getRegex()},cd={...es,br:ue(La).replace("{2,}","*").getRegex(),text:ue(es.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Kr={normal:as,gfm:jc,pedantic:Fc},or={normal:ls,gfm:es,breaks:cd,pedantic:ld},dd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Aa=(e)=>dd[e];function st(e,t){if(t){if(He.escapeTest.test(e))return e.replace(He.escapeReplace,Aa)}else if(He.escapeTestNoEncode.test(e))return e.replace(He.escapeReplaceNoEncode,Aa);return e}function Ta(e){try{e=encodeURI(e).replace(He.percentDecode,"%")}catch{return null}return e}function Ea(e,t){let n=e.replace(He.findPipe,(a,s,l)=>{let i=!1,c=s;for(;--c>=0&&l[c]==="\\";)i=!i;return i?"|":" |"}),o=n.split(He.splitPipe),r=0;if(o[0].trim()||o.shift(),o.length>0&&!o.at(-1)?.trim()&&o.pop(),t)if(o.length>t)o.splice(t);else for(;o.length<t;)o.push("");for(;r<o.length;r++)o[r]=o[r].trim().replace(He.slashPipe,"|");return o}function sr(e,t,n){let o=e.length;if(o===0)return"";let r=0;for(;r<o;){let a=e.charAt(o-r-1);if(a===t&&!n)r++;else if(a!==t&&n)r++;else break}return e.slice(0,o-r)}function ud(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let o=0;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])n++;else if(e[o]===t[1]&&(n--,n<0))return o;return n>0?-2:-1}function pd(e,t=0){let n=t,o="";for(let r of e)if(r==="\t"){let a=4-n%4;o+=" ".repeat(a),n+=a}else o+=r,n++;return o}function Ra(e,t,n,o,r){let a=t.href,s=t.title||null,l=e[1].replace(r.other.outputLinkReplace,"$1");o.state.inLink=!0;let i={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:s,text:l,tokens:o.inlineTokens(l)};return o.state.inLink=!1,i}function fd(e,t,n){let o=e.match(n.other.indentCodeCompensation);if(o===null)return t;let r=o[1];return t.split(`
14
+ `).map((a)=>{let s=a.match(n.other.beginningSpace);if(s===null)return a;let[l]=s;return l.length>=r.length?a.slice(r.length):a}).join(`
15
+ `)}var Yr=class{options;rules;lexer;constructor(e){this.options=e||Zt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:sr(n,`
16
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],o=fd(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let o=sr(n,"#");(this.options.pedantic||!o||this.rules.other.endingSpaceChar.test(o))&&(n=o.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:sr(t[0],`
17
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=sr(t[0],`
18
18
  `).split(`
19
- `),Y="",q="",G=[];for(;J.length>0;){let X=!1,W=[],_;for(_=0;_<J.length;_++)if(this.rules.other.blockquoteStart.test(J[_]))W.push(J[_]),X=!0;else if(!X)W.push(J[_]);else break;J=J.slice(_);let H=W.join(`
20
- `),U=H.replace(this.rules.other.blockquoteSetextReplace,`
21
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");Y=Y?`${Y}
22
- ${H}`:H,q=q?`${q}
23
- ${U}`:U;let K=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(U,G,!0),this.lexer.state.top=K,J.length===0)break;let N=G.at(-1);if(N?.type==="code")break;if(N?.type==="blockquote"){let O=N,M=O.raw+`
24
- `+J.join(`
25
- `),L=this.blockquote(M);G[G.length-1]=L,Y=Y.substring(0,Y.length-O.raw.length)+L.raw,q=q.substring(0,q.length-O.text.length)+L.text;break}else if(N?.type==="list"){let O=N,M=O.raw+`
26
- `+J.join(`
27
- `),L=this.list(M);G[G.length-1]=L,Y=Y.substring(0,Y.length-N.raw.length)+L.raw,q=q.substring(0,q.length-O.raw.length)+L.raw,J=M.substring(G.at(-1).raw.length).split(`
28
- `);continue}}return{type:"blockquote",raw:Y,tokens:G,text:q}}}list($){let Q=this.rules.block.list.exec($);if(Q){let J=Q[1].trim(),Y=J.length>1,q={type:"list",raw:"",ordered:Y,start:Y?+J.slice(0,-1):"",loose:!1,items:[]};J=Y?`\\d{1,9}\\${J.slice(-1)}`:`\\${J}`,this.options.pedantic&&(J=Y?J:"[*+-]");let G=this.rules.other.listItemRegex(J),X=!1;for(;$;){let _=!1,H="",U="";if(!(Q=G.exec($))||this.rules.block.hr.test($))break;H=Q[0],$=$.substring(H.length);let K=aQ(Q[2].split(`
29
- `,1)[0],Q[1].length),N=$.split(`
30
- `,1)[0],O=!K.trim(),M=0;if(this.options.pedantic?(M=2,U=K.trimStart()):O?M=Q[1].length+1:(M=K.search(this.rules.other.nonSpaceChar),M=M>4?1:M,U=K.slice(M),M+=Q[1].length),O&&this.rules.other.blankLine.test(N)&&(H+=N+`
31
- `,$=$.substring(N.length+1),_=!0),!_){let L=this.rules.other.nextBulletRegex(M),F=this.rules.other.hrRegex(M),w=this.rules.other.fencesBeginRegex(M),z=this.rules.other.headingBeginRegex(M),A=this.rules.other.htmlBeginRegex(M),T=this.rules.other.blockquoteBeginRegex(M);for(;$;){let S=$.split(`
32
- `,1)[0],j;if(N=S,this.options.pedantic?(N=N.replace(this.rules.other.listReplaceNesting," "),j=N):j=N.replace(this.rules.other.tabCharGlobal," "),w.test(N)||z.test(N)||A.test(N)||T.test(N)||L.test(N)||F.test(N))break;if(j.search(this.rules.other.nonSpaceChar)>=M||!N.trim())U+=`
33
- `+j.slice(M);else{if(O||K.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(K)||z.test(K)||F.test(K))break;U+=`
34
- `+N}O=!N.trim(),H+=S+`
35
- `,$=$.substring(S.length+1),K=j.slice(M)}}q.loose||(X?q.loose=!0:this.rules.other.doubleBlankLine.test(H)&&(X=!0)),q.items.push({type:"list_item",raw:H,task:!!this.options.gfm&&this.rules.other.listIsTask.test(U),loose:!1,text:U,tokens:[]}),q.raw+=H}let W=q.items.at(-1);if(W)W.raw=W.raw.trimEnd(),W.text=W.text.trimEnd();else return;q.raw=q.raw.trimEnd();for(let _ of q.items){if(this.lexer.state.top=!1,_.tokens=this.lexer.blockTokens(_.text,[]),_.task){if(_.text=_.text.replace(this.rules.other.listReplaceTask,""),_.tokens[0]?.type==="text"||_.tokens[0]?.type==="paragraph"){_.tokens[0].raw=_.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),_.tokens[0].text=_.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let U=this.lexer.inlineQueue.length-1;U>=0;U--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[U].src)){this.lexer.inlineQueue[U].src=this.lexer.inlineQueue[U].src.replace(this.rules.other.listReplaceTask,"");break}}let H=this.rules.other.listTaskCheckbox.exec(_.raw);if(H){let U={type:"checkbox",raw:H[0]+" ",checked:H[0]!=="[ ]"};_.checked=U.checked,q.loose?_.tokens[0]&&["paragraph","text"].includes(_.tokens[0].type)&&"tokens"in _.tokens[0]&&_.tokens[0].tokens?(_.tokens[0].raw=U.raw+_.tokens[0].raw,_.tokens[0].text=U.raw+_.tokens[0].text,_.tokens[0].tokens.unshift(U)):_.tokens.unshift({type:"paragraph",raw:U.raw,text:U.raw,tokens:[U]}):_.tokens.unshift(U)}}if(!q.loose){let H=_.tokens.filter((K)=>K.type==="space"),U=H.length>0&&H.some((K)=>this.rules.other.anyLine.test(K.raw));q.loose=U}}if(q.loose)for(let _ of q.items){_.loose=!0;for(let H of _.tokens)H.type==="text"&&(H.type="paragraph")}return q}}html($){let Q=this.rules.block.html.exec($);if(Q)return{type:"html",block:!0,raw:Q[0],pre:Q[1]==="pre"||Q[1]==="script"||Q[1]==="style",text:Q[0]}}def($){let Q=this.rules.block.def.exec($);if(Q){let J=Q[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),Y=Q[2]?Q[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",q=Q[3]?Q[3].substring(1,Q[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):Q[3];return{type:"def",tag:J,raw:Q[0],href:Y,title:q}}}table($){let Q=this.rules.block.table.exec($);if(!Q||!this.rules.other.tableDelimiter.test(Q[2]))return;let J=P5(Q[1]),Y=Q[2].replace(this.rules.other.tableAlignChars,"").split("|"),q=Q[3]?.trim()?Q[3].replace(this.rules.other.tableRowBlankLine,"").split(`
36
- `):[],G={type:"table",raw:Q[0],header:[],align:[],rows:[]};if(J.length===Y.length){for(let X of Y)this.rules.other.tableAlignRight.test(X)?G.align.push("right"):this.rules.other.tableAlignCenter.test(X)?G.align.push("center"):this.rules.other.tableAlignLeft.test(X)?G.align.push("left"):G.align.push(null);for(let X=0;X<J.length;X++)G.header.push({text:J[X],tokens:this.lexer.inline(J[X]),header:!0,align:G.align[X]});for(let X of q)G.rows.push(P5(X,G.header.length).map((W,_)=>({text:W,tokens:this.lexer.inline(W),header:!1,align:G.align[_]})));return G}}lheading($){let Q=this.rules.block.lheading.exec($);if(Q){let J=Q[1].trim();return{type:"heading",raw:Q[0],depth:Q[2].charAt(0)==="="?1:2,text:J,tokens:this.lexer.inline(J)}}}paragraph($){let Q=this.rules.block.paragraph.exec($);if(Q){let J=Q[1].charAt(Q[1].length-1)===`
37
- `?Q[1].slice(0,-1):Q[1];return{type:"paragraph",raw:Q[0],text:J,tokens:this.lexer.inline(J)}}}text($){let Q=this.rules.block.text.exec($);if(Q)return{type:"text",raw:Q[0],text:Q[0],tokens:this.lexer.inline(Q[0])}}escape($){let Q=this.rules.inline.escape.exec($);if(Q)return{type:"escape",raw:Q[0],text:Q[1]}}tag($){let Q=this.rules.inline.tag.exec($);if(Q)return!this.lexer.state.inLink&&this.rules.other.startATag.test(Q[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(Q[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(Q[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(Q[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:Q[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:Q[0]}}link($){let Q=this.rules.inline.link.exec($);if(Q){let J=Q[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(J)){if(!this.rules.other.endAngleBracket.test(J))return;let G=Y2(J.slice(0,-1),"\\");if((J.length-G.length)%2===0)return}else{let G=oQ(Q[2],"()");if(G===-2)return;if(G>-1){let X=(Q[0].indexOf("!")===0?5:4)+Q[1].length+G;Q[2]=Q[2].substring(0,G),Q[0]=Q[0].substring(0,X).trim(),Q[3]=""}}let Y=Q[2],q="";if(this.options.pedantic){let G=this.rules.other.pedanticHrefTitle.exec(Y);G&&(Y=G[1],q=G[3])}else q=Q[3]?Q[3].slice(1,-1):"";return Y=Y.trim(),this.rules.other.startAngleBracket.test(Y)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(J)?Y=Y.slice(1):Y=Y.slice(1,-1)),S5(Q,{href:Y&&Y.replace(this.rules.inline.anyPunctuation,"$1"),title:q&&q.replace(this.rules.inline.anyPunctuation,"$1")},Q[0],this.lexer,this.rules)}}reflink($,Q){let J;if((J=this.rules.inline.reflink.exec($))||(J=this.rules.inline.nolink.exec($))){let Y=(J[2]||J[1]).replace(this.rules.other.multipleSpaceGlobal," "),q=Q[Y.toLowerCase()];if(!q){let G=J[0].charAt(0);return{type:"text",raw:G,text:G}}return S5(J,q,J[0],this.lexer,this.rules)}}emStrong($,Q,J=""){let Y=this.rules.inline.emStrongLDelim.exec($);if(!Y||!Y[1]&&!Y[2]&&!Y[3]&&!Y[4]||Y[4]&&J.match(this.rules.other.unicodeAlphaNumeric))return;if(!(Y[1]||Y[3])||!J||this.rules.inline.punctuation.exec(J)){let q=[...Y[0]].length-1,G,X,W=q,_=0,H=Y[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(H.lastIndex=0,Q=Q.slice(-1*$.length+q);(Y=H.exec(Q))!==null;){if(G=Y[1]||Y[2]||Y[3]||Y[4]||Y[5]||Y[6],!G)continue;if(X=[...G].length,Y[3]||Y[4]){W+=X;continue}else if((Y[5]||Y[6])&&q%3&&!((q+X)%3)){_+=X;continue}if(W-=X,W>0)continue;X=Math.min(X,X+W+_);let U=[...Y[0]][0].length,K=$.slice(0,q+Y.index+U+X);if(Math.min(q,X)%2){let O=K.slice(1,-1);return{type:"em",raw:K,text:O,tokens:this.lexer.inlineTokens(O)}}let N=K.slice(2,-2);return{type:"strong",raw:K,text:N,tokens:this.lexer.inlineTokens(N)}}}}codespan($){let Q=this.rules.inline.code.exec($);if(Q){let J=Q[2].replace(this.rules.other.newLineCharGlobal," "),Y=this.rules.other.nonSpaceChar.test(J),q=this.rules.other.startingSpaceChar.test(J)&&this.rules.other.endingSpaceChar.test(J);return Y&&q&&(J=J.substring(1,J.length-1)),{type:"codespan",raw:Q[0],text:J}}}br($){let Q=this.rules.inline.br.exec($);if(Q)return{type:"br",raw:Q[0]}}del($,Q,J=""){let Y=this.rules.inline.delLDelim.exec($);if(!Y)return;if(!Y[1]||!J||this.rules.inline.punctuation.exec(J)){let q=[...Y[0]].length-1,G,X,W=q,_=this.rules.inline.delRDelim;for(_.lastIndex=0,Q=Q.slice(-1*$.length+q);(Y=_.exec(Q))!==null;){if(G=Y[1]||Y[2]||Y[3]||Y[4]||Y[5]||Y[6],!G||(X=[...G].length,X!==q))continue;if(Y[3]||Y[4]){W+=X;continue}if(W-=X,W>0)continue;X=Math.min(X,X+W);let H=[...Y[0]][0].length,U=$.slice(0,q+Y.index+H+X),K=U.slice(q,-q);return{type:"del",raw:U,text:K,tokens:this.lexer.inlineTokens(K)}}}}autolink($){let Q=this.rules.inline.autolink.exec($);if(Q){let J,Y;return Q[2]==="@"?(J=Q[1],Y="mailto:"+J):(J=Q[1],Y=J),{type:"link",raw:Q[0],text:J,href:Y,tokens:[{type:"text",raw:J,text:J}]}}}url($){let Q;if(Q=this.rules.inline.url.exec($)){let J,Y;if(Q[2]==="@")J=Q[0],Y="mailto:"+J;else{let q;do q=Q[0],Q[0]=this.rules.inline._backpedal.exec(Q[0])?.[0]??"";while(q!==Q[0]);J=Q[0],Q[1]==="www."?Y="http://"+Q[0]:Y=Q[0]}return{type:"link",raw:Q[0],text:J,href:Y,tokens:[{type:"text",raw:J,text:J}]}}}inlineText($){let Q=this.rules.inline.text.exec($);if(Q){let J=this.lexer.state.inRawBlock;return{type:"text",raw:Q[0],text:Q[0],escaped:J}}}},i$=class ${tokens;options;state;inlineQueue;tokenizer;constructor(Q){this.tokens=[],this.tokens.links=Object.create(null),this.options=Q||e1,this.options.tokenizer=this.options.tokenizer||new c2,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let J={other:k$,block:u2.normal,inline:q2.normal};this.options.pedantic?(J.block=u2.pedantic,J.inline=q2.pedantic):this.options.gfm&&(J.block=u2.gfm,this.options.breaks?J.inline=q2.breaks:J.inline=q2.gfm),this.tokenizer.rules=J}static get rules(){return{block:u2,inline:q2}}static lex(Q,J){return new $(J).lex(Q)}static lexInline(Q,J){return new $(J).inlineTokens(Q)}lex(Q){Q=Q.replace(k$.carriageReturn,`
38
- `),this.blockTokens(Q,this.tokens);for(let J=0;J<this.inlineQueue.length;J++){let Y=this.inlineQueue[J];this.inlineTokens(Y.src,Y.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(Q,J=[],Y=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(Q=Q.replace(k$.tabCharGlobal," ").replace(k$.spaceLine,""));Q;){let q;if(this.options.extensions?.block?.some((X)=>(q=X.call({lexer:this},Q,J))?(Q=Q.substring(q.raw.length),J.push(q),!0):!1))continue;if(q=this.tokenizer.space(Q)){Q=Q.substring(q.raw.length);let X=J.at(-1);q.raw.length===1&&X!==void 0?X.raw+=`
39
- `:J.push(q);continue}if(q=this.tokenizer.code(Q)){Q=Q.substring(q.raw.length);let X=J.at(-1);X?.type==="paragraph"||X?.type==="text"?(X.raw+=(X.raw.endsWith(`
19
+ `),o="",r="",a=[];for(;n.length>0;){let s=!1,l=[],i;for(i=0;i<n.length;i++)if(this.rules.other.blockquoteStart.test(n[i]))l.push(n[i]),s=!0;else if(!s)l.push(n[i]);else break;n=n.slice(i);let c=l.join(`
20
+ `),d=c.replace(this.rules.other.blockquoteSetextReplace,`
21
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");o=o?`${o}
22
+ ${c}`:c,r=r?`${r}
23
+ ${d}`:d;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,a,!0),this.lexer.state.top=u,n.length===0)break;let p=a.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,h=f.raw+`
24
+ `+n.join(`
25
+ `),x=this.blockquote(h);a[a.length-1]=x,o=o.substring(0,o.length-f.raw.length)+x.raw,r=r.substring(0,r.length-f.text.length)+x.text;break}else if(p?.type==="list"){let f=p,h=f.raw+`
26
+ `+n.join(`
27
+ `),x=this.list(h);a[a.length-1]=x,o=o.substring(0,o.length-p.raw.length)+x.raw,r=r.substring(0,r.length-f.raw.length)+x.raw,n=h.substring(a.at(-1).raw.length).split(`
28
+ `);continue}}return{type:"blockquote",raw:o,tokens:a,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),o=n.length>1,r={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let a=this.rules.other.listItemRegex(n),s=!1;for(;e;){let i=!1,c="",d="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let u=pd(t[2].split(`
29
+ `,1)[0],t[1].length),p=e.split(`
30
+ `,1)[0],f=!u.trim(),h=0;if(this.options.pedantic?(h=2,d=u.trimStart()):f?h=t[1].length+1:(h=u.search(this.rules.other.nonSpaceChar),h=h>4?1:h,d=u.slice(h),h+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(c+=p+`
31
+ `,e=e.substring(p.length+1),i=!0),!i){let x=this.rules.other.nextBulletRegex(h),g=this.rules.other.hrRegex(h),k=this.rules.other.fencesBeginRegex(h),m=this.rules.other.headingBeginRegex(h),b=this.rules.other.htmlBeginRegex(h),w=this.rules.other.blockquoteBeginRegex(h);for(;e;){let y=e.split(`
32
+ `,1)[0],S;if(p=y,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),S=p):S=p.replace(this.rules.other.tabCharGlobal," "),k.test(p)||m.test(p)||b.test(p)||w.test(p)||x.test(p)||g.test(p))break;if(S.search(this.rules.other.nonSpaceChar)>=h||!p.trim())d+=`
33
+ `+S.slice(h);else{if(f||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||k.test(u)||m.test(u)||g.test(u))break;d+=`
34
+ `+p}f=!p.trim(),c+=y+`
35
+ `,e=e.substring(y.length+1),u=S.slice(h)}}r.loose||(s?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),r.raw+=c}let l=r.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let i of r.items){if(this.lexer.state.top=!1,i.tokens=this.lexer.blockTokens(i.text,[]),i.task){if(i.text=i.text.replace(this.rules.other.listReplaceTask,""),i.tokens[0]?.type==="text"||i.tokens[0]?.type==="paragraph"){i.tokens[0].raw=i.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),i.tokens[0].text=i.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let c=this.rules.other.listTaskCheckbox.exec(i.raw);if(c){let d={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};i.checked=d.checked,r.loose?i.tokens[0]&&["paragraph","text"].includes(i.tokens[0].type)&&"tokens"in i.tokens[0]&&i.tokens[0].tokens?(i.tokens[0].raw=d.raw+i.tokens[0].raw,i.tokens[0].text=d.raw+i.tokens[0].text,i.tokens[0].tokens.unshift(d)):i.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):i.tokens.unshift(d)}}if(!r.loose){let c=i.tokens.filter((u)=>u.type==="space"),d=c.length>0&&c.some((u)=>this.rules.other.anyLine.test(u.raw));r.loose=d}}if(r.loose)for(let i of r.items){i.loose=!0;for(let c of i.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),o=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Ea(t[1]),o=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
36
+ `):[],a={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let s of o)this.rules.other.tableAlignRight.test(s)?a.align.push("right"):this.rules.other.tableAlignCenter.test(s)?a.align.push("center"):this.rules.other.tableAlignLeft.test(s)?a.align.push("left"):a.align.push(null);for(let s=0;s<n.length;s++)a.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:a.align[s]});for(let s of r)a.rows.push(Ea(s,a.header.length).map((l,i)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:a.align[i]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
37
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=sr(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=ud(t[2],"()");if(a===-2)return;if(a>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let o=t[2],r="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(o);a&&(o=a[1],r=a[3])}else r=t[3]?t[3].slice(1,-1):"";return o=o.trim(),this.rules.other.startAngleBracket.test(o)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?o=o.slice(1):o=o.slice(1,-1)),Ra(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[o.toLowerCase()];if(!r){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return Ra(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||!o[1]&&!o[2]&&!o[3]&&!o[4]||o[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(o[1]||o[3])||!n||this.rules.inline.punctuation.exec(n)){let r=[...o[0]].length-1,a,s,l=r,i=0,c=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(o=c.exec(t))!==null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(s=[...a].length,o[3]||o[4]){l+=s;continue}else if((o[5]||o[6])&&r%3&&!((r+s)%3)){i+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l+i);let d=[...o[0]][0].length,u=e.slice(0,r+o.index+d+s);if(Math.min(r,s)%2){let f=u.slice(1,-1);return{type:"em",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}let p=u.slice(2,-2);return{type:"strong",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),o=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return o&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let o=this.rules.inline.delLDelim.exec(e);if(!o)return;if(!o[1]||!n||this.rules.inline.punctuation.exec(n)){let r=[...o[0]].length-1,a,s,l=r,i=this.rules.inline.delRDelim;for(i.lastIndex=0,t=t.slice(-1*e.length+r);(o=i.exec(t))!==null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a||(s=[...a].length,s!==r))continue;if(o[3]||o[4]){l+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l);let c=[...o[0]][0].length,d=e.slice(0,r+o.index+c+s),u=d.slice(r,-r);return{type:"del",raw:d,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;return t[2]==="@"?(n=t[1],o="mailto:"+n):(n=t[1],o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,o;if(t[2]==="@")n=t[0],o="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?o="http://"+t[0]:o=t[0]}return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ge=class e{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Zt,this.options.tokenizer=this.options.tokenizer||new Yr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:He,block:Kr.normal,inline:or.normal};this.options.pedantic?(n.block=Kr.pedantic,n.inline=or.pedantic):this.options.gfm&&(n.block=Kr.gfm,this.options.breaks?n.inline=or.breaks:n.inline=or.gfm),this.tokenizer.rules=n}static get rules(){return{block:Kr,inline:or}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(t){t=t.replace(He.carriageReturn,`
38
+ `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let o=this.inlineQueue[n];this.inlineTokens(o.src,o.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],o=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(He.tabCharGlobal," ").replace(He.spaceLine,""));t;){let r;if(this.options.extensions?.block?.some((s)=>(r=s.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let s=n.at(-1);r.raw.length===1&&s!==void 0?s.raw+=`
39
+ `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
40
40
  `)?"":`
41
- `)+q.raw,X.text+=`
42
- `+q.text,this.inlineQueue.at(-1).src=X.text):J.push(q);continue}if(q=this.tokenizer.fences(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.heading(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.hr(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.blockquote(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.list(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.html(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.def(Q)){Q=Q.substring(q.raw.length);let X=J.at(-1);X?.type==="paragraph"||X?.type==="text"?(X.raw+=(X.raw.endsWith(`
41
+ `)+r.raw,s.text+=`
42
+ `+r.text,this.inlineQueue.at(-1).src=s.text):n.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
43
43
  `)?"":`
44
- `)+q.raw,X.text+=`
45
- `+q.raw,this.inlineQueue.at(-1).src=X.text):this.tokens.links[q.tag]||(this.tokens.links[q.tag]={href:q.href,title:q.title},J.push(q));continue}if(q=this.tokenizer.table(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}if(q=this.tokenizer.lheading(Q)){Q=Q.substring(q.raw.length),J.push(q);continue}let G=Q;if(this.options.extensions?.startBlock){let X=1/0,W=Q.slice(1),_;this.options.extensions.startBlock.forEach((H)=>{_=H.call({lexer:this},W),typeof _=="number"&&_>=0&&(X=Math.min(X,_))}),X<1/0&&X>=0&&(G=Q.substring(0,X+1))}if(this.state.top&&(q=this.tokenizer.paragraph(G))){let X=J.at(-1);Y&&X?.type==="paragraph"?(X.raw+=(X.raw.endsWith(`
44
+ `)+r.raw,s.text+=`
45
+ `+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},n.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),n.push(r);continue}let a=t;if(this.options.extensions?.startBlock){let s=1/0,l=t.slice(1),i;this.options.extensions.startBlock.forEach((c)=>{i=c.call({lexer:this},l),typeof i=="number"&&i>=0&&(s=Math.min(s,i))}),s<1/0&&s>=0&&(a=t.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(a))){let s=n.at(-1);o&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
46
46
  `)?"":`
47
- `)+q.raw,X.text+=`
48
- `+q.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=X.text):J.push(q),Y=G.length!==Q.length,Q=Q.substring(q.raw.length);continue}if(q=this.tokenizer.text(Q)){Q=Q.substring(q.raw.length);let X=J.at(-1);X?.type==="text"?(X.raw+=(X.raw.endsWith(`
47
+ `)+r.raw,s.text+=`
48
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(r),o=a.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
49
49
  `)?"":`
50
- `)+q.raw,X.text+=`
51
- `+q.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=X.text):J.push(q);continue}if(Q){let X="Infinite loop on byte: "+Q.charCodeAt(0);if(this.options.silent){console.error(X);break}else throw Error(X)}}return this.state.top=!0,J}inline(Q,J=[]){return this.inlineQueue.push({src:Q,tokens:J}),J}inlineTokens(Q,J=[]){this.tokenizer.lexer=this;let Y=Q,q=null;if(this.tokens.links){let _=Object.keys(this.tokens.links);if(_.length>0)for(;(q=this.tokenizer.rules.inline.reflinkSearch.exec(Y))!==null;)_.includes(q[0].slice(q[0].lastIndexOf("[")+1,-1))&&(Y=Y.slice(0,q.index)+"["+"a".repeat(q[0].length-2)+"]"+Y.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(q=this.tokenizer.rules.inline.anyPunctuation.exec(Y))!==null;)Y=Y.slice(0,q.index)+"++"+Y.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let G;for(;(q=this.tokenizer.rules.inline.blockSkip.exec(Y))!==null;)G=q[2]?q[2].length:0,Y=Y.slice(0,q.index+G)+"["+"a".repeat(q[0].length-G-2)+"]"+Y.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);Y=this.options.hooks?.emStrongMask?.call({lexer:this},Y)??Y;let X=!1,W="";for(;Q;){X||(W=""),X=!1;let _;if(this.options.extensions?.inline?.some((U)=>(_=U.call({lexer:this},Q,J))?(Q=Q.substring(_.raw.length),J.push(_),!0):!1))continue;if(_=this.tokenizer.escape(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.tag(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.link(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.reflink(Q,this.tokens.links)){Q=Q.substring(_.raw.length);let U=J.at(-1);_.type==="text"&&U?.type==="text"?(U.raw+=_.raw,U.text+=_.text):J.push(_);continue}if(_=this.tokenizer.emStrong(Q,Y,W)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.codespan(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.br(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.del(Q,Y,W)){Q=Q.substring(_.raw.length),J.push(_);continue}if(_=this.tokenizer.autolink(Q)){Q=Q.substring(_.raw.length),J.push(_);continue}if(!this.state.inLink&&(_=this.tokenizer.url(Q))){Q=Q.substring(_.raw.length),J.push(_);continue}let H=Q;if(this.options.extensions?.startInline){let U=1/0,K=Q.slice(1),N;this.options.extensions.startInline.forEach((O)=>{N=O.call({lexer:this},K),typeof N=="number"&&N>=0&&(U=Math.min(U,N))}),U<1/0&&U>=0&&(H=Q.substring(0,U+1))}if(_=this.tokenizer.inlineText(H)){Q=Q.substring(_.raw.length),_.raw.slice(-1)!=="_"&&(W=_.raw.slice(-1)),X=!0;let U=J.at(-1);U?.type==="text"?(U.raw+=_.raw,U.text+=_.text):J.push(_);continue}if(Q){let U="Infinite loop on byte: "+Q.charCodeAt(0);if(this.options.silent){console.error(U);break}else throw Error(U)}}return J}},l2=class{options;parser;constructor($){this.options=$||e1}space($){return""}code({text:$,lang:Q,escaped:J}){let Y=(Q||"").match(k$.notSpaceStart)?.[0],q=$.replace(k$.endingNewline,"")+`
52
- `;return Y?'<pre><code class="language-'+Y1(Y)+'">'+(J?q:Y1(q,!0))+`</code></pre>
53
- `:"<pre><code>"+(J?q:Y1(q,!0))+`</code></pre>
54
- `}blockquote({tokens:$}){return`<blockquote>
55
- ${this.parser.parse($)}</blockquote>
56
- `}html({text:$}){return $}def($){return""}heading({tokens:$,depth:Q}){return`<h${Q}>${this.parser.parseInline($)}</h${Q}>
57
- `}hr($){return`<hr>
58
- `}list($){let{ordered:Q,start:J}=$,Y="";for(let X=0;X<$.items.length;X++){let W=$.items[X];Y+=this.listitem(W)}let q=Q?"ol":"ul",G=Q&&J!==1?' start="'+J+'"':"";return"<"+q+G+`>
59
- `+Y+"</"+q+`>
60
- `}listitem($){return`<li>${this.parser.parse($.tokens)}</li>
61
- `}checkbox({checked:$}){return"<input "+($?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:$}){return`<p>${this.parser.parseInline($)}</p>
62
- `}table($){let Q="",J="";for(let q=0;q<$.header.length;q++)J+=this.tablecell($.header[q]);Q+=this.tablerow({text:J});let Y="";for(let q=0;q<$.rows.length;q++){let G=$.rows[q];J="";for(let X=0;X<G.length;X++)J+=this.tablecell(G[X]);Y+=this.tablerow({text:J})}return Y&&(Y=`<tbody>${Y}</tbody>`),`<table>
50
+ `)+r.raw,s.text+=`
51
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(r);continue}if(t){let s="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw Error(s)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let o=t,r=null;if(this.tokens.links){let i=Object.keys(this.tokens.links);if(i.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(o))!==null;)i.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(o=o.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(o))!==null;)o=o.slice(0,r.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(o))!==null;)a=r[2]?r[2].length:0,o=o.slice(0,r.index+a)+"["+"a".repeat(r[0].length-a-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);o=this.options.hooks?.emStrongMask?.call({lexer:this},o)??o;let s=!1,l="";for(;t;){s||(l=""),s=!1;let i;if(this.options.extensions?.inline?.some((d)=>(i=d.call({lexer:this},t,n))?(t=t.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.escape(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.tag(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.link(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(i.raw.length);let d=n.at(-1);i.type==="text"&&d?.type==="text"?(d.raw+=i.raw,d.text+=i.text):n.push(i);continue}if(i=this.tokenizer.emStrong(t,o,l)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.codespan(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.br(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.del(t,o,l)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.autolink(t)){t=t.substring(i.raw.length),n.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(t))){t=t.substring(i.raw.length),n.push(i);continue}let c=t;if(this.options.extensions?.startInline){let d=1/0,u=t.slice(1),p;this.options.extensions.startInline.forEach((f)=>{p=f.call({lexer:this},u),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(c=t.substring(0,d+1))}if(i=this.tokenizer.inlineText(c)){t=t.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(l=i.raw.slice(-1)),s=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=i.raw,d.text+=i.text):n.push(i);continue}if(t){let d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw Error(d)}}return n}},Xr=class{options;parser;constructor(e){this.options=e||Zt}space(e){return""}code({text:e,lang:t,escaped:n}){let o=(t||"").match(He.notSpaceStart)?.[0],r=e.replace(He.endingNewline,"")+`
52
+ `;return o?'<pre><code class="language-'+st(o)+'">'+(n?r:st(r,!0))+`</code></pre>
53
+ `:"<pre><code>"+(n?r:st(r,!0))+`</code></pre>
54
+ `}blockquote({tokens:e}){return`<blockquote>
55
+ ${this.parser.parse(e)}</blockquote>
56
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
57
+ `}hr(e){return`<hr>
58
+ `}list(e){let{ordered:t,start:n}=e,o="";for(let s=0;s<e.items.length;s++){let l=e.items[s];o+=this.listitem(l)}let r=t?"ol":"ul",a=t&&n!==1?' start="'+n+'"':"";return"<"+r+a+`>
59
+ `+o+"</"+r+`>
60
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
61
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
62
+ `}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let o="";for(let r=0;r<e.rows.length;r++){let a=e.rows[r];n="";for(let s=0;s<a.length;s++)n+=this.tablecell(a[s]);o+=this.tablerow({text:n})}return o&&(o=`<tbody>${o}</tbody>`),`<table>
63
63
  <thead>
64
- `+Q+`</thead>
65
- `+Y+`</table>
66
- `}tablerow({text:$}){return`<tr>
67
- ${$}</tr>
68
- `}tablecell($){let Q=this.parser.parseInline($.tokens),J=$.header?"th":"td";return($.align?`<${J} align="${$.align}">`:`<${J}>`)+Q+`</${J}>
69
- `}strong({tokens:$}){return`<strong>${this.parser.parseInline($)}</strong>`}em({tokens:$}){return`<em>${this.parser.parseInline($)}</em>`}codespan({text:$}){return`<code>${Y1($,!0)}</code>`}br($){return"<br>"}del({tokens:$}){return`<del>${this.parser.parseInline($)}</del>`}link({href:$,title:Q,tokens:J}){let Y=this.parser.parseInline(J),q=A5($);if(q===null)return Y;$=q;let G='<a href="'+$+'"';return Q&&(G+=' title="'+Y1(Q)+'"'),G+=">"+Y+"</a>",G}image({href:$,title:Q,text:J,tokens:Y}){Y&&(J=this.parser.parseInline(Y,this.parser.textRenderer));let q=A5($);if(q===null)return Y1(J);$=q;let G=`<img src="${$}" alt="${Y1(J)}"`;return Q&&(G+=` title="${Y1(Q)}"`),G+=">",G}text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):("escaped"in $)&&$.escaped?$.text:Y1($.text)}},s4=class{strong({text:$}){return $}em({text:$}){return $}codespan({text:$}){return $}del({text:$}){return $}html({text:$}){return $}text({text:$}){return $}link({text:$}){return""+$}image({text:$}){return""+$}br(){return""}checkbox({raw:$}){return $}},o$=class ${options;renderer;textRenderer;constructor(Q){this.options=Q||e1,this.options.renderer=this.options.renderer||new l2,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new s4}static parse(Q,J){return new $(J).parse(Q)}static parseInline(Q,J){return new $(J).parseInline(Q)}parse(Q){this.renderer.parser=this;let J="";for(let Y=0;Y<Q.length;Y++){let q=Q[Y];if(this.options.extensions?.renderers?.[q.type]){let X=q,W=this.options.extensions.renderers[X.type].call({parser:this},X);if(W!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(X.type)){J+=W||"";continue}}let G=q;switch(G.type){case"space":{J+=this.renderer.space(G);break}case"hr":{J+=this.renderer.hr(G);break}case"heading":{J+=this.renderer.heading(G);break}case"code":{J+=this.renderer.code(G);break}case"table":{J+=this.renderer.table(G);break}case"blockquote":{J+=this.renderer.blockquote(G);break}case"list":{J+=this.renderer.list(G);break}case"checkbox":{J+=this.renderer.checkbox(G);break}case"html":{J+=this.renderer.html(G);break}case"def":{J+=this.renderer.def(G);break}case"paragraph":{J+=this.renderer.paragraph(G);break}case"text":{J+=this.renderer.text(G);break}default:{let X='Token with "'+G.type+'" type was not found.';if(this.options.silent)return console.error(X),"";throw Error(X)}}}return J}parseInline(Q,J=this.renderer){this.renderer.parser=this;let Y="";for(let q=0;q<Q.length;q++){let G=Q[q];if(this.options.extensions?.renderers?.[G.type]){let W=this.options.extensions.renderers[G.type].call({parser:this},G);if(W!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(G.type)){Y+=W||"";continue}}let X=G;switch(X.type){case"escape":{Y+=J.text(X);break}case"html":{Y+=J.html(X);break}case"link":{Y+=J.link(X);break}case"image":{Y+=J.image(X);break}case"checkbox":{Y+=J.checkbox(X);break}case"strong":{Y+=J.strong(X);break}case"em":{Y+=J.em(X);break}case"codespan":{Y+=J.codespan(X);break}case"br":{Y+=J.br(X);break}case"del":{Y+=J.del(X);break}case"text":{Y+=J.text(X);break}default:{let W='Token with "'+X.type+'" type was not found.';if(this.options.silent)return console.error(W),"";throw Error(W)}}}return Y}},X2=class{options;block;constructor($){this.options=$||e1}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess($){return $}postprocess($){return $}processAllTokens($){return $}emStrongMask($){return $}provideLexer($=this.block){return $?i$.lex:i$.lexInline}provideParser($=this.block){return $?o$.parse:o$.parseInline}},t4=class{defaults=c4();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=o$;Renderer=l2;TextRenderer=s4;Lexer=i$;Tokenizer=c2;Hooks=X2;constructor(...$){this.use(...$)}walkTokens($,Q){let J=[];for(let Y of $)switch(J=J.concat(Q.call(this,Y)),Y.type){case"table":{let q=Y;for(let G of q.header)J=J.concat(this.walkTokens(G.tokens,Q));for(let G of q.rows)for(let X of G)J=J.concat(this.walkTokens(X.tokens,Q));break}case"list":{let q=Y;J=J.concat(this.walkTokens(q.items,Q));break}default:{let q=Y;this.defaults.extensions?.childTokens?.[q.type]?this.defaults.extensions.childTokens[q.type].forEach((G)=>{let X=q[G].flat(1/0);J=J.concat(this.walkTokens(X,Q))}):q.tokens&&(J=J.concat(this.walkTokens(q.tokens,Q)))}}return J}use(...$){let Q=this.defaults.extensions||{renderers:{},childTokens:{}};return $.forEach((J)=>{let Y={...J};if(Y.async=this.defaults.async||Y.async||!1,J.extensions&&(J.extensions.forEach((q)=>{if(!q.name)throw Error("extension name required");if("renderer"in q){let G=Q.renderers[q.name];G?Q.renderers[q.name]=function(...X){let W=q.renderer.apply(this,X);return W===!1&&(W=G.apply(this,X)),W}:Q.renderers[q.name]=q.renderer}if("tokenizer"in q){if(!q.level||q.level!=="block"&&q.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let G=Q[q.level];G?G.unshift(q.tokenizer):Q[q.level]=[q.tokenizer],q.start&&(q.level==="block"?Q.startBlock?Q.startBlock.push(q.start):Q.startBlock=[q.start]:q.level==="inline"&&(Q.startInline?Q.startInline.push(q.start):Q.startInline=[q.start]))}"childTokens"in q&&q.childTokens&&(Q.childTokens[q.name]=q.childTokens)}),Y.extensions=Q),J.renderer){let q=this.defaults.renderer||new l2(this.defaults);for(let G in J.renderer){if(!(G in q))throw Error(`renderer '${G}' does not exist`);if(["options","parser"].includes(G))continue;let X=G,W=J.renderer[X],_=q[X];q[X]=(...H)=>{let U=W.apply(q,H);return U===!1&&(U=_.apply(q,H)),U||""}}Y.renderer=q}if(J.tokenizer){let q=this.defaults.tokenizer||new c2(this.defaults);for(let G in J.tokenizer){if(!(G in q))throw Error(`tokenizer '${G}' does not exist`);if(["options","rules","lexer"].includes(G))continue;let X=G,W=J.tokenizer[X],_=q[X];q[X]=(...H)=>{let U=W.apply(q,H);return U===!1&&(U=_.apply(q,H)),U}}Y.tokenizer=q}if(J.hooks){let q=this.defaults.hooks||new X2;for(let G in J.hooks){if(!(G in q))throw Error(`hook '${G}' does not exist`);if(["options","block"].includes(G))continue;let X=G,W=J.hooks[X],_=q[X];X2.passThroughHooks.has(G)?q[X]=(H)=>{if(this.defaults.async&&X2.passThroughHooksRespectAsync.has(G))return(async()=>{let K=await W.call(q,H);return _.call(q,K)})();let U=W.call(q,H);return _.call(q,U)}:q[X]=(...H)=>{if(this.defaults.async)return(async()=>{let K=await W.apply(q,H);return K===!1&&(K=await _.apply(q,H)),K})();let U=W.apply(q,H);return U===!1&&(U=_.apply(q,H)),U}}Y.hooks=q}if(J.walkTokens){let q=this.defaults.walkTokens,G=J.walkTokens;Y.walkTokens=function(X){let W=[];return W.push(G.call(this,X)),q&&(W=W.concat(q.call(this,X))),W}}this.defaults={...this.defaults,...Y}}),this}setOptions($){return this.defaults={...this.defaults,...$},this}lexer($,Q){return i$.lex($,Q??this.defaults)}parser($,Q){return o$.parse($,Q??this.defaults)}parseMarkdown($){return(Q,J)=>{let Y={...J},q={...this.defaults,...Y},G=this.onError(!!q.silent,!!q.async);if(this.defaults.async===!0&&Y.async===!1)return G(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof Q>"u"||Q===null)return G(Error("marked(): input parameter is undefined or null"));if(typeof Q!="string")return G(Error("marked(): input parameter is of type "+Object.prototype.toString.call(Q)+", string expected"));if(q.hooks&&(q.hooks.options=q,q.hooks.block=$),q.async)return(async()=>{let X=q.hooks?await q.hooks.preprocess(Q):Q,W=await(q.hooks?await q.hooks.provideLexer($):$?i$.lex:i$.lexInline)(X,q),_=q.hooks?await q.hooks.processAllTokens(W):W;q.walkTokens&&await Promise.all(this.walkTokens(_,q.walkTokens));let H=await(q.hooks?await q.hooks.provideParser($):$?o$.parse:o$.parseInline)(_,q);return q.hooks?await q.hooks.postprocess(H):H})().catch(G);try{q.hooks&&(Q=q.hooks.preprocess(Q));let X=(q.hooks?q.hooks.provideLexer($):$?i$.lex:i$.lexInline)(Q,q);q.hooks&&(X=q.hooks.processAllTokens(X)),q.walkTokens&&this.walkTokens(X,q.walkTokens);let W=(q.hooks?q.hooks.provideParser($):$?o$.parse:o$.parseInline)(X,q);return q.hooks&&(W=q.hooks.postprocess(W)),W}catch(X){return G(X)}}}onError($,Q){return(J)=>{if(J.message+=`
70
- Please report this to https://github.com/markedjs/marked.`,$){let Y="<p>An error occurred:</p><pre>"+Y1(J.message+"",!0)+"</pre>";return Q?Promise.resolve(Y):Y}if(Q)return Promise.reject(J);throw J}}},t1=new t4;function K$($,Q){return t1.parse($,Q)}K$.options=K$.setOptions=function($){return t1.setOptions($),K$.defaults=t1.defaults,w5(K$.defaults),K$};K$.getDefaults=c4;K$.defaults=e1;K$.use=function(...$){return t1.use(...$),K$.defaults=t1.defaults,w5(K$.defaults),K$};K$.walkTokens=function($,Q){return t1.walkTokens($,Q)};K$.parseInline=t1.parseInline;K$.Parser=o$;K$.parser=o$.parse;K$.Renderer=l2;K$.TextRenderer=s4;K$.Lexer=i$;K$.lexer=i$.lex;K$.Tokenizer=c2;K$.Hooks=X2;K$.parse=K$;var{options:wG,setOptions:TG,use:jG,walkTokens:bG,parseInline:ZG}=K$;var VG=o$.parse,CG=i$.lex;import{useEffect as k5,useMemo as e4,useRef as sQ,useState as _2}from"react";import{jsxDEV as S$}from"react/jsx-dev-runtime";function $3({open:$,onClose:Q,onSubmit:J,includedRemoteIds:Y,onToggleRemoteId:q}){let{annotations:G,generalNote:X,submittableResponses:W,feedbackEntries:_}=a1(),H=v$().threads!==null,[U,K]=_2(""),[N,O]=_2(!1),[M,L]=_2(!1),[F,w]=_2(null),z=sQ(null),[A,T]=_2(!1),S=e4(()=>G.filter((V)=>V.source==="remote"),[G]);if($&&!A)O(!1),L(!1),w(null);if(!$&&A)O(!1),L(!1),w(null);if($!==A)T($);let j=e4(()=>e0(G,X,W,_,Y,{annotationIds:H}),[G,X,W,_,Y,H]),Z=N?U:j;if(k5(()=>{if($&&M&&z.current)z.current.focus()},[$,M]),k5(()=>{if(!$)return;let V=(C)=>{if(C.key==="Escape")Q()};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[$,Q]),!$)return null;let y=Z.trim().length>0;return S$("div",{className:"fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-center justify-center p-8",onClick:Q,children:S$("div",{className:"bg-bg-surface border border-border-medium rounded-xl shadow-lg w-full max-w-2xl flex flex-col",style:{height:"80vh"},onClick:(V)=>V.stopPropagation(),children:[S$("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border-subtle flex-shrink-0",children:[S$("div",{className:"flex items-center gap-3",children:[S$("span",{className:"text-[13px] font-medium text-text-primary font-body",children:"Response preview"},void 0,!1,void 0,this),N&&S$("button",{onClick:()=>{O(!1),L(!1)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body",children:"Reset"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),S$("div",{className:"flex items-center gap-2",children:[S$("div",{className:"flex items-center bg-bg-base rounded-md p-0.5",children:[S$("button",{onClick:()=>L(!1),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${!M?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Preview"},void 0,!1,void 0,this),S$("button",{onClick:()=>L(!0),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${M?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),S$("button",{onClick:Q,className:"text-text-tertiary hover:text-text-secondary w-7 h-7 flex items-center justify-center rounded-md hover:bg-border-subtle transition-colors",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),M?S$("textarea",{ref:z,value:Z,onChange:(V)=>{K(V.currentTarget.value),O(!0)},className:"flex-1 w-full bg-bg-base p-5 text-[13px] font-mono text-text-code resize-none focus:outline-none leading-relaxed placeholder:text-text-disabled",placeholder:"Your feedback will appear here..."},void 0,!1,void 0,this):S$("div",{className:"flex-1 overflow-y-auto p-5",children:S$(V0,{text:Z},void 0,!1,void 0,this)},void 0,!1,void 0,this),S.length>0&&S$("div",{className:"px-5 py-2 border-t border-border-subtle flex-shrink-0",children:S$("span",{className:"text-[12px] text-text-secondary font-body",children:["Reviewer feedback: ",Y.size,"/",S.length," included"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F&&S$("div",{className:"px-5 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[S$("span",{children:F},void 0,!1,void 0,this),S$("button",{onClick:()=>{w(null),J(Z)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),S$("div",{className:"flex justify-end gap-2 px-5 py-3 border-t border-border-subtle flex-shrink-0",children:[S$("button",{onClick:Q,className:"px-4 py-2 rounded-lg text-[13px] font-body text-text-tertiary hover:text-text-secondary transition-colors",children:"Cancel"},void 0,!1,void 0,this),S$("button",{onClick:()=>{let V=Q2(W,_);if(V.length>0){w(`Please answer: ${V.join(", ")}`);return}w(null),J(Z)},disabled:!y,className:`px-6 py-2 rounded-lg font-body text-[13px] font-medium transition-all ${y?"bg-btn-primary text-btn-primary-text hover:opacity-90":"bg-bg-input text-text-disabled cursor-default"}`,children:"Submit feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var tQ=/!\[([^\]]*)\]\((\/tmp\/agent-canvas\/uploads\/([^)]+))\)/g;function eQ($){return $.replace(tQ,(Q,J,Y,q)=>`![${J}](/api/uploads/${q})`)}var E5={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Z0=($)=>$.replace(/[&<>"']/g,(Q)=>E5[Q]??Q),$J=($)=>$.replace(/&(?!#?\w+;)|[<>"']/g,(Q)=>E5[Q]??Q),y5=($)=>/^(?:https?|mailto):/i.test($)||!/^[^/?#]*:/.test($),f5=($)=>$?` title="${Z0($)}"`:"",QJ=new t4({renderer:{html:({text:$})=>Z0($),text($){return"tokens"in $&&$.tokens?this.parser.parseInline($.tokens):$J($.text)},link($){let Q=this.parser.parseInline($.tokens);return y5($.href)?`<a href="${Z0($.href)}"${f5($.title)}>${Q}</a>`:Q},image:($)=>y5($.href)?`<img src="${Z0($.href)}" alt="${Z0($.text)}"${f5($.title)}>`:Z0($.text)}});function i2($){return QJ.parse($,{async:!1})}function V0({text:$}){let Q=e4(()=>i2(eQ($)),[$]);return S$("div",{className:"prose-canvas font-body text-body text-text-primary leading-relaxed",dangerouslySetInnerHTML:{__html:Q}},void 0,!1,void 0,this)}import{useId as JJ,useState as Q3,useSyncExternalStore as qJ}from"react";import{jsxDEV as w$}from"react/jsx-dev-runtime";var YJ=[],XJ=()=>()=>{},GJ=()=>YJ;function _J(){let $=v$().threads;return qJ($?.subscribe??XJ,$?.current??GJ)}var WJ={open:"Answered",queued:"Reply sent",working:"Agent is on it",resolved:"Resolved"};function J3(){let $=v$().threads,Q=_J(),[J,Y]=Q3(()=>new Map),q=(W,_)=>Y((H)=>new Map(H).set(W,_));if($===null||Q.length===0)return null;let G=Q.filter((W)=>W.state!=="resolved"),X=Q.filter((W)=>W.state==="resolved");return w$("section",{"aria-label":"Threads",className:"px-3 pt-1 pb-3 border-b border-border-subtle",children:[w$("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-1 mb-1",children:"Threads"},void 0,!1,void 0,this),G.map((W)=>w$(v5,{thread:W,store:$,draft:J.get(W.id)??"",onDraft:(_)=>q(W.id,_)},W.id,!1,void 0,this)),X.length>0&&w$("details",{className:"mt-1",children:[w$("summary",{className:"text-[11px] text-text-tertiary font-body px-1 cursor-pointer",children:["Resolved (",X.length,")"]},void 0,!0,void 0,this),X.map((W)=>w$(v5,{thread:W,store:$,draft:J.get(W.id)??"",onDraft:(_)=>q(W.id,_)},W.id,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function v5({thread:$,store:Q,draft:J,onDraft:Y}){let q=JJ(),[G,X]=Q3(null),[W,_]=Q3(!1),H=async(N)=>{_(!0),X(null);try{await N()}catch(O){X(O instanceof Error?O.message:String(O))}finally{_(!1)}},U=()=>H(async()=>{await Q.reply($.id,J.trim()),Y("")}),K=$.filePath===g$?"Agent response":$.filePath??$.canvasFile?.replace(/\.jsx$/,"");return w$("article",{className:"rounded-lg border border-border-subtle bg-bg-elevated px-3 py-2 mt-2","data-thread-id":$.id,children:[w$("div",{className:"flex items-center justify-between gap-2 text-[11px] text-text-tertiary font-body",children:[w$("span",{className:"truncate",children:[K?`${K} · `:"","Round ",$.revision]},void 0,!0,void 0,this),w$("span",{children:WJ[$.state]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$.snippet.trim()&&w$("blockquote",{className:"mt-1 border-l-2 border-border-medium pl-2 text-[12px] text-text-secondary font-body line-clamp-3",children:$.snippet},void 0,!1,void 0,this),w$("ol",{className:"mt-2 space-y-2",children:$.comments.map((N)=>w$("li",{className:"text-[13px] font-body",children:[w$("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary",children:N.author==="agent"?"Agent":"You"},void 0,!1,void 0,this),N.author==="agent"?w$(V0,{text:N.body},void 0,!1,void 0,this):w$("p",{className:"whitespace-pre-wrap text-text-primary",children:N.body},void 0,!1,void 0,this)]},N.id,!0,void 0,this))},void 0,!1,void 0,this),w$("label",{className:"sr-only",htmlFor:q,children:"Reply"},void 0,!1,void 0,this),w$("textarea",{id:q,value:J,onInput:(N)=>Y(N.currentTarget.value),placeholder:"Reply to the agent",rows:2,className:"mt-2 w-full rounded-md bg-bg-input px-2 py-1.5 text-[13px] font-body text-text-primary"},void 0,!1,void 0,this),G&&w$("p",{role:"alert",className:"text-[12px] text-accent-red font-body",children:G},void 0,!1,void 0,this),w$("div",{className:"mt-1 flex justify-end gap-2",children:[w$("button",{type:"button",disabled:W,onClick:()=>H(()=>Q.setResolved($.id,$.state!=="resolved")),className:"px-2.5 py-1 rounded text-[12px] font-body text-text-secondary hover:text-text-primary",children:$.state==="resolved"?"Reopen":"Resolve"},void 0,!1,void 0,this),w$("button",{type:"button",disabled:W||J.trim()==="",onClick:U,className:"px-2.5 py-1 rounded text-[12px] font-body font-medium bg-btn-primary text-btn-primary-text disabled:opacity-50",children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as E,Fragment as o2}from"react/jsx-dev-runtime";function a2({onSubmit:$,collapseButton:Q}){let{isReadOnly:J,selectedRevision:Y,currentRevision:q,revisions:G,agentWatching:X}=Y3(h$),W=Y3(HJ),_=G.find((N)=>N.revision===Y),H=J&&Y===q,U=!!_?.feedbackConsumed,K=_?.label||`Round ${Y}`;if(J)return E(BJ,{sessionId:W,revision:Y,label:K,waitingForUpdate:H,feedbackConsumed:U,agentWatching:X,collapseButton:Q},void 0,!1,void 0,this);return E(OJ,{onSubmit:$,agentWatching:X,collapseButton:Q},void 0,!1,void 0,this)}function KJ({sessionId:$,revision:Q,label:J,waitingForUpdate:Y,feedbackConsumed:q,agentWatching:G,collapseButton:X}){let _=v$().isShared;return E("div",{className:"flex flex-col h-full",children:[E("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[E("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:Y?"Feedback sent":`Feedback — ${J}`},void 0,!1,void 0,this),X]},void 0,!0,void 0,this),Y&&!_&&E(x5,{feedbackConsumed:q,agentWatching:G},void 0,!1,void 0,this),E(h5,{sessionId:$,revision:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function x5({feedbackConsumed:$,agentWatching:Q}){if($)return E("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-green-muted flex items-center gap-2 flex-shrink-0",children:[E("span",{className:"w-2 h-2 rounded-full bg-accent-green animate-pulse"},void 0,!1,void 0,this),E("span",{className:"text-[12px] font-body text-accent-green",children:"Feedback received — waiting for next revision..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q)return E("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-blue-muted flex items-center gap-2 flex-shrink-0",children:[E("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"},void 0,!1,void 0,this),E("span",{className:"text-[12px] font-body text-accent-blue",children:"Waiting for agent to pick up feedback..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return E("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-amber-muted flex items-center gap-2 flex-shrink-0",children:[E("span",{className:"w-2 h-2 rounded-full bg-accent-amber"},void 0,!1,void 0,this),E("span",{className:"text-[12px] font-body text-accent-amber",children:"Agent disconnected — tell Claude to check feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function BJ({sessionId:$,revision:Q,label:J,waitingForUpdate:Y,feedbackConsumed:q,agentWatching:G,collapseButton:X}){let{annotations:W,generalNote:_}=a1(),H=W.length>0||_.trim().length>0,[U,K]=C0("feedback");if(!H)return E(KJ,{sessionId:$,revision:Q,label:J,waitingForUpdate:Y,feedbackConsumed:q,agentWatching:G,collapseButton:X},void 0,!1,void 0,this);return E("div",{className:"flex flex-col h-full",children:[E("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[E("div",{className:"flex items-center gap-1 bg-bg-input rounded-md p-0.5",children:[E("button",{onClick:()=>K("feedback"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors ${U==="feedback"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Feedback"},void 0,!1,void 0,this),E("button",{onClick:()=>K("annotations"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors flex items-center gap-1.5 ${U==="annotations"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:["Annotations",E("span",{className:"inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded-full bg-border-subtle text-[10px] font-medium",children:W.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),X]},void 0,!0,void 0,this),Y&&E(x5,{feedbackConsumed:q,agentWatching:G},void 0,!1,void 0,this),U==="feedback"?E(h5,{sessionId:$,revision:Q},void 0,!1,void 0,this):E(o2,{children:[E("div",{className:"flex-1 overflow-y-auto",children:E(u5,{annotations:W,readOnly:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this),_.trim()&&E("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:E("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:_},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function h5({sessionId:$,revision:Q}){let J=v$(),[Y,q]=C0(null),[G,X]=C0(!0);return m5(()=>{if(X(!0),!J.fsAvailable){q(null),X(!1);return}fetch(`/api/session/${$}/revision/${Q}/feedback`).then((W)=>W.json()).then((W)=>{q(K5.parse(W).feedback||null),X(!1)}).catch(()=>{q(null),X(!1)})},[$,Q]),E("div",{className:"flex-1 overflow-y-auto px-4",children:[E("div",{className:"-mx-4",children:E(J3,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),G?E("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"Loading..."},void 0,!1,void 0,this):Y?E(V0,{text:Y},void 0,!1,void 0,this):E("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"No feedback was submitted for this revision."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function NJ($){let Q=$.filter((X)=>X.filePath===g$),J=$.filter((X)=>!X.filePath),Y=$.filter((X)=>c1(X)!==void 0),q={};for(let X of Y){let W=c1(X);if(!W)continue;let _=q[W];if(_)_.push(X);else q[W]=[X]}let G=[Q,J,Y].filter((X)=>X.length>0).length>1;return{response:Q,plan:J,fileGroups:q,hasMultipleGroups:G}}function g5({children:$}){return E("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-3 mb-1 mt-1",children:$},void 0,!1,void 0,this)}function u5({annotations:$,readOnly:Q,includedRemoteIds:J,onToggleRemoteId:Y}){let{setActiveView:q}=Y3(q1),{response:G,plan:X,fileGroups:W,hasMultipleGroups:_}=NJ($),H=q3((N)=>{let O=c1(N);if(!O)return;q({type:"file",path:O}),setTimeout(()=>{let M=J2(N);if(M)M.scrollIntoView({behavior:"smooth",block:"center"})},150)},[q]),U=q3((N)=>u4(N,q),[q]),K={readOnly:Q,onSelect:H,onReveal:U,includedRemoteIds:J,onToggleRemoteId:Y};return E(o2,{children:[G.length>0&&E(o2,{children:[_&&E(g5,{children:"Agent Response"},void 0,!1,void 0,this),E(t0,{annotations:G,...K},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X.length>0&&E(o2,{children:[_&&E(g5,{children:"Canvas"},void 0,!1,void 0,this),E(t0,{annotations:X,...K},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Object.entries(W).map(([N,O])=>E("div",{children:[E("button",{onClick:()=>q({type:"file",path:N}),className:"flex items-center gap-1.5 text-[10px] uppercase tracking-widest text-text-tertiary hover:text-text-secondary font-body px-3 pt-3 pb-1 truncate transition-colors w-full text-left",title:N,children:[E(I1,{name:N.split("/").pop()||N,type:"file"},void 0,!1,void 0,this),E("span",{className:"truncate",children:N},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(t0,{annotations:O,...K},void 0,!1,void 0,this)]},N,!0,void 0,this))]},void 0,!0,void 0,this)}function OJ({onSubmit:$,agentWatching:Q,collapseButton:J}){let Y=v$(),[q,G]=C0(!1),{annotations:X,generalNote:W,submittableResponses:_,feedbackEntries:H}=a1(),U=UJ(()=>X.filter((j)=>j.source==="remote"),[X]),[K,N]=C0(()=>new Set);m5(()=>{if(U.length===0)return;N((j)=>{let Z=new Set(j);for(let y of U)Z.add(y.id);return Z.size===j.size?j:Z})},[U]);let O=q3((j)=>{N((Z)=>{let y=new Set(Z);if(y.has(j))y.delete(j);else y.add(j);return y})},[]),M=Array.from(_.values()).some($2),L=H.size>0,F=X.length>0||W.trim().length>0||M||L,[w,z]=C0(null),A=Y.threads!==null,T=(j)=>{let Z=A?X.filter((y)=>y.source!=="remote").map(zJ):[];$(j,Z,J5(_))},S=()=>{T(e0(X,W,_,H,K,{annotationIds:A}))};return E("div",{className:"flex flex-col h-full",children:[E("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[E("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body flex items-center gap-2",children:["Annotations",X.length>0&&E("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-border-subtle text-[10px] font-medium text-text-secondary",children:X.length},void 0,!1,void 0,this),!Y.isShared&&E("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${Q?"bg-accent-green":"bg-accent-amber"}`,title:Q?"Agent connected":"Agent disconnected"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J]},void 0,!0,void 0,this),E("div",{className:"flex-1 overflow-y-auto",children:[E(J3,{},void 0,!1,void 0,this),X.length===0&&E("p",{className:"text-[12px] text-text-tertiary px-3 py-4 leading-relaxed font-body",children:"Select text in the canvas or in files to add annotations."},void 0,!1,void 0,this),E(u5,{annotations:X,includedRemoteIds:K,onToggleRemoteId:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this),E(b4,{hasContent:F,onSubmit:()=>{let j=Q2(_,H);if(j.length>0){z(`Please answer: ${j.join(", ")}`);return}z(null),S()},onSubmitEmpty:()=>$("No feedback — looks good.",[],[]),notice:w&&E("div",{className:"px-4 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[E("span",{children:w},void 0,!1,void 0,this),E("button",{onClick:()=>{z(null),S()},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),secondaryAction:E("button",{onClick:()=>G(!0),className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-border-subtle text-text-secondary hover:bg-border-medium hover:text-text-primary",children:"Preview"},void 0,!1,void 0,this)},void 0,!1,void 0,this),E($3,{open:q,onClose:()=>G(!1),onSubmit:T,includedRemoteIds:K,onToggleRemoteId:O},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zJ($){return{id:$.id,snippet:$.snippet,note:$.note,canvasFile:$.canvasFile,filePath:$.filePath}}import{useFeedback as cH}from"#canvas/runtime";import B_ from"react";import{jsxDEV as O_}from"react/jsx-dev-runtime";K$.setOptions({gfm:!0,breaks:!1});import{jsxDEV as L_}from"react/jsx-dev-runtime";import{jsxDEV as S_}from"react/jsx-dev-runtime";import{useAnnotations as C_,useResponseRegistration as R_}from"#canvas/runtime";import{useEffect as I_,useMemo as k_,useRef as y_,useState as f_}from"react";import{jsxDEV as b_}from"react/jsx-dev-runtime";import{jsxDEV as g_}from"react/jsx-dev-runtime";import{useEffect as p_,useRef as c_}from"react";function W2(){return window.hljs}import{jsxDEV as r_}from"react/jsx-dev-runtime";import{jsxDEV as t_}from"react/jsx-dev-runtime";import{ActiveViewCtx as QW,SessionContext as JW}from"#canvas/runtime";import{useContext as YW,useEffect as XW,useRef as GW,useState as _W}from"react";import{jsxDEV as KW}from"react/jsx-dev-runtime";import{SessionContext as OW}from"#canvas/runtime";import{useContext as MW,useState as FW}from"react";import{jsxDEV as AW}from"react/jsx-dev-runtime";import{useMemo as jW}from"react";import{jsxDEV as ZW}from"react/jsx-dev-runtime";K$.setOptions({gfm:!0,breaks:!1});import{useAnnotations as DW,useCanvasFile as IW}from"#canvas/runtime";import{useCallback as EW,useEffect as vW,useRef as gW,useState as mW}from"react";import hW from"react-dom";import{jsxDEV as cW,Fragment as lW}from"react/jsx-dev-runtime";import{jsxDEV as oW}from"react/jsx-dev-runtime";import{jsxDEV as sW}from"react/jsx-dev-runtime";import{useState as QH}from"react";import{jsxDEV as YH}from"react/jsx-dev-runtime";import{jsxDEV as _H}from"react/jsx-dev-runtime";import{jsxDEV as KH}from"react/jsx-dev-runtime";import{useAnnotations as OH,useResponseRegistration as zH}from"#canvas/runtime";import{useRef as LH,useState as AH}from"react";import{jsxDEV as wH}from"react/jsx-dev-runtime";import{CanvasFileCtx as AJ,SessionContext as PJ}from"#canvas/runtime";import n2,{useContext as p5,useEffect as k1,useMemo as U2,useRef as SJ,useState as X1}from"react";import{createPortal as wJ}from"react-dom";import{createContext as LJ}from"react";var H2=LJ(()=>{});import{jsxDEV as O$,Fragment as ZJ}from"react/jsx-dev-runtime";class c5 extends n2.Component{state={error:null};static getDerivedStateFromError($){return{error:$}}componentDidCatch($,Q){this.props.reportError({revision:this.props.revision,filename:this.props.filename,message:$.message,...$.stack?{stack:$.stack}:{},...Q.componentStack?{componentStack:Q.componentStack}:{}})}render(){if(!this.state.error)return this.props.children;return O$(l5,{message:this.state.error.message},void 0,!1,void 0,this)}}function l5({message:$}){return O$("div",{className:"bg-accent-red-muted rounded-lg p-5",children:[O$("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Canvas render failed"},void 0,!1,void 0,this),O$("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:$},void 0,!1,void 0,this),O$("p",{className:"text-meta font-body text-text-tertiary mt-3",children:"The error was sent back to the canvas author."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function R0({revision:$,filename:Q}){let J=p5(PJ),Y=v$(),q=p5(H2),[G,X]=X1(null),[W,_]=X1(null),[H,U]=X1(!0),K=SJ(null),{annotations:N,addAnnotationWithId:O,removeAnnotation:M,updateAnnotation:L,addAnnotationImage:F,removeAnnotationImage:w,activeAnnotationId:z,setActiveAnnotationId:A,registerCanvasRendered:T}=a1(),S=U2(()=>N.filter((g)=>!g.filePath&&(!g.canvasFile||g.canvasFile===Q)),[N,Q]),[j,Z]=X1(null),[y,V]=X1(null),[C,v]=X1(null),[h,o]=X1(null),[B$,a]=X1(!1);k1(()=>{U(!0),_(null),o(null),Y.loadCanvasModule(Q,$).then((g)=>{X(()=>g.default),U(!1)}).catch((g)=>{let c=g instanceof Error?g:Error(String(g));_(c.message),U(!1),q({revision:$,filename:Q,message:c.message,...c.stack?{stack:c.stack}:{}})})},[J,$,Q,q]),k1(()=>{if(G)T(Q)},[G,Q,T]);let U$=document.getElementById("plan-scroll-container"),{popovers:Y$,isPopoverOpen:N$}=R1({containerRef:K,restoreKey:G,restoreAnnotations:S,extractContext:(g)=>P1(g,K.current),canvasFile:Q,scrollContainer:U$}),{popovers:Q$,isDrawing:_$,isPopoverOpen:F$}=I4({containerRef:K,restoreKey:G,canvasFile:Q,scrollContainer:U$}),n=N$||F$,d=U2(()=>{let g=new Map;for(let c of S)if(c.snippet.startsWith("["))g.set(c.snippet,c.id);return g},[S]);k1(()=>{let g=K.current;if(!g)return;let c=(D)=>{if(C||n||_$)return;let x=D.target;if(x.closest("[data-block-comment-btn]"))return;a(!1);let r=x.closest(Y0);if(r&&g.contains(r)){let C$=$0(g).indexOf(r);o(C$>=0?C$:null)}else o(null);let z$=x.closest(S1);if(z$&&g.contains(z$)){V(z$);let L$=s$(z$),C$=L$?d.get(L$):void 0;if(C$&&C$!==z)A(C$)}else V(null)},f=(D)=>{if(C||n)return;if(D.relatedTarget?.closest("[data-block-comment-btn]"))return;V(null),A(null)};return g.addEventListener("mousemove",c),g.addEventListener("mouseleave",f),()=>{g.removeEventListener("mousemove",c),g.removeEventListener("mouseleave",f)}},[G,C,n,_$,d,z]),k1(()=>{let g=(c)=>{let f=c.target.tagName;if(f==="INPUT"||f==="TEXTAREA"||c.target.isContentEditable)return;if(C||n)return;let D=K.current;if(!D)return;if(c.key==="ArrowDown"){c.preventDefault(),a(!0);let x=$0(D);if(x.length===0)return;o((r)=>{if(r===null)return 0;return Math.min(r+1,x.length-1)})}else if(c.key==="ArrowUp"){c.preventDefault(),a(!0);let x=$0(D);if(x.length===0)return;o((r)=>{if(r===null)return x.length-1;return Math.max(r-1,0)})}else if(c.key==="a"||c.key==="A"){if(h===null||!D)return;let r=$0(D)[h];if(!r)return;if(!r.matches(S1))return;c.preventDefault();let z$=s$(r);if(!z$)return;let L$=d.get(z$);if(L$)A(L$),v({anchorEl:r,snippet:z$,annId:L$});else v({anchorEl:r,snippet:z$})}else if(c.key===" "||c.key==="Enter"){if(h===null)return;let r=$0(D)[h];if(!r)return;let z$=r.getAttribute("data-md");if(z$==="choice-option"||z$==="multichoice-option")c.preventDefault(),r.dispatchEvent(new CustomEvent("kb-select",{bubbles:!0}));else if(z$==="userinput"){c.preventDefault();let L$=r.querySelector("textarea");if(L$){L$.focus();let C$=(f$)=>{if(f$.key==="Escape")f$.preventDefault(),L$.blur(),a(!0)};L$.addEventListener("keydown",C$),L$.addEventListener("blur",()=>L$.removeEventListener("keydown",C$),{once:!0})}}else if(z$==="rangeinput"){c.preventDefault();let L$=r.querySelector("input[type='range']");if(L$){L$.focus();let C$=(f$)=>{if(f$.key==="Escape"||f$.key==="ArrowUp"||f$.key==="ArrowDown")f$.preventDefault(),L$.blur(),a(!0)};L$.addEventListener("keydown",C$),L$.addEventListener("blur",()=>L$.removeEventListener("keydown",C$),{once:!0})}}}else if(c.key==="Escape")o(null),a(!1),A(null)};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[h,C,n,d]),k1(()=>{let g=K.current;if(!g||h===null||!B$)return;let f=$0(g)[h];if(!f)return;f.style.outline="2px solid var(--color-accent-blue)",f.style.outlineOffset="-2px",f.style.borderRadius="8px",f.scrollIntoView({block:"nearest",behavior:"smooth"});let D=s$(f),x=D?d.get(D):void 0;if(x)A(x);return()=>{f.style.outline="",f.style.outlineOffset="",f.style.borderRadius=""}},[h,B$,d]);let X$=U2(()=>G?O$(G,{},void 0,!1,void 0,this):null,[G]);if(H)return O$("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-body",children:"Loading canvas..."},void 0,!1,void 0,this);if(W)return O$(l5,{message:W},void 0,!1,void 0,this);if(!G)return O$("div",{className:"text-text-tertiary text-center py-8 font-body text-body",children:"No canvas loaded"},void 0,!1,void 0,this);return O$(AJ.Provider,{value:Q,children:[O$("div",{ref:K,className:"plan-content plan-updated","data-canvas-file":Q,children:O$(c5,{revision:$,filename:Q,reportError:q,children:X$},`${$}:${Q}`,!1,void 0,this)},void 0,!1,void 0,this),j&&O$(bJ,{note:j.note,onSave:(g)=>{L(j.id,g),Z(null)},onCancel:()=>Z(null)},void 0,!1,void 0,this),Y$,Q$,O$(TJ,{containerRef:K,hoveredBlock:y,focusedBlockIndex:h,blockPopover:C,blockAnnotationMap:d,activeAnnotationId:z,onOpen:(g,c,f)=>{if(f)A(f),v({anchorEl:g,snippet:c,annId:f});else v({anchorEl:g,snippet:c})}},void 0,!1,void 0,this),C&&!C.annId&&O$(Q1,{anchorEl:C.anchorEl,scrollContainer:U$,snippet:C.snippet,truncateAt:80,onAdd:(g,c)=>{let f=x$();O(f,C.snippet,g,void 0,void 0,c,Q),v(null)},onCancel:()=>v(null)},void 0,!1,void 0,this),C?.annId&&(()=>{let g=S.find((c)=>c.id===C.annId);if(!g)return null;return O$(r1,{anchorEl:C.anchorEl,scrollContainer:U$,initialNote:g.note,initialImages:g.images,onUpdate:(c,f)=>{L(C.annId,c);let D=g.images||[];for(let x of f)if(!D.includes(x))F(C.annId,x);for(let x of D)if(!f.includes(x))w(C.annId,x)},onDelete:()=>{M(C.annId),A(null),v(null)},onClose:()=>v(null)},void 0,!1,void 0,this)})()]},void 0,!0,void 0,this)}function $0($){return Array.from($.querySelectorAll(Y0))}function TJ({containerRef:$,hoveredBlock:Q,focusedBlockIndex:J,blockPopover:Y,blockAnnotationMap:q,activeAnnotationId:G,onOpen:X}){let[W,_]=X1([]);k1(()=>{let O=$.current;if(!O||q.size===0){_([]);return}let M=[];for(let L of O.querySelectorAll(S1)){let F=s$(L);if(F&&q.has(F))M.push(L)}_(M)},[q,$.current]);let[H,U]=X1(null);k1(()=>{if(!G||!$.current){U(null);return}for(let O of $.current.querySelectorAll(Y0)){let M=s$(O);if(M&&q.get(M)===G){U(O);return}}U(null)},[G,q]),k1(()=>{if(!H)return;return H.style.boxShadow="inset 0 0 0 1.5px var(--color-highlight-bg)",H.style.borderRadius="8px",()=>{H.style.boxShadow="",H.style.borderRadius=""}},[H]);let K=U2(()=>{if(J===null||!$.current)return null;let O=$0($.current)[J];if(!O)return null;return O.matches(S1)?O:null},[J,$.current]),N=U2(()=>{let O=new Set(W);if(Q)O.add(Q);if(K)O.add(K);if(Y?.anchorEl)O.add(Y.anchorEl);return Array.from(O)},[W,Q,K,Y]);return O$(ZJ,{children:N.map((O)=>O$(jJ,{block:O,isHovered:O===Q||O===K||O===Y?.anchorEl,blockAnnotationMap:q,activeAnnotationId:G,onOpen:X},O.getAttribute("data-task-id")||O.getAttribute("data-md-title")||O.textContent?.slice(0,30)||"block",!1,void 0,this))},void 0,!1,void 0,this)}function jJ({block:$,isHovered:Q,blockAnnotationMap:J,activeAnnotationId:Y,onOpen:q}){let G=s$($);if(!G)return null;let X=J.get(G),W=!!X;return wJ(O$("button",{"data-block-comment-btn":!0,onClick:(H)=>{H.stopPropagation(),q(H.currentTarget,G,X)},className:`absolute top-1 right-1 z-10 w-6 h-6 flex items-center justify-center rounded transition-all duration-150 ${W?X===Y?"text-accent-amber bg-accent-amber-muted":"text-accent-amber opacity-60 hover:opacity-100":Q?"text-text-disabled hover:text-text-tertiary opacity-50 hover:opacity-100":"text-text-disabled opacity-0 group-hover/section:opacity-20 hover:!opacity-80"}`,title:W?"Edit annotation":"Add annotation",children:O$("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:W?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:O$("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),$)}function bJ({note:$,onSave:Q,onCancel:J}){let[Y,q]=n2.useState($),G=n2.useRef(null);return n2.useEffect(()=>{G.current?.focus(),G.current?.select()},[]),O$("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center",onClick:J,children:O$("div",{className:"bg-bg-elevated border border-border-hover rounded-lg shadow-md p-4 w-80",onClick:(X)=>X.stopPropagation(),children:[O$("div",{className:"text-tiny uppercase tracking-widest text-text-tertiary font-body mb-2",children:"Edit annotation"},void 0,!1,void 0,this),O$("textarea",{ref:G,value:Y,onChange:(X)=>q(X.currentTarget.value),className:"w-full bg-transparent border-none text-body font-body text-text-primary resize-vertical focus:outline-none min-h-[60px]",onKeyDown:(X)=>{if(X.key==="Enter"&&(X.ctrlKey||X.metaKey))Q(Y.trim());if(X.key==="Escape")J()}},void 0,!1,void 0,this),O$("div",{className:"flex justify-end gap-2 mt-2",children:[O$("button",{onClick:J,className:"text-meta text-text-tertiary font-body px-3 py-1",children:"Cancel"},void 0,!1,void 0,this),O$("button",{onClick:()=>Q(Y.trim()),className:"text-meta font-medium font-body px-3 py-1 rounded-md bg-highlight-bg text-text-primary border border-highlight-border",children:"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import v1,{useCallback as k0,useEffect as u$,useLayoutEffect as Bq,useMemo as o6,useRef as W1,useState as M$}from"react";import{createRoot as Nq}from"react-dom/client";var VJ=500,CJ=1e4,G3=B.string().max(CJ),d5=B.object({id:B.string().min(1).max(200),type:B.enum(["select","radio","checkbox","text","range"]),label:B.string().max(1000),value:B.union([G3,B.array(G3).max(500),B.number(),B.null()]),note:G3.optional()}),xU=B.array(d5).max(VJ);function r5($){return $.flatMap((Q)=>{let J=d5.safeParse(Q);if(!J.success)return[];let{value:Y,note:q,...G}=J.data,X=Array.isArray(Y)?Y.length>0:typeof Y==="string"?Y.trim()!=="":Y!==null,W=q?.trim()??"";if(!X&&!W)return[];return[{...G,value:Y,...W?{note:W}:{}}]})}var i5=B.object({shareId:B.string(),url:B.string(),revision:B.number(),createdAt:B.string(),ownerToken:B.string().optional(),expiresAt:B.string().optional(),lastFeedbackAt:B.string().optional(),encryptionKey:B.string().optional()}),RJ=B.object({revision:B.number(),label:B.string().optional(),canvasFiles:B.array(B.object({filename:B.string(),diffStats:B.object({added:B.number(),removed:B.number()}).optional()})),createdAt:B.string(),hasFeedback:B.boolean(),feedbackConsumed:B.boolean(),response:B.string().optional()}).passthrough(),o5=B.object({encryption:B.object({alg:B.literal("AES-GCM"),v:B.literal(1)}).optional(),origin:B.object({sessionId:B.string().optional(),label:B.string().optional(),revision:B.number().optional(),createdAt:B.string().optional()}).optional(),currentRevision:B.number().optional(),revisions:B.array(RJ).optional(),canvasFiles:B.array(B.string()).optional(),projectRoot:B.string().optional(),shares:B.array(i5).optional(),shareEnabled:B.boolean().optional()}).passthrough(),_3=B.object({entries:B.array(B.object({name:B.string(),type:B.enum(["file","dir"])}))}),DJ=B.object({id:B.string(),shareId:B.string(),revision:B.number(),submittedAt:B.string(),author:S4,annotations:B.array(w4.omit({source:!0,author:!0})),generalNote:B.string().optional()}),a5=B.object({entries:B.array(DJ)}),n5=B.union([B.object({ok:B.literal(!0),share:i5}),B.object({ok:B.literal(!1).optional(),error:B.string().optional()})]),s5=B.union([B.object({ok:B.literal(!0)}),B.object({ok:B.literal(!1).optional(),error:B.string().optional()})]);var IJ=B.object({id:B.string(),name:B.string(),path:B.string(),size:B.number().int()});var t5={alg:"AES-GCM",v:1};async function e5($){let Q=yJ($);return crypto.subtle.importKey("raw",Q,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function N1($,Q){let J=crypto.getRandomValues(new Uint8Array(12)),Y=new TextEncoder().encode(Q),q=await crypto.subtle.encrypt({name:"AES-GCM",iv:J},$,Y),G=new Uint8Array(J.byteLength+q.byteLength);return G.set(J,0),G.set(new Uint8Array(q),J.byteLength),kJ(G)}async function K2($,Q){let J=$6(Q);if(J.byteLength<28)throw Error("Ciphertext too short");let Y=J.subarray(0,12),q=J.subarray(12),G=await crypto.subtle.decrypt({name:"AES-GCM",iv:Y},$,q);return new TextDecoder().decode(G)}function kJ($){let Q="",J=32768;for(let Y=0;Y<$.byteLength;Y+=J)Q+=String.fromCharCode.apply(null,Array.from($.subarray(Y,Y+J)));return btoa(Q)}function $6($){let Q=atob($),J=new Uint8Array(Q.length);for(let Y=0;Y<Q.length;Y++)J[Y]=Q.charCodeAt(Y);return J}function yJ($){let Q=$.replace(/-/g,"+").replace(/_/g,"/")+"===".slice(($.length+3)%4);return $6(Q)}function fJ($){let Q;try{Q=new URL($)}catch{return!1}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"||Q.hostname==="[::1]"||Q.hostname.endsWith(".localhost")}var y1=B.string().max(500),EJ=4000,vJ=1000,gJ=1000,mJ=B.object({label:y1,file:B.string().max(vJ),line:B.number().int().positive(),column:B.number().int().nonnegative()}),J6=B.object({url:B.string().min(1).max(2000),selector:B.string().max(2000),role:y1.optional(),name:y1.optional(),text:y1.optional(),components:B.array(B.string().max(200)).max(20).optional(),sources:B.array(mJ).max(10).optional(),context:y1.optional(),browser:B.object({name:y1,viewport:B.object({width:B.number().int().nonnegative(),height:B.number().int().nonnegative(),scale:B.number().positive()}),colorScheme:B.enum(["light","dark"])}).optional(),style:B.string().max(gJ).optional(),html:B.string().max(EJ).optional(),quote:B.object({exact:B.string().min(1).max(2000),before:y1,after:y1}).optional()}),xJ=B.enum(["user","agent"]),W3=B.object({id:B.string(),author:xJ,body:B.string().min(1).max(20000),createdAt:B.string()}),H3=B.enum(["open","queued","working","resolved"]),hJ=B.object({id:B.string(),anchor:J6,state:H3,comments:B.array(W3).min(1),screenshot:B.string().optional(),createdAt:B.string(),updatedAt:B.string()}),oU=B.object({threads:B.array(hJ)}),U3=B.string().trim().min(1).max(20000),Q6="data:image/png;base64,",uJ=B.string().startsWith(Q6).max(8000000).transform(($)=>Uint8Array.from(atob($.slice(Q6.length)),(Q)=>Q.charCodeAt(0))),aU=B.object({anchor:J6,body:U3,send:B.boolean(),screenshot:uJ.optional()}),nU=B.object({body:U3,send:B.boolean()}),sU=B.object({body:U3,resolve:B.boolean()}),q6=B.string().url().refine(($)=>fJ($),"must be an http(s) URL on localhost"),tU=B.object({target:q6}),eU=B.object({target:q6,port:B.number().int().min(1).max(65535)});var B2=B.object({id:B.string(),state:H3,revision:B.number().int(),snippet:B.string(),canvasFile:B.string().optional(),filePath:B.string().optional(),comments:B.array(W3),createdAt:B.string(),updatedAt:B.string()}),UK=B.object({threads:B.array(B2)}),Y6=B.string().trim().min(1).max(20000),KK=B.object({body:Y6,resolve:B.boolean()}),BK=B.object({body:Y6}),NK=B.object({resolved:B.boolean()});var pJ=B.object({threads:B.array(B2)}),cJ=B.object({thread:B2});async function X6($){let Q=await $.json().catch(()=>null),J=B.object({error:B.string()}).safeParse(Q);return Error(J.success?J.data.error:`Thread request failed with status ${$.status}`)}function lJ($,Q){let J=new Map(Q.map((G)=>[G.id,G])),Y=$.map((G)=>{let X=J.get(G.id);return X!==void 0&&X.updatedAt>=G.updatedAt?X:G}),q=new Set($.map((G)=>G.id));return[...Y,...Q.filter((G)=>!q.has(G.id))]}function G6($){let Q=[],J=new Set,Y=`/api/session/${encodeURIComponent($)}/threads`,q=(X)=>{Q=lJ(Q,X);for(let W of J)W()},G=async(X,W)=>{let _=await fetch(`${Y}/${X}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!_.ok)throw await X6(_);q([cJ.parse(await _.json()).thread])};return{subscribe(X){return J.add(X),()=>J.delete(X)},current:()=>Q,async load(){let X=await fetch(Y,{cache:"no-store"});if(!X.ok)throw await X6(X);q(pJ.parse(await X.json()).threads)},receive(X){let W=B.array(B2).safeParse(X);if(W.success)q(W.data)},reply:(X,W)=>G(`${encodeURIComponent(X)}/comments`,{body:W}),setResolved:(X,W)=>G(`${encodeURIComponent(X)}/resolved`,{resolved:W})}}function dJ(){if(typeof window>"u")return null;let $=window.location.hash.replace(/^#/,"");if(!$)return null;for(let Q of $.split("&")){let[J,Y]=Q.split("=");if(J==="k"&&Y)return decodeURIComponent(Y)}return null}function rJ(){if(typeof window<"u"&&window.__CANVAS_SHARE__?.shareId){let Q=dJ();return{isShared:!0,shareId:window.__CANVAS_SHARE__.shareId,encryptionKey:Q?e5(Q):null}}return{isShared:!1,sessionId:typeof window<"u"?window.location.pathname.replace("/s/",""):""}}var W$=rJ();function iJ(){return W$.isShared&&W$.encryptionKey!==null}function oJ(){return W$.isShared?W$.shareId:W$.sessionId}function aJ(){if(W$.isShared)return`/s/${W$.shareId}/meta`;return`/api/session/${W$.sessionId}/meta`}function nJ($,Q){let J=$.replace(/\.jsx$/,".js");if(W$.isShared)return`/s/${W$.shareId}/canvas/${encodeURIComponent(J)}`;let Y=Q?`?rev=${Q}&t=${Date.now()}`:`?t=${Date.now()}`;return`/api/session/${W$.sessionId}/canvas/${encodeURIComponent(J)}${Y}`}function sJ(){if(W$.isShared)return`/s/${W$.shareId}/upload`;return`/api/session/${W$.sessionId}/upload`}async function tJ($){let Q=await $.json().catch(()=>null);if(typeof Q==="object"&&Q!==null&&"error"in Q&&typeof Q.error==="string")return Error(Q.error);return Error(`Request failed with status ${$.status}`)}var _6="agent-canvas-project-theme",W6=0;async function H6(){if(W$.isShared)return;let $=++W6,Q=await fetch(`/api/session/${encodeURIComponent(W$.sessionId)}/theme.css`,{cache:"no-store"}),J=Q.ok?await Q.text():"";if(!Q.ok)console.warn(`Project theme not applied: ${(await tJ(Q)).message}`);if($!==W6)return;let Y=document.getElementById(_6);if(Y===null)Y=document.createElement("style"),Y.id=_6,document.head.append(Y);Y.textContent=J}async function U6(){let $=await fetch(aJ());if(!$.ok)throw Error(`meta ${$.status}`);let Q=o5.parse(await $.json());if(Q.encryption&&W$.isShared&&W$.encryptionKey){let J=await W$.encryptionKey;if(Q.origin){let Y={...Q.origin};if(Y.sessionId)Y.sessionId=await K2(J,Y.sessionId);if(Y.label)Y.label=await K2(J,Y.label);Q.origin=Y}for(let Y of Q.revisions??[])if(Y.label)try{Y.label=await K2(J,Y.label)}catch{}}return Q}var eJ=async($,Q)=>{let J=nJ($,Q);if(!iJ())return import(J);let Y=await fetch(J);if(!Y.ok)throw Error(`canvas ${Y.status}`);let q=await Y.text(),G=await W$.encryptionKey,X=await K2(G,q),W=new Blob([X],{type:"application/javascript"}),_=URL.createObjectURL(W);try{return await import(_)}finally{setTimeout(()=>URL.revokeObjectURL(_),0)}},K6="canvas-reviewer-identity";function K3(){try{let $=localStorage.getItem(K6);if(!$)return null;return JSON.parse($)}catch{return null}}function B6($){let Q=K3();if(!Q)Q={id:crypto.randomUUID?.()||String(Date.now()),name:$};else Q.name=$;return localStorage.setItem(K6,JSON.stringify(Q)),Q}async function $7($,Q){let J=await Promise.all($.annotations.map(async(Y)=>{let q={id:Y.id,createdAt:Y.createdAt,snippet:await N1(Q,String(Y.snippet??"")),note:await N1(Q,String(Y.note??""))};if(Y.filePath)q.filePath=await N1(Q,String(Y.filePath));if(Y.canvasFile)q.canvasFile=await N1(Q,String(Y.canvasFile));if(Y.context!==void 0&&Y.context!==null)q.context=await N1(Q,JSON.stringify(Y.context));if(Y.attachments)q.attachments=Y.attachments;return q}));return{author:{id:$.author.id,name:await N1(Q,$.author.name)},revision:$.revision,annotations:J,...$.generalNote?{generalNote:await N1(Q,$.generalNote)}:{},...$.responses&&$.responses.length>0?{responses:await N1(Q,JSON.stringify($.responses))}:{},encryption:t5}}async function N6($){if(!W$.isShared)throw Error("submitSharedFeedback called outside shared mode");let Q=$;if(W$.encryptionKey){let Y=await W$.encryptionKey;Q=await $7($,Y)}let J=await fetch(`/s/${W$.shareId}/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!J.ok){let Y=await J.text().catch(()=>"");throw Error(`Feedback submission failed: ${J.status} ${Y}`)}}var O1=!W$.isShared,O6=!W$.isShared,s2=W$.isShared?null:G6(W$.sessionId),z6={get sessionId(){return oJ()},isShared:W$.isShared,fsAvailable:O1,uploadUrl:sJ,loadCanvasModule:eJ,threads:s2};import V6,{useCallback as C6,useContext as M7,useEffect as E1,useMemo as Q4,useRef as z1,useState as Z$}from"react";function f1($,Q){let J=$.length,Y=Q.length;if(J===0||Y===0)return[];let q=Array.from({length:J+1},()=>Array(Y+1).fill(0));for(let _=1;_<=J;_++)for(let H=1;H<=Y;H++)q[_][H]=$[_-1]===Q[H-1]?q[_-1][H-1]+1:Math.max(q[_-1][H],q[_][H-1]);let G=[],X=J,W=Y;while(X>0&&W>0)if($[X-1]===Q[W-1])G.unshift($[X-1]),X--,W--;else if(q[X-1][W]>q[X][W-1])X--;else W--;return G}function M6($){let Q=[],J=[],Y=document.createTreeWalker($,NodeFilter.SHOW_TEXT,{acceptNode(G){let X=G.parentElement;if(!X)return NodeFilter.FILTER_REJECT;if(X.closest("svg, .select-none, [data-no-diff]"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}}),q;while(q=Y.nextNode()){let X=(q.nodeValue||"").match(/\S+|\s+/g);if(!X)continue;let W=0;for(let _ of X)Q.push(_),J.push({text:_,node:q,offset:W}),W+=_.length}return{words:Q,map:J}}function B3($,Q){if($.length>5000||Q.length>5000)return Q7($,Q);return A6($,Q)}function A6($,Q){let J=t2($,Q),Y=[],q=[],G=0,X=0,W=0;while(G<$.length||X<Q.length)if(W<J.length&&G<$.length&&X<Q.length&&$[G]===J[W]&&Q[X]===J[W])Y.push({type:"same",index:G}),q.push({type:"same",index:X}),G++,X++,W++;else if(G<$.length&&(W>=J.length||$[G]!==J[W]))Y.push({type:"removed",index:G}),G++;else if(X<Q.length)q.push({type:"added",index:X}),X++;return{oldOps:Y,newOps:q}}function t2($,Q){let J=$.length,Y=Q.length;if(J===0||Y===0)return[];if(J===1)return Q.includes($[0])?[$[0]]:[];if(Y===1)return $.includes(Q[0])?[Q[0]]:[];if(J*Y<=1e6)return f1($,Q);let q=Math.floor(J/2),G=$.slice(0,q),X=$.slice(q),W=F6(G,Q),_=F6([...X].reverse(),[...Q].reverse()),H=0,U=0;for(let O=0;O<=Y;O++){let M=W[O]+_[Y-O];if(M>H)H=M,U=O}let K=Q.slice(0,U),N=Q.slice(U);return[...t2(G,K),...t2(X,N)]}function F6($,Q){let J=Q.length,Y=Array(J+1).fill(0),q=Array(J+1).fill(0);for(let G=0;G<$.length;G++){for(let X=1;X<=J;X++)q[X]=$[G]===Q[X-1]?Y[X-1]+1:Math.max(Y[X],q[X-1]);[Y,q]=[q,Y],q.fill(0)}return Y}function Q7($,Q){let Y=(M)=>{let L=[];for(let F=0;F<M.length;F+=200){let w=Math.min(F+200,M.length);L.push({start:F,end:w,text:M.slice(F,w).join("")})}return L},q=Y($),G=Y(Q),X=q.map((M)=>M.text),W=G.map((M)=>M.text),_=t2(X,W),H=[],U=[],K=0,N=0,O=0;while(K<q.length||N<G.length)if(O<_.length&&K<q.length&&N<G.length&&X[K]===_[O]&&W[N]===_[O]){for(let M=q[K].start;M<q[K].end;M++)H.push({type:"same",index:M});for(let M=G[N].start;M<G[N].end;M++)U.push({type:"same",index:M});K++,N++,O++}else if(K<q.length&&(O>=_.length||X[K]!==_[O]))if(N<G.length&&(O>=_.length||W[N]!==_[O])){let M=A6($.slice(q[K].start,q[K].end),Q.slice(G[N].start,G[N].end));for(let L of M.oldOps)H.push({type:L.type,index:L.index+q[K].start});for(let L of M.newOps)U.push({type:L.type,index:L.index+G[N].start});K++,N++}else{for(let M=q[K].start;M<q[K].end;M++)H.push({type:"removed",index:M});K++}else if(N<G.length){for(let M=G[N].start;M<G[N].end;M++)U.push({type:"added",index:M});N++}return{oldOps:H,newOps:U}}function L6($,Q,J){let Y=new Map;for(let q of $){if(q.type==="same")continue;let G=Q[q.index];if(!G||!G.node.parentNode)continue;let X=Y.get(G.node);if(!X)X=[],Y.set(G.node,X);X.push({offset:G.offset,length:G.text.length})}for(let[q,G]of Y){if(!q.parentNode)continue;let X=q.nodeValue||"";G.sort((K,N)=>K.offset-N.offset);let W=[];for(let K of G){let N=W[W.length-1];if(N&&K.offset<=N.offset+N.length)N.length=Math.max(N.length,K.offset+K.length-N.offset);else W.push({...K})}let _=q.parentNode,H=document.createDocumentFragment(),U=0;for(let K of W){if(K.offset>U)H.appendChild(document.createTextNode(X.slice(U,K.offset)));let N=document.createElement("span");N.className=J,N.textContent=X.slice(K.offset,K.offset+K.length),H.appendChild(N),U=K.offset+K.length}if(U<X.length)H.appendChild(document.createTextNode(X.slice(U)));_.replaceChild(H,q)}}function e2($,Q){let J=J7($,Q),Y=M6($),q=M6(Q),{oldOps:G,newOps:X}=B3(Y.words,q.words),W=G.some((_)=>_.type==="removed")||X.some((_)=>_.type==="added");return L6(G,Y.map,"diff-removed"),L6(X,q.map,"diff-added"),W||J}function J7($,Q){let J=Array.from($.querySelectorAll('[data-md="mermaid"]')),Y=Array.from(Q.querySelectorAll('[data-md="mermaid"]')),q=!1,G=Math.max(J.length,Y.length);for(let X=0;X<G;X++){let W=J[X],_=Y[X];if(!W&&_){_.classList.add("diff-block-added"),_.style.position="relative",q=!0;continue}if(W&&!_){W.classList.add("diff-block-removed"),W.style.position="relative",q=!0;continue}if(!W||!_)continue;let H=(W.getAttribute("data-md-source")||"").trim(),U=(_.getAttribute("data-md-source")||"").trim();if(H===U)continue;q=!0,W.style.borderLeft="3px solid var(--color-accent-red)",W.style.paddingLeft="8px",_.style.borderLeft="3px solid var(--color-accent-green)",_.style.paddingLeft="8px";let K=H.split(`
71
- `),N=U.split(`
72
- `),O=f1(K,N),M=(L,F,w)=>{let z=document.createElement("div");z.className="mt-2 bg-bg-code rounded-md overflow-hidden text-tiny font-mono",z.setAttribute("data-no-diff","true");let A=0,T=0;while(T<L.length){let S=document.createElement("div");if(S.className="px-3 py-0.5 whitespace-pre-wrap",A<F.length&&L[T]===F[A])S.textContent=" "+L[T],T++,A++;else S.classList.add(w==="old"?"diff-removed":"diff-added"),S.textContent=(w==="old"?"- ":"+ ")+L[T],T++;z.appendChild(S)}return z};W.appendChild(M(K,O,"old")),_.appendChild(M(N,O,"new"))}return q}import{useContext as q7,useEffect as Y7,useRef as X7,useState as G7}from"react";import{jsxDEV as y$,Fragment as P6}from"react/jsx-dev-runtime";function _7($){return $.label||`Round ${$.revision}`}function W7($){let Q=Date.now()-new Date($).getTime(),J=Math.floor(Q/1000);if(J<60)return"just now";let Y=Math.floor(J/60);if(Y<60)return`${Y}m ago`;let q=Math.floor(Y/60);if(q<24)return`${q}h ago`;return`${Math.floor(q/24)}d ago`}function N2({value:$,onChange:Q,accent:J="default",className:Y}){let{currentRevision:q,revisions:G}=q7(h$),[X,W]=G7(!1),_=X7(null);Y7(()=>{if(!X)return;let K=(N)=>{if(_.current&&!_.current.contains(N.target))W(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[X]);let H=G.find((K)=>K.revision===$);return y$("div",{className:"relative",ref:_,children:[y$("button",{onClick:()=>W(!X),className:`flex items-center gap-1.5 text-[12px] font-body font-medium px-2 py-1 rounded-md transition-colors hover:bg-bg-elevated ${{default:"text-text-secondary hover:text-text-primary",red:"text-accent-red",green:"text-accent-green",amber:"text-accent-amber bg-highlight-selected"}[J]} ${Y||""}`,children:[H?_7(H):`Round ${$}`,y$("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`text-text-tertiary transition-transform duration-200 ${X?"rotate-180":""}`,children:y$("path",{d:"M2.5 4l2.5 2.5L7.5 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&y$("div",{className:"absolute top-full left-0 mt-1 w-64 bg-bg-elevated border border-border-hover rounded-lg shadow-lg z-50 py-1 max-h-80 overflow-y-auto",children:[...G].reverse().map((K)=>y$("button",{onClick:()=>{Q(K.revision),W(!1)},className:`w-full flex items-center gap-2 px-3 py-2 text-[12px] font-body transition-colors ${K.revision===$?"bg-bg-surface text-text-primary":"text-text-secondary hover:bg-bg-surface hover:text-text-primary"}`,children:[y$("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${K.revision===q?"bg-accent-green":K.hasFeedback?"bg-accent-amber":"bg-border-hover"}`},void 0,!1,void 0,this),y$("span",{className:"flex-1 text-left truncate",children:K.label?y$(P6,{children:[K.label," ",y$("span",{className:"text-text-tertiary",children:["#",K.revision]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):y$(P6,{children:["Round ",K.revision]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y$("span",{className:"text-[10px] text-text-tertiary flex-shrink-0 flex items-center gap-1.5",children:[(()=>{let N=K.canvasFiles?.reduce((O,M)=>{if(M.diffStats)O.added+=M.diffStats.added,O.removed+=M.diffStats.removed;return O},{added:0,removed:0});if(N&&(N.added>0||N.removed>0))return y$("span",{className:"font-mono",children:[y$("span",{className:"text-accent-green",children:["+",N.added]},void 0,!0,void 0,this)," ",y$("span",{className:"text-accent-red",children:["-",N.removed]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return null})(),K.revision===q?"current":K.hasFeedback?"sent":W7(K.createdAt)]},void 0,!0,void 0,this)]},K.revision,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function D0($){let Q=[],J=$.querySelectorAll(":scope > [data-md]");for(let Y of J)Q.push(O2(Y));if(Q.length===0){let Y=$.querySelectorAll("[data-md]"),q=new Set;for(let G of Y){let X=G.parentElement?.closest("[data-md]");if(X&&$.contains(X))continue;if(q.has(G))continue;q.add(G),Q.push(O2(G))}}return Q}function O2($){let Q=$.getAttribute("data-md")||"unknown",J=H7($,Q),Y=[];if(Q==="section"){let q=$.querySelector(":scope > div.mt-6, :scope > div:last-child");if(q)for(let G of q.querySelectorAll(":scope > [data-md]"))Y.push(O2(G))}else if(Q==="table")for(let q of $.querySelectorAll(":scope table > tbody > tr"))Y.push({key:"tr:"+(q.textContent||"").slice(0,80),type:"tr",element:q,children:[]});else if(Q==="checklist")for(let q of $.querySelectorAll(":scope > [data-md='checklist-item']"))Y.push(O2(q));else for(let q of $.querySelectorAll("[data-md]"))if(q.parentElement?.closest("[data-md]")===$)Y.push(O2(q));return{key:J,type:Q,element:$,children:Y}}function H7($,Q){switch(Q){case"section":return"section:"+($.getAttribute("data-md-title")||"");case"item":return"item:"+($.getAttribute("data-task-id")||$.getAttribute("data-md-label")||"");case"codeblock":case"diff":return Q+":"+($.textContent||"").slice(0,80);case"checklist-item":return"checklist-item:"+($.getAttribute("data-md-label")||$.textContent?.slice(0,60)||"");case"checklist":return"checklist:"+$.querySelectorAll("[data-md='checklist-item']").length;case"markdown":return"markdown:"+($.getAttribute("data-md-file")||"inline");case"mermaid":return"mermaid:"+($.getAttribute("data-md-source")||"").slice(0,80);case"callout":return"callout:"+($.getAttribute("data-md-type")||"")+":"+($.textContent||"").slice(0,60);default:return Q+":"+($.getAttribute("data-md-label")||$.textContent?.slice(0,60)||"")}}function z2($,Q){let J=$.map((H)=>H.key),Y=Q.map((H)=>H.key),q=f1(J,Y),G=[],X=0,W=0,_=0;while(X<$.length||W<Q.length)if(_<q.length&&X<$.length&&W<Q.length&&J[X]===q[_]&&Y[W]===q[_]){let H=$[X],U=Q[W],K=H.children.length>0||U.children.length>0?z2(H.children,U.children):void 0;G.push({kind:"matched",oldBlock:H,newBlock:U,childMatches:K}),X++,W++,_++}else if(X<$.length&&(_>=q.length||J[X]!==q[_]))G.push({kind:"removed",oldBlock:$[X]}),X++;else if(W<Q.length)G.push({kind:"added",newBlock:Q[W]}),W++;return G}function $4($){let Q=document.createDocumentFragment(),J=!1;for(let Y of $)if(Y.kind==="removed")J=!0,Q.appendChild(w6(Y.oldBlock.element));else if(Y.kind==="added")J=!0,Q.appendChild(U7(Y.newBlock.element));else{let q=Y.newBlock.element.cloneNode(!0),G=Y.newBlock.type;if(G==="mermaid"){if(Z6(Y.oldBlock.element,q))J=!0}else if(Y.childMatches&&Y.childMatches.length>0&&(G==="table"||G==="checklist")){if(j6(q,Y.childMatches,G))J=!0}else if(Y.childMatches&&Y.childMatches.length>0){if(T6(Y.oldBlock,q,Y.childMatches,G))J=!0}else if(G==="markdown"){if(b6(Y.oldBlock.element,q))J=!0}else if(Q0(Y.oldBlock.element,q,!1))J=!0;Q.appendChild(q)}return{fragment:Q,hasChanges:J}}function w6($){let Q=$.cloneNode(!0);return Q.classList.add("diff-block-removed"),Q.style.position="relative",N3(Q,"Removed","var(--color-accent-red)"),Q}function U7($){let Q=$.cloneNode(!0);return Q.classList.add("diff-block-added"),Q.style.position="relative",N3(Q,"Added","var(--color-accent-green)"),Q}function T6($,Q,J,Y){let q=!1,G=K7($,Q),X,W;if(Y==="section"){let _=$.element.querySelector(":scope > div:first-child"),H=Q.querySelector(":scope > div:first-child");if(_&&H){if(Q0(_,H,!1))q=!0}X=$.element.querySelector(":scope > div.mt-6, :scope > div:last-child"),W=Q.querySelector(":scope > div.mt-6, :scope > div:last-child")}else X=$.element,W=Q;if(!X||!W)return q;for(let _ of J)if(_.kind==="matched"){let H=G.newMap.get(_.newBlock.element);if(H){if(_.newBlock.type==="mermaid"){if(Z6(_.oldBlock.element,H))q=!0}else if(_.childMatches&&_.childMatches.length>0&&(_.newBlock.type==="table"||_.newBlock.type==="checklist")){if(j6(H,_.childMatches,_.newBlock.type))q=!0}else if(_.childMatches&&_.childMatches.length>0){if(T6(_.oldBlock,H,_.childMatches,_.newBlock.type))q=!0}else if(_.newBlock.type==="markdown"){if(b6(_.oldBlock.element,H))q=!0}else if(Q0(_.oldBlock.element,H,!1))q=!0}}else if(_.kind==="removed"){q=!0;let H=w6(_.oldBlock.element),U=N7(J,_,G.newMap),K=U?O7(W,U):null;W.insertBefore(H,K)}else if(_.kind==="added"){q=!0;let H=G.newMap.get(_.newBlock.element);if(H)H.classList.add("diff-block-added"),H.style.position="relative",N3(H,"Added","var(--color-accent-green)")}if(Q0(X,W,!0))q=!0;return q}function j6($,Q,J){let Y=J==="table"?$.querySelector(":scope table > tbody"):$;if(!Y)return!1;let q=!1;Y.innerHTML="";for(let G of Q)if(G.kind==="removed"){q=!0;let X=G.oldBlock.element.cloneNode(!0);X.classList.add(J==="table"?"diff-row-removed":"diff-item-removed"),Y.appendChild(X)}else if(G.kind==="added"){q=!0;let X=G.newBlock.element.cloneNode(!0);X.classList.add(J==="table"?"diff-row-added":"diff-item-added"),Y.appendChild(X)}else{let X=G.newBlock.element.cloneNode(!0);if(Q0(G.oldBlock.element,X,!1))q=!0;Y.appendChild(X)}return q}function K7($,Q){return{newMap:{get(J){return B7(Q,J)}}}}function B7($,Q){let J=Q.getAttribute("data-md");if(!J)return null;let Y=Q.getAttribute("data-md-label"),q=Q.getAttribute("data-md-title"),G=`[data-md="${J}"]`;if(q)G+=`[data-md-title="${CSS.escape(q)}"]`;else if(Y)G+=`[data-md-label="${CSS.escape(Y)}"]`;let X=$.querySelectorAll(G);if(X.length===1)return X[0];let W=(Q.textContent||"").slice(0,100),_=null,H=-1;for(let U of X){let K=(U.textContent||"").slice(0,100),N=0;for(let O=0;O<Math.min(W.length,K.length);O++)if(W[O]===K[O])N++;if(N>H)H=N,_=U}return _}function N7($,Q,J){let Y=$.indexOf(Q);for(let q=Y+1;q<$.length;q++){let G=$[q];if((G.kind==="matched"||G.kind==="added")&&G.newBlock)return J.get(G.newBlock.element)||null}return null}function O7($,Q){let J=Q;while(J&&J.parentElement!==$)J=J.parentElement;return J}function b6($,Q){let J=Array.from($.children),Y=Array.from(Q.children);if(J.length===0&&Y.length===0)return Q0($,Q,!1);let q=J.map((N)=>N.tagName.toLowerCase()),G=Y.map((N)=>N.tagName.toLowerCase()),X=f1(q,G),W=[],_=0,H=0,U=0;while(_<J.length||H<Y.length)if(U<X.length&&_<J.length&&H<Y.length&&q[_]===X[U]&&G[H]===X[U])W.push({kind:"matched",oldChild:J[_],newChild:Y[H]}),_++,H++,U++;else if(_<J.length&&(U>=X.length||q[_]!==X[U]))W.push({kind:"removed",oldChild:J[_]}),_++;else if(H<Y.length)W.push({kind:"added",newChild:Y[H]}),H++;let K=!1;while(Q.firstChild)Q.removeChild(Q.firstChild);for(let N of W)if(N.kind==="matched"){let O=(N.oldChild.textContent||"").match(/\S+/g)||[],M=(N.newChild.textContent||"").match(/\S+/g)||[],L=f1(O,M),F=Math.max(O.length,M.length);if((F>0?1-L.length/F:0)>0.5){K=!0;let z=N.oldChild.cloneNode(!0);z.classList.add("diff-block-removed"),Q.appendChild(z),N.newChild.classList.add("diff-block-added"),Q.appendChild(N.newChild)}else{if(Q0(N.oldChild,N.newChild,!1))K=!0;Q.appendChild(N.newChild)}}else if(N.kind==="removed"){K=!0;let O=N.oldChild.cloneNode(!0);O.classList.add("diff-block-removed"),Q.appendChild(O)}else K=!0,N.newChild.classList.add("diff-block-added"),Q.appendChild(N.newChild);return K}function S6($,Q){let J=Q?new Set(Array.from($.querySelectorAll("[data-md]"))):new Set,Y=[],q=[],G=document.createTreeWalker($,NodeFilter.SHOW_TEXT,{acceptNode(W){let _=W.parentElement;if(!_)return NodeFilter.FILTER_REJECT;if(_.closest("svg, .select-none, [data-no-diff]"))return NodeFilter.FILTER_REJECT;if(Q){for(let H of J)if(H.contains(W))return NodeFilter.FILTER_REJECT}return NodeFilter.FILTER_ACCEPT}}),X;while(X=G.nextNode()){let _=(X.nodeValue||"").match(/\S+|\s+/g);if(!_)continue;let H=0;for(let U of _)Y.push(U),q.push({text:U,node:X,offset:H}),H+=U.length}return{words:Y,map:q}}function Q0($,Q,J){let Y=S6($,J),q=S6(Q,J);if(Y.words.length===0&&q.words.length===0)return!1;let{oldOps:G,newOps:X}=B3(Y.words,q.words),W=G.some((F)=>F.type==="removed"),_=X.some((F)=>F.type==="added");if(!W&&!_)return!1;let H=[],U=[];for(let F of G)if(F.type==="same")H.push(F.index);for(let F of X)if(F.type==="same")U.push(F.index);let K=new Map;for(let F=0;F<H.length&&F<U.length;F++)K.set(H[F],U[F]);let N=[];{let F=[],w=-1;for(let z of G)if(z.type==="same"){if(F.length>0)N.push({text:F.join(""),anchorNewIdx:w>=0?K.get(w)??null:null}),F=[];w=z.index}else if(z.type==="removed")F.push(Y.words[z.index]);if(F.length>0)N.push({text:F.join(""),anchorNewIdx:w>=0?K.get(w)??null:null})}let O=new Map,M=new Map;for(let F of X){if(F.type!=="added")continue;let w=q.map[F.index];if(!w?.node.parentNode)continue;let z=O.get(w.node);if(!z)z=[],O.set(w.node,z);z.push({start:w.offset,end:w.offset+w.text.length})}for(let F of N)if(F.anchorNewIdx===null){if(q.map.length>0){let w=q.map[0].node,z=M.get(w);if(!z)z=[],M.set(w,z);z.push({offset:0,text:F.text})}}else{let w=q.map[F.anchorNewIdx];if(!w)continue;let z=M.get(w.node);if(!z)z=[],M.set(w.node,z);z.push({offset:w.offset+w.text.length,text:F.text})}let L=new Set([...O.keys(),...M.keys()]);for(let F of L)z7(F,O.get(F)||[],M.get(F)||[]);return!0}function z7($,Q,J){if(!$.parentNode)return;let Y=$.nodeValue||"";Q.sort((U,K)=>U.start-K.start);let q=[];for(let U of Q){let K=q[q.length-1];if(K&&U.start<=K.end)K.end=Math.max(K.end,U.end);else q.push({...U})}J.sort((U,K)=>U.offset-K.offset);let G=$.parentNode,X=document.createDocumentFragment(),W=0,_=0,H=0;while(W<=Y.length){let U=_<q.length?q[_].start:1/0,K=H<J.length?J[H].offset:1/0,N=Math.min(U,K);if(N===1/0){if(W<Y.length)X.appendChild(document.createTextNode(Y.slice(W)));break}let O=Math.max(N,W);if(O>W)X.appendChild(document.createTextNode(Y.slice(W,O))),W=O;while(H<J.length&&J[H].offset<=W){let M=document.createElement("span");M.className="diff-removed",M.textContent=J[H].text,X.appendChild(M),H++}if(_<q.length&&q[_].start<=W){let M=q[_],L=document.createElement("span");L.className="diff-added",L.textContent=Y.slice(W,M.end),X.appendChild(L),W=M.end,_++;while(H<J.length&&J[H].offset<=W){let F=document.createElement("span");F.className="diff-removed",F.textContent=J[H].text,X.appendChild(F),H++}}}while(H<J.length){let U=document.createElement("span");U.className="diff-removed",U.textContent=J[H].text,X.appendChild(U),H++}G.replaceChild(X,$)}function Z6($,Q){let J=($.getAttribute("data-md-source")||"").trim(),Y=(Q.getAttribute("data-md-source")||"").trim();if(J===Y)return!1;let q=J.split(`
73
- `),G=Y.split(`
74
- `),X=f1(q,G),W=[],_=0,H=0,U=0;while(_<q.length||H<G.length)if(U<X.length&&_<q.length&&H<G.length&&q[_]===X[U]&&G[H]===X[U])W.push({type:"same",line:q[_]}),_++,H++,U++;else if(_<q.length&&(U>=X.length||q[_]!==X[U]))W.push({type:"removed",line:q[_]}),_++;else if(H<G.length)W.push({type:"added",line:G[H]}),H++;let K=document.createElement("div");K.className="mt-2 bg-bg-code rounded-md overflow-hidden text-tiny font-mono",K.setAttribute("data-no-diff","true");for(let N of W){let O=document.createElement("div");if(O.className="px-3 py-0.5 whitespace-pre-wrap",N.type==="removed")O.classList.add("diff-removed"),O.textContent="- "+N.line;else if(N.type==="added")O.classList.add("diff-added"),O.textContent="+ "+N.line;else O.textContent=" "+N.line;K.appendChild(O)}return Q.appendChild(K),!0}function N3($,Q,J){let Y=document.createElement("span");Y.className="diff-block-label",Y.textContent=Q,Y.style.color=J,Y.style.backgroundColor=`color-mix(in srgb, ${J} 12%, transparent)`,$.appendChild(Y)}import{jsxDEV as u}from"react/jsx-dev-runtime";function F7($,Q,J){let Y=$.find((X)=>X.revision===Q),q=$.find((X)=>X.revision===J),G=new Set;for(let X of Y?.canvasFiles||[])G.add(X.filename);for(let X of q?.canvasFiles||[])G.add(X.filename);return[...G].sort()}function R6({initialLeft:$,initialRight:Q,sessionId:J,onExit:Y}){let[q,G]=Z$($),[X,W]=Z$(Q),[_,H]=Z$("unified"),[U,K]=Z$(!0),[N,O]=Z$(!1),{revisions:M}=M7(h$),L=Q4(()=>F7(M,q,X),[M,q,X]),[F,w]=Z$(()=>L[0]||"plan.jsx");E1(()=>{if(!L.includes(F))w(L[0]||"plan.jsx")},[L,F]);let z=Q4(()=>{return M.find((S)=>S.revision===q)?.canvasFiles.some((S)=>S.filename===F)??!1},[M,q,F]),A=Q4(()=>{return M.find((S)=>S.revision===X)?.canvasFiles.some((S)=>S.filename===F)??!1},[M,X,F]);return u("div",{className:"flex flex-col h-screen",children:[u("div",{className:"flex items-center justify-between px-6 py-3 border-b border-border-subtle bg-bg-surface flex-shrink-0",children:[u("div",{className:"flex items-center gap-3",children:[u("span",{className:"text-[13px] font-body font-medium text-text-primary",children:"Compare"},void 0,!1,void 0,this),u(N2,{value:q,onChange:G,accent:"red"},void 0,!1,void 0,this),u("span",{className:"text-text-tertiary text-[13px]",children:"→"},void 0,!1,void 0,this),u(N2,{value:X,onChange:W,accent:"green"},void 0,!1,void 0,this),N&&!U&&u("span",{className:"text-[11px] font-body text-text-tertiary bg-bg-elevated px-2 py-0.5 rounded",children:"No changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u("div",{className:"flex items-center gap-4",children:[u("div",{className:"flex items-center bg-bg-elevated rounded-md p-0.5",children:[u("button",{onClick:()=>H("unified"),className:`text-[11px] font-body px-2.5 py-1 rounded transition-colors ${_==="unified"?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Unified"},void 0,!1,void 0,this),u("button",{onClick:()=>H("side-by-side"),className:`text-[11px] font-body px-2.5 py-1 rounded transition-colors ${_==="side-by-side"?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Side-by-side"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_==="side-by-side"&&u(L7,{},void 0,!1,void 0,this),u("button",{onClick:Y,className:"text-[12px] font-body font-medium text-text-secondary hover:text-text-primary px-3 py-1.5 rounded-md hover:bg-bg-elevated transition-colors",children:"Exit Compare"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),L.length>1&&u("div",{className:"flex items-center gap-1 px-6 py-2 border-b border-border-subtle bg-bg-surface flex-shrink-0 overflow-x-auto",children:L.map((T)=>{let S=T.replace(/\.jsx$/,""),j=T===F,Z=M.find((C)=>C.revision===q)?.canvasFiles.some((C)=>C.filename===T),y=M.find((C)=>C.revision===X)?.canvasFiles.some((C)=>C.filename===T),V=!Z?" (added)":!y?" (removed)":"";return u("button",{onClick:()=>w(T),className:`text-[12px] font-body px-3 py-1 rounded-md transition-colors whitespace-nowrap ${j?"bg-bg-elevated text-text-primary font-medium":"text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated"}`,children:[S,V&&u("span",{className:`ml-1 text-[10px] ${!Z?"text-accent-green":"text-accent-red"}`,children:V},void 0,!1,void 0,this)]},T,!0,void 0,this)})},void 0,!1,void 0,this),!z||!A?u("div",{className:"flex-1 flex items-center justify-center",children:u("div",{className:"text-center text-text-tertiary font-body",children:[u("div",{className:"text-lg mb-2",children:!z?"New file":"Removed file"},void 0,!1,void 0,this),u("div",{className:"text-[13px]",children:[F.replace(/\.jsx$/,"")," ",!z?"was added":"was removed"," in this revision"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this):_==="unified"?u(A7,{sessionId:J,leftRev:q,rightRev:X,filename:F,onDiffResult:(T,S)=>{O(T),K(S)}},`unified-${q}-${X}-${F}`,!1,void 0,this):u(P7,{sessionId:J,leftRev:q,rightRev:X,filename:F,onDiffResult:(T,S)=>{O(T),K(S)}},`sbs-${q}-${X}-${F}`,!1,void 0,this)]},void 0,!0,void 0,this)}function L7(){let[$,Q]=Z$(!0);return E1(()=>{return document.documentElement.dataset.syncScroll=$?"1":"0",()=>{delete document.documentElement.dataset.syncScroll}},[$]),u("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[u("input",{type:"checkbox",checked:$,onChange:(J)=>Q(J.target.checked),className:"accent-accent-amber w-3.5 h-3.5"},void 0,!1,void 0,this),u("span",{className:"text-[11px] font-body text-text-secondary",children:"Sync scroll"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function A7({sessionId:$,leftRev:Q,rightRev:J,filename:Y,onDiffResult:q}){let G=z1(null),X=z1(null),W=z1(null),[_,H]=Z$(!1),[U,K]=Z$(!1),[N,O]=Z$(!1),[M,L]=Z$(null),[F,w]=Z$(!1),{annotations:z}=G1(),A=z.filter((S)=>!S.filePath&&(!S.canvasFile||S.canvasFile===Y)),{popovers:T}=R1({containerRef:W,restoreKey:N,restoreAnnotations:A,extractContext:(S)=>P1(S,W.current)});return E1(()=>{if(N||M)return;let S=setTimeout(()=>{console.warn("[unified-diff] still loading after 10s",{leftReady:_,rightReady:U,oldRef:!!G.current,newRef:!!X.current}),w(!0)},1e4);return()=>clearTimeout(S)},[N,M,_,U]),E1(()=>{if(!_||!U||N)return;if(!G.current||!X.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!G.current||!X.current||!W.current){console.warn("[unified-diff] refs lost between rAF frames",{old:!!G.current,new:!!X.current,unified:!!W.current});return}try{let S=D0(G.current),j=D0(X.current),Z=z2(S,j),{fragment:y,hasChanges:V}=$4(Z);W.current.innerHTML="",W.current.appendChild(y),O(!0),q(!0,V)}catch(S){console.error("[unified-diff] diff computation failed",S),L(S instanceof Error?S.message:String(S))}})})},[_,U,N]),u("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[!N&&!M&&u("div",{style:{position:"absolute",left:-9999,visibility:"hidden",pointerEvents:"none",width:720},children:[u(M1,{ref:G,sessionId:$,revision:Q,filename:Y,onReady:()=>H(!0),onError:(S)=>L(`Rev ${Q}: ${S}`)},void 0,!1,void 0,this),u(M1,{ref:X,sessionId:$,revision:J,filename:Y,onReady:()=>K(!0),onError:(S)=>L(`Rev ${J}: ${S}`)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:[!N&&!M&&u("div",{className:"flex flex-col items-center justify-center h-64 text-text-tertiary font-body text-body gap-2",children:[u("span",{children:"Loading..."},void 0,!1,void 0,this),F&&u("span",{className:"text-[11px]",children:"Taking longer than expected — check Network tab for pending requests"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M&&u("div",{className:"bg-accent-red-muted rounded-lg p-5 mt-8",children:[u("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Failed to load revision"},void 0,!1,void 0,this),u("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:M},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u("div",{ref:W},void 0,!1,void 0,this)]},void 0,!0,void 0,this),T]},void 0,!0,void 0,this)}function P7({sessionId:$,leftRev:Q,rightRev:J,filename:Y,onDiffResult:q}){let G=z1(null),X=z1(null),[W,_]=Z$(!1),[H,U]=Z$(!1),[K,N]=Z$(!1),O=z1(null),M=z1(null),L=z1(null),F=z1(!1),w=C6(()=>_(!0),[]),z=C6(()=>U(!0),[]),{annotations:A}=G1(),T=A.filter((j)=>!j.filePath&&(!j.canvasFile||j.canvasFile===Y)),{popovers:S}=R1({containerRef:O,restoreKey:K,restoreAnnotations:T,extractContext:(j)=>P1(j,O.current)});return E1(()=>{if(!W||!H||K)return;if(!G.current||!X.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!G.current||!X.current)return;let j=e2(G.current,X.current);N(!0),q(!0,j)})})},[W,H,K]),E1(()=>{let j=M.current,Z=L.current;if(!j||!Z)return;let y=(v,h)=>{if(document.documentElement.dataset.syncScroll==="0")return;if(F.current)return;F.current=!0;let o=v.scrollHeight-v.clientHeight,B$=h.scrollHeight-h.clientHeight;if(o>0&&B$>0)h.scrollTop=v.scrollTop/o*B$;requestAnimationFrame(()=>{F.current=!1})},V=()=>y(j,Z),C=()=>y(Z,j);return j.addEventListener("scroll",V),Z.addEventListener("scroll",C),()=>{j.removeEventListener("scroll",V),Z.removeEventListener("scroll",C)}},[]),u("div",{ref:O,className:"flex flex-1 min-h-0",children:[u("div",{ref:M,className:"w-1/2 overflow-y-auto border-r border-border-subtle",children:u("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:u(M1,{ref:G,sessionId:$,revision:Q,filename:Y,onReady:w},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),u("div",{ref:L,className:"w-1/2 overflow-y-auto",children:u("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:u(M1,{ref:X,sessionId:$,revision:J,filename:Y,onReady:z},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),S]},void 0,!0,void 0,this)}var M1=V6.memo(V6.forwardRef(({sessionId:$,revision:Q,filename:J,onReady:Y,onError:q},G)=>{let[X,W]=Z$(null),[_,H]=Z$(null),[U,K]=Z$(!0);E1(()=>{K(!0),H(null);let O=J.replace(/\.jsx$/,".js");import(`/api/session/${$}/canvas/${encodeURIComponent(O)}?rev=${Q}&t=${Date.now()}`).then((M)=>{if(!M.default){H("Module has no default export"),K(!1),q?.("Module has no default export");return}W(()=>M.default),K(!1)}).catch((M)=>{H(M.message),K(!1),q?.(M.message)})},[$,Q,J]),E1(()=>{if(!X)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{Y()})})},[X]);let N=Q4(()=>X?u(X,{},void 0,!1,void 0,this):null,[X]);if(U)return u("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-body",children:"Loading..."},void 0,!1,void 0,this);if(_)return u("div",{className:"bg-accent-red-muted rounded-lg p-5",children:[u("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Error"},void 0,!1,void 0,this),u("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!X)return u("div",{className:"text-text-tertiary text-center py-8 font-body text-body",children:"No canvas loaded"},void 0,!1,void 0,this);return u("div",{ref:G,children:N},void 0,!1,void 0,this)}));function I0($){return $ instanceof Error&&$.message?$.message:String($)}var J4={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rs:"rust",go:"go",rb:"ruby",java:"java",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",css:"css",html:"html",sh:"bash",bash:"bash",toml:"toml",sql:"sql",xml:"xml",c:"c",cpp:"cpp",h:"c"};function D6($){let Q=[];return q4($,Q,0),Q.join(`
64
+ `+t+`</thead>
65
+ `+o+`</table>
66
+ `}tablerow({text:e}){return`<tr>
67
+ ${e}</tr>
68
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
69
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${st(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let o=this.parser.parseInline(n),r=Ta(e);if(r===null)return o;e=r;let a='<a href="'+e+'"';return t&&(a+=' title="'+st(t)+'"'),a+=">"+o+"</a>",a}image({href:e,title:t,text:n,tokens:o}){o&&(n=this.parser.parseInline(o,this.parser.textRenderer));let r=Ta(e);if(r===null)return st(n);e=r;let a=`<img src="${e}" alt="${st(n)}"`;return t&&(a+=` title="${st(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):("escaped"in e)&&e.escaped?e.text:st(e.text)}},cs=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ke=class e{options;renderer;textRenderer;constructor(t){this.options=t||Zt,this.options.renderer=this.options.renderer||new Xr,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cs}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let s=r,l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=l||"";continue}}let a=r;switch(a.type){case"space":{n+=this.renderer.space(a);break}case"hr":{n+=this.renderer.hr(a);break}case"heading":{n+=this.renderer.heading(a);break}case"code":{n+=this.renderer.code(a);break}case"table":{n+=this.renderer.table(a);break}case"blockquote":{n+=this.renderer.blockquote(a);break}case"list":{n+=this.renderer.list(a);break}case"checkbox":{n+=this.renderer.checkbox(a);break}case"html":{n+=this.renderer.html(a);break}case"def":{n+=this.renderer.def(a);break}case"paragraph":{n+=this.renderer.paragraph(a);break}case"text":{n+=this.renderer.text(a);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw Error(s)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let o="";for(let r=0;r<t.length;r++){let a=t[r];if(this.options.extensions?.renderers?.[a.type]){let l=this.options.extensions.renderers[a.type].call({parser:this},a);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){o+=l||"";continue}}let s=a;switch(s.type){case"escape":{o+=n.text(s);break}case"html":{o+=n.html(s);break}case"link":{o+=n.link(s);break}case"image":{o+=n.image(s);break}case"checkbox":{o+=n.checkbox(s);break}case"strong":{o+=n.strong(s);break}case"em":{o+=n.em(s);break}case"codespan":{o+=n.codespan(s);break}case"br":{o+=n.br(s);break}case"del":{o+=n.del(s);break}case"text":{o+=n.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw Error(l)}}}return o}},ar=class{options;block;constructor(e){this.options=e||Zt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Ge.lex:Ge.lexInline}provideParser(e=this.block){return e?Ke.parse:Ke.parseInline}},ds=class{defaults=ts();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ke;Renderer=Xr;TextRenderer=cs;Lexer=Ge;Tokenizer=Yr;Hooks=ar;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let r=o;for(let a of r.header)n=n.concat(this.walkTokens(a.tokens,t));for(let a of r.rows)for(let s of a)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let r=o;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=o;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach((a)=>{let s=r[a].flat(1/0);n=n.concat(this.walkTokens(s,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((n)=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach((r)=>{if(!r.name)throw Error("extension name required");if("renderer"in r){let a=t.renderers[r.name];a?t.renderers[r.name]=function(...s){let l=r.renderer.apply(this,s);return l===!1&&(l=a.apply(this,s)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let a=t[r.level];a?a.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),o.extensions=t),n.renderer){let r=this.defaults.renderer||new Xr(this.defaults);for(let a in n.renderer){if(!(a in r))throw Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let s=a,l=n.renderer[s],i=r[s];r[s]=(...c)=>{let d=l.apply(r,c);return d===!1&&(d=i.apply(r,c)),d||""}}o.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new Yr(this.defaults);for(let a in n.tokenizer){if(!(a in r))throw Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let s=a,l=n.tokenizer[s],i=r[s];r[s]=(...c)=>{let d=l.apply(r,c);return d===!1&&(d=i.apply(r,c)),d}}o.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new ar;for(let a in n.hooks){if(!(a in r))throw Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let s=a,l=n.hooks[s],i=r[s];ar.passThroughHooks.has(a)?r[s]=(c)=>{if(this.defaults.async&&ar.passThroughHooksRespectAsync.has(a))return(async()=>{let u=await l.call(r,c);return i.call(r,u)})();let d=l.call(r,c);return i.call(r,d)}:r[s]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await l.apply(r,c);return u===!1&&(u=await i.apply(r,c)),u})();let d=l.apply(r,c);return d===!1&&(d=i.apply(r,c)),d}}o.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,a=n.walkTokens;o.walkTokens=function(s){let l=[];return l.push(a.call(this,s)),r&&(l=l.concat(r.call(this,s))),l}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ge.lex(e,t??this.defaults)}parser(e,t){return Ke.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let o={...n},r={...this.defaults,...o},a=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&o.async===!1)return a(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let s=r.hooks?await r.hooks.preprocess(t):t,l=await(r.hooks?await r.hooks.provideLexer(e):e?Ge.lex:Ge.lexInline)(s,r),i=r.hooks?await r.hooks.processAllTokens(l):l;r.walkTokens&&await Promise.all(this.walkTokens(i,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(i,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(a);try{r.hooks&&(t=r.hooks.preprocess(t));let s=(r.hooks?r.hooks.provideLexer(e):e?Ge.lex:Ge.lexInline)(t,r);r.hooks&&(s=r.hooks.processAllTokens(s)),r.walkTokens&&this.walkTokens(s,r.walkTokens);let l=(r.hooks?r.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(s,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(s){return a(s)}}}onError(e,t){return(n)=>{if(n.message+=`
70
+ Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+st(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}}},Qt=new ds;function fe(e,t){return Qt.parse(e,t)}fe.options=fe.setOptions=function(e){return Qt.setOptions(e),fe.defaults=Qt.defaults,Ca(fe.defaults),fe};fe.getDefaults=ts;fe.defaults=Zt;fe.use=function(...e){return Qt.use(...e),fe.defaults=Qt.defaults,Ca(fe.defaults),fe};fe.walkTokens=function(e,t){return Qt.walkTokens(e,t)};fe.parseInline=Qt.parseInline;fe.Parser=Ke;fe.parser=Ke.parse;fe.Renderer=Xr;fe.TextRenderer=cs;fe.Lexer=Ge;fe.lexer=Ge.lex;fe.Tokenizer=Yr;fe.Hooks=ar;fe.parse=fe;var{options:ng,setOptions:rg,use:og,walkTokens:sg,parseInline:ag}=fe;var ig=Ke.parse,lg=Ge.lex;import{useEffect as Da,useMemo as us,useRef as md,useState as lr}from"react";import{jsxDEV as Se}from"react/jsx-dev-runtime";function ps({open:e,onClose:t,onSubmit:n,includedRemoteIds:o,onToggleRemoteId:r}){let{annotations:a,generalNote:s,submittableResponses:l,feedbackEntries:i}=Jt(),c=je().threads!==null,[d,u]=lr(""),[p,f]=lr(!1),[h,x]=lr(!1),[g,k]=lr(null),m=md(null),[b,w]=lr(!1),y=us(()=>a.filter((E)=>E.source==="remote"),[a]);if(e&&!b)f(!1),x(!1),k(null);if(!e&&b)f(!1),x(!1),k(null);if(e!==b)w(e);let S=us(()=>er(a,s,l,i,o,{annotationIds:c}),[a,s,l,i,o,c]),T=p?d:S;if(Da(()=>{if(e&&h&&m.current)m.current.focus()},[e,h]),Da(()=>{if(!e)return;let E=(C)=>{if(C.key==="Escape")t()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e,t]),!e)return null;let M=T.trim().length>0;return Se("div",{className:"fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-center justify-center p-8",onClick:t,children:Se("div",{className:"bg-bg-surface border border-border-medium rounded-xl shadow-lg w-full max-w-2xl flex flex-col",style:{height:"80vh"},onClick:(E)=>E.stopPropagation(),children:[Se("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border-subtle flex-shrink-0",children:[Se("div",{className:"flex items-center gap-3",children:[Se("span",{className:"text-[13px] font-medium text-text-primary font-body",children:"Response preview"},void 0,!1,void 0,this),p&&Se("button",{onClick:()=>{f(!1),x(!1)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body",children:"Reset"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Se("div",{className:"flex items-center gap-2",children:[Se("div",{className:"flex items-center bg-bg-base rounded-md p-0.5",children:[Se("button",{onClick:()=>x(!1),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${!h?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Preview"},void 0,!1,void 0,this),Se("button",{onClick:()=>x(!0),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${h?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Se("button",{onClick:t,className:"text-text-tertiary hover:text-text-secondary w-7 h-7 flex items-center justify-center rounded-md hover:bg-border-subtle transition-colors",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h?Se("textarea",{ref:m,value:T,onChange:(E)=>{u(E.currentTarget.value),f(!0)},className:"flex-1 w-full bg-bg-base p-5 text-[13px] font-mono text-text-code resize-none focus:outline-none leading-relaxed placeholder:text-text-disabled",placeholder:"Your feedback will appear here..."},void 0,!1,void 0,this):Se("div",{className:"flex-1 overflow-y-auto p-5",children:Se(kn,{text:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),y.length>0&&Se("div",{className:"px-5 py-2 border-t border-border-subtle flex-shrink-0",children:Se("span",{className:"text-[12px] text-text-secondary font-body",children:["Reviewer feedback: ",o.size,"/",y.length," included"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),g&&Se("div",{className:"px-5 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[Se("span",{children:g},void 0,!1,void 0,this),Se("button",{onClick:()=>{k(null),n(T)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Se("div",{className:"flex justify-end gap-2 px-5 py-3 border-t border-border-subtle flex-shrink-0",children:[Se("button",{onClick:t,className:"px-4 py-2 rounded-lg text-[13px] font-body text-text-tertiary hover:text-text-secondary transition-colors",children:"Cancel"},void 0,!1,void 0,this),Se("button",{onClick:()=>{let E=nr(l,i);if(E.length>0){k(`Please answer: ${E.join(", ")}`);return}k(null),n(T)},disabled:!M,className:`px-6 py-2 rounded-lg font-body text-[13px] font-medium transition-all ${M?"bg-btn-primary text-btn-primary-text hover:opacity-90":"bg-bg-input text-text-disabled cursor-default"}`,children:"Submit feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var hd=/!\[([^\]]*)\]\((\/tmp\/agent-canvas\/uploads\/([^)]+))\)/g;function gd(e){return e.replace(hd,(t,n,o,r)=>`![${n}](/api/uploads/${r})`)}var Ba={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},yn=(e)=>e.replace(/[&<>"']/g,(t)=>Ba[t]??t),xd=(e)=>e.replace(/&(?!#?\w+;)|[<>"']/g,(t)=>Ba[t]??t),ja=(e)=>/^(?:https?|mailto):/i.test(e)||!/^[^/?#]*:/.test(e),Fa=(e)=>e?` title="${yn(e)}"`:"",bd=new ds({renderer:{html:({text:e})=>yn(e),text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):xd(e.text)},link(e){let t=this.parser.parseInline(e.tokens);return ja(e.href)?`<a href="${yn(e.href)}"${Fa(e.title)}>${t}</a>`:t},image:(e)=>ja(e.href)?`<img src="${yn(e.href)}" alt="${yn(e.text)}"${Fa(e.title)}>`:yn(e.text)}});function eo(e){return bd.parse(e,{async:!1})}function kn({text:e}){let t=us(()=>eo(gd(e)),[e]);return Se("div",{className:"prose-canvas font-body text-body text-text-primary leading-relaxed",dangerouslySetInnerHTML:{__html:t}},void 0,!1,void 0,this)}import{useId as vd,useState as fs,useSyncExternalStore as yd}from"react";import{jsxDEV as Te}from"react/jsx-dev-runtime";var kd=[],wd=()=>()=>{},Sd=()=>kd;function Ad(){let e=je().threads;return yd(e?.subscribe??wd,e?.current??Sd)}var Td={open:"Answered",queued:"Reply sent",working:"Agent is on it",resolved:"Resolved"};function ms(){let e=je().threads,t=Ad(),[n,o]=fs(()=>new Map),r=(l,i)=>o((c)=>new Map(c).set(l,i));if(e===null||t.length===0)return null;let a=t.filter((l)=>l.state!=="resolved"),s=t.filter((l)=>l.state==="resolved");return Te("section",{"aria-label":"Threads",className:"px-3 pt-1 pb-3 border-b border-border-subtle",children:[Te("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-1 mb-1",children:"Threads"},void 0,!1,void 0,this),a.map((l)=>Te(za,{thread:l,store:e,draft:n.get(l.id)??"",onDraft:(i)=>r(l.id,i)},l.id,!1,void 0,this)),s.length>0&&Te("details",{className:"mt-1",children:[Te("summary",{className:"text-[11px] text-text-tertiary font-body px-1 cursor-pointer",children:["Resolved (",s.length,")"]},void 0,!0,void 0,this),s.map((l)=>Te(za,{thread:l,store:e,draft:n.get(l.id)??"",onDraft:(i)=>r(l.id,i)},l.id,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function za({thread:e,store:t,draft:n,onDraft:o}){let r=vd(),[a,s]=fs(null),[l,i]=fs(!1),c=async(p)=>{i(!0),s(null);try{await p()}catch(f){s(f instanceof Error?f.message:String(f))}finally{i(!1)}},d=()=>c(async()=>{await t.reply(e.id,n.trim()),o("")}),u=e.filePath===Be?"Agent response":e.filePath??e.canvasFile?.replace(/\.jsx$/,"");return Te("article",{className:"rounded-lg border border-border-subtle bg-bg-elevated px-3 py-2 mt-2","data-thread-id":e.id,children:[Te("div",{className:"flex items-center justify-between gap-2 text-[11px] text-text-tertiary font-body",children:[Te("span",{className:"truncate",children:[u?`${u} · `:"","Round ",e.revision]},void 0,!0,void 0,this),Te("span",{children:Td[e.state]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.snippet.trim()&&Te("blockquote",{className:"mt-1 border-l-2 border-border-medium pl-2 text-[12px] text-text-secondary font-body line-clamp-3",children:e.snippet},void 0,!1,void 0,this),Te("ol",{className:"mt-2 space-y-2",children:e.comments.map((p)=>Te("li",{className:"text-[13px] font-body",children:[Te("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary",children:p.author==="agent"?"Agent":"You"},void 0,!1,void 0,this),p.author==="agent"?Te(kn,{text:p.body},void 0,!1,void 0,this):Te("p",{className:"whitespace-pre-wrap text-text-primary",children:p.body},void 0,!1,void 0,this)]},p.id,!0,void 0,this))},void 0,!1,void 0,this),Te("label",{className:"sr-only",htmlFor:r,children:"Reply"},void 0,!1,void 0,this),Te("textarea",{id:r,value:n,onInput:(p)=>o(p.currentTarget.value),placeholder:"Reply to the agent",rows:2,className:"mt-2 w-full rounded-md bg-bg-input px-2 py-1.5 text-[13px] font-body text-text-primary"},void 0,!1,void 0,this),a&&Te("p",{role:"alert",className:"text-[12px] text-accent-red font-body",children:a},void 0,!1,void 0,this),Te("div",{className:"mt-1 flex justify-end gap-2",children:[Te("button",{type:"button",disabled:l,onClick:()=>c(()=>t.setResolved(e.id,e.state!=="resolved")),className:"px-2.5 py-1 rounded text-[12px] font-body text-text-secondary hover:text-text-primary",children:e.state==="resolved"?"Reopen":"Resolve"},void 0,!1,void 0,this),Te("button",{type:"button",disabled:l||n.trim()==="",onClick:d,className:"px-2.5 py-1 rounded text-[12px] font-body font-medium bg-btn-primary text-btn-primary-text disabled:opacity-50",children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as H,Fragment as to}from"react/jsx-dev-runtime";function no({onSubmit:e,collapseButton:t}){let{isReadOnly:n,selectedRevision:o,currentRevision:r,revisions:a,agentWatching:s}=gs(Ve),l=gs(Ed),i=a.find((p)=>p.revision===o),c=n&&o===r,d=!!i?.feedbackConsumed,u=i?.label||`Round ${o}`;if(n)return H(Nd,{sessionId:l,revision:o,label:u,waitingForUpdate:c,feedbackConsumed:d,agentWatching:s,collapseButton:t},void 0,!1,void 0,this);return H(Md,{onSubmit:e,agentWatching:s,collapseButton:t},void 0,!1,void 0,this)}function Cd({sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:a,collapseButton:s}){let i=je().isShared;return H("div",{className:"flex flex-col h-full",children:[H("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[H("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:o?"Feedback sent":`Feedback — ${n}`},void 0,!1,void 0,this),s]},void 0,!0,void 0,this),o&&!i&&H(Ua,{feedbackConsumed:r,agentWatching:a},void 0,!1,void 0,this),H(Wa,{sessionId:e,revision:t},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ua({feedbackConsumed:e,agentWatching:t}){if(e)return H("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-green-muted flex items-center gap-2 flex-shrink-0",children:[H("span",{className:"w-2 h-2 rounded-full bg-accent-green animate-pulse"},void 0,!1,void 0,this),H("span",{className:"text-[12px] font-body text-accent-green",children:"Feedback received — waiting for next revision..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(t)return H("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-blue-muted flex items-center gap-2 flex-shrink-0",children:[H("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"},void 0,!1,void 0,this),H("span",{className:"text-[12px] font-body text-accent-blue",children:"Waiting for agent to pick up feedback..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return H("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-amber-muted flex items-center gap-2 flex-shrink-0",children:[H("span",{className:"w-2 h-2 rounded-full bg-accent-amber"},void 0,!1,void 0,this),H("span",{className:"text-[12px] font-body text-accent-amber",children:"Agent disconnected — tell Claude to check feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Nd({sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:a,collapseButton:s}){let{annotations:l,generalNote:i}=Jt(),c=l.length>0||i.trim().length>0,[d,u]=wn("feedback");if(!c)return H(Cd,{sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:a,collapseButton:s},void 0,!1,void 0,this);return H("div",{className:"flex flex-col h-full",children:[H("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[H("div",{className:"flex items-center gap-1 bg-bg-input rounded-md p-0.5",children:[H("button",{onClick:()=>u("feedback"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors ${d==="feedback"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Feedback"},void 0,!1,void 0,this),H("button",{onClick:()=>u("annotations"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors flex items-center gap-1.5 ${d==="annotations"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:["Annotations",H("span",{className:"inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded-full bg-border-subtle text-[10px] font-medium",children:l.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s]},void 0,!0,void 0,this),o&&H(Ua,{feedbackConsumed:r,agentWatching:a},void 0,!1,void 0,this),d==="feedback"?H(Wa,{sessionId:e,revision:t},void 0,!1,void 0,this):H(to,{children:[H("div",{className:"flex-1 overflow-y-auto",children:H(Ga,{annotations:l,readOnly:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this),i.trim()&&H("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:H("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:i},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Wa({sessionId:e,revision:t}){let n=je(),[o,r]=wn(null),[a,s]=wn(!0);return Va(()=>{if(s(!0),!n.fsAvailable){r(null),s(!1);return}fetch(`/api/session/${e}/revision/${t}/feedback`).then((l)=>l.json()).then((l)=>{r(xa.parse(l).feedback||null),s(!1)}).catch(()=>{r(null),s(!1)})},[e,t]),H("div",{className:"flex-1 overflow-y-auto px-4",children:[H("div",{className:"-mx-4",children:H(ms,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),a?H("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"Loading..."},void 0,!1,void 0,this):o?H(kn,{text:o},void 0,!1,void 0,this):H("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"No feedback was submitted for this revision."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _d(e){let t=e.filter((s)=>s.filePath===Be),n=e.filter((s)=>!s.filePath),o=e.filter((s)=>qt(s)!==void 0),r={};for(let s of o){let l=qt(s);if(!l)continue;let i=r[l];if(i)i.push(s);else r[l]=[s]}let a=[t,n,o].filter((s)=>s.length>0).length>1;return{response:t,plan:n,fileGroups:r,hasMultipleGroups:a}}function qa({children:e}){return H("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-3 mb-1 mt-1",children:e},void 0,!1,void 0,this)}function Ga({annotations:e,readOnly:t,includedRemoteIds:n,onToggleRemoteId:o}){let{setActiveView:r}=gs(ot),{response:a,plan:s,fileGroups:l,hasMultipleGroups:i}=_d(e),c=hs((p)=>{let f=qt(p);if(!f)return;r({type:"file",path:f}),setTimeout(()=>{let h=rr(p);if(h)h.scrollIntoView({behavior:"smooth",block:"center"})},150)},[r]),d=hs((p)=>Zo(p,r),[r]),u={readOnly:t,onSelect:c,onReveal:d,includedRemoteIds:n,onToggleRemoteId:o};return H(to,{children:[a.length>0&&H(to,{children:[i&&H(qa,{children:"Agent Response"},void 0,!1,void 0,this),H(Zn,{annotations:a,...u},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s.length>0&&H(to,{children:[i&&H(qa,{children:"Canvas"},void 0,!1,void 0,this),H(Zn,{annotations:s,...u},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Object.entries(l).map(([p,f])=>H("div",{children:[H("button",{onClick:()=>r({type:"file",path:p}),className:"flex items-center gap-1.5 text-[10px] uppercase tracking-widest text-text-tertiary hover:text-text-secondary font-body px-3 pt-3 pb-1 truncate transition-colors w-full text-left",title:p,children:[H(Lt,{name:p.split("/").pop()||p,type:"file"},void 0,!1,void 0,this),H("span",{className:"truncate",children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H(Zn,{annotations:f,...u},void 0,!1,void 0,this)]},p,!0,void 0,this))]},void 0,!0,void 0,this)}function Md({onSubmit:e,agentWatching:t,collapseButton:n}){let o=je(),[r,a]=wn(!1),{annotations:s,generalNote:l,submittableResponses:i,feedbackEntries:c}=Jt(),d=Rd(()=>s.filter((S)=>S.source==="remote"),[s]),[u,p]=wn(()=>new Set);Va(()=>{if(d.length===0)return;p((S)=>{let T=new Set(S);for(let M of d)T.add(M.id);return T.size===S.size?S:T})},[d]);let f=hs((S)=>{p((T)=>{let M=new Set(T);if(M.has(S))M.delete(S);else M.add(S);return M})},[]),h=Array.from(i.values()).some(tr),x=c.size>0,g=s.length>0||l.trim().length>0||h||x,[k,m]=wn(null),b=o.threads!==null,w=(S)=>{let T=b?s.filter((M)=>M.source!=="remote").map(Ld):[];e(S,T,la(i))},y=()=>{w(er(s,l,i,c,u,{annotationIds:b}))};return H("div",{className:"flex flex-col h-full",children:[H("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[H("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body flex items-center gap-2",children:["Annotations",s.length>0&&H("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-border-subtle text-[10px] font-medium text-text-secondary",children:s.length},void 0,!1,void 0,this),!o.isShared&&H("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${t?"bg-accent-green":"bg-accent-amber"}`,title:t?"Agent connected":"Agent disconnected"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n]},void 0,!0,void 0,this),H("div",{className:"flex-1 overflow-y-auto",children:[H(ms,{},void 0,!1,void 0,this),s.length===0&&H("p",{className:"text-[12px] text-text-tertiary px-3 py-4 leading-relaxed font-body",children:"Select text in the canvas or in files to add annotations."},void 0,!1,void 0,this),H(Ga,{annotations:s,includedRemoteIds:u,onToggleRemoteId:f},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H(Oo,{hasContent:g,onSubmit:()=>{let S=nr(i,c);if(S.length>0){m(`Please answer: ${S.join(", ")}`);return}m(null),y()},onSubmitEmpty:()=>e("No feedback — looks good.",[],[]),notice:k&&H("div",{className:"px-4 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[H("span",{children:k},void 0,!1,void 0,this),H("button",{onClick:()=>{m(null),y()},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),secondaryAction:H("button",{onClick:()=>a(!0),className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-border-subtle text-text-secondary hover:bg-border-medium hover:text-text-primary",children:"Preview"},void 0,!1,void 0,this)},void 0,!1,void 0,this),H(ps,{open:r,onClose:()=>a(!1),onSubmit:w,includedRemoteIds:u,onToggleRemoteId:f},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ld(e){return{id:e.id,snippet:e.snippet,note:e.note,canvasFile:e.canvasFile,filePath:e.filePath}}import{useFeedback as zb}from"#canvas/runtime";import Wg from"react";fe.setOptions({gfm:!0,breaks:!1});import{useAnnotations as ex,useResponseRegistration as tx}from"#canvas/runtime";import{useEffect as rx,useMemo as ox,useRef as sx,useState as ax}from"react";import{useEffect as px,useRef as fx}from"react";function cr(){return window.hljs}import{ActiveViewCtx as kx,SessionContext as wx}from"#canvas/runtime";import{useContext as Ax,useEffect as Tx,useRef as Ex,useState as Rx}from"react";import{SessionContext as Lx}from"#canvas/runtime";import{useContext as Px,useState as $x}from"react";import{useMemo as Fx}from"react";fe.setOptions({gfm:!0,breaks:!1});import{useAnnotations as Vx,useCanvasFile as Ux}from"#canvas/runtime";import{useCallback as Jx,useEffect as Yx,useRef as Xx,useState as Qx}from"react";import eb from"react-dom";import{useState as lb}from"react";import{useAnnotations as hb,useResponseRegistration as gb}from"#canvas/runtime";import{useRef as vb,useState as yb}from"react";import{CanvasFileCtx as Hd,SessionContext as Od}from"#canvas/runtime";import ro,{useContext as Ka,useEffect as It,useMemo as ur,useRef as Dd,useState as at}from"react";import{createPortal as jd}from"react-dom";import{createContext as $d}from"react";var dr=$d(()=>{});import{jsxDEV as ge,Fragment as qd}from"react/jsx-dev-runtime";class Ja extends ro.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.reportError({revision:this.props.revision,filename:this.props.filename,message:e.message,...e.stack?{stack:e.stack}:{},...t.componentStack?{componentStack:t.componentStack}:{}})}render(){if(!this.state.error)return this.props.children;return ge(Ya,{message:this.state.error.message},void 0,!1,void 0,this)}}function Ya({message:e}){return ge("div",{className:"bg-accent-red-muted rounded-lg p-5",children:[ge("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Canvas render failed"},void 0,!1,void 0,this),ge("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:e},void 0,!1,void 0,this),ge("p",{className:"text-meta font-body text-text-tertiary mt-3",children:"The error was sent back to the canvas author."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Sn({revision:e,filename:t}){let n=Ka(Od),o=je(),r=Ka(dr),[a,s]=at(null),[l,i]=at(null),[c,d]=at(!0),u=Dd(null),{annotations:p,addAnnotationWithId:f,removeAnnotation:h,updateAnnotation:x,addAnnotationImage:g,removeAnnotationImage:k,activeAnnotationId:m,setActiveAnnotationId:b,registerCanvasRendered:w}=Jt(),y=ur(()=>p.filter((D)=>!D.filePath&&(!D.canvasFile||D.canvasFile===t)),[p,t]),[S,T]=at(null),[M,E]=at(null),[C,O]=at(null),[B,Y]=at(null),[me,X]=at(!1);It(()=>{d(!0),i(null),Y(null),o.loadCanvasModule(t,e).then((D)=>{s(()=>D.default),d(!1)}).catch((D)=>{let V=D instanceof Error?D:Error(String(D));i(V.message),d(!1),r({revision:e,filename:t,message:V.message,...V.stack?{stack:V.stack}:{}})})},[n,e,t,r]),It(()=>{if(a)w(t)},[a,t,w]);let pe=document.getElementById("plan-scroll-container"),{popovers:se,isPopoverOpen:he}=_t({containerRef:u,restoreKey:a,restoreAnnotations:y,extractContext:(D)=>At(D,u.current),canvasFile:t,scrollContainer:pe}),{popovers:ne,isDrawing:ce,isPopoverOpen:ve}=qo({containerRef:u,restoreKey:a,canvasFile:t,scrollContainer:pe}),Q=he||ve,W=ur(()=>{let D=new Map;for(let V of y)if(V.snippet.startsWith("["))D.set(V.snippet,V.id);return D},[y]);It(()=>{let D=u.current;if(!D)return;let V=(N)=>{if(C||Q||ce)return;let F=N.target;if(F.closest("[data-block-comment-btn]"))return;X(!1);let K=F.closest(on);if(K&&D.contains(K)){let Me=en(D).indexOf(K);Y(Me>=0?Me:null)}else Y(null);let xe=F.closest(Tt);if(xe&&D.contains(xe)){E(xe);let ke=Xe(xe),Me=ke?W.get(ke):void 0;if(Me&&Me!==m)b(Me)}else E(null)},P=(N)=>{if(C||Q)return;if(N.relatedTarget?.closest("[data-block-comment-btn]"))return;E(null),b(null)};return D.addEventListener("mousemove",V),D.addEventListener("mouseleave",P),()=>{D.removeEventListener("mousemove",V),D.removeEventListener("mouseleave",P)}},[a,C,Q,ce,W,m]),It(()=>{let D=(V)=>{let P=V.target.tagName;if(P==="INPUT"||P==="TEXTAREA"||V.target.isContentEditable)return;if(C||Q)return;let N=u.current;if(!N)return;if(V.key==="ArrowDown"){V.preventDefault(),X(!0);let F=en(N);if(F.length===0)return;Y((K)=>{if(K===null)return 0;return Math.min(K+1,F.length-1)})}else if(V.key==="ArrowUp"){V.preventDefault(),X(!0);let F=en(N);if(F.length===0)return;Y((K)=>{if(K===null)return F.length-1;return Math.max(K-1,0)})}else if(V.key==="a"||V.key==="A"){if(B===null||!N)return;let K=en(N)[B];if(!K)return;if(!K.matches(Tt))return;V.preventDefault();let xe=Xe(K);if(!xe)return;let ke=W.get(xe);if(ke)b(ke),O({anchorEl:K,snippet:xe,annId:ke});else O({anchorEl:K,snippet:xe})}else if(V.key===" "||V.key==="Enter"){if(B===null)return;let K=en(N)[B];if(!K)return;let xe=K.getAttribute("data-md");if(xe==="choice-option"||xe==="multichoice-option")V.preventDefault(),K.dispatchEvent(new CustomEvent("kb-select",{bubbles:!0}));else if(xe==="userinput"){V.preventDefault();let ke=K.querySelector("textarea");if(ke){ke.focus();let Me=(De)=>{if(De.key==="Escape")De.preventDefault(),ke.blur(),X(!0)};ke.addEventListener("keydown",Me),ke.addEventListener("blur",()=>ke.removeEventListener("keydown",Me),{once:!0})}}else if(xe==="rangeinput"){V.preventDefault();let ke=K.querySelector("input[type='range']");if(ke){ke.focus();let Me=(De)=>{if(De.key==="Escape"||De.key==="ArrowUp"||De.key==="ArrowDown")De.preventDefault(),ke.blur(),X(!0)};ke.addEventListener("keydown",Me),ke.addEventListener("blur",()=>ke.removeEventListener("keydown",Me),{once:!0})}}}else if(V.key==="Escape")Y(null),X(!1),b(null)};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[B,C,Q,W]),It(()=>{let D=u.current;if(!D||B===null||!me)return;let P=en(D)[B];if(!P)return;P.style.outline="2px solid var(--color-accent-blue)",P.style.outlineOffset="-2px",P.style.borderRadius="8px",P.scrollIntoView({block:"nearest",behavior:"smooth"});let N=Xe(P),F=N?W.get(N):void 0;if(F)b(F);return()=>{P.style.outline="",P.style.outlineOffset="",P.style.borderRadius=""}},[B,me,W]);let ae=ur(()=>a?ge(a,{},void 0,!1,void 0,this):null,[a]);if(c)return ge("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-body",children:"Loading canvas..."},void 0,!1,void 0,this);if(l)return ge(Ya,{message:l},void 0,!1,void 0,this);if(!a)return ge("div",{className:"text-text-tertiary text-center py-8 font-body text-body",children:"No canvas loaded"},void 0,!1,void 0,this);return ge(Hd.Provider,{value:t,children:[ge("div",{ref:u,className:"plan-content plan-updated","data-canvas-file":t,children:ge(Ja,{revision:e,filename:t,reportError:r,children:ae},`${e}:${t}`,!1,void 0,this)},void 0,!1,void 0,this),S&&ge(zd,{note:S.note,onSave:(D)=>{x(S.id,D),T(null)},onCancel:()=>T(null)},void 0,!1,void 0,this),se,ne,ge(Fd,{containerRef:u,hoveredBlock:M,focusedBlockIndex:B,blockPopover:C,blockAnnotationMap:W,activeAnnotationId:m,onOpen:(D,V,P)=>{if(P)b(P),O({anchorEl:D,snippet:V,annId:P});else O({anchorEl:D,snippet:V})}},void 0,!1,void 0,this),C&&!C.annId&&ge(nt,{anchorEl:C.anchorEl,scrollContainer:pe,snippet:C.snippet,truncateAt:80,onAdd:(D,V)=>{let P=qe();f(P,C.snippet,D,void 0,void 0,V,t),O(null)},onCancel:()=>O(null)},void 0,!1,void 0,this),C?.annId&&(()=>{let D=y.find((V)=>V.id===C.annId);if(!D)return null;return ge(Wt,{anchorEl:C.anchorEl,scrollContainer:pe,initialNote:D.note,initialImages:D.images,onUpdate:(V,P)=>{x(C.annId,V);let N=D.images||[];for(let F of P)if(!N.includes(F))g(C.annId,F);for(let F of N)if(!P.includes(F))k(C.annId,F)},onDelete:()=>{h(C.annId),b(null),O(null)},onClose:()=>O(null)},void 0,!1,void 0,this)})()]},void 0,!0,void 0,this)}function en(e){return Array.from(e.querySelectorAll(on))}function Fd({containerRef:e,hoveredBlock:t,focusedBlockIndex:n,blockPopover:o,blockAnnotationMap:r,activeAnnotationId:a,onOpen:s}){let[l,i]=at([]);It(()=>{let f=e.current;if(!f||r.size===0){i([]);return}let h=[];for(let x of f.querySelectorAll(Tt)){let g=Xe(x);if(g&&r.has(g))h.push(x)}i(h)},[r,e.current]);let[c,d]=at(null);It(()=>{if(!a||!e.current){d(null);return}for(let f of e.current.querySelectorAll(on)){let h=Xe(f);if(h&&r.get(h)===a){d(f);return}}d(null)},[a,r]),It(()=>{if(!c)return;return c.style.boxShadow="inset 0 0 0 1.5px var(--color-highlight-bg)",c.style.borderRadius="8px",()=>{c.style.boxShadow="",c.style.borderRadius=""}},[c]);let u=ur(()=>{if(n===null||!e.current)return null;let f=en(e.current)[n];if(!f)return null;return f.matches(Tt)?f:null},[n,e.current]),p=ur(()=>{let f=new Set(l);if(t)f.add(t);if(u)f.add(u);if(o?.anchorEl)f.add(o.anchorEl);return Array.from(f)},[l,t,u,o]);return ge(qd,{children:p.map((f)=>ge(Bd,{block:f,isHovered:f===t||f===u||f===o?.anchorEl,blockAnnotationMap:r,activeAnnotationId:a,onOpen:s},f.getAttribute("data-task-id")||f.getAttribute("data-md-title")||f.textContent?.slice(0,30)||"block",!1,void 0,this))},void 0,!1,void 0,this)}function Bd({block:e,isHovered:t,blockAnnotationMap:n,activeAnnotationId:o,onOpen:r}){let a=Xe(e);if(!a)return null;let s=n.get(a),l=!!s;return jd(ge("button",{"data-block-comment-btn":!0,onClick:(c)=>{c.stopPropagation(),r(c.currentTarget,a,s)},className:`absolute top-1 right-1 z-10 w-6 h-6 flex items-center justify-center rounded transition-all duration-150 ${l?s===o?"text-accent-amber bg-accent-amber-muted":"text-accent-amber opacity-60 hover:opacity-100":t?"text-text-disabled hover:text-text-tertiary opacity-50 hover:opacity-100":"text-text-disabled opacity-0 group-hover/section:opacity-20 hover:!opacity-80"}`,title:l?"Edit annotation":"Add annotation",children:ge("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:l?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:ge("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e)}function zd({note:e,onSave:t,onCancel:n}){let[o,r]=ro.useState(e),a=ro.useRef(null);return ro.useEffect(()=>{a.current?.focus(),a.current?.select()},[]),ge("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center",onClick:n,children:ge("div",{className:"bg-bg-elevated border border-border-hover rounded-lg shadow-md p-4 w-80",onClick:(s)=>s.stopPropagation(),children:[ge("div",{className:"text-tiny uppercase tracking-widest text-text-tertiary font-body mb-2",children:"Edit annotation"},void 0,!1,void 0,this),ge("textarea",{ref:a,value:o,onChange:(s)=>r(s.currentTarget.value),className:"w-full bg-transparent border-none text-body font-body text-text-primary resize-vertical focus:outline-none min-h-[60px]",onKeyDown:(s)=>{if(s.key==="Enter"&&(s.ctrlKey||s.metaKey))t(o.trim());if(s.key==="Escape")n()}},void 0,!1,void 0,this),ge("div",{className:"flex justify-end gap-2 mt-2",children:[ge("button",{onClick:n,className:"text-meta text-text-tertiary font-body px-3 py-1",children:"Cancel"},void 0,!1,void 0,this),ge("button",{onClick:()=>t(o.trim()),className:"text-meta font-medium font-body px-3 py-1 rounded-md bg-highlight-bg text-text-primary border border-highlight-border",children:"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import Ot,{useCallback as En,useEffect as Ue,useLayoutEffect as Np,useMemo as el,useRef as ct,useState as be}from"react";import{createRoot as _p}from"react-dom/client";var Vd=500,Ud=1e4,bs=R().max(Ud),Xa=z({id:R().min(1).max(200),type:zt(["select","radio","checkbox","text","range"]),label:R().max(1000),value:Dr([bs,ye(bs).max(500),Ce(),zl()]),note:bs.optional()}),Dv=ye(Xa).max(Vd);function Qa(e){return e.flatMap((t)=>{let n=Xa.safeParse(t);if(!n.success)return[];let{value:o,note:r,...a}=n.data,s=Array.isArray(o)?o.length>0:typeof o==="string"?o.trim()!=="":o!==null,l=r?.trim()??"";if(!s&&!l)return[];return[{...a,value:o,...l?{note:l}:{}}]})}var Za=z({shareId:R(),url:R(),revision:Ce(),createdAt:R(),ownerToken:R().optional(),expiresAt:R().optional(),lastFeedbackAt:R().optional(),encryptionKey:R().optional()}),Wd=z({revision:Ce(),label:R().optional(),canvasFiles:ye(z({filename:R(),diffStats:z({added:Ce(),removed:Ce()}).optional()})),createdAt:R(),hasFeedback:tt(),feedbackConsumed:tt(),response:R().optional()}).passthrough(),ei=z({encryption:z({alg:fn("AES-GCM"),v:fn(1)}).optional(),origin:z({sessionId:R().optional(),label:R().optional(),revision:Ce().optional(),createdAt:R().optional()}).optional(),currentRevision:Ce().optional(),revisions:ye(Wd).optional(),canvasFiles:ye(R()).optional(),projectRoot:R().optional(),shares:ye(Za).optional(),shareEnabled:tt().optional()}).passthrough(),vs=z({entries:ye(z({name:R(),type:zt(["file","dir"])}))}),Gd=z({id:R(),shareId:R(),revision:Ce(),submittedAt:R(),author:Io,annotations:ye(Po.omit({source:!0,author:!0})),generalNote:R().optional()}),ti=z({entries:ye(Gd)}),ni=Dr([z({ok:fn(!0),share:Za}),z({ok:fn(!1).optional(),error:R().optional()})]),ri=Dr([z({ok:fn(!0)}),z({ok:fn(!1).optional(),error:R().optional()})]);var Kd=z({id:R(),name:R(),path:R(),size:Ce().int()});var oi={alg:"AES-GCM",v:1};async function si(e){let t=Yd(e);return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function xt(e,t){let n=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,o),a=new Uint8Array(n.byteLength+r.byteLength);return a.set(n,0),a.set(new Uint8Array(r),n.byteLength),Jd(a)}async function pr(e,t){let n=ai(t);if(n.byteLength<28)throw Error("Ciphertext too short");let o=n.subarray(0,12),r=n.subarray(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:o},e,r);return new TextDecoder().decode(a)}function Jd(e){let t="",n=32768;for(let o=0;o<e.byteLength;o+=n)t+=String.fromCharCode.apply(null,Array.from(e.subarray(o,o+n)));return btoa(t)}function ai(e){let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function Yd(e){let t=e.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((e.length+3)%4);return ai(t)}function Xd(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"||t.hostname.endsWith(".localhost")}var Pt=R().max(500),Qd=4000,Zd=1000,eu=1000,tu=z({label:Pt,file:R().max(Zd),line:Ce().int().positive(),column:Ce().int().nonnegative()}),li=z({url:R().min(1).max(2000),selector:R().max(2000),role:Pt.optional(),name:Pt.optional(),text:Pt.optional(),components:ye(R().max(200)).max(20).optional(),sources:ye(tu).max(10).optional(),context:Pt.optional(),browser:z({name:Pt,viewport:z({width:Ce().int().nonnegative(),height:Ce().int().nonnegative(),scale:Ce().positive()}),colorScheme:zt(["light","dark"])}).optional(),style:R().max(eu).optional(),html:R().max(Qd).optional(),quote:z({exact:R().min(1).max(2000),before:Pt,after:Pt}).optional()}),nu=zt(["user","agent"]),ys=z({id:R(),author:nu,body:R().min(1).max(20000),createdAt:R()}),ks=zt(["open","queued","working","resolved"]),ru=z({id:R(),anchor:li,state:ks,comments:ye(ys).min(1),screenshot:R().optional(),createdAt:R(),updatedAt:R()}),Gv=z({threads:ye(ru)}),ws=R().trim().min(1).max(20000),ii="data:image/png;base64,",ou=R().startsWith(ii).max(8000000).transform((e)=>Uint8Array.from(atob(e.slice(ii.length)),(t)=>t.charCodeAt(0))),Kv=z({anchor:li,body:ws,send:tt(),screenshot:ou.optional()}),Jv=z({body:ws,send:tt()}),Yv=z({body:ws,resolve:tt()}),ci=R().url().refine((e)=>Xd(e),"must be an http(s) URL on localhost"),Xv=z({target:ci}),Qv=z({target:ci,port:Ce().int().min(1).max(65535)});var fr=z({id:R(),state:ks,revision:Ce().int(),snippet:R(),canvasFile:R().optional(),filePath:R().optional(),comments:ye(ys),createdAt:R(),updatedAt:R()}),cy=z({threads:ye(fr)}),di=R().trim().min(1).max(20000),dy=z({body:di,resolve:tt()}),uy=z({body:di}),py=z({resolved:tt()});var su=z({threads:ye(fr)}),au=z({thread:fr});async function ui(e){let t=await e.json().catch(()=>null),n=z({error:R()}).safeParse(t);return Error(n.success?n.data.error:`Thread request failed with status ${e.status}`)}function iu(e,t){let n=new Map(t.map((a)=>[a.id,a])),o=e.map((a)=>{let s=n.get(a.id);return s!==void 0&&s.updatedAt>=a.updatedAt?s:a}),r=new Set(e.map((a)=>a.id));return[...o,...t.filter((a)=>!r.has(a.id))]}function pi(e){let t=[],n=new Set,o=`/api/session/${encodeURIComponent(e)}/threads`,r=(s)=>{t=iu(t,s);for(let l of n)l()},a=async(s,l)=>{let i=await fetch(`${o}/${s}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok)throw await ui(i);r([au.parse(await i.json()).thread])};return{subscribe(s){return n.add(s),()=>n.delete(s)},current:()=>t,async load(){let s=await fetch(o,{cache:"no-store"});if(!s.ok)throw await ui(s);r(su.parse(await s.json()).threads)},receive(s){let l=ye(fr).safeParse(s);if(l.success)r(l.data)},reply:(s,l)=>a(`${encodeURIComponent(s)}/comments`,{body:l}),setResolved:(s,l)=>a(`${encodeURIComponent(s)}/resolved`,{resolved:l})}}function lu(){if(typeof window>"u")return null;let e=window.location.hash.replace(/^#/,"");if(!e)return null;for(let t of e.split("&")){let[n,o]=t.split("=");if(n==="k"&&o)return decodeURIComponent(o)}return null}function cu(){if(typeof window<"u"&&window.__CANVAS_SHARE__?.shareId){let t=lu();return{isShared:!0,shareId:window.__CANVAS_SHARE__.shareId,encryptionKey:t?si(t):null}}return{isShared:!1,sessionId:typeof window<"u"?window.location.pathname.replace("/s/",""):""}}var de=cu();function du(){return de.isShared&&de.encryptionKey!==null}function uu(){return de.isShared?de.shareId:de.sessionId}function pu(){if(de.isShared)return`/s/${de.shareId}/meta`;return`/api/session/${de.sessionId}/meta`}function fu(e,t){let n=e.replace(/\.jsx$/,".js");if(de.isShared)return`/s/${de.shareId}/canvas/${encodeURIComponent(n)}`;let o=t?`?rev=${t}&t=${Date.now()}`:`?t=${Date.now()}`;return`/api/session/${de.sessionId}/canvas/${encodeURIComponent(n)}${o}`}function mu(){if(de.isShared)return`/s/${de.shareId}/upload`;return`/api/session/${de.sessionId}/upload`}async function hu(e){let t=await e.json().catch(()=>null);if(typeof t==="object"&&t!==null&&"error"in t&&typeof t.error==="string")return Error(t.error);return Error(`Request failed with status ${e.status}`)}var fi="agent-canvas-project-theme",mi=0;async function hi(){if(de.isShared)return;let e=++mi,t=await fetch(`/api/session/${encodeURIComponent(de.sessionId)}/theme.css`,{cache:"no-store"}),n=t.ok?await t.text():"";if(!t.ok)console.warn(`Project theme not applied: ${(await hu(t)).message}`);if(e!==mi)return;let o=document.getElementById(fi);if(o===null)o=document.createElement("style"),o.id=fi,document.head.append(o);o.textContent=n}async function gi(){let e=await fetch(pu());if(!e.ok)throw Error(`meta ${e.status}`);let t=ei.parse(await e.json());if(t.encryption&&de.isShared&&de.encryptionKey){let n=await de.encryptionKey;if(t.origin){let o={...t.origin};if(o.sessionId)o.sessionId=await pr(n,o.sessionId);if(o.label)o.label=await pr(n,o.label);t.origin=o}for(let o of t.revisions??[])if(o.label)try{o.label=await pr(n,o.label)}catch{}}return t}var gu=async(e,t)=>{let n=fu(e,t);if(!du())return import(n);let o=await fetch(n);if(!o.ok)throw Error(`canvas ${o.status}`);let r=await o.text(),a=await de.encryptionKey,s=await pr(a,r),l=new Blob([s],{type:"application/javascript"}),i=URL.createObjectURL(l);try{return await import(i)}finally{setTimeout(()=>URL.revokeObjectURL(i),0)}},xi="canvas-reviewer-identity";function Ss(){try{let e=localStorage.getItem(xi);if(!e)return null;return JSON.parse(e)}catch{return null}}function bi(e){let t=Ss();if(!t)t={id:crypto.randomUUID?.()||String(Date.now()),name:e};else t.name=e;return localStorage.setItem(xi,JSON.stringify(t)),t}async function xu(e,t){let n=await Promise.all(e.annotations.map(async(o)=>{let r={id:o.id,createdAt:o.createdAt,snippet:await xt(t,String(o.snippet??"")),note:await xt(t,String(o.note??""))};if(o.filePath)r.filePath=await xt(t,String(o.filePath));if(o.canvasFile)r.canvasFile=await xt(t,String(o.canvasFile));if(o.context!==void 0&&o.context!==null)r.context=await xt(t,JSON.stringify(o.context));if(o.attachments)r.attachments=o.attachments;return r}));return{author:{id:e.author.id,name:await xt(t,e.author.name)},revision:e.revision,annotations:n,...e.generalNote?{generalNote:await xt(t,e.generalNote)}:{},...e.responses&&e.responses.length>0?{responses:await xt(t,JSON.stringify(e.responses))}:{},encryption:oi}}async function vi(e){if(!de.isShared)throw Error("submitSharedFeedback called outside shared mode");let t=e;if(de.encryptionKey){let o=await de.encryptionKey;t=await xu(e,o)}let n=await fetch(`/s/${de.shareId}/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let o=await n.text().catch(()=>"");throw Error(`Feedback submission failed: ${n.status} ${o}`)}}var bt=!de.isShared,yi=!de.isShared,oo=de.isShared?null:pi(de.sessionId),ki={get sessionId(){return uu()},isShared:de.isShared,fsAvailable:bt,uploadUrl:mu,loadCanvasModule:gu,threads:oo};import Ii,{useCallback as Pi,useContext as Iu,useEffect as Ht,useMemo as lo,useRef as vt,useState as _e}from"react";function $t(e,t){let n=e.length,o=t.length;if(n===0||o===0)return[];let r=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let i=1;i<=n;i++)for(let c=1;c<=o;c++)r[i][c]=e[i-1]===t[c-1]?r[i-1][c-1]+1:Math.max(r[i-1][c],r[i][c-1]);let a=[],s=n,l=o;while(s>0&&l>0)if(e[s-1]===t[l-1])a.unshift(e[s-1]),s--,l--;else if(r[s-1][l]>r[s][l-1])s--;else l--;return a}function wi(e){let t=[],n=[],o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(a){let s=a.parentElement;if(!s)return NodeFilter.FILTER_REJECT;if(s.closest("svg, .select-none, [data-no-diff]"))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT}}),r;while(r=o.nextNode()){let s=(r.nodeValue||"").match(/\S+|\s+/g);if(!s)continue;let l=0;for(let i of s)t.push(i),n.push({text:i,node:r,offset:l}),l+=i.length}return{words:t,map:n}}function As(e,t){if(e.length>5000||t.length>5000)return bu(e,t);return Ti(e,t)}function Ti(e,t){let n=so(e,t),o=[],r=[],a=0,s=0,l=0;while(a<e.length||s<t.length)if(l<n.length&&a<e.length&&s<t.length&&e[a]===n[l]&&t[s]===n[l])o.push({type:"same",index:a}),r.push({type:"same",index:s}),a++,s++,l++;else if(a<e.length&&(l>=n.length||e[a]!==n[l]))o.push({type:"removed",index:a}),a++;else if(s<t.length)r.push({type:"added",index:s}),s++;return{oldOps:o,newOps:r}}function so(e,t){let n=e.length,o=t.length;if(n===0||o===0)return[];if(n===1)return t.includes(e[0])?[e[0]]:[];if(o===1)return e.includes(t[0])?[t[0]]:[];if(n*o<=1e6)return $t(e,t);let r=Math.floor(n/2),a=e.slice(0,r),s=e.slice(r),l=Si(a,t),i=Si([...s].reverse(),[...t].reverse()),c=0,d=0;for(let f=0;f<=o;f++){let h=l[f]+i[o-f];if(h>c)c=h,d=f}let u=t.slice(0,d),p=t.slice(d);return[...so(a,u),...so(s,p)]}function Si(e,t){let n=t.length,o=Array(n+1).fill(0),r=Array(n+1).fill(0);for(let a=0;a<e.length;a++){for(let s=1;s<=n;s++)r[s]=e[a]===t[s-1]?o[s-1]+1:Math.max(o[s],r[s-1]);[o,r]=[r,o],r.fill(0)}return o}function bu(e,t){let o=(h)=>{let x=[];for(let g=0;g<h.length;g+=200){let k=Math.min(g+200,h.length);x.push({start:g,end:k,text:h.slice(g,k).join("")})}return x},r=o(e),a=o(t),s=r.map((h)=>h.text),l=a.map((h)=>h.text),i=so(s,l),c=[],d=[],u=0,p=0,f=0;while(u<r.length||p<a.length)if(f<i.length&&u<r.length&&p<a.length&&s[u]===i[f]&&l[p]===i[f]){for(let h=r[u].start;h<r[u].end;h++)c.push({type:"same",index:h});for(let h=a[p].start;h<a[p].end;h++)d.push({type:"same",index:h});u++,p++,f++}else if(u<r.length&&(f>=i.length||s[u]!==i[f]))if(p<a.length&&(f>=i.length||l[p]!==i[f])){let h=Ti(e.slice(r[u].start,r[u].end),t.slice(a[p].start,a[p].end));for(let x of h.oldOps)c.push({type:x.type,index:x.index+r[u].start});for(let x of h.newOps)d.push({type:x.type,index:x.index+a[p].start});u++,p++}else{for(let h=r[u].start;h<r[u].end;h++)c.push({type:"removed",index:h});u++}else if(p<a.length){for(let h=a[p].start;h<a[p].end;h++)d.push({type:"added",index:h});p++}return{oldOps:c,newOps:d}}function Ai(e,t,n){let o=new Map;for(let r of e){if(r.type==="same")continue;let a=t[r.index];if(!a||!a.node.parentNode)continue;let s=o.get(a.node);if(!s)s=[],o.set(a.node,s);s.push({offset:a.offset,length:a.text.length})}for(let[r,a]of o){if(!r.parentNode)continue;let s=r.nodeValue||"";a.sort((u,p)=>u.offset-p.offset);let l=[];for(let u of a){let p=l[l.length-1];if(p&&u.offset<=p.offset+p.length)p.length=Math.max(p.length,u.offset+u.length-p.offset);else l.push({...u})}let i=r.parentNode,c=document.createDocumentFragment(),d=0;for(let u of l){if(u.offset>d)c.appendChild(document.createTextNode(s.slice(d,u.offset)));let p=document.createElement("span");p.className=n,p.textContent=s.slice(u.offset,u.offset+u.length),c.appendChild(p),d=u.offset+u.length}if(d<s.length)c.appendChild(document.createTextNode(s.slice(d)));i.replaceChild(c,r)}}function ao(e,t){let n=vu(e,t),o=wi(e),r=wi(t),{oldOps:a,newOps:s}=As(o.words,r.words),l=a.some((i)=>i.type==="removed")||s.some((i)=>i.type==="added");return Ai(a,o.map,"diff-removed"),Ai(s,r.map,"diff-added"),l||n}function vu(e,t){let n=Array.from(e.querySelectorAll('[data-md="mermaid"]')),o=Array.from(t.querySelectorAll('[data-md="mermaid"]')),r=!1,a=Math.max(n.length,o.length);for(let s=0;s<a;s++){let l=n[s],i=o[s];if(!l&&i){i.classList.add("diff-block-added"),i.style.position="relative",r=!0;continue}if(l&&!i){l.classList.add("diff-block-removed"),l.style.position="relative",r=!0;continue}if(!l||!i)continue;let c=(l.getAttribute("data-md-source")||"").trim(),d=(i.getAttribute("data-md-source")||"").trim();if(c===d)continue;r=!0,l.style.borderLeft="3px solid var(--color-accent-red)",l.style.paddingLeft="8px",i.style.borderLeft="3px solid var(--color-accent-green)",i.style.paddingLeft="8px";let u=c.split(`
71
+ `),p=d.split(`
72
+ `),f=$t(u,p),h=(x,g,k)=>{let m=document.createElement("div");m.className="mt-2 bg-bg-code rounded-md overflow-hidden text-tiny font-mono",m.setAttribute("data-no-diff","true");let b=0,w=0;while(w<x.length){let y=document.createElement("div");if(y.className="px-3 py-0.5 whitespace-pre-wrap",b<g.length&&x[w]===g[b])y.textContent=" "+x[w],w++,b++;else y.classList.add(k==="old"?"diff-removed":"diff-added"),y.textContent=(k==="old"?"- ":"+ ")+x[w],w++;m.appendChild(y)}return m};l.appendChild(h(u,f,"old")),i.appendChild(h(p,f,"new"))}return r}import{useContext as yu,useEffect as ku,useRef as wu,useState as Su}from"react";import{jsxDEV as Oe,Fragment as Ei}from"react/jsx-dev-runtime";function Au(e){return e.label||`Round ${e.revision}`}function Tu(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/1000);if(n<60)return"just now";let o=Math.floor(n/60);if(o<60)return`${o}m ago`;let r=Math.floor(o/60);if(r<24)return`${r}h ago`;return`${Math.floor(r/24)}d ago`}function mr({value:e,onChange:t,accent:n="default",className:o}){let{currentRevision:r,revisions:a}=yu(Ve),[s,l]=Su(!1),i=wu(null);ku(()=>{if(!s)return;let u=(p)=>{if(i.current&&!i.current.contains(p.target))l(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[s]);let c=a.find((u)=>u.revision===e);return Oe("div",{className:"relative",ref:i,children:[Oe("button",{onClick:()=>l(!s),className:`flex items-center gap-1.5 text-[12px] font-body font-medium px-2 py-1 rounded-md transition-colors hover:bg-bg-elevated ${{default:"text-text-secondary hover:text-text-primary",red:"text-accent-red",green:"text-accent-green",amber:"text-accent-amber bg-highlight-selected"}[n]} ${o||""}`,children:[c?Au(c):`Round ${e}`,Oe("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`text-text-tertiary transition-transform duration-200 ${s?"rotate-180":""}`,children:Oe("path",{d:"M2.5 4l2.5 2.5L7.5 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s&&Oe("div",{className:"absolute top-full left-0 mt-1 w-64 bg-bg-elevated border border-border-hover rounded-lg shadow-lg z-50 py-1 max-h-80 overflow-y-auto",children:[...a].reverse().map((u)=>Oe("button",{onClick:()=>{t(u.revision),l(!1)},className:`w-full flex items-center gap-2 px-3 py-2 text-[12px] font-body transition-colors ${u.revision===e?"bg-bg-surface text-text-primary":"text-text-secondary hover:bg-bg-surface hover:text-text-primary"}`,children:[Oe("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${u.revision===r?"bg-accent-green":u.hasFeedback?"bg-accent-amber":"bg-border-hover"}`},void 0,!1,void 0,this),Oe("span",{className:"flex-1 text-left truncate",children:u.label?Oe(Ei,{children:[u.label," ",Oe("span",{className:"text-text-tertiary",children:["#",u.revision]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):Oe(Ei,{children:["Round ",u.revision]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Oe("span",{className:"text-[10px] text-text-tertiary flex-shrink-0 flex items-center gap-1.5",children:[(()=>{let p=u.canvasFiles?.reduce((f,h)=>{if(h.diffStats)f.added+=h.diffStats.added,f.removed+=h.diffStats.removed;return f},{added:0,removed:0});if(p&&(p.added>0||p.removed>0))return Oe("span",{className:"font-mono",children:[Oe("span",{className:"text-accent-green",children:["+",p.added]},void 0,!0,void 0,this)," ",Oe("span",{className:"text-accent-red",children:["-",p.removed]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return null})(),u.revision===r?"current":u.hasFeedback?"sent":Tu(u.createdAt)]},void 0,!0,void 0,this)]},u.revision,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function An(e){let t=[],n=e.querySelectorAll(":scope > [data-md]");for(let o of n)t.push(hr(o));if(t.length===0){let o=e.querySelectorAll("[data-md]"),r=new Set;for(let a of o){let s=a.parentElement?.closest("[data-md]");if(s&&e.contains(s))continue;if(r.has(a))continue;r.add(a),t.push(hr(a))}}return t}function hr(e){let t=e.getAttribute("data-md")||"unknown",n=Eu(e,t),o=[];if(t==="section"){let r=e.querySelector(":scope > div.mt-6, :scope > div:last-child");if(r)for(let a of r.querySelectorAll(":scope > [data-md]"))o.push(hr(a))}else if(t==="table")for(let r of e.querySelectorAll(":scope table > tbody > tr"))o.push({key:"tr:"+(r.textContent||"").slice(0,80),type:"tr",element:r,children:[]});else if(t==="checklist")for(let r of e.querySelectorAll(":scope > [data-md='checklist-item']"))o.push(hr(r));else for(let r of e.querySelectorAll("[data-md]"))if(r.parentElement?.closest("[data-md]")===e)o.push(hr(r));return{key:n,type:t,element:e,children:o}}function Eu(e,t){switch(t){case"section":return"section:"+(e.getAttribute("data-md-title")||"");case"item":return"item:"+(e.getAttribute("data-task-id")||e.getAttribute("data-md-label")||"");case"codeblock":case"diff":return t+":"+(e.textContent||"").slice(0,80);case"checklist-item":return"checklist-item:"+(e.getAttribute("data-md-label")||e.textContent?.slice(0,60)||"");case"checklist":return"checklist:"+e.querySelectorAll("[data-md='checklist-item']").length;case"markdown":return"markdown:"+(e.getAttribute("data-md-file")||"inline");case"mermaid":return"mermaid:"+(e.getAttribute("data-md-source")||"").slice(0,80);case"callout":return"callout:"+(e.getAttribute("data-md-type")||"")+":"+(e.textContent||"").slice(0,60);default:return t+":"+(e.getAttribute("data-md-label")||e.textContent?.slice(0,60)||"")}}function gr(e,t){let n=e.map((c)=>c.key),o=t.map((c)=>c.key),r=$t(n,o),a=[],s=0,l=0,i=0;while(s<e.length||l<t.length)if(i<r.length&&s<e.length&&l<t.length&&n[s]===r[i]&&o[l]===r[i]){let c=e[s],d=t[l],u=c.children.length>0||d.children.length>0?gr(c.children,d.children):void 0;a.push({kind:"matched",oldBlock:c,newBlock:d,childMatches:u}),s++,l++,i++}else if(s<e.length&&(i>=r.length||n[s]!==r[i]))a.push({kind:"removed",oldBlock:e[s]}),s++;else if(l<t.length)a.push({kind:"added",newBlock:t[l]}),l++;return a}function io(e){let t=document.createDocumentFragment(),n=!1;for(let o of e)if(o.kind==="removed")n=!0,t.appendChild(Ci(o.oldBlock.element));else if(o.kind==="added")n=!0,t.appendChild(Ru(o.newBlock.element));else{let r=o.newBlock.element.cloneNode(!0),a=o.newBlock.type;if(a==="mermaid"){if(Li(o.oldBlock.element,r))n=!0}else if(o.childMatches&&o.childMatches.length>0&&(a==="table"||a==="checklist")){if(_i(r,o.childMatches,a))n=!0}else if(o.childMatches&&o.childMatches.length>0){if(Ni(o.oldBlock,r,o.childMatches,a))n=!0}else if(a==="markdown"){if(Mi(o.oldBlock.element,r))n=!0}else if(tn(o.oldBlock.element,r,!1))n=!0;t.appendChild(r)}return{fragment:t,hasChanges:n}}function Ci(e){let t=e.cloneNode(!0);return t.classList.add("diff-block-removed"),t.style.position="relative",Ts(t,"Removed","var(--color-accent-red)"),t}function Ru(e){let t=e.cloneNode(!0);return t.classList.add("diff-block-added"),t.style.position="relative",Ts(t,"Added","var(--color-accent-green)"),t}function Ni(e,t,n,o){let r=!1,a=Cu(e,t),s,l;if(o==="section"){let i=e.element.querySelector(":scope > div:first-child"),c=t.querySelector(":scope > div:first-child");if(i&&c){if(tn(i,c,!1))r=!0}s=e.element.querySelector(":scope > div.mt-6, :scope > div:last-child"),l=t.querySelector(":scope > div.mt-6, :scope > div:last-child")}else s=e.element,l=t;if(!s||!l)return r;for(let i of n)if(i.kind==="matched"){let c=a.newMap.get(i.newBlock.element);if(c){if(i.newBlock.type==="mermaid"){if(Li(i.oldBlock.element,c))r=!0}else if(i.childMatches&&i.childMatches.length>0&&(i.newBlock.type==="table"||i.newBlock.type==="checklist")){if(_i(c,i.childMatches,i.newBlock.type))r=!0}else if(i.childMatches&&i.childMatches.length>0){if(Ni(i.oldBlock,c,i.childMatches,i.newBlock.type))r=!0}else if(i.newBlock.type==="markdown"){if(Mi(i.oldBlock.element,c))r=!0}else if(tn(i.oldBlock.element,c,!1))r=!0}}else if(i.kind==="removed"){r=!0;let c=Ci(i.oldBlock.element),d=_u(n,i,a.newMap),u=d?Mu(l,d):null;l.insertBefore(c,u)}else if(i.kind==="added"){r=!0;let c=a.newMap.get(i.newBlock.element);if(c)c.classList.add("diff-block-added"),c.style.position="relative",Ts(c,"Added","var(--color-accent-green)")}if(tn(s,l,!0))r=!0;return r}function _i(e,t,n){let o=n==="table"?e.querySelector(":scope table > tbody"):e;if(!o)return!1;let r=!1;o.innerHTML="";for(let a of t)if(a.kind==="removed"){r=!0;let s=a.oldBlock.element.cloneNode(!0);s.classList.add(n==="table"?"diff-row-removed":"diff-item-removed"),o.appendChild(s)}else if(a.kind==="added"){r=!0;let s=a.newBlock.element.cloneNode(!0);s.classList.add(n==="table"?"diff-row-added":"diff-item-added"),o.appendChild(s)}else{let s=a.newBlock.element.cloneNode(!0);if(tn(a.oldBlock.element,s,!1))r=!0;o.appendChild(s)}return r}function Cu(e,t){return{newMap:{get(n){return Nu(t,n)}}}}function Nu(e,t){let n=t.getAttribute("data-md");if(!n)return null;let o=t.getAttribute("data-md-label"),r=t.getAttribute("data-md-title"),a=`[data-md="${n}"]`;if(r)a+=`[data-md-title="${CSS.escape(r)}"]`;else if(o)a+=`[data-md-label="${CSS.escape(o)}"]`;let s=e.querySelectorAll(a);if(s.length===1)return s[0];let l=(t.textContent||"").slice(0,100),i=null,c=-1;for(let d of s){let u=(d.textContent||"").slice(0,100),p=0;for(let f=0;f<Math.min(l.length,u.length);f++)if(l[f]===u[f])p++;if(p>c)c=p,i=d}return i}function _u(e,t,n){let o=e.indexOf(t);for(let r=o+1;r<e.length;r++){let a=e[r];if((a.kind==="matched"||a.kind==="added")&&a.newBlock)return n.get(a.newBlock.element)||null}return null}function Mu(e,t){let n=t;while(n&&n.parentElement!==e)n=n.parentElement;return n}function Mi(e,t){let n=Array.from(e.children),o=Array.from(t.children);if(n.length===0&&o.length===0)return tn(e,t,!1);let r=n.map((p)=>p.tagName.toLowerCase()),a=o.map((p)=>p.tagName.toLowerCase()),s=$t(r,a),l=[],i=0,c=0,d=0;while(i<n.length||c<o.length)if(d<s.length&&i<n.length&&c<o.length&&r[i]===s[d]&&a[c]===s[d])l.push({kind:"matched",oldChild:n[i],newChild:o[c]}),i++,c++,d++;else if(i<n.length&&(d>=s.length||r[i]!==s[d]))l.push({kind:"removed",oldChild:n[i]}),i++;else if(c<o.length)l.push({kind:"added",newChild:o[c]}),c++;let u=!1;while(t.firstChild)t.removeChild(t.firstChild);for(let p of l)if(p.kind==="matched"){let f=(p.oldChild.textContent||"").match(/\S+/g)||[],h=(p.newChild.textContent||"").match(/\S+/g)||[],x=$t(f,h),g=Math.max(f.length,h.length);if((g>0?1-x.length/g:0)>0.5){u=!0;let m=p.oldChild.cloneNode(!0);m.classList.add("diff-block-removed"),t.appendChild(m),p.newChild.classList.add("diff-block-added"),t.appendChild(p.newChild)}else{if(tn(p.oldChild,p.newChild,!1))u=!0;t.appendChild(p.newChild)}}else if(p.kind==="removed"){u=!0;let f=p.oldChild.cloneNode(!0);f.classList.add("diff-block-removed"),t.appendChild(f)}else u=!0,p.newChild.classList.add("diff-block-added"),t.appendChild(p.newChild);return u}function Ri(e,t){let n=t?new Set(Array.from(e.querySelectorAll("[data-md]"))):new Set,o=[],r=[],a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(l){let i=l.parentElement;if(!i)return NodeFilter.FILTER_REJECT;if(i.closest("svg, .select-none, [data-no-diff]"))return NodeFilter.FILTER_REJECT;if(t){for(let c of n)if(c.contains(l))return NodeFilter.FILTER_REJECT}return NodeFilter.FILTER_ACCEPT}}),s;while(s=a.nextNode()){let i=(s.nodeValue||"").match(/\S+|\s+/g);if(!i)continue;let c=0;for(let d of i)o.push(d),r.push({text:d,node:s,offset:c}),c+=d.length}return{words:o,map:r}}function tn(e,t,n){let o=Ri(e,n),r=Ri(t,n);if(o.words.length===0&&r.words.length===0)return!1;let{oldOps:a,newOps:s}=As(o.words,r.words),l=a.some((g)=>g.type==="removed"),i=s.some((g)=>g.type==="added");if(!l&&!i)return!1;let c=[],d=[];for(let g of a)if(g.type==="same")c.push(g.index);for(let g of s)if(g.type==="same")d.push(g.index);let u=new Map;for(let g=0;g<c.length&&g<d.length;g++)u.set(c[g],d[g]);let p=[];{let g=[],k=-1;for(let m of a)if(m.type==="same"){if(g.length>0)p.push({text:g.join(""),anchorNewIdx:k>=0?u.get(k)??null:null}),g=[];k=m.index}else if(m.type==="removed")g.push(o.words[m.index]);if(g.length>0)p.push({text:g.join(""),anchorNewIdx:k>=0?u.get(k)??null:null})}let f=new Map,h=new Map;for(let g of s){if(g.type!=="added")continue;let k=r.map[g.index];if(!k?.node.parentNode)continue;let m=f.get(k.node);if(!m)m=[],f.set(k.node,m);m.push({start:k.offset,end:k.offset+k.text.length})}for(let g of p)if(g.anchorNewIdx===null){if(r.map.length>0){let k=r.map[0].node,m=h.get(k);if(!m)m=[],h.set(k,m);m.push({offset:0,text:g.text})}}else{let k=r.map[g.anchorNewIdx];if(!k)continue;let m=h.get(k.node);if(!m)m=[],h.set(k.node,m);m.push({offset:k.offset+k.text.length,text:g.text})}let x=new Set([...f.keys(),...h.keys()]);for(let g of x)Lu(g,f.get(g)||[],h.get(g)||[]);return!0}function Lu(e,t,n){if(!e.parentNode)return;let o=e.nodeValue||"";t.sort((d,u)=>d.start-u.start);let r=[];for(let d of t){let u=r[r.length-1];if(u&&d.start<=u.end)u.end=Math.max(u.end,d.end);else r.push({...d})}n.sort((d,u)=>d.offset-u.offset);let a=e.parentNode,s=document.createDocumentFragment(),l=0,i=0,c=0;while(l<=o.length){let d=i<r.length?r[i].start:1/0,u=c<n.length?n[c].offset:1/0,p=Math.min(d,u);if(p===1/0){if(l<o.length)s.appendChild(document.createTextNode(o.slice(l)));break}let f=Math.max(p,l);if(f>l)s.appendChild(document.createTextNode(o.slice(l,f))),l=f;while(c<n.length&&n[c].offset<=l){let h=document.createElement("span");h.className="diff-removed",h.textContent=n[c].text,s.appendChild(h),c++}if(i<r.length&&r[i].start<=l){let h=r[i],x=document.createElement("span");x.className="diff-added",x.textContent=o.slice(l,h.end),s.appendChild(x),l=h.end,i++;while(c<n.length&&n[c].offset<=l){let g=document.createElement("span");g.className="diff-removed",g.textContent=n[c].text,s.appendChild(g),c++}}}while(c<n.length){let d=document.createElement("span");d.className="diff-removed",d.textContent=n[c].text,s.appendChild(d),c++}a.replaceChild(s,e)}function Li(e,t){let n=(e.getAttribute("data-md-source")||"").trim(),o=(t.getAttribute("data-md-source")||"").trim();if(n===o)return!1;let r=n.split(`
73
+ `),a=o.split(`
74
+ `),s=$t(r,a),l=[],i=0,c=0,d=0;while(i<r.length||c<a.length)if(d<s.length&&i<r.length&&c<a.length&&r[i]===s[d]&&a[c]===s[d])l.push({type:"same",line:r[i]}),i++,c++,d++;else if(i<r.length&&(d>=s.length||r[i]!==s[d]))l.push({type:"removed",line:r[i]}),i++;else if(c<a.length)l.push({type:"added",line:a[c]}),c++;let u=document.createElement("div");u.className="mt-2 bg-bg-code rounded-md overflow-hidden text-tiny font-mono",u.setAttribute("data-no-diff","true");for(let p of l){let f=document.createElement("div");if(f.className="px-3 py-0.5 whitespace-pre-wrap",p.type==="removed")f.classList.add("diff-removed"),f.textContent="- "+p.line;else if(p.type==="added")f.classList.add("diff-added"),f.textContent="+ "+p.line;else f.textContent=" "+p.line;u.appendChild(f)}return t.appendChild(u),!0}function Ts(e,t,n){let o=document.createElement("span");o.className="diff-block-label",o.textContent=t,o.style.color=n,o.style.backgroundColor=`color-mix(in srgb, ${n} 12%, transparent)`,e.appendChild(o)}import{jsxDEV as q}from"react/jsx-dev-runtime";function Pu(e,t,n){let o=e.find((s)=>s.revision===t),r=e.find((s)=>s.revision===n),a=new Set;for(let s of o?.canvasFiles||[])a.add(s.filename);for(let s of r?.canvasFiles||[])a.add(s.filename);return[...a].sort()}function $i({initialLeft:e,initialRight:t,sessionId:n,onExit:o}){let[r,a]=_e(e),[s,l]=_e(t),[i,c]=_e("unified"),[d,u]=_e(!0),[p,f]=_e(!1),{revisions:h}=Iu(Ve),x=lo(()=>Pu(h,r,s),[h,r,s]),[g,k]=_e(()=>x[0]||"plan.jsx");Ht(()=>{if(!x.includes(g))k(x[0]||"plan.jsx")},[x,g]);let m=lo(()=>h.find((y)=>y.revision===r)?.canvasFiles.some((y)=>y.filename===g)??!1,[h,r,g]),b=lo(()=>h.find((y)=>y.revision===s)?.canvasFiles.some((y)=>y.filename===g)??!1,[h,s,g]);return q("div",{className:"flex flex-col h-screen",children:[q("div",{className:"flex items-center justify-between px-6 py-3 border-b border-border-subtle bg-bg-surface flex-shrink-0",children:[q("div",{className:"flex items-center gap-3",children:[q("span",{className:"text-[13px] font-body font-medium text-text-primary",children:"Compare"},void 0,!1,void 0,this),q(mr,{value:r,onChange:a,accent:"red"},void 0,!1,void 0,this),q("span",{className:"text-text-tertiary text-[13px]",children:"→"},void 0,!1,void 0,this),q(mr,{value:s,onChange:l,accent:"green"},void 0,!1,void 0,this),p&&!d&&q("span",{className:"text-[11px] font-body text-text-tertiary bg-bg-elevated px-2 py-0.5 rounded",children:"No changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q("div",{className:"flex items-center gap-4",children:[q("div",{className:"flex items-center bg-bg-elevated rounded-md p-0.5",children:[q("button",{onClick:()=>c("unified"),className:`text-[11px] font-body px-2.5 py-1 rounded transition-colors ${i==="unified"?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Unified"},void 0,!1,void 0,this),q("button",{onClick:()=>c("side-by-side"),className:`text-[11px] font-body px-2.5 py-1 rounded transition-colors ${i==="side-by-side"?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Side-by-side"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i==="side-by-side"&&q($u,{},void 0,!1,void 0,this),q("button",{onClick:o,className:"text-[12px] font-body font-medium text-text-secondary hover:text-text-primary px-3 py-1.5 rounded-md hover:bg-bg-elevated transition-colors",children:"Exit Compare"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x.length>1&&q("div",{className:"flex items-center gap-1 px-6 py-2 border-b border-border-subtle bg-bg-surface flex-shrink-0 overflow-x-auto",children:x.map((w)=>{let y=w.replace(/\.jsx$/,""),S=w===g,T=h.find((C)=>C.revision===r)?.canvasFiles.some((C)=>C.filename===w),M=h.find((C)=>C.revision===s)?.canvasFiles.some((C)=>C.filename===w),E=!T?" (added)":!M?" (removed)":"";return q("button",{onClick:()=>k(w),className:`text-[12px] font-body px-3 py-1 rounded-md transition-colors whitespace-nowrap ${S?"bg-bg-elevated text-text-primary font-medium":"text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated"}`,children:[y,E&&q("span",{className:`ml-1 text-[10px] ${!T?"text-accent-green":"text-accent-red"}`,children:E},void 0,!1,void 0,this)]},w,!0,void 0,this)})},void 0,!1,void 0,this),!m||!b?q("div",{className:"flex-1 flex items-center justify-center",children:q("div",{className:"text-center text-text-tertiary font-body",children:[q("div",{className:"text-lg mb-2",children:!m?"New file":"Removed file"},void 0,!1,void 0,this),q("div",{className:"text-[13px]",children:[g.replace(/\.jsx$/,"")," ",!m?"was added":"was removed"," in this revision"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this):i==="unified"?q(Hu,{sessionId:n,leftRev:r,rightRev:s,filename:g,onDiffResult:(w,y)=>{f(w),u(y)}},`unified-${r}-${s}-${g}`,!1,void 0,this):q(Ou,{sessionId:n,leftRev:r,rightRev:s,filename:g,onDiffResult:(w,y)=>{f(w),u(y)}},`sbs-${r}-${s}-${g}`,!1,void 0,this)]},void 0,!0,void 0,this)}function $u(){let[e,t]=_e(!0);return Ht(()=>(document.documentElement.dataset.syncScroll=e?"1":"0",()=>{delete document.documentElement.dataset.syncScroll}),[e]),q("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[q("input",{type:"checkbox",checked:e,onChange:(n)=>t(n.target.checked),className:"accent-accent-amber w-3.5 h-3.5"},void 0,!1,void 0,this),q("span",{className:"text-[11px] font-body text-text-secondary",children:"Sync scroll"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Hu({sessionId:e,leftRev:t,rightRev:n,filename:o,onDiffResult:r}){let a=vt(null),s=vt(null),l=vt(null),[i,c]=_e(!1),[d,u]=_e(!1),[p,f]=_e(!1),[h,x]=_e(null),[g,k]=_e(!1),{annotations:m}=it(),b=m.filter((y)=>!y.filePath&&(!y.canvasFile||y.canvasFile===o)),{popovers:w}=_t({containerRef:l,restoreKey:p,restoreAnnotations:b,extractContext:(y)=>At(y,l.current)});return Ht(()=>{if(p||h)return;let y=setTimeout(()=>{console.warn("[unified-diff] still loading after 10s",{leftReady:i,rightReady:d,oldRef:!!a.current,newRef:!!s.current}),k(!0)},1e4);return()=>clearTimeout(y)},[p,h,i,d]),Ht(()=>{if(!i||!d||p)return;if(!a.current||!s.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!a.current||!s.current||!l.current){console.warn("[unified-diff] refs lost between rAF frames",{old:!!a.current,new:!!s.current,unified:!!l.current});return}try{let y=An(a.current),S=An(s.current),T=gr(y,S),{fragment:M,hasChanges:E}=io(T);l.current.innerHTML="",l.current.appendChild(M),f(!0),r(!0,E)}catch(y){console.error("[unified-diff] diff computation failed",y),x(y instanceof Error?y.message:String(y))}})})},[i,d,p]),q("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[!p&&!h&&q("div",{style:{position:"absolute",left:-9999,visibility:"hidden",pointerEvents:"none",width:720},children:[q(yt,{ref:a,sessionId:e,revision:t,filename:o,onReady:()=>c(!0),onError:(y)=>x(`Rev ${t}: ${y}`)},void 0,!1,void 0,this),q(yt,{ref:s,sessionId:e,revision:n,filename:o,onReady:()=>u(!0),onError:(y)=>x(`Rev ${n}: ${y}`)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:[!p&&!h&&q("div",{className:"flex flex-col items-center justify-center h-64 text-text-tertiary font-body text-body gap-2",children:[q("span",{children:"Loading..."},void 0,!1,void 0,this),g&&q("span",{className:"text-[11px]",children:"Taking longer than expected — check Network tab for pending requests"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h&&q("div",{className:"bg-accent-red-muted rounded-lg p-5 mt-8",children:[q("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Failed to load revision"},void 0,!1,void 0,this),q("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:h},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q("div",{ref:l},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w]},void 0,!0,void 0,this)}function Ou({sessionId:e,leftRev:t,rightRev:n,filename:o,onDiffResult:r}){let a=vt(null),s=vt(null),[l,i]=_e(!1),[c,d]=_e(!1),[u,p]=_e(!1),f=vt(null),h=vt(null),x=vt(null),g=vt(!1),k=Pi(()=>i(!0),[]),m=Pi(()=>d(!0),[]),{annotations:b}=it(),w=b.filter((S)=>!S.filePath&&(!S.canvasFile||S.canvasFile===o)),{popovers:y}=_t({containerRef:f,restoreKey:u,restoreAnnotations:w,extractContext:(S)=>At(S,f.current)});return Ht(()=>{if(!l||!c||u)return;if(!a.current||!s.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!a.current||!s.current)return;let S=ao(a.current,s.current);p(!0),r(!0,S)})})},[l,c,u]),Ht(()=>{let S=h.current,T=x.current;if(!S||!T)return;let M=(O,B)=>{if(document.documentElement.dataset.syncScroll==="0")return;if(g.current)return;g.current=!0;let Y=O.scrollHeight-O.clientHeight,me=B.scrollHeight-B.clientHeight;if(Y>0&&me>0)B.scrollTop=O.scrollTop/Y*me;requestAnimationFrame(()=>{g.current=!1})},E=()=>M(S,T),C=()=>M(T,S);return S.addEventListener("scroll",E),T.addEventListener("scroll",C),()=>{S.removeEventListener("scroll",E),T.removeEventListener("scroll",C)}},[]),q("div",{ref:f,className:"flex flex-1 min-h-0",children:[q("div",{ref:h,className:"w-1/2 overflow-y-auto border-r border-border-subtle",children:q("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:q(yt,{ref:a,sessionId:e,revision:t,filename:o,onReady:k},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),q("div",{ref:x,className:"w-1/2 overflow-y-auto",children:q("div",{className:"max-w-[720px] mx-auto px-6 pt-8 pb-32",children:q(yt,{ref:s,sessionId:e,revision:n,filename:o,onReady:m},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),y]},void 0,!0,void 0,this)}var yt=Ii.memo(Ii.forwardRef(({sessionId:e,revision:t,filename:n,onReady:o,onError:r},a)=>{let[s,l]=_e(null),[i,c]=_e(null),[d,u]=_e(!0);Ht(()=>{u(!0),c(null);let f=n.replace(/\.jsx$/,".js");import(`/api/session/${e}/canvas/${encodeURIComponent(f)}?rev=${t}&t=${Date.now()}`).then((h)=>{if(!h.default){c("Module has no default export"),u(!1),r?.("Module has no default export");return}l(()=>h.default),u(!1)}).catch((h)=>{c(h.message),u(!1),r?.(h.message)})},[e,t,n]),Ht(()=>{if(!s)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{o()})})},[s]);let p=lo(()=>s?q(s,{},void 0,!1,void 0,this):null,[s]);if(d)return q("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-body",children:"Loading..."},void 0,!1,void 0,this);if(i)return q("div",{className:"bg-accent-red-muted rounded-lg p-5",children:[q("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Error"},void 0,!1,void 0,this),q("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:i},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(!s)return q("div",{className:"text-text-tertiary text-center py-8 font-body text-body",children:"No canvas loaded"},void 0,!1,void 0,this);return q("div",{ref:a,children:p},void 0,!1,void 0,this)}));function Tn(e){return e instanceof Error&&e.message?e.message:String(e)}var co={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rs:"rust",go:"go",rb:"ruby",java:"java",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",css:"css",html:"html",sh:"bash",bash:"bash",toml:"toml",sql:"sql",xml:"xml",c:"c",cpp:"cpp",h:"c"};function Hi(e){let t=[];return uo(e,t,0),t.join(`
75
75
  `).replace(/\n{3,}/g,`
76
76
 
77
77
  `).trim()+`
78
- `}var S7=new Set(["CODE","SPAN","STRONG","EM","A","B","I","U","SMALL","SUB","SUP","MARK","ABBR"]);function q4($,Q,J){if(w7($)){let Y=T7($);if(Y)Q.push(Y,"");return}for(let Y of $.childNodes)if(Y.nodeType===Node.ELEMENT_NODE)j7(Y,Q,J);else if(Y.nodeType===Node.TEXT_NODE){let q=Y.textContent?.trim();if(q)Q.push(q,"")}}function w7($){for(let Q of $.childNodes){if(Q.nodeType===Node.TEXT_NODE)continue;if(Q.nodeType===Node.ELEMENT_NODE){let J=Q;if(!S7.has(J.tagName)||J.hasAttribute("data-md"))return!1}}return $.childNodes.length>0}function T7($){let Q="";for(let J of $.childNodes)if(J.nodeType===Node.TEXT_NODE)Q+=J.textContent||"";else if(J.nodeType===Node.ELEMENT_NODE){let Y=J;if(Y.tagName==="CODE")Q+="`"+(Y.textContent||"")+"`";else Q+=Y.textContent||""}return Q.trim()}function j7($,Q,J){let Y=$.getAttribute("data-md");if(Y)switch(Y){case"section":return b7($,Q,J);case"item":return Z7($,Q);case"codeblock":return V7($,Q);case"callout":return C7($,Q);case"note":return R7($,Q);case"markdown":return f7($,Q);case"table":return D7($,Q);case"checklist":return I7($,Q);case"diff":return k7($,Q);case"mermaid":return y7($,Q);case"choice":return E7($,Q);case"multichoice":return v7($,Q);case"choice-option":case"multichoice-option":return;case"userinput":return g7($,Q);case"rangeinput":return m7($,Q);case"checklist-item":return;case"filepreview":return x7($,Q);case"priority":return h7($,Q)}if($.querySelector("button, input, select, textarea"))return;if($.children.length>0)q4($,Q,J);else{let q=$.textContent?.trim();if(q)Q.push(q,"")}}function b7($,Q,J){let Y=$.getAttribute("data-md-title")||"Untitled",q=J===0?"##":"###";Q.push(`${q} ${Y}`,"");let G=$.querySelector(":scope > div:last-of-type");if(G)q4(G,Q,J+1)}function Z7($,Q){let J=$.getAttribute("data-md-label")||"",Y=$.getAttribute("data-md-status"),q=$.getAttribute("data-md-badge"),G="-";if(Y==="done")G="- [x]";else if(Y)G="- [ ]";let X=`${G} **${J}**`;if(q)X+=` \`${q}\``;Q.push(X);let W=$.querySelector(".text-text-secondary");if(W){let _=[];q4(W,_,0);for(let H of _)Q.push(H?` ${H}`:"")}Q.push("")}function V7($,Q){let J=$.getAttribute("data-md-language")||"",q=$.querySelector("code")?.textContent||"";Q.push(`\`\`\`${J}`,q,"```","")}function C7($,Q){let J=$.getAttribute("data-md-type")||"info",Y={info:"Info",warning:"Warning",danger:"Danger",tip:"Tip"},q=u7($.querySelector(".text-text-secondary")||$);Q.push(`> **${Y[J]||J}:** ${q}`,"")}function R7($,Q){let J=$.textContent?.trim()||"";Q.push(`> *${J}*`,"")}function D7($,Q){let J=$.querySelector("table");if(!J)return;let Y=[];for(let q of J.querySelectorAll("thead th"))Y.push(q.textContent?.trim()||"");if(Y.length===0)return;Q.push(`| ${Y.join(" | ")} |`),Q.push(`| ${Y.map(()=>"---").join(" | ")} |`);for(let q of J.querySelectorAll("tbody tr")){let G=[];for(let X of q.querySelectorAll("td"))G.push(X.textContent?.trim()||"");Q.push(`| ${G.join(" | ")} |`)}Q.push("")}function I7($,Q){for(let J of $.querySelectorAll("li")){let Y=J.querySelector(".bg-accent-green")!==null,q=J.textContent?.trim()||"";Q.push(`- [${Y?"x":" "}] ${q}`)}Q.push("")}function k7($,Q){let J=$.getAttribute("data-md-language")||"";Q.push(`\`\`\`diff${J?` (${J})`:""}`);for(let Y of $.querySelectorAll("[class*='flex']")){let q=Y.querySelector(".text-accent-red")?"-":Y.querySelector(".text-accent-green")?"+":" ",G=Y.querySelector("code");if(G)Q.push(`${q} ${G.textContent}`)}Q.push("```","")}function y7($,Q){let J=$.getAttribute("data-md-source")||"";if(J)Q.push("```mermaid",J,"```","")}function f7($,Q){let J=$.getAttribute("data-md-source")||"";if(J)Q.push(J,"")}function E7($,Q){let J=$.getAttribute("data-md-label")||"";Q.push(`**${J}:**`);for(let Y of $.querySelectorAll("[data-md='choice-option']")){let q=Y.getAttribute("data-md-label")||Y.textContent?.trim()||"",G=Y.querySelector(".bg-accent-amber")!==null;Q.push(`- ${G?"(x)":"( )"} ${q}`)}Q.push("")}function v7($,Q){let J=$.getAttribute("data-md-label")||"";Q.push(`**${J}:**`);for(let Y of $.querySelectorAll("[data-md='multichoice-option']")){let q=Y.getAttribute("data-md-label")||Y.textContent?.trim()||"",G=Y.querySelector(".bg-accent-amber")!==null;Q.push(`- [${G?"x":" "}] ${q}`)}Q.push("")}function g7($,Q){let J=$.getAttribute("data-md-label")||"",q=$.querySelector("textarea")?.value?.trim()||"";Q.push(`**${J}:** ${q||"_empty_"}`,"")}function m7($,Q){let J=$.getAttribute("data-md-label")||"",Y=$.querySelector("input[type='range']"),G=$.querySelector(".font-mono")?.textContent?.trim()||Y?.value||"—";Q.push(`**${J}:** ${G}`,"")}function x7($,Q){let J=$.getAttribute("data-md-path")||"",Y=$.getAttribute("data-md-lines")||"",G=$.querySelector("code")?.textContent||"",X=J.split(".").pop()||"",W=J4[X]||"",_=Y?`${J} (L${Y})`:J;Q.push(_,"",`\`\`\`${W}`,G,"```","")}function h7($,Q){}function u7($){return $?.textContent?.trim()||""}import{SessionContext as p7}from"#canvas/runtime";import{useContext as I6,useEffect as c7,useMemo as l7,useState as k6}from"react";import{jsxDEV as s,Fragment as O3}from"react/jsx-dev-runtime";function y6({embedded:$}={}){if(!O1)return s("div",{className:$?"px-4 py-3":"p-4",children:[s("div",{className:"text-[11px] uppercase tracking-widest text-text-tertiary font-body mb-2",children:"Files"},void 0,!1,void 0,this),s("p",{className:"text-[11px] text-text-tertiary font-body leading-relaxed",children:"File browsing is not available in shared view. File previews embedded in the canvas still work."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return s(d7,{embedded:$},void 0,!1,void 0,this)}function d7({embedded:$}){let Q=I6(p7),{annotations:J,addAnnotation:Y}=G1(),{setActiveView:q}=I6(q1),[G,X]=k6(!1),[W,_]=k6({}),{annCountMap:H,annotatedFiles:U}=l7(()=>{let z=new Map;for(let A of J)if(A.filePath&&A.filePath!==g$)z.set(A.filePath,(z.get(A.filePath)||0)+1);return{annCountMap:z,annotatedFiles:[...z.keys()]}},[J]),K=async(z)=>{let A=await fetch(`/api/tree?session=${Q}&path=${encodeURIComponent(z)}`),T=_3.safeParse(await A.json());if(T.success)_((S)=>({...S,[z]:{entries:T.data.entries,expanded:!0,loaded:!0}}))};c7(()=>{if(!G&&!W[""])K("")},[G]);let N=(z)=>{if(W[z]?.loaded)_((A)=>({...A,[z]:{...A[z],expanded:!A[z].expanded}}));else K(z)},O=(z)=>{q({type:"file",path:z})},M=async(z)=>{let A=await fetch(`/api/file?session=${Q}&path=${encodeURIComponent(z)}`),T=D1.safeParse(await A.json());if(T.success&&"content"in T.data){let{content:S}=T.data,j=S.split(`
78
+ `}var Du=new Set(["CODE","SPAN","STRONG","EM","A","B","I","U","SMALL","SUB","SUP","MARK","ABBR"]);function uo(e,t,n){if(ju(e)){let o=Fu(e);if(o)t.push(o,"");return}for(let o of e.childNodes)if(o.nodeType===Node.ELEMENT_NODE)Bu(o,t,n);else if(o.nodeType===Node.TEXT_NODE){let r=o.textContent?.trim();if(r)t.push(r,"")}}function ju(e){for(let t of e.childNodes){if(t.nodeType===Node.TEXT_NODE)continue;if(t.nodeType===Node.ELEMENT_NODE){let n=t;if(!Du.has(n.tagName)||n.hasAttribute("data-md"))return!1}}return e.childNodes.length>0}function Fu(e){let t="";for(let n of e.childNodes)if(n.nodeType===Node.TEXT_NODE)t+=n.textContent||"";else if(n.nodeType===Node.ELEMENT_NODE){let o=n;if(o.tagName==="CODE")t+="`"+(o.textContent||"")+"`";else t+=o.textContent||""}return t.trim()}function Bu(e,t,n){let o=e.getAttribute("data-md");if(o)switch(o){case"section":return zu(e,t,n);case"item":return qu(e,t);case"codeblock":return Vu(e,t);case"callout":return Uu(e,t);case"note":return Wu(e,t);case"markdown":return Xu(e,t);case"table":return Gu(e,t);case"checklist":return Ku(e,t);case"diff":return Ju(e,t);case"mermaid":return Yu(e,t);case"choice":return Qu(e,t);case"multichoice":return Zu(e,t);case"choice-option":case"multichoice-option":return;case"userinput":return ep(e,t);case"rangeinput":return tp(e,t);case"checklist-item":return;case"filepreview":return np(e,t);case"priority":return rp(e,t)}if(e.querySelector("button, input, select, textarea"))return;if(e.children.length>0)uo(e,t,n);else{let r=e.textContent?.trim();if(r)t.push(r,"")}}function zu(e,t,n){let o=e.getAttribute("data-md-title")||"Untitled",r=n===0?"##":"###";t.push(`${r} ${o}`,"");let a=e.querySelector(":scope > div:last-of-type");if(a)uo(a,t,n+1)}function qu(e,t){let n=e.getAttribute("data-md-label")||"",o=e.getAttribute("data-md-status"),r=e.getAttribute("data-md-badge"),a="-";if(o==="done")a="- [x]";else if(o)a="- [ ]";let s=`${a} **${n}**`;if(r)s+=` \`${r}\``;t.push(s);let l=e.querySelector(".text-text-secondary");if(l){let i=[];uo(l,i,0);for(let c of i)t.push(c?` ${c}`:"")}t.push("")}function Vu(e,t){let n=e.getAttribute("data-md-language")||"",r=e.querySelector("code")?.textContent||"";t.push(`\`\`\`${n}`,r,"```","")}function Uu(e,t){let n=e.getAttribute("data-md-type")||"info",o={info:"Info",warning:"Warning",danger:"Danger",tip:"Tip"},r=op(e.querySelector(".text-text-secondary")||e);t.push(`> **${o[n]||n}:** ${r}`,"")}function Wu(e,t){let n=e.textContent?.trim()||"";t.push(`> *${n}*`,"")}function Gu(e,t){let n=e.querySelector("table");if(!n)return;let o=[];for(let r of n.querySelectorAll("thead th"))o.push(r.textContent?.trim()||"");if(o.length===0)return;t.push(`| ${o.join(" | ")} |`),t.push(`| ${o.map(()=>"---").join(" | ")} |`);for(let r of n.querySelectorAll("tbody tr")){let a=[];for(let s of r.querySelectorAll("td"))a.push(s.textContent?.trim()||"");t.push(`| ${a.join(" | ")} |`)}t.push("")}function Ku(e,t){for(let n of e.querySelectorAll("li")){let o=n.querySelector(".bg-accent-green")!==null,r=n.textContent?.trim()||"";t.push(`- [${o?"x":" "}] ${r}`)}t.push("")}function Ju(e,t){let n=e.getAttribute("data-md-language")||"";t.push(`\`\`\`diff${n?` (${n})`:""}`);for(let o of e.querySelectorAll("[class*='flex']")){let r=o.querySelector(".text-accent-red")?"-":o.querySelector(".text-accent-green")?"+":" ",a=o.querySelector("code");if(a)t.push(`${r} ${a.textContent}`)}t.push("```","")}function Yu(e,t){let n=e.getAttribute("data-md-source")||"";if(n)t.push("```mermaid",n,"```","")}function Xu(e,t){let n=e.getAttribute("data-md-source")||"";if(n)t.push(n,"")}function Qu(e,t){let n=e.getAttribute("data-md-label")||"";t.push(`**${n}:**`);for(let o of e.querySelectorAll("[data-md='choice-option']")){let r=o.getAttribute("data-md-label")||o.textContent?.trim()||"",a=o.querySelector(".bg-accent-amber")!==null;t.push(`- ${a?"(x)":"( )"} ${r}`)}t.push("")}function Zu(e,t){let n=e.getAttribute("data-md-label")||"";t.push(`**${n}:**`);for(let o of e.querySelectorAll("[data-md='multichoice-option']")){let r=o.getAttribute("data-md-label")||o.textContent?.trim()||"",a=o.querySelector(".bg-accent-amber")!==null;t.push(`- [${a?"x":" "}] ${r}`)}t.push("")}function ep(e,t){let n=e.getAttribute("data-md-label")||"",r=e.querySelector("textarea")?.value?.trim()||"";t.push(`**${n}:** ${r||"_empty_"}`,"")}function tp(e,t){let n=e.getAttribute("data-md-label")||"",o=e.querySelector("input[type='range']"),a=e.querySelector(".font-mono")?.textContent?.trim()||o?.value||"—";t.push(`**${n}:** ${a}`,"")}function np(e,t){let n=e.getAttribute("data-md-path")||"",o=e.getAttribute("data-md-lines")||"",a=e.querySelector("code")?.textContent||"",s=n.split(".").pop()||"",l=co[s]||"",i=o?`${n} (L${o})`:n;t.push(i,"",`\`\`\`${l}`,a,"```","")}function rp(e,t){}function op(e){return e?.textContent?.trim()||""}import{SessionContext as sp}from"#canvas/runtime";import{useContext as Oi,useEffect as ap,useMemo as ip,useState as Di}from"react";import{jsxDEV as Z,Fragment as Es}from"react/jsx-dev-runtime";function ji({embedded:e}={}){if(!bt)return Z("div",{className:e?"px-4 py-3":"p-4",children:[Z("div",{className:"text-[11px] uppercase tracking-widest text-text-tertiary font-body mb-2",children:"Files"},void 0,!1,void 0,this),Z("p",{className:"text-[11px] text-text-tertiary font-body leading-relaxed",children:"File browsing is not available in shared view. File previews embedded in the canvas still work."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return Z(lp,{embedded:e},void 0,!1,void 0,this)}function lp({embedded:e}){let t=Oi(sp),{annotations:n,addAnnotation:o}=it(),{setActiveView:r}=Oi(ot),[a,s]=Di(!1),[l,i]=Di({}),{annCountMap:c,annotatedFiles:d}=ip(()=>{let m=new Map;for(let b of n)if(b.filePath&&b.filePath!==Be)m.set(b.filePath,(m.get(b.filePath)||0)+1);return{annCountMap:m,annotatedFiles:[...m.keys()]}},[n]),u=async(m)=>{let b=await fetch(`/api/tree?session=${t}&path=${encodeURIComponent(m)}`),w=vs.safeParse(await b.json());if(w.success)i((y)=>({...y,[m]:{entries:w.data.entries,expanded:!0,loaded:!0}}))};ap(()=>{if(!a&&!l[""])u("")},[a]);let p=(m)=>{if(l[m]?.loaded)i((b)=>({...b,[m]:{...b[m],expanded:!b[m].expanded}}));else u(m)},f=(m)=>{r({type:"file",path:m})},h=async(m)=>{let b=await fetch(`/api/file?session=${t}&path=${encodeURIComponent(m)}`),w=Mt.safeParse(await b.json());if(w.success&&"content"in w.data){let{content:y}=w.data,S=y.split(`
79
79
  `).slice(0,3).join(`
80
- `)+(S.split(`
80
+ `)+(y.split(`
81
81
  `).length>3?`
82
- ...`:"");Y(j,"Include this file for context",z)}},L=async(z)=>{let A=[];if(W[z]?.loaded)A=W[z].entries;else{let T=await fetch(`/api/tree?session=${Q}&path=${encodeURIComponent(z)}`),S=_3.safeParse(await T.json());if(S.success)A=S.data.entries}await Promise.all(A.filter((T)=>T.type==="file").map((T)=>M(z?`${z}/${T.name}`:T.name)))},F=(z)=>H.get(z)||0,w=(z,A=0)=>{let T=W[z];if(!T?.expanded)return null;return T.entries.map((S)=>{let j=z?`${z}/${S.name}`:S.name,Z=F(j);return s("div",{children:[s("div",{className:"group/item flex items-center py-[3px] hover:bg-bg-elevated text-[13px] font-body cursor-default transition-colors duration-100",style:{paddingLeft:`${16+A*16}px`,paddingRight:"8px"},children:S.type==="dir"?s(O3,{children:[s("span",{onClick:()=>N(j),className:"flex items-center gap-1.5 flex-1 text-text-secondary hover:text-text-primary cursor-pointer truncate",children:[s(I1,{name:S.name,type:"dir",expanded:W[j]?.expanded},void 0,!1,void 0,this),s("span",{className:"truncate",children:S.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s("button",{onClick:(y)=>{y.stopPropagation(),L(j)},className:"text-[11px] text-text-tertiary hover:text-text-secondary opacity-0 group-hover/item:opacity-100 transition-opacity px-1 flex-shrink-0",title:"Add all files in folder",children:"+"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):s(O3,{children:[s("span",{onClick:()=>O(j),className:`flex-1 truncate cursor-pointer flex items-center gap-1.5 ${Z>0?"text-text-primary":"text-text-secondary hover:text-text-primary"}`,children:[s(I1,{name:S.name,type:"file"},void 0,!1,void 0,this),s("span",{className:"truncate",children:S.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s("div",{className:"flex items-center gap-1 flex-shrink-0 ml-1",children:[Z>0&&s("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center",children:Z},void 0,!1,void 0,this),s("button",{onClick:(y)=>{y.stopPropagation(),M(j)},className:"text-[11px] text-text-tertiary hover:text-text-secondary opacity-0 group-hover/item:opacity-100 transition-opacity px-1",title:"Add file to context",children:"+"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),S.type==="dir"&&w(j,A+1)]},j,!0,void 0,this)})};if($)return s(O3,{children:[s("div",{className:"flex items-center justify-between px-4 pt-3 pb-2 flex-shrink-0",children:s("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Files"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s("div",{className:"flex-1 overflow-y-auto",children:w("")},void 0,!1,void 0,this),U.length>0&&s("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:[s("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body mb-1.5",children:"Referenced"},void 0,!1,void 0,this),U.map((z)=>s("div",{onClick:()=>O(z),className:"flex items-center justify-between text-[12px] font-body text-text-secondary hover:text-text-primary cursor-pointer py-0.5",children:[s("span",{className:"truncate",children:z.split("/").pop()},void 0,!1,void 0,this),s("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center flex-shrink-0 ml-1",children:F(z)},void 0,!1,void 0,this)]},z,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(G)return s("div",{className:"hidden lg:flex w-8 border-r border-border-subtle bg-bg-surface flex-col items-center flex-shrink-0",children:s("button",{onClick:()=>X(!1),className:"mt-3 p-1 text-text-tertiary hover:text-text-secondary transition-colors",children:s("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:s("path",{d:"M5 3l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);return s("div",{className:"hidden lg:flex w-60 border-r border-border-subtle bg-bg-surface flex-col flex-shrink-0 overflow-hidden",children:[s("div",{className:"flex items-center justify-between px-4 pt-4 pb-3 flex-shrink-0",children:[s("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Files"},void 0,!1,void 0,this),s("button",{onClick:()=>X(!0),className:"text-text-tertiary hover:text-text-secondary transition-colors p-0.5",children:s("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:s("path",{d:"M9 3l-4 4 4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s("div",{className:"flex-1 overflow-y-auto",children:w("")},void 0,!1,void 0,this),U.length>0&&s("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:[s("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body mb-1.5",children:"Referenced"},void 0,!1,void 0,this),U.map((z)=>s("div",{onClick:()=>O(z),className:"flex items-center justify-between text-[12px] font-body text-text-secondary hover:text-text-primary cursor-pointer py-0.5",children:[s("span",{className:"truncate",children:z.split("/").pop()},void 0,!1,void 0,this),s("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center flex-shrink-0 ml-1",children:F(z)},void 0,!1,void 0,this)]},z,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{SessionContext as r7}from"#canvas/runtime";import{useCallback as i7,useContext as o7,useEffect as f6,useMemo as E6,useRef as Y4,useState as M2}from"react";import{jsxDEV as D$}from"react/jsx-dev-runtime";function v6($){let Q=$ instanceof HTMLElement?$:$.parentElement;while(Q){if(Q.hasAttribute("data-line-num"))return Q;Q=Q.parentElement}return null}function a7($){let Q=$.toString().trim(),J=v6($.startContainer),Y=v6($.endContainer),q=J?parseInt(J.getAttribute("data-line-num"),10):void 0,G=Y?parseInt(Y.getAttribute("data-line-num"),10):void 0,X="",W="";if(Q.length<30&&J&&J===Y){let _=J.querySelector("code");if(_){let H=_.textContent||"",U=H.indexOf(Q);if(U>=0)X=H.slice(0,U).trimStart(),W=H.slice(U+Q.length).trimEnd()}}return{before:X,after:W,hierarchy:[],lineStart:q,lineEnd:G}}function n7({html:$}){return D$("code",{className:"py-px",dangerouslySetInnerHTML:{__html:$}},void 0,!1,void 0,this)}function g6({path:$}){if(!O1)return D$("div",{className:"max-w-[720px] mx-auto px-6 pt-12 pb-32",children:D$("div",{className:"p-4 rounded-lg border border-border-subtle bg-bg-surface",children:[D$("div",{className:"text-[11px] uppercase tracking-widest text-text-tertiary font-body mb-2",children:"File not available"},void 0,!1,void 0,this),D$("p",{className:"text-[13px] text-text-secondary font-body leading-relaxed",children:["Opening ",D$("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:$},void 0,!1,void 0,this)," ","requires filesystem access, which isn't available in shared view. If the canvas author wanted this file visible, they should embed it as a"," ",D$("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"<FilePreview>"},void 0,!1,void 0,this)," in the canvas."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this);return D$(s7,{path:$},void 0,!1,void 0,this)}function s7({path:$}){let Q=o7(r7),{annotations:J}=G1(),[Y,q]=M2(null),[G,X]=M2(!0),[W,_]=M2(null),H=Y4(null),[U,K]=M2(null),[N,O]=M2(null),M=Y4(null),L=Y4(null),F=Y4([]),w=J.filter((V)=>V.filePath===$),z=H.current?.closest("#plan-scroll-container"),{popovers:A,openCreatePopover:T}=R1({containerRef:H,restoreKey:`${Y}:${$}`,restoreAnnotations:w,extractContext:a7,filePath:$,scrollContainer:z});f6(()=>{X(!0),_(null),fetch(`/api/file?session=${Q}&path=${encodeURIComponent($)}`).then((V)=>V.json()).then((V)=>{let C=D1.parse(V);if("error"in C)_(C.error),X(!1);else q(C.content),X(!1)}).catch(()=>{_("Failed to fetch file"),X(!1)})},[Q,$]);let S=i7((V,C)=>{V.preventDefault(),M.current=C,L.current=C,K(C),O(C)},[]);f6(()=>{let V=(v)=>{if(M.current===null)return;let h=v.target.closest("[data-line-num]");if(h){let o=parseInt(h.getAttribute("data-line-num"),10);L.current=o,O(o)}},C=()=>{let v=M.current;if(v===null)return;M.current=null;let h=L.current??v,o=Math.min(v,h),B$=Math.max(v,h),U$=F.current.slice(o-1,B$).join(`
83
- `);if(!U$.trim()){K(null),O(null);return}let Y$=`__pending_${Date.now()}`,N$={before:"",after:"",hierarchy:[],lineStart:o,lineEnd:B$};if(H.current){let Q$=H.current.querySelectorAll("[data-line-num]"),_$=Q$[o-1],F$=Q$[B$-1];if(_$&&F$){let d=_$.querySelector("code"),X$=F$.querySelector("code");if(d&&X$)try{let g=document.createRange();g.setStartBefore(d.firstChild||d),g.setEndAfter(X$.lastChild||X$),A1(g,Y$)}catch{}}let n=Q$[B$-1];if(n)T(n,Y$,U$,N$)}K(null),O(null)};return document.addEventListener("mousemove",V),document.addEventListener("mouseup",C),()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",C)}},[]);let j=E6(()=>{if(!Y)return null;let V=W2();if(!V)return null;let C=$.split(".").pop()||"",v=J4[C];try{return(v?V.highlight(Y,{language:v}):V.highlightAuto(Y)).value.split(`
84
- `)}catch{return null}},[Y,$]),Z=E6(()=>{if(U===null)return null;let V=N??U;return{start:Math.min(U,V),end:Math.max(U,V)}},[U,N]);if(G)return D$("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-[13px]",children:["Loading ",$,"..."]},void 0,!0,void 0,this);if(W)return D$("div",{className:"p-8 text-accent-red font-body text-[13px]",children:W},void 0,!1,void 0,this);if(!Y)return null;let y=Y.split(`
85
- `);return F.current=y,D$("div",{children:[D$("pre",{ref:H,className:"text-code font-mono text-text-code bg-bg-base select-text cursor-text py-3 hljs",children:y.map((V,C)=>{let v=C+1,h=Z&&v>=Z.start&&v<=Z.end;return D$("div",{"data-line-num":v,className:`flex px-5 ${h?"bg-accent-blue/10":"hover:bg-bg-elevated-half"}`,children:[D$("span",{className:"text-text-tertiary select-none w-10 text-right pr-4 shrink-0 py-px text-[12px] cursor-pointer opacity-40 hover:opacity-100 hover:text-accent-blue",onMouseDown:(o)=>S(o,v),children:v},void 0,!1,void 0,this),j?D$(n7,{html:j[C]||" "},void 0,!1,void 0,this):D$("code",{className:"py-px",children:V||" "},void 0,!1,void 0,this)]},C,!0,void 0,this)})},void 0,!1,void 0,this),A]},void 0,!0,void 0,this)}import{SessionContext as t7}from"#canvas/runtime";import{useCallback as m6,useContext as z3,useEffect as x6,useMemo as e7,useRef as F2,useState as F1}from"react";import{jsxDEV as i}from"react/jsx-dev-runtime";function M3($,Q){if(!$)return[];return $.canvasFiles.map((J)=>{if(!J.diffStats)return{filename:J.filename,status:"new"};if(J.diffStats.added===0&&J.diffStats.removed===0)return{filename:J.filename,status:"unchanged",diffStats:J.diffStats};return{filename:J.filename,status:"changed",diffStats:J.diffStats}})}function h6($){return $.filter((Q)=>Q.status!=="unchanged").map((Q)=>Q.filename)}function u6({revision:$,responseBanner:Q}){let{setActiveView:J}=z3(q1),{revisions:Y}=z3(h$),q=Y.find((H)=>H.revision===$),G=Y.find((H)=>H.revision===$-1),X=e7(()=>M3(q,G),[q,G]),W=X.filter((H)=>H.status!=="unchanged"),_=X.filter((H)=>H.status==="unchanged");return i("div",{className:"max-w-[720px] mx-auto px-6 pt-12 pb-32",children:[Q,W.map((H)=>i(Qq,{change:H,revision:$,previousRevision:G?.revision,onOpenTab:()=>J({type:"canvas",filename:H.filename})},H.filename,!1,void 0,this)),_.length>0&&i("div",{className:"mt-8 border-t border-border-subtle pt-4",children:[i("div",{className:"text-[11px] font-body font-medium uppercase tracking-widest text-text-tertiary mb-3",children:"Unchanged"},void 0,!1,void 0,this),_.map((H)=>i(Xq,{change:H,revision:$,onOpenTab:()=>J({type:"canvas",filename:H.filename})},H.filename,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function $q({mode:$,onChange:Q,showDiff:J}){if(!J)return null;return i("div",{className:"flex items-center bg-bg-elevated rounded-md p-0.5",children:["rendered","unified","side-by-side"].map((Y)=>i("button",{onClick:()=>Q(Y),className:`text-[10px] font-body px-2 py-0.5 rounded transition-colors ${$===Y?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:Y==="rendered"?"Full":Y==="unified"?"Unified":"Split"},Y,!1,void 0,this))},void 0,!1,void 0,this)}function Qq({change:$,revision:Q,previousRevision:J,onOpenTab:Y}){let q=$.filename.replace(/\.jsx$/,""),G=$.status==="new",X=$.diffStats,W=$.status==="changed"&&J!=null,[_,H]=F1("rendered");return i("div",{className:"mb-8",children:[i("div",{className:"flex items-center gap-2 mb-3 pb-2 border-b border-border-subtle",children:[i("span",{className:`text-[11px] font-mono px-1.5 py-0.5 rounded ${G?"bg-accent-green/10 text-accent-green border border-accent-green/20":"bg-accent-amber/10 text-accent-amber border border-accent-amber/20"}`,children:G?"new":"modified"},void 0,!1,void 0,this),i("span",{className:"text-[14px] font-body font-medium text-text-primary",children:q},void 0,!1,void 0,this),X&&(X.added>0||X.removed>0)&&i("span",{className:"text-[11px] font-mono text-text-tertiary",children:[i("span",{className:"text-accent-green",children:["+",X.added]},void 0,!0,void 0,this)," ",i("span",{className:"text-accent-red",children:["-",X.removed]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i($q,{mode:_,onChange:H,showDiff:W},void 0,!1,void 0,this),i("button",{onClick:Y,className:`${W?"":"ml-auto"} text-[11px] font-body font-medium text-accent-blue hover:text-accent-blue/80 transition-colors`,children:"Open in tab"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_==="rendered"?i("div",{"data-canvas-file":$.filename,children:i(R0,{revision:Q,filename:$.filename},void 0,!1,void 0,this)},void 0,!1,void 0,this):W&&J!=null?i(Jq,{filename:$.filename,leftRev:J,rightRev:Q,mode:_},`${_}-${Q}-${J}`,!1,void 0,this):null]},void 0,!0,void 0,this)}function Jq({filename:$,leftRev:Q,rightRev:J,mode:Y}){let q=z3(t7);if(Y==="unified")return i(qq,{sessionId:q,filename:$,leftRev:Q,rightRev:J},void 0,!1,void 0,this);return i(Yq,{sessionId:q,filename:$,leftRev:Q,rightRev:J},void 0,!1,void 0,this)}function qq({sessionId:$,filename:Q,leftRev:J,rightRev:Y}){let q=F2(null),G=F2(null),X=F2(null),[W,_]=F1(!1),[H,U]=F1(!1),[K,N]=F1(!1),[O,M]=F1(null);return x6(()=>{if(!W||!H||K)return;if(!q.current||!G.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!q.current||!G.current||!X.current)return;try{let L=D0(q.current),F=D0(G.current),w=z2(L,F),{fragment:z}=$4(w);X.current.innerHTML="",X.current.appendChild(z),N(!0)}catch(L){M(L instanceof Error?L.message:String(L))}})})},[W,H,K]),i("div",{children:[!K&&!O&&i("div",{style:{position:"absolute",left:-9999,visibility:"hidden",pointerEvents:"none",width:720},children:[i(M1,{ref:q,sessionId:$,revision:J,filename:Q,onReady:()=>_(!0),onError:(L)=>M(L)},void 0,!1,void 0,this),i(M1,{ref:G,sessionId:$,revision:Y,filename:Q,onReady:()=>U(!0),onError:(L)=>M(L)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!K&&!O&&i("div",{className:"flex items-center justify-center h-24 text-text-tertiary font-body text-[13px]",children:"Computing diff..."},void 0,!1,void 0,this),O&&i("div",{className:"text-accent-red text-[13px] font-body p-3 bg-accent-red-muted rounded-lg",children:O},void 0,!1,void 0,this),i("div",{ref:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Yq({sessionId:$,filename:Q,leftRev:J,rightRev:Y}){let q=F2(null),G=F2(null),[X,W]=F1(!1),[_,H]=F1(!1),[U,K]=F1(!1),N=m6(()=>W(!0),[]),O=m6(()=>H(!0),[]);return x6(()=>{if(!X||!_||U)return;if(!q.current||!G.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!q.current||!G.current)return;e2(q.current,G.current),K(!0)})})},[X,_,U]),i("div",{className:"flex gap-0 border-y border-border-subtle overflow-hidden w-screen relative left-1/2 -translate-x-1/2",children:[i("div",{className:"w-1/2 border-r border-border-subtle",children:[i("div",{className:"px-2 py-1 text-[10px] font-body font-medium text-text-tertiary bg-bg-elevated border-b border-border-subtle",children:["Rev ",J]},void 0,!0,void 0,this),i("div",{className:"px-6 py-4 max-w-[600px] mx-auto",children:i(M1,{ref:q,sessionId:$,revision:J,filename:Q,onReady:N},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{className:"w-1/2",children:[i("div",{className:"px-2 py-1 text-[10px] font-body font-medium text-text-tertiary bg-bg-elevated border-b border-border-subtle",children:["Rev ",Y]},void 0,!0,void 0,this),i("div",{className:"px-6 py-4 max-w-[600px] mx-auto",children:i(M1,{ref:G,sessionId:$,revision:Y,filename:Q,onReady:O},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Xq({change:$,revision:Q,onOpenTab:J}){let[Y,q]=F1(!1),G=$.filename.replace(/\.jsx$/,"");return i("div",{className:"mb-2",children:[i("div",{className:"flex items-center gap-2 py-1.5",children:[i("button",{onClick:()=>q(!Y),className:"text-text-tertiary hover:text-text-secondary transition-colors",children:i("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform duration-150 ${Y?"rotate-90":""}`,children:i("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{className:"text-[13px] font-body text-text-secondary",children:G},void 0,!1,void 0,this),i("button",{onClick:J,className:"ml-auto text-[11px] font-body text-text-tertiary hover:text-accent-blue transition-colors",children:"Open in tab"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y&&i("div",{className:"ml-5 mt-1 mb-3","data-canvas-file":$.filename,children:i(R0,{revision:Q,filename:$.filename},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useEffect as Gq,useRef as _q,useState as Wq}from"react";import{jsxDEV as a$}from"react/jsx-dev-runtime";function p6({open:$,onClose:Q,onSubmit:J}){let[Y,q]=Wq(""),G=_q(null);if(Gq(()=>{if($)q(""),setTimeout(()=>G.current?.focus(),50)},[$]),!$)return null;let X=Y.trim(),W=X.length>=1&&X.length<=80,_=()=>{if(!W)return;J(X)};return a$("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:Q,children:a$("div",{className:"bg-bg-surface border border-border-medium rounded-lg shadow-xl w-full max-w-md mx-4 p-5",onClick:(H)=>H.stopPropagation(),children:[a$("div",{className:"flex items-center justify-between mb-3",children:[a$("h2",{className:"text-sm font-medium text-text-primary font-body",children:"Your name"},void 0,!1,void 0,this),a$("button",{onClick:Q,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:a$("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a$("p",{className:"text-[13px] text-text-secondary font-body mb-3 leading-relaxed",children:"Before you leave feedback, please enter a name so the canvas author knows who reviewed it. This is stored locally in your browser."},void 0,!1,void 0,this),a$("input",{ref:G,type:"text",value:Y,onChange:(H)=>q(H.target.value),onKeyDown:(H)=>{if(H.key==="Enter")_()},maxLength:80,placeholder:"e.g. Alice",className:"w-full px-3 py-2 text-[13px] font-body bg-bg-input border border-border-medium rounded text-text-primary placeholder:text-text-disabled focus:outline-none focus:border-accent-blue"},void 0,!1,void 0,this),a$("div",{className:"flex justify-end gap-2 mt-4",children:[a$("button",{onClick:Q,className:"px-3 py-1.5 text-[12px] font-body font-medium rounded text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors",children:"Cancel"},void 0,!1,void 0,this),a$("button",{onClick:_,disabled:!W,className:"px-3 py-1.5 text-[12px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity disabled:opacity-50",children:"Submit feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{useEffect as c6,useRef as Hq,useState as l6}from"react";import{jsxDEV as _1}from"react/jsx-dev-runtime";function d6($,Q){if(Q){let J=Q.replace(/\/+$/,"").split("/");return J[J.length-1]||$}return $.length>30?$.slice(0,30)+"...":$}function F3({currentSessionId:$,projectRoot:Q}){let[J,Y]=l6([]),[q,G]=l6(!1),X=Hq(null);c6(()=>{if(!O1)return;let H=async()=>{try{let N=await(await fetch("/api/sessions")).json();Y((O)=>{let M=JSON.stringify(N);return JSON.stringify(O)===M?O:N})}catch{}};H();let U=setInterval(H,5000);return()=>clearInterval(U)},[]),c6(()=>{if(!q)return;let H=(U)=>{if(X.current&&!X.current.contains(U.target))G(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[q]);let W=J.filter((H)=>H.id!==$),_=d6($,Q);return _1("div",{className:"relative",ref:X,children:[_1("div",{className:"flex items-center gap-1.5 font-body text-body font-medium",children:[_1("a",{href:`/s/${$}`,className:"text-text-primary hover:text-text-secondary transition-colors",children:_},void 0,!1,void 0,this),W.length>0&&_1("button",{onClick:()=>G(!q),className:"flex items-center justify-center text-text-tertiary hover:text-text-secondary transition-colors",children:_1("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:`transition-transform duration-200 ${q?"rotate-180":""}`,children:_1("path",{d:"M3 5l3 3 3-3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q&&W.length>0&&_1("div",{className:"absolute top-full left-0 mt-2 w-64 bg-bg-elevated border border-border-hover rounded-lg shadow-lg z-50 py-1 overflow-hidden",children:W.map((H)=>_1("a",{href:`/s/${H.id}`,className:"flex items-center gap-2.5 px-4 py-2.5 text-body font-body text-text-secondary hover:bg-bg-surface hover:text-text-primary transition-colors",children:[_1("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${H.currentRevision>0?"bg-accent-green":"bg-border-hover"}`},void 0,!1,void 0,this),_1("span",{className:"truncate",children:d6(H.id,H.projectRoot)},void 0,!1,void 0,this)]},H.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as L3,useEffect as Uq,useState as X4}from"react";import{jsxDEV as G$}from"react/jsx-dev-runtime";function r6({sessionId:$,revision:Q,open:J,shareEnabled:Y,existingShares:q,onClose:G,onShareCreated:X,onShareRevoked:W}){let[_,H]=X4(!1),[U,K]=X4(!1),[N,O]=X4(null),[M,L]=X4(!1),F=q.find((T)=>T.revision===Q);Uq(()=>{if(!J)H(!1),K(!1),O(null),L(!1)},[J]);let w=L3(async()=>{H(!0),O(null);try{let T=await fetch(`/api/session/${$}/revision/${Q}/share`,{method:"POST"}),S=n5.parse(await T.json());if(!S.ok)throw Error(S.error||`HTTP ${T.status}`);if(!T.ok)throw Error(`HTTP ${T.status}`);X(S.share)}catch(T){O(I0(T))}finally{H(!1)}},[$,Q,X]),z=L3(async(T)=>{if(!window.confirm("Revoke this share link? Reviewers will no longer be able to view or comment."))return;K(!0),O(null);try{let S=await fetch(`/api/session/${$}/shares/${T}/revoke`,{method:"POST"}),j=s5.parse(await S.json());if(!j.ok)throw Error(j.error||`HTTP ${S.status}`);if(!S.ok)throw Error(`HTTP ${S.status}`);W(T)}catch(S){O(I0(S))}finally{K(!1)}},[$,W]),A=L3((T)=>{navigator.clipboard.writeText(T).then(()=>{L(!0),setTimeout(()=>L(!1),1500)})},[]);if(!J)return null;return G$("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:G,children:G$("div",{className:"bg-bg-surface border border-border-medium rounded-lg shadow-xl w-full max-w-md mx-4 p-5",onClick:(T)=>T.stopPropagation(),children:[G$("div",{className:"flex items-center justify-between mb-3",children:[G$("h2",{className:"text-sm font-medium text-text-primary font-body",children:"Share this revision"},void 0,!1,void 0,this),G$("button",{onClick:G,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:G$("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!Y?G$("div",{className:"text-[13px] text-text-secondary font-body space-y-2",children:[G$("p",{children:"Canvas sharing is not configured."},void 0,!1,void 0,this),G$("p",{className:"text-text-tertiary",children:["Set ",G$("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"CANVAS_SHARE_ENDPOINT"},void 0,!1,void 0,this)," to the URL of a deployed"," ",G$("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"canvas-share"},void 0,!1,void 0,this)," worker and restart the daemon."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):F?G$("div",{className:"space-y-3",children:[G$("p",{className:"text-[13px] text-text-secondary font-body",children:"This revision is shared:"},void 0,!1,void 0,this),G$("div",{className:"flex gap-2",children:[G$("input",{type:"text",readOnly:!0,value:F.url,className:"flex-1 px-2 py-1.5 text-[12px] font-mono bg-bg-input border border-border-medium rounded text-text-primary",onFocus:(T)=>T.currentTarget.select()},void 0,!1,void 0,this),G$("button",{onClick:()=>A(F.url),className:"px-3 py-1.5 text-[12px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity whitespace-nowrap",children:M?"Copied!":"Copy"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F.expiresAt&&G$("p",{className:"text-[11px] text-text-tertiary font-body",children:["Expires ",new Date(F.expiresAt).toLocaleDateString(),"."]},void 0,!0,void 0,this),F.encryptionKey&&G$("p",{className:"text-[11px] text-accent-green font-body flex items-center gap-1.5",children:[G$("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[G$("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},void 0,!1,void 0,this),G$("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),"End-to-end encrypted — the key is part of the link and never leaves your browser."]},void 0,!0,void 0,this),G$("p",{className:"text-[11px] text-text-tertiary font-body",children:"Anyone with this link can view and leave feedback. Reviewer feedback will appear in your annotation sidebar within seconds."},void 0,!1,void 0,this),G$("div",{className:"flex items-center justify-between pt-1",children:[G$("button",{onClick:w,disabled:_||U,className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body underline disabled:opacity-50",children:_?"Creating...":"Create a new link"},void 0,!1,void 0,this),F.ownerToken&&G$("button",{onClick:()=>z(F.shareId),disabled:_||U,className:"text-[11px] text-accent-red hover:opacity-80 font-body underline disabled:opacity-50",children:U?"Revoking...":"Revoke link"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):G$("div",{className:"space-y-3",children:[G$("p",{className:"text-[13px] text-text-secondary font-body",children:"Create a public link to this revision. Anyone with the link can view the canvas and leave feedback. Reviewer feedback will sync back here automatically."},void 0,!1,void 0,this),G$("button",{onClick:w,disabled:_,className:"w-full px-3 py-2 text-[13px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity disabled:opacity-50",children:_?"Creating share link...":"Create share link"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),N&&G$("div",{className:"mt-3 px-3 py-2 rounded bg-accent-red/10 border border-accent-red/20 text-[12px] text-accent-red font-body",children:N},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function i6({onClick:$,title:Q="Share this revision",hasShare:J}){return G$("button",{onClick:$,className:`group p-1.5 transition-colors ${J?"text-accent-blue hover:opacity-80":"text-text-tertiary hover:text-text-secondary"}`,title:Q,children:G$("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[G$("circle",{cx:"18",cy:"5",r:"3"},void 0,!1,void 0,this),G$("circle",{cx:"6",cy:"12",r:"3"},void 0,!1,void 0,this),G$("circle",{cx:"18",cy:"19",r:"3"},void 0,!1,void 0,this),G$("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"},void 0,!1,void 0,this),G$("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as P,Fragment as L2}from"react/jsx-dev-runtime";function a6($){let Q=[];for(let J of $)for(let Y of J.annotations)Q.push({...Y,source:"remote",author:J.author});return Q}function Oq($){if($==="auto")return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return $}function n6($){document.documentElement.dataset.theme=Oq($)}function $8(){let[$,Q]=M$(()=>{let q=localStorage.getItem("canvas-theme");if(q==="light"||q==="dark"||q==="auto")return q;return"auto"});return u$(()=>{if(n6($),$!=="auto")return;let q=window.matchMedia("(prefers-color-scheme: dark)"),G=()=>n6("auto");return q.addEventListener("change",G),()=>q.removeEventListener("change",G)},[$]),P("button",{onClick:()=>{let q=$==="auto"?"light":$==="light"?"dark":"auto";localStorage.setItem("canvas-theme",q),Q(q)},className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:{auto:"Theme: system (click for light)",light:"Theme: light (click for dark)",dark:"Theme: dark (click for system)"}[$],children:$==="auto"?P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"},void 0,!1,void 0,this),P("line",{x1:"8",y1:"21",x2:"16",y2:"21"},void 0,!1,void 0,this),P("line",{x1:"12",y1:"17",x2:"12",y2:"21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$==="dark"?P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:P("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"},void 0,!1,void 0,this)},void 0,!1,void 0,this):P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P("circle",{cx:"12",cy:"12",r:"5"},void 0,!1,void 0,this),P("line",{x1:"12",y1:"1",x2:"12",y2:"3"},void 0,!1,void 0,this),P("line",{x1:"12",y1:"21",x2:"12",y2:"23"},void 0,!1,void 0,this),P("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},void 0,!1,void 0,this),P("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},void 0,!1,void 0,this),P("line",{x1:"1",y1:"12",x2:"3",y2:"12"},void 0,!1,void 0,this),P("line",{x1:"21",y1:"12",x2:"23",y2:"12"},void 0,!1,void 0,this),P("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},void 0,!1,void 0,this),P("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Q8(){let{currentRevision:$,selectedRevision:Q,revisions:J,setSelectedRevision:Y,setCompareRevision:q}=v1.useContext(h$);if(J.length<=1){let W=J[0]?.label||`Round ${$}`;return P("span",{className:"text-[11px] text-text-tertiary font-body",children:W},void 0,!1,void 0,this)}return P("div",{className:"flex flex-col gap-1",children:[P(N2,{value:Q,onChange:Y,accent:Q===$?"default":"amber"},void 0,!1,void 0,this),P("button",{onClick:()=>{let X;if(Q===$)X=[...J].reverse().find((_)=>_.revision<$)?.revision??Math.max(1,$-1);else X=Q;q({left:X,right:$})},className:"text-[11px] font-body font-medium px-2 py-0.5 rounded-md text-accent-blue hover:bg-accent-blue-muted transition-colors self-start",children:"Compare"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zq(){let $=W$.isShared?W$.shareId:W$.sessionId,Q=W$.isShared,[J,Y]=M$(1),[q,G]=M$(1),[X,W]=M$([]),[_,H]=M$(null),[U,K]=M$(!1),[N,O]=M$(!1),[M,L]=M$(!1),[F,w]=M$([]),[z,A]=M$({type:"overview"}),[T,S]=M$([]),j=W1(null),Z=W1([]),y=W1(new Set),[V,C]=M$(),[v,h]=M$(!1),[o,B$]=M$(!1),[a,U$]=M$(!1),[Y$,N$]=M$(!1),[Q$,_$]=M$([]),[F$,n]=M$(!1),[d,X$]=M$(new Map),[g,c]=M$(!1),[f,D]=M$(null),[x,r]=M$(null),z$=k0((I)=>{if(Q)return;let e=`${I.revision}\x00${I.filename}\x00${I.message}`;if(y.current.has(e))return;y.current.add(e);let J$=JSON.stringify({type:"render-error",error:I});if(j.current?.readyState===WebSocket.OPEN)j.current.send(J$);else Z.current.push(I)},[Q]);u$(()=>{if(!x)return;let I=setTimeout(()=>r(null),4000);return()=>clearTimeout(I)},[x]);let L$=Math.max(0,...X.map((I)=>I.revision));u$(()=>{if(Q||!V)return;H6().catch((I)=>console.warn("Project theme not applied:",I))},[Q,V,L$]),u$(()=>{let I=["Agent Canvas"];if(V){let e=V.replace(/\/+$/,"").split("/");I.push(e[e.length-1]||$)}else if($)I.push($);if(z.type==="file")I.push(z.path.split("/").pop()||z.path);else if(z.type==="overview")I.push("Overview");else if(z.type==="canvas"&&F.length>1&&z.filename)I.push(z.filename.replace(/\.jsx$/,""));else if(_)I.push("Compare");document.title=I.join(" — ")},[$,V,z,_]);let C$=W1(new Map),f$=X.find((I)=>I.revision===q),A3=q!==J||!!f$?.hasFeedback||N,P3=q===J&&(!!f$?.hasFeedback||N)?"next":"current",S3=k0((I)=>{let e=z.type==="overview"?"overview":z.type==="canvas"?`canvas:${z.filename}`:`file:${z.path}`;if(C$.current.set(e,window.scrollY),A(I),I.type==="file")S((J$)=>J$.includes(I.path)?J$:[...J$,I.path])},[z]),J8=k0((I)=>{C$.current.delete(`file:${I}`),S((e)=>e.filter((J$)=>J$!==I)),A((e)=>{if(e.type==="file"&&e.path===I)return F.length>1?{type:"overview"}:{type:"canvas",filename:F[0]||""};return e})},[F]);Bq(()=>{let I=z.type==="overview"?"overview":z.type==="canvas"?`canvas:${z.filename}`:`file:${z.path}`;window.scrollTo(0,C$.current.get(I)||0)},[z]),u$(()=>{if(!$)return;U6().then((I)=>{if(I.currentRevision){let e=I.revisions||[];for(let J$ of e)if(J$.hasFeedback)o1(localStorage,$,J$.revision);x2(localStorage,$,I.currentRevision,e),Y(I.currentRevision),G(I.currentRevision),W(e)}if(I.canvasFiles){let e=I.canvasFiles.sort();w(e),A((J$)=>{if(J$.type==="overview")return e.length>1?J$:{type:"canvas",filename:e[0]||""};if(J$.type==="canvas"&&(!J$.filename||!e.includes(J$.filename)))return{type:"canvas",filename:e[0]||""};return J$})}if(I.projectRoot)C(I.projectRoot);if(Array.isArray(I.shares))_$(I.shares);n(!!I.shareEnabled)}).catch(()=>{})},[$]),u$(()=>{if(!$||!q||Q)return;fetch(`/api/session/${$}/revision/${q}/remote-feedback`).then((I)=>I.json()).then((I)=>{let e=a5.safeParse(I);if(!e.success)return;let J$=a6(e.data.entries);X$((n$)=>{let m$=new Map(n$);return m$.set(q,J$),m$})}).catch(()=>{})},[$,q,Q]),u$(()=>{if(!$)return;if(!O6){K(!0);return}let I=null,e=()=>{let J$=window.location.protocol==="https:"?"wss:":"ws:",n$=new WebSocket(`${J$}//${window.location.host}/ws/session/${$}`);j.current=n$,n$.onopen=()=>{K(!0),s2?.load().catch((m$)=>console.warn(`[threads] ${I0(m$)}`));for(let m$ of Z.current)n$.send(JSON.stringify({type:"render-error",error:m$}));Z.current=[]},n$.onclose=()=>{K(!1),I=setTimeout(e,2000)},n$.onmessage=(m$)=>{try{let T$=JSON.parse(m$.data);if(T$.type==="plan-updated"){let I$=Array.isArray(T$.revisions)?T$.revisions:[];if(x2(localStorage,$,T$.currentRevision,I$),Y(T$.currentRevision),G(T$.currentRevision),H(null),I$.length>0){W(I$);let L1=I$.find((g1)=>g1.revision===T$.currentRevision);if(L1?.canvasFiles){let g1=L1.canvasFiles.map((f0)=>f0.filename).sort();w(g1);let _4=I$.find((f0)=>f0.revision===T$.currentRevision-1),y0=M3(L1,_4),J0=h6(y0);if(J0.length===1)A({type:"canvas",filename:J0[0]});else if(J0.length>1||g1.length>1)A({type:"overview"});else A({type:"canvas",filename:g1[0]||""})}}}if(T$.type==="revision-updated"){if(Array.isArray(T$.revisions)){let I$=T$.revisions;for(let L1 of I$)if(L1.hasFeedback)o1(localStorage,$,L1.revision);W(I$)}}if(T$.type==="threads")s2?.receive(T$.threads);if(T$.type==="watcher-status")L(!!T$.watching);if(T$.type==="remote-feedback"){let I$=T$.revision,L1=T$.entries||[],g1=a6(L1);X$((_4)=>{let y0=new Map(_4),J0=y0.get(I$)||[],f0=new Set(J0.map((W4)=>W4.id)),q8=[...J0,...g1.filter((W4)=>!f0.has(W4.id))];return y0.set(I$,q8),y0})}}catch{}}};return e(),()=>{if(I)clearTimeout(I);j.current?.close()}},[$]);let G4=k0(async(I,e)=>{try{let J$=localStorage.getItem(`canvas:${$}:rev:${q}`),n$=[],m$=[];if(J$)try{let T$=w0(JSON.parse(J$));n$=(T$?.annotations??[]).filter((I$)=>I$.source!=="remote"),m$=r5((T$?.responses??[]).map(([,I$])=>I$))}catch{}await N6({author:e,revision:q,annotations:n$,generalNote:I,...m$.length>0?{responses:m$}:{}}),o1(localStorage,$,q),O(!0),r({kind:"success",message:"Feedback submitted. The canvas author will see it shortly."})}catch(J$){r({kind:"error",message:`Failed to submit feedback: ${I0(J$)}`})}},[$,q]),w3=k0(async(I,e)=>{if(Q){let J$=K3();if(!J$){D(I),c(!0);return}await G4(I,J$);return}if(j.current?.readyState===WebSocket.OPEN)j.current.send(JSON.stringify({type:"submit",feedback:I,annotations:e}))},[Q,G4]);if(!$)return P("div",{className:"flex items-center justify-center h-screen text-text-tertiary font-body",children:"No session selected."},void 0,!1,void 0,this);return P(h2.Provider,{value:z6,children:P(e6.Provider,{value:$,children:P(H2.Provider,{value:z$,children:P(h$.Provider,{value:{currentRevision:J,selectedRevision:q,revisions:X,setSelectedRevision:G,isReadOnly:A3,compareRevision:_,setCompareRevision:H,agentWatching:M},children:P(h4,{sessionId:$,revision:q,isReadOnly:A3,draftPhase:P3,remoteAnnotations:d.get(q),canvasFiles:F,children:P(q1.Provider,{value:{activeView:z,setActiveView:S3,openFiles:T,closeFile:J8,canvasFiles:F},children:P(Kq.Provider,{value:{setActiveView:S3},children:P("div",{className:"min-h-screen bg-bg-base",children:[P(Mq,{sessionId:$,projectRoot:V,connected:U,onMobileSidebar:()=>h(!v),collapsed:o,onToggle:()=>B$((I)=>!I)},void 0,!1,void 0,this),P(Fq,{collapsed:a,onToggle:()=>U$((I)=>!I),children:P(a2,{onSubmit:w3},void 0,!1,void 0,this)},void 0,!1,void 0,this),_!==null?P("div",{className:`${o?"lg:ml-0":"lg:ml-60"} ${a?"lg:mr-0":"lg:mr-[var(--sidebar-width,320px)]"} transition-[margin] duration-200`,children:P(R6,{initialLeft:_.left,initialRight:_.right,sessionId:$,onExit:()=>H(null)},void 0,!1,void 0,this)},void 0,!1,void 0,this):P("div",{className:`relative ${o?"lg:ml-0":"lg:ml-60"} ${a?"lg:mr-0":"lg:mr-[var(--sidebar-width,320px)]"} transition-[margin] duration-200`,id:"plan-scroll-container",children:[P("div",{className:"lg:hidden sticky top-0 z-20 flex items-center justify-between px-4 py-2 border-b border-border-subtle bg-bg-surface",children:[P("div",{className:"flex items-center gap-2",children:[!Q&&P(F3,{currentSessionId:$,projectRoot:V},void 0,!1,void 0,this),Q&&P("span",{className:"text-[11px] text-text-tertiary font-body",children:"Shared canvas"},void 0,!1,void 0,this),!Q&&P("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-accent-green":"bg-accent-red"}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("div",{className:"flex items-center gap-1",children:[P(Q8,{},void 0,!1,void 0,this),P("button",{onClick:()=>h(!v),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Annotations",children:P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:P("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),P($8,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),P(Lq,{},void 0,!1,void 0,this),z.type==="overview"&&P(u6,{revision:q,responseBanner:f$?.response?P(s6,{markdown:f$.response},void 0,!1,void 0,this):void 0},void 0,!1,void 0,this),z.type==="canvas"&&F.includes(z.filename)&&P("div",{className:"relative max-w-[720px] mx-auto px-6 pt-12 pb-32",children:[F$&&P("div",{className:"absolute top-3 right-12 z-10",children:P(i6,{onClick:()=>N$(!0),hasShare:Q$.some((I)=>I.revision===q),title:Q$.some((I)=>I.revision===q)?"Manage share link":"Share this revision"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P("button",{onClick:()=>{let I=document.querySelector(`[data-canvas-file="${z.filename}"] .plan-content`);if(!I)return;let e=D6(I);navigator.clipboard.writeText(e).then(()=>{let J$=document.getElementById("export-md-btn");if(J$)J$.setAttribute("data-copied","true"),setTimeout(()=>{J$.removeAttribute("data-copied")},1500)})},id:"export-md-btn",className:"group absolute top-3 right-6 p-1.5 text-text-tertiary hover:text-text-secondary transition-colors z-10",title:"Copy as Markdown",children:[P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"group-[[data-copied=true]]:hidden",children:[P("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},void 0,!1,void 0,this),P("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"hidden group-[[data-copied=true]]:block text-green-500",children:P("polyline",{points:"20 6 9 17 4 12"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F.length<=1&&f$?.response&&P(s6,{markdown:f$.response},void 0,!1,void 0,this),P("div",{"data-canvas-file":z.filename,children:P(R0,{revision:q,filename:z.filename},z.filename,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),T.map((I)=>P("div",{style:{display:z.type==="file"&&z.path===I?void 0:"none"},children:P(g6,{path:I},void 0,!1,void 0,this)},I,!1,void 0,this))]},void 0,!0,void 0,this),v&&P("div",{className:"lg:hidden fixed inset-0 z-40 flex",children:[P("div",{className:"flex-1",onClick:()=>h(!1)},void 0,!1,void 0,this),P("div",{className:"w-80 max-w-[85vw] bg-bg-surface border-l border-border-subtle flex flex-col shadow-lg",children:[P("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border-subtle flex-shrink-0",children:[P("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Sidebar"},void 0,!1,void 0,this),P("button",{onClick:()=>h(!1),className:"text-text-tertiary hover:text-text-secondary w-7 h-7 flex items-center justify-center",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("div",{className:"flex-1 overflow-hidden",children:P(a2,{onSubmit:w3},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),P(r6,{sessionId:$,revision:q,open:Y$,shareEnabled:F$,existingShares:Q$,onClose:()=>N$(!1),onShareCreated:(I)=>{_$((e)=>[...e.filter((J$)=>J$.shareId!==I.shareId),I]),r({kind:"success",message:"Share link created. Copy and send it to reviewers."})},onShareRevoked:(I)=>{_$((e)=>e.filter((J$)=>J$.shareId!==I)),r({kind:"success",message:"Share link revoked."})}},void 0,!1,void 0,this),P(p6,{open:g,onClose:()=>{c(!1),D(null)},onSubmit:async(I)=>{let e=B6(I);if(c(!1),f!==null)await G4(f,e),D(null)}},void 0,!1,void 0,this),x&&P("div",{className:`fixed bottom-4 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-lg text-[13px] font-body font-medium flex items-center gap-2 ${x.kind==="error"?"bg-accent-red text-white":"bg-accent-green text-white"}`,children:[x.message,P("button",{onClick:()=>r(null),className:"ml-2 opacity-70 hover:opacity-100",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},`${$}:${q}:${P3}`,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Mq({sessionId:$,projectRoot:Q,connected:J,onMobileSidebar:Y,collapsed:q,onToggle:G}){let X=W$.isShared;return P(L2,{children:[q&&P("button",{onClick:G,className:"hidden lg:flex fixed top-3 left-3 z-20 w-7 h-7 items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors bg-bg-surface border border-border-subtle",title:"Show sidebar",children:P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},void 0,!1,void 0,this),P("line",{x1:"9",y1:"3",x2:"9",y2:"21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),P("div",{className:`hidden lg:flex w-60 flex-col fixed top-0 left-0 bottom-0 bg-bg-surface border-r border-border-subtle z-10 transition-transform duration-200 ${q?"-translate-x-full":""}`,children:[P("div",{className:"px-4 pt-4 pb-3 flex-shrink-0 border-b border-border-subtle",children:[P("div",{className:"flex items-center gap-2 mb-2",children:[P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"text-text-tertiary flex-shrink-0",children:P("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this),X?P("span",{className:"text-[12px] font-body text-text-secondary truncate flex-1",children:"Shared canvas"},void 0,!1,void 0,this):P(L2,{children:[P(F3,{currentSessionId:$,projectRoot:Q},void 0,!1,void 0,this),P("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${J?"bg-accent-green":"bg-accent-red"}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("button",{onClick:G,className:"ml-auto w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Hide sidebar",children:P("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P("polyline",{points:"11 17 6 12 11 7"},void 0,!1,void 0,this),P("polyline",{points:"18 17 13 12 18 7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P(Q8,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("div",{className:"flex-1 flex flex-col overflow-hidden",children:P(y6,{embedded:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this),P("div",{className:"px-4 py-3 border-t border-border-subtle flex items-center justify-between flex-shrink-0",children:[P("span",{className:"text-[10px] text-text-tertiary font-body uppercase tracking-widest",children:"Theme"},void 0,!1,void 0,this),P($8,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Fq({children:$,collapsed:Q,onToggle:J}){let[Y,q]=M$(()=>{let U=localStorage.getItem("canvas-sidebar-width");return U?parseInt(U,10):320}),G=W1(!1),X=W1(0),W=W1(0),_=W1(Y);_.current=Y;let H=k0((U)=>{U.preventDefault(),G.current=!0,X.current=U.clientX,W.current=_.current;let K=(O)=>{if(!G.current)return;let M=X.current-O.clientX,L=Math.max(240,Math.min(600,W.current+M));q(L),_.current=L},N=()=>{G.current=!1,localStorage.setItem("canvas-sidebar-width",String(_.current)),document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",N),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",K),document.addEventListener("mouseup",N),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);return u$(()=>{return document.documentElement.style.setProperty("--sidebar-width",`${Y}px`),()=>{document.documentElement.style.removeProperty("--sidebar-width")}},[Y]),P(L2,{children:[Q&&P("button",{onClick:J,className:"hidden lg:flex fixed top-3 right-3 z-20 w-7 h-7 items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors bg-bg-surface border border-border-subtle",title:"Show annotations",children:P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:P("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),P("div",{className:`hidden lg:flex flex-col fixed top-0 right-0 bottom-0 bg-bg-surface border-l border-border-subtle z-10 transition-transform duration-200 ${Q?"translate-x-full":""}`,style:{width:Y},children:[P("div",{onMouseDown:H,className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-accent-blue/30 transition-colors z-20",style:{marginLeft:"-2px"}},void 0,!1,void 0,this),v1.Children.map($,(U)=>v1.isValidElement(U)?v1.cloneElement(U,{collapseButton:P("button",{onClick:J,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Hide annotations",children:P("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P("polyline",{points:"13 17 18 12 13 7"},void 0,!1,void 0,this),P("polyline",{points:"6 17 11 12 6 7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}):U)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function s6({markdown:$}){let[Q,J]=M$(!1),Y=o6(()=>i2($),[$]),q=W1(null),{annotations:G,addAnnotationWithId:X,removeAnnotation:W,updateAnnotation:_,addAnnotationImage:H,removeAnnotationImage:U,activeAnnotationId:K,setActiveAnnotationId:N}=G1(),[O,M]=M$(null),[L,F]=M$(null),w=o6(()=>G.filter((j)=>j.filePath===g$),[G]),[z,A]=M$($);if($!==z)A($),J(!1);u$(()=>{if(!q.current||w.length===0)return;let j=setTimeout(()=>{if(q.current)m0(q.current,w)},50);return()=>clearTimeout(j)},[Y,w.length]);let T=W1(null);if(u$(()=>{v0(K,T.current),T.current=K},[K]),u$(()=>{let j=q.current;if(!j)return;let Z=(C)=>{let v=C.target.closest("[data-annotation-id]");if(!v)return;C.stopPropagation();let h=v.getAttribute("data-annotation-id");if(h===K)F({anchorEl:v,annId:h});else N(h)},y=(C)=>{let v=C.target.closest("[data-annotation-id]");if(v)N(v.getAttribute("data-annotation-id"))},V=(C)=>{let v=C.target.closest("[data-annotation-id]"),h=C.relatedTarget?.closest?.("[data-annotation-id]");if(v&&!h)N(null)};return j.addEventListener("click",Z),j.addEventListener("mouseover",y),j.addEventListener("mouseout",V),()=>{j.removeEventListener("click",Z),j.removeEventListener("mouseover",y),j.removeEventListener("mouseout",V)}},[Y,K]),u$(()=>{let j=()=>{let Z=window.getSelection();if(!Z||Z.isCollapsed||!Z.toString().trim())return;if(!q.current)return;let y=Z.getRangeAt(0);if(!q.current.contains(y.startContainer))return;if(y.startContainer.parentElement?.closest?.("[data-annotation-id]"))return;let V=Z.toString().trim();if(V.length<2)return;let C=y.cloneRange(),v=P1(y,q.current),h=`__pending_${Date.now()}`;try{A1(C,h)}catch{}window.getSelection()?.removeAllRanges();let o=document.querySelectorAll(`[data-annotation-id="${h}"]`),B$=o[o.length-1];if(!B$)return;M({anchorEl:B$,tempId:h,snippet:V,ctx:v})};return document.addEventListener("mouseup",j),()=>document.removeEventListener("mouseup",j)},[]),Q)return null;let S=document.getElementById("plan-scroll-container");return P("div",{className:"mb-6 rounded-lg border border-accent-blue/20 bg-accent-blue/5 relative",children:[P("button",{onClick:()=>J(!0),className:"absolute top-2 right-2 w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:P("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P("div",{className:"px-4 py-3 pr-10",children:[P("div",{className:"flex items-center gap-2 mb-1.5",children:[P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-blue flex-shrink-0",children:P("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),P("span",{className:"text-[11px] font-medium uppercase tracking-widest text-accent-blue font-body",children:"Agent Response"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("div",{ref:q,className:"prose-canvas text-sm",dangerouslySetInnerHTML:{__html:Y}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O&&P(Q1,{anchorEl:O.anchorEl,scrollContainer:S,snippet:O.snippet,truncateAt:80,onAdd:(j,Z)=>{let y=x$();g0(O.tempId,y),X(y,O.snippet,j,g$,O.ctx,Z),M(null)},onCancel:()=>{x0(O.tempId),M(null)}},void 0,!1,void 0,this),L&&(()=>{let j=G.find((Z)=>Z.id===L.annId);if(!j)return null;return P(r1,{anchorEl:L.anchorEl,scrollContainer:S,initialNote:j.note,initialImages:j.images,onUpdate:(Z,y)=>{_(L.annId,Z);let V=j.images||[];for(let C of y)if(!V.includes(C))H(L.annId,C);for(let C of V)if(!y.includes(C))U(L.annId,C)},onDelete:()=>{W(L.annId),N(null)},onClose:()=>F(null)},void 0,!1,void 0,this)})()]},void 0,!0,void 0,this)}function Lq(){let{activeView:$,setActiveView:Q,openFiles:J,closeFile:Y,canvasFiles:q}=v1.useContext(q1),G=v1.useContext(e6),{addAnnotationWithId:X,setActiveAnnotationId:W}=G1();if(!(q.length>1||J.length>0))return null;return P("div",{className:"flex items-center border-b border-border-medium bg-bg-surface overflow-x-auto sticky top-0 z-10",children:[q.length>1&&P(L2,{children:[P("button",{onClick:()=>Q({type:"overview"}),className:`flex items-center gap-1.5 px-4 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${$.type==="overview"?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[P("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"opacity-60",children:P("path",{d:"M12 7L2 12l10 5 10-5-10-5z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Overview",$.type==="overview"&&P("span",{className:"absolute bottom-0 left-3 right-3 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q.map((H,U)=>{let K=H.replace(/\.jsx$/,""),N=$.type==="canvas"&&$.filename===H;return P(v1.Fragment,{children:[P("button",{onClick:()=>Q({type:"canvas",filename:H}),className:`flex items-center gap-1.5 px-4 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${N?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[K,N&&P("span",{className:"absolute bottom-0 left-3 right-3 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U<q.length-1&&P("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},H,!0,void 0,this)}),J.length>0&&P(L2,{children:[P("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this),J.map((H,U)=>{let K=H.split("/").pop()||H,N=$.type==="file"&&$.path===H;return P(v1.Fragment,{children:[P("div",{className:"flex items-center",children:[P("button",{onClick:()=>Q({type:"file",path:H}),className:`flex items-center gap-1.5 pl-3 pr-1 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${N?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[P(I1,{name:K,type:"file"},void 0,!1,void 0,this),K,N&&P("span",{className:"absolute bottom-0 left-3 right-1 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P("button",{onClick:(O)=>{O.stopPropagation(),Y(H)},className:"text-text-tertiary hover:text-text-secondary px-1.5 py-1 text-[10px] transition-colors rounded hover:bg-bg-input",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U<J.length-1&&P("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},H,!0,void 0,this)})]},void 0,!0,void 0,this),P("div",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:$.type==="file"&&O1&&P("button",{onClick:async()=>{let H=$.path;try{let U=await fetch(`/api/file?session=${G}&path=${encodeURIComponent(H)}`),K=D1.parse(await U.json());if("content"in K){let N=K.content.split(`
82
+ ...`:"");o(S,"Include this file for context",m)}},x=async(m)=>{let b=[];if(l[m]?.loaded)b=l[m].entries;else{let w=await fetch(`/api/tree?session=${t}&path=${encodeURIComponent(m)}`),y=vs.safeParse(await w.json());if(y.success)b=y.data.entries}await Promise.all(b.filter((w)=>w.type==="file").map((w)=>h(m?`${m}/${w.name}`:w.name)))},g=(m)=>c.get(m)||0,k=(m,b=0)=>{let w=l[m];if(!w?.expanded)return null;return w.entries.map((y)=>{let S=m?`${m}/${y.name}`:y.name,T=g(S);return Z("div",{children:[Z("div",{className:"group/item flex items-center py-[3px] hover:bg-bg-elevated text-[13px] font-body cursor-default transition-colors duration-100",style:{paddingLeft:`${16+b*16}px`,paddingRight:"8px"},children:y.type==="dir"?Z(Es,{children:[Z("span",{onClick:()=>p(S),className:"flex items-center gap-1.5 flex-1 text-text-secondary hover:text-text-primary cursor-pointer truncate",children:[Z(Lt,{name:y.name,type:"dir",expanded:l[S]?.expanded},void 0,!1,void 0,this),Z("span",{className:"truncate",children:y.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z("button",{onClick:(M)=>{M.stopPropagation(),x(S)},className:"text-[11px] text-text-tertiary hover:text-text-secondary opacity-0 group-hover/item:opacity-100 transition-opacity px-1 flex-shrink-0",title:"Add all files in folder",children:"+"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):Z(Es,{children:[Z("span",{onClick:()=>f(S),className:`flex-1 truncate cursor-pointer flex items-center gap-1.5 ${T>0?"text-text-primary":"text-text-secondary hover:text-text-primary"}`,children:[Z(Lt,{name:y.name,type:"file"},void 0,!1,void 0,this),Z("span",{className:"truncate",children:y.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z("div",{className:"flex items-center gap-1 flex-shrink-0 ml-1",children:[T>0&&Z("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center",children:T},void 0,!1,void 0,this),Z("button",{onClick:(M)=>{M.stopPropagation(),h(S)},className:"text-[11px] text-text-tertiary hover:text-text-secondary opacity-0 group-hover/item:opacity-100 transition-opacity px-1",title:"Add file to context",children:"+"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y.type==="dir"&&k(S,b+1)]},S,!0,void 0,this)})};if(e)return Z(Es,{children:[Z("div",{className:"flex items-center justify-between px-4 pt-3 pb-2 flex-shrink-0",children:Z("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Files"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Z("div",{className:"flex-1 overflow-y-auto",children:k("")},void 0,!1,void 0,this),d.length>0&&Z("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:[Z("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body mb-1.5",children:"Referenced"},void 0,!1,void 0,this),d.map((m)=>Z("div",{onClick:()=>f(m),className:"flex items-center justify-between text-[12px] font-body text-text-secondary hover:text-text-primary cursor-pointer py-0.5",children:[Z("span",{className:"truncate",children:m.split("/").pop()},void 0,!1,void 0,this),Z("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center flex-shrink-0 ml-1",children:g(m)},void 0,!1,void 0,this)]},m,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(a)return Z("div",{className:"hidden lg:flex w-8 border-r border-border-subtle bg-bg-surface flex-col items-center flex-shrink-0",children:Z("button",{onClick:()=>s(!1),className:"mt-3 p-1 text-text-tertiary hover:text-text-secondary transition-colors",children:Z("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:Z("path",{d:"M5 3l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);return Z("div",{className:"hidden lg:flex w-60 border-r border-border-subtle bg-bg-surface flex-col flex-shrink-0 overflow-hidden",children:[Z("div",{className:"flex items-center justify-between px-4 pt-4 pb-3 flex-shrink-0",children:[Z("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Files"},void 0,!1,void 0,this),Z("button",{onClick:()=>s(!0),className:"text-text-tertiary hover:text-text-secondary transition-colors p-0.5",children:Z("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:Z("path",{d:"M9 3l-4 4 4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z("div",{className:"flex-1 overflow-y-auto",children:k("")},void 0,!1,void 0,this),d.length>0&&Z("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:[Z("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body mb-1.5",children:"Referenced"},void 0,!1,void 0,this),d.map((m)=>Z("div",{onClick:()=>f(m),className:"flex items-center justify-between text-[12px] font-body text-text-secondary hover:text-text-primary cursor-pointer py-0.5",children:[Z("span",{className:"truncate",children:m.split("/").pop()},void 0,!1,void 0,this),Z("span",{className:"text-[10px] font-medium bg-badge-bg text-accent-amber px-1.5 py-px rounded-full min-w-[18px] text-center flex-shrink-0 ml-1",children:g(m)},void 0,!1,void 0,this)]},m,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{SessionContext as cp}from"#canvas/runtime";import{useCallback as dp,useContext as up,useEffect as Fi,useMemo as Bi,useRef as po,useState as xr}from"react";import{jsxDEV as Ie}from"react/jsx-dev-runtime";function zi(e){let t=e instanceof HTMLElement?e:e.parentElement;while(t){if(t.hasAttribute("data-line-num"))return t;t=t.parentElement}return null}function pp(e){let t=e.toString().trim(),n=zi(e.startContainer),o=zi(e.endContainer),r=n?parseInt(n.getAttribute("data-line-num"),10):void 0,a=o?parseInt(o.getAttribute("data-line-num"),10):void 0,s="",l="";if(t.length<30&&n&&n===o){let i=n.querySelector("code");if(i){let c=i.textContent||"",d=c.indexOf(t);if(d>=0)s=c.slice(0,d).trimStart(),l=c.slice(d+t.length).trimEnd()}}return{before:s,after:l,hierarchy:[],lineStart:r,lineEnd:a}}function fp({html:e}){return Ie("code",{className:"py-px",dangerouslySetInnerHTML:{__html:e}},void 0,!1,void 0,this)}function qi({path:e}){if(!bt)return Ie("div",{className:"max-w-[720px] mx-auto px-6 pt-12 pb-32",children:Ie("div",{className:"p-4 rounded-lg border border-border-subtle bg-bg-surface",children:[Ie("div",{className:"text-[11px] uppercase tracking-widest text-text-tertiary font-body mb-2",children:"File not available"},void 0,!1,void 0,this),Ie("p",{className:"text-[13px] text-text-secondary font-body leading-relaxed",children:["Opening ",Ie("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:e},void 0,!1,void 0,this)," ","requires filesystem access, which isn't available in shared view. If the canvas author wanted this file visible, they should embed it as a"," ",Ie("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"<FilePreview>"},void 0,!1,void 0,this)," in the canvas."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this);return Ie(mp,{path:e},void 0,!1,void 0,this)}function mp({path:e}){let t=up(cp),{annotations:n}=it(),[o,r]=xr(null),[a,s]=xr(!0),[l,i]=xr(null),c=po(null),[d,u]=xr(null),[p,f]=xr(null),h=po(null),x=po(null),g=po([]),k=n.filter((E)=>E.filePath===e),m=c.current?.closest("#plan-scroll-container"),{popovers:b,openCreatePopover:w}=_t({containerRef:c,restoreKey:`${o}:${e}`,restoreAnnotations:k,extractContext:pp,filePath:e,scrollContainer:m});Fi(()=>{s(!0),i(null),fetch(`/api/file?session=${t}&path=${encodeURIComponent(e)}`).then((E)=>E.json()).then((E)=>{let C=Mt.parse(E);if("error"in C)i(C.error),s(!1);else r(C.content),s(!1)}).catch(()=>{i("Failed to fetch file"),s(!1)})},[t,e]);let y=dp((E,C)=>{E.preventDefault(),h.current=C,x.current=C,u(C),f(C)},[]);Fi(()=>{let E=(O)=>{if(h.current===null)return;let B=O.target.closest("[data-line-num]");if(B){let Y=parseInt(B.getAttribute("data-line-num"),10);x.current=Y,f(Y)}},C=()=>{let O=h.current;if(O===null)return;h.current=null;let B=x.current??O,Y=Math.min(O,B),me=Math.max(O,B),pe=g.current.slice(Y-1,me).join(`
83
+ `);if(!pe.trim()){u(null),f(null);return}let se=`__pending_${Date.now()}`,he={before:"",after:"",hierarchy:[],lineStart:Y,lineEnd:me};if(c.current){let ne=c.current.querySelectorAll("[data-line-num]"),ce=ne[Y-1],ve=ne[me-1];if(ce&&ve){let W=ce.querySelector("code"),ae=ve.querySelector("code");if(W&&ae)try{let D=document.createRange();D.setStartBefore(W.firstChild||W),D.setEndAfter(ae.lastChild||ae),St(D,se)}catch{}}let Q=ne[me-1];if(Q)w(Q,se,pe,he)}u(null),f(null)};return document.addEventListener("mousemove",E),document.addEventListener("mouseup",C),()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",C)}},[]);let S=Bi(()=>{if(!o)return null;let E=cr();if(!E)return null;let C=e.split(".").pop()||"",O=co[C];try{return(O?E.highlight(o,{language:O}):E.highlightAuto(o)).value.split(`
84
+ `)}catch{return null}},[o,e]),T=Bi(()=>{if(d===null)return null;let E=p??d;return{start:Math.min(d,E),end:Math.max(d,E)}},[d,p]);if(a)return Ie("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-[13px]",children:["Loading ",e,"..."]},void 0,!0,void 0,this);if(l)return Ie("div",{className:"p-8 text-accent-red font-body text-[13px]",children:l},void 0,!1,void 0,this);if(!o)return null;let M=o.split(`
85
+ `);return g.current=M,Ie("div",{children:[Ie("pre",{ref:c,className:"text-code font-mono text-text-code bg-bg-base select-text cursor-text py-3 hljs",children:M.map((E,C)=>{let O=C+1,B=T&&O>=T.start&&O<=T.end;return Ie("div",{"data-line-num":O,className:`flex px-5 ${B?"bg-accent-blue/10":"hover:bg-bg-elevated-half"}`,children:[Ie("span",{className:"text-text-tertiary select-none w-10 text-right pr-4 shrink-0 py-px text-[12px] cursor-pointer opacity-40 hover:opacity-100 hover:text-accent-blue",onMouseDown:(Y)=>y(Y,O),children:O},void 0,!1,void 0,this),S?Ie(fp,{html:S[C]||" "},void 0,!1,void 0,this):Ie("code",{className:"py-px",children:E||" "},void 0,!1,void 0,this)]},C,!0,void 0,this)})},void 0,!1,void 0,this),b]},void 0,!0,void 0,this)}import{SessionContext as hp}from"#canvas/runtime";import{useCallback as Vi,useContext as Rs,useEffect as Ui,useMemo as gp,useRef as br,useState as kt}from"react";import{jsxDEV as J}from"react/jsx-dev-runtime";function Cs(e,t){if(!e)return[];return e.canvasFiles.map((n)=>{if(!n.diffStats)return{filename:n.filename,status:"new"};if(n.diffStats.added===0&&n.diffStats.removed===0)return{filename:n.filename,status:"unchanged",diffStats:n.diffStats};return{filename:n.filename,status:"changed",diffStats:n.diffStats}})}function Wi(e){return e.filter((t)=>t.status!=="unchanged").map((t)=>t.filename)}function Gi({revision:e,responseBanner:t}){let{setActiveView:n}=Rs(ot),{revisions:o}=Rs(Ve),r=o.find((c)=>c.revision===e),a=o.find((c)=>c.revision===e-1),s=gp(()=>Cs(r,a),[r,a]),l=s.filter((c)=>c.status!=="unchanged"),i=s.filter((c)=>c.status==="unchanged");return J("div",{className:"max-w-[720px] mx-auto px-6 pt-12 pb-32",children:[t,l.map((c)=>J(bp,{change:c,revision:e,previousRevision:a?.revision,onOpenTab:()=>n({type:"canvas",filename:c.filename})},c.filename,!1,void 0,this)),i.length>0&&J("div",{className:"mt-8 border-t border-border-subtle pt-4",children:[J("div",{className:"text-[11px] font-body font-medium uppercase tracking-widest text-text-tertiary mb-3",children:"Unchanged"},void 0,!1,void 0,this),i.map((c)=>J(wp,{change:c,revision:e,onOpenTab:()=>n({type:"canvas",filename:c.filename})},c.filename,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function xp({mode:e,onChange:t,showDiff:n}){if(!n)return null;return J("div",{className:"flex items-center bg-bg-elevated rounded-md p-0.5",children:["rendered","unified","side-by-side"].map((o)=>J("button",{onClick:()=>t(o),className:`text-[10px] font-body px-2 py-0.5 rounded transition-colors ${e===o?"bg-bg-surface text-text-primary font-medium shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:o==="rendered"?"Full":o==="unified"?"Unified":"Split"},o,!1,void 0,this))},void 0,!1,void 0,this)}function bp({change:e,revision:t,previousRevision:n,onOpenTab:o}){let r=e.filename.replace(/\.jsx$/,""),a=e.status==="new",s=e.diffStats,l=e.status==="changed"&&n!=null,[i,c]=kt("rendered");return J("div",{className:"mb-8",children:[J("div",{className:"flex items-center gap-2 mb-3 pb-2 border-b border-border-subtle",children:[J("span",{className:`text-[11px] font-mono px-1.5 py-0.5 rounded ${a?"bg-accent-green/10 text-accent-green border border-accent-green/20":"bg-accent-amber/10 text-accent-amber border border-accent-amber/20"}`,children:a?"new":"modified"},void 0,!1,void 0,this),J("span",{className:"text-[14px] font-body font-medium text-text-primary",children:r},void 0,!1,void 0,this),s&&(s.added>0||s.removed>0)&&J("span",{className:"text-[11px] font-mono text-text-tertiary",children:[J("span",{className:"text-accent-green",children:["+",s.added]},void 0,!0,void 0,this)," ",J("span",{className:"text-accent-red",children:["-",s.removed]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),J(xp,{mode:i,onChange:c,showDiff:l},void 0,!1,void 0,this),J("button",{onClick:o,className:`${l?"":"ml-auto"} text-[11px] font-body font-medium text-accent-blue hover:text-accent-blue/80 transition-colors`,children:"Open in tab"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i==="rendered"?J("div",{"data-canvas-file":e.filename,children:J(Sn,{revision:t,filename:e.filename},void 0,!1,void 0,this)},void 0,!1,void 0,this):l&&n!=null?J(vp,{filename:e.filename,leftRev:n,rightRev:t,mode:i},`${i}-${t}-${n}`,!1,void 0,this):null]},void 0,!0,void 0,this)}function vp({filename:e,leftRev:t,rightRev:n,mode:o}){let r=Rs(hp);if(o==="unified")return J(yp,{sessionId:r,filename:e,leftRev:t,rightRev:n},void 0,!1,void 0,this);return J(kp,{sessionId:r,filename:e,leftRev:t,rightRev:n},void 0,!1,void 0,this)}function yp({sessionId:e,filename:t,leftRev:n,rightRev:o}){let r=br(null),a=br(null),s=br(null),[l,i]=kt(!1),[c,d]=kt(!1),[u,p]=kt(!1),[f,h]=kt(null);return Ui(()=>{if(!l||!c||u)return;if(!r.current||!a.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!r.current||!a.current||!s.current)return;try{let x=An(r.current),g=An(a.current),k=gr(x,g),{fragment:m}=io(k);s.current.innerHTML="",s.current.appendChild(m),p(!0)}catch(x){h(x instanceof Error?x.message:String(x))}})})},[l,c,u]),J("div",{children:[!u&&!f&&J("div",{style:{position:"absolute",left:-9999,visibility:"hidden",pointerEvents:"none",width:720},children:[J(yt,{ref:r,sessionId:e,revision:n,filename:t,onReady:()=>i(!0),onError:(x)=>h(x)},void 0,!1,void 0,this),J(yt,{ref:a,sessionId:e,revision:o,filename:t,onReady:()=>d(!0),onError:(x)=>h(x)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!u&&!f&&J("div",{className:"flex items-center justify-center h-24 text-text-tertiary font-body text-[13px]",children:"Computing diff..."},void 0,!1,void 0,this),f&&J("div",{className:"text-accent-red text-[13px] font-body p-3 bg-accent-red-muted rounded-lg",children:f},void 0,!1,void 0,this),J("div",{ref:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kp({sessionId:e,filename:t,leftRev:n,rightRev:o}){let r=br(null),a=br(null),[s,l]=kt(!1),[i,c]=kt(!1),[d,u]=kt(!1),p=Vi(()=>l(!0),[]),f=Vi(()=>c(!0),[]);return Ui(()=>{if(!s||!i||d)return;if(!r.current||!a.current)return;requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!r.current||!a.current)return;ao(r.current,a.current),u(!0)})})},[s,i,d]),J("div",{className:"flex gap-0 border-y border-border-subtle overflow-hidden w-screen relative left-1/2 -translate-x-1/2",children:[J("div",{className:"w-1/2 border-r border-border-subtle",children:[J("div",{className:"px-2 py-1 text-[10px] font-body font-medium text-text-tertiary bg-bg-elevated border-b border-border-subtle",children:["Rev ",n]},void 0,!0,void 0,this),J("div",{className:"px-6 py-4 max-w-[600px] mx-auto",children:J(yt,{ref:r,sessionId:e,revision:n,filename:t,onReady:p},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J("div",{className:"w-1/2",children:[J("div",{className:"px-2 py-1 text-[10px] font-body font-medium text-text-tertiary bg-bg-elevated border-b border-border-subtle",children:["Rev ",o]},void 0,!0,void 0,this),J("div",{className:"px-6 py-4 max-w-[600px] mx-auto",children:J(yt,{ref:a,sessionId:e,revision:o,filename:t,onReady:f},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function wp({change:e,revision:t,onOpenTab:n}){let[o,r]=kt(!1),a=e.filename.replace(/\.jsx$/,"");return J("div",{className:"mb-2",children:[J("div",{className:"flex items-center gap-2 py-1.5",children:[J("button",{onClick:()=>r(!o),className:"text-text-tertiary hover:text-text-secondary transition-colors",children:J("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform duration-150 ${o?"rotate-90":""}`,children:J("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),J("span",{className:"text-[13px] font-body text-text-secondary",children:a},void 0,!1,void 0,this),J("button",{onClick:n,className:"ml-auto text-[11px] font-body text-text-tertiary hover:text-accent-blue transition-colors",children:"Open in tab"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&J("div",{className:"ml-5 mt-1 mb-3","data-canvas-file":e.filename,children:J(Sn,{revision:t,filename:e.filename},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useEffect as Sp,useRef as Ap,useState as Tp}from"react";import{jsxDEV as Je}from"react/jsx-dev-runtime";function Ki({open:e,onClose:t,onSubmit:n}){let[o,r]=Tp(""),a=Ap(null);if(Sp(()=>{if(e)r(""),setTimeout(()=>a.current?.focus(),50)},[e]),!e)return null;let s=o.trim(),l=s.length>=1&&s.length<=80,i=()=>{if(!l)return;n(s)};return Je("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:t,children:Je("div",{className:"bg-bg-surface border border-border-medium rounded-lg shadow-xl w-full max-w-md mx-4 p-5",onClick:(c)=>c.stopPropagation(),children:[Je("div",{className:"flex items-center justify-between mb-3",children:[Je("h2",{className:"text-sm font-medium text-text-primary font-body",children:"Your name"},void 0,!1,void 0,this),Je("button",{onClick:t,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:Je("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Je("p",{className:"text-[13px] text-text-secondary font-body mb-3 leading-relaxed",children:"Before you leave feedback, please enter a name so the canvas author knows who reviewed it. This is stored locally in your browser."},void 0,!1,void 0,this),Je("input",{ref:a,type:"text",value:o,onChange:(c)=>r(c.target.value),onKeyDown:(c)=>{if(c.key==="Enter")i()},maxLength:80,placeholder:"e.g. Alice",className:"w-full px-3 py-2 text-[13px] font-body bg-bg-input border border-border-medium rounded text-text-primary placeholder:text-text-disabled focus:outline-none focus:border-accent-blue"},void 0,!1,void 0,this),Je("div",{className:"flex justify-end gap-2 mt-4",children:[Je("button",{onClick:t,className:"px-3 py-1.5 text-[12px] font-body font-medium rounded text-text-secondary hover:text-text-primary hover:bg-bg-elevated transition-colors",children:"Cancel"},void 0,!1,void 0,this),Je("button",{onClick:i,disabled:!l,className:"px-3 py-1.5 text-[12px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity disabled:opacity-50",children:"Submit feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{useEffect as Ji,useRef as Ep,useState as Yi}from"react";import{jsxDEV as lt}from"react/jsx-dev-runtime";function Xi(e,t){if(t){let n=t.replace(/\/+$/,"").split("/");return n[n.length-1]||e}return e.length>30?e.slice(0,30)+"...":e}function Ns({currentSessionId:e,projectRoot:t}){let[n,o]=Yi([]),[r,a]=Yi(!1),s=Ep(null);Ji(()=>{if(!bt)return;let c=async()=>{try{let p=await(await fetch("/api/sessions")).json();o((f)=>{let h=JSON.stringify(p);return JSON.stringify(f)===h?f:p})}catch{}};c();let d=setInterval(c,5000);return()=>clearInterval(d)},[]),Ji(()=>{if(!r)return;let c=(d)=>{if(s.current&&!s.current.contains(d.target))a(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[r]);let l=n.filter((c)=>c.id!==e),i=Xi(e,t);return lt("div",{className:"relative",ref:s,children:[lt("div",{className:"flex items-center gap-1.5 font-body text-body font-medium",children:[lt("a",{href:`/s/${e}`,className:"text-text-primary hover:text-text-secondary transition-colors",children:i},void 0,!1,void 0,this),l.length>0&&lt("button",{onClick:()=>a(!r),className:"flex items-center justify-center text-text-tertiary hover:text-text-secondary transition-colors",children:lt("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:`transition-transform duration-200 ${r?"rotate-180":""}`,children:lt("path",{d:"M3 5l3 3 3-3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r&&l.length>0&&lt("div",{className:"absolute top-full left-0 mt-2 w-64 bg-bg-elevated border border-border-hover rounded-lg shadow-lg z-50 py-1 overflow-hidden",children:l.map((c)=>lt("a",{href:`/s/${c.id}`,className:"flex items-center gap-2.5 px-4 py-2.5 text-body font-body text-text-secondary hover:bg-bg-surface hover:text-text-primary transition-colors",children:[lt("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${c.currentRevision>0?"bg-accent-green":"bg-border-hover"}`},void 0,!1,void 0,this),lt("span",{className:"truncate",children:Xi(c.id,c.projectRoot)},void 0,!1,void 0,this)]},c.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as _s,useEffect as Rp,useState as fo}from"react";import{jsxDEV as le}from"react/jsx-dev-runtime";function Qi({sessionId:e,revision:t,open:n,shareEnabled:o,existingShares:r,onClose:a,onShareCreated:s,onShareRevoked:l}){let[i,c]=fo(!1),[d,u]=fo(!1),[p,f]=fo(null),[h,x]=fo(!1),g=r.find((w)=>w.revision===t);Rp(()=>{if(!n)c(!1),u(!1),f(null),x(!1)},[n]);let k=_s(async()=>{c(!0),f(null);try{let w=await fetch(`/api/session/${e}/revision/${t}/share`,{method:"POST"}),y=ni.parse(await w.json());if(!y.ok)throw Error(y.error||`HTTP ${w.status}`);if(!w.ok)throw Error(`HTTP ${w.status}`);s(y.share)}catch(w){f(Tn(w))}finally{c(!1)}},[e,t,s]),m=_s(async(w)=>{if(!window.confirm("Revoke this share link? Reviewers will no longer be able to view or comment."))return;u(!0),f(null);try{let y=await fetch(`/api/session/${e}/shares/${w}/revoke`,{method:"POST"}),S=ri.parse(await y.json());if(!S.ok)throw Error(S.error||`HTTP ${y.status}`);if(!y.ok)throw Error(`HTTP ${y.status}`);l(w)}catch(y){f(Tn(y))}finally{u(!1)}},[e,l]),b=_s((w)=>{navigator.clipboard.writeText(w).then(()=>{x(!0),setTimeout(()=>x(!1),1500)})},[]);if(!n)return null;return le("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:a,children:le("div",{className:"bg-bg-surface border border-border-medium rounded-lg shadow-xl w-full max-w-md mx-4 p-5",onClick:(w)=>w.stopPropagation(),children:[le("div",{className:"flex items-center justify-between mb-3",children:[le("h2",{className:"text-sm font-medium text-text-primary font-body",children:"Share this revision"},void 0,!1,void 0,this),le("button",{onClick:a,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:le("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!o?le("div",{className:"text-[13px] text-text-secondary font-body space-y-2",children:[le("p",{children:"Canvas sharing is not configured."},void 0,!1,void 0,this),le("p",{className:"text-text-tertiary",children:["Set ",le("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"CANVAS_SHARE_ENDPOINT"},void 0,!1,void 0,this)," to the URL of a deployed"," ",le("code",{className:"px-1 py-0.5 rounded bg-bg-elevated text-text-primary text-[11px]",children:"canvas-share"},void 0,!1,void 0,this)," worker and restart the daemon."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):g?le("div",{className:"space-y-3",children:[le("p",{className:"text-[13px] text-text-secondary font-body",children:"This revision is shared:"},void 0,!1,void 0,this),le("div",{className:"flex gap-2",children:[le("input",{type:"text",readOnly:!0,value:g.url,className:"flex-1 px-2 py-1.5 text-[12px] font-mono bg-bg-input border border-border-medium rounded text-text-primary",onFocus:(w)=>w.currentTarget.select()},void 0,!1,void 0,this),le("button",{onClick:()=>b(g.url),className:"px-3 py-1.5 text-[12px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity whitespace-nowrap",children:h?"Copied!":"Copy"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g.expiresAt&&le("p",{className:"text-[11px] text-text-tertiary font-body",children:["Expires ",new Date(g.expiresAt).toLocaleDateString(),"."]},void 0,!0,void 0,this),g.encryptionKey&&le("p",{className:"text-[11px] text-accent-green font-body flex items-center gap-1.5",children:[le("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[le("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},void 0,!1,void 0,this),le("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),"End-to-end encrypted — the key is part of the link and never leaves your browser."]},void 0,!0,void 0,this),le("p",{className:"text-[11px] text-text-tertiary font-body",children:"Anyone with this link can view and leave feedback. Reviewer feedback will appear in your annotation sidebar within seconds."},void 0,!1,void 0,this),le("div",{className:"flex items-center justify-between pt-1",children:[le("button",{onClick:k,disabled:i||d,className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body underline disabled:opacity-50",children:i?"Creating...":"Create a new link"},void 0,!1,void 0,this),g.ownerToken&&le("button",{onClick:()=>m(g.shareId),disabled:i||d,className:"text-[11px] text-accent-red hover:opacity-80 font-body underline disabled:opacity-50",children:d?"Revoking...":"Revoke link"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):le("div",{className:"space-y-3",children:[le("p",{className:"text-[13px] text-text-secondary font-body",children:"Create a public link to this revision. Anyone with the link can view the canvas and leave feedback. Reviewer feedback will sync back here automatically."},void 0,!1,void 0,this),le("button",{onClick:k,disabled:i,className:"w-full px-3 py-2 text-[13px] font-body font-medium rounded bg-accent-blue text-white hover:opacity-90 transition-opacity disabled:opacity-50",children:i?"Creating share link...":"Create share link"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p&&le("div",{className:"mt-3 px-3 py-2 rounded bg-accent-red/10 border border-accent-red/20 text-[12px] text-accent-red font-body",children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Zi({onClick:e,title:t="Share this revision",hasShare:n}){return le("button",{onClick:e,className:`group p-1.5 transition-colors ${n?"text-accent-blue hover:opacity-80":"text-text-tertiary hover:text-text-secondary"}`,title:t,children:le("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[le("circle",{cx:"18",cy:"5",r:"3"},void 0,!1,void 0,this),le("circle",{cx:"6",cy:"12",r:"3"},void 0,!1,void 0,this),le("circle",{cx:"18",cy:"19",r:"3"},void 0,!1,void 0,this),le("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"},void 0,!1,void 0,this),le("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as v,Fragment as vr}from"react/jsx-dev-runtime";function tl(e){let t=[];for(let n of e)for(let o of n.annotations)t.push({...o,source:"remote",author:n.author});return t}function Mp(e){if(e==="auto")return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return e}function nl(e){document.documentElement.dataset.theme=Mp(e)}function al(){let[e,t]=be(()=>{let r=localStorage.getItem("canvas-theme");if(r==="light"||r==="dark"||r==="auto")return r;return"auto"});return Ue(()=>{if(nl(e),e!=="auto")return;let r=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>nl("auto");return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[e]),v("button",{onClick:()=>{let r=e==="auto"?"light":e==="light"?"dark":"auto";localStorage.setItem("canvas-theme",r),t(r)},className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:{auto:"Theme: system (click for light)",light:"Theme: light (click for dark)",dark:"Theme: dark (click for system)"}[e],children:e==="auto"?v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"},void 0,!1,void 0,this),v("line",{x1:"8",y1:"21",x2:"16",y2:"21"},void 0,!1,void 0,this),v("line",{x1:"12",y1:"17",x2:"12",y2:"21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):e==="dark"?v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:v("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"},void 0,!1,void 0,this)},void 0,!1,void 0,this):v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v("circle",{cx:"12",cy:"12",r:"5"},void 0,!1,void 0,this),v("line",{x1:"12",y1:"1",x2:"12",y2:"3"},void 0,!1,void 0,this),v("line",{x1:"12",y1:"21",x2:"12",y2:"23"},void 0,!1,void 0,this),v("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},void 0,!1,void 0,this),v("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},void 0,!1,void 0,this),v("line",{x1:"1",y1:"12",x2:"3",y2:"12"},void 0,!1,void 0,this),v("line",{x1:"21",y1:"12",x2:"23",y2:"12"},void 0,!1,void 0,this),v("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},void 0,!1,void 0,this),v("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function il(){let{currentRevision:e,selectedRevision:t,revisions:n,setSelectedRevision:o,setCompareRevision:r}=Ot.useContext(Ve);if(n.length<=1){let l=n[0]?.label||`Round ${e}`;return v("span",{className:"text-[11px] text-text-tertiary font-body",children:l},void 0,!1,void 0,this)}return v("div",{className:"flex flex-col gap-1",children:[v(mr,{value:t,onChange:o,accent:t===e?"default":"amber"},void 0,!1,void 0,this),v("button",{onClick:()=>{let s;if(t===e)s=[...n].reverse().find((i)=>i.revision<e)?.revision??Math.max(1,e-1);else s=t;r({left:s,right:e})},className:"text-[11px] font-body font-medium px-2 py-0.5 rounded-md text-accent-blue hover:bg-accent-blue-muted transition-colors self-start",children:"Compare"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Lp(){let e=de.isShared?de.shareId:de.sessionId,t=de.isShared,[n,o]=be(1),[r,a]=be(1),[s,l]=be([]),[i,c]=be(null),[d,u]=be(!1),[p,f]=be(!1),[h,x]=be(!1),[g,k]=be([]),[m,b]=be({type:"overview"}),[w,y]=be([]),S=ct(null),T=ct([]),M=ct(new Set),[E,C]=be(),[O,B]=be(!1),[Y,me]=be(!1),[X,pe]=be(!1),[se,he]=be(!1),[ne,ce]=be([]),[ve,Q]=be(!1),[W,ae]=be(new Map),[D,V]=be(!1),[P,N]=be(null),[F,K]=be(null),xe=En((_)=>{if(t)return;let te=`${_.revision}\x00${_.filename}\x00${_.message}`;if(M.current.has(te))return;M.current.add(te);let oe=JSON.stringify({type:"render-error",error:_});if(S.current?.readyState===WebSocket.OPEN)S.current.send(oe);else T.current.push(_)},[t]);Ue(()=>{if(!F)return;let _=setTimeout(()=>K(null),4000);return()=>clearTimeout(_)},[F]);let ke=Math.max(0,...s.map((_)=>_.revision));Ue(()=>{if(t||!E)return;hi().catch((_)=>console.warn("Project theme not applied:",_))},[t,E,ke]),Ue(()=>{let _=["Agent Canvas"];if(E){let te=E.replace(/\/+$/,"").split("/");_.push(te[te.length-1]||e)}else if(e)_.push(e);if(m.type==="file")_.push(m.path.split("/").pop()||m.path);else if(m.type==="overview")_.push("Overview");else if(m.type==="canvas"&&g.length>1&&m.filename)_.push(m.filename.replace(/\.jsx$/,""));else if(i)_.push("Compare");document.title=_.join(" — ")},[e,E,m,i]);let Me=ct(new Map),De=s.find((_)=>_.revision===r),Ms=r!==n||!!De?.hasFeedback||p,Ls=r===n&&(!!De?.hasFeedback||p)?"next":"current",Is=En((_)=>{let te=m.type==="overview"?"overview":m.type==="canvas"?`canvas:${m.filename}`:`file:${m.path}`;if(Me.current.set(te,window.scrollY),b(_),_.type==="file")y((oe)=>oe.includes(_.path)?oe:[...oe,_.path])},[m]),ll=En((_)=>{Me.current.delete(`file:${_}`),y((te)=>te.filter((oe)=>oe!==_)),b((te)=>{if(te.type==="file"&&te.path===_)return g.length>1?{type:"overview"}:{type:"canvas",filename:g[0]||""};return te})},[g]);Np(()=>{let _=m.type==="overview"?"overview":m.type==="canvas"?`canvas:${m.filename}`:`file:${m.path}`;window.scrollTo(0,Me.current.get(_)||0)},[m]),Ue(()=>{if(!e)return;gi().then((_)=>{if(_.currentRevision){let te=_.revisions||[];for(let oe of te)if(oe.hasFeedback)Kt(localStorage,e,oe.revision);Wr(localStorage,e,_.currentRevision,te),o(_.currentRevision),a(_.currentRevision),l(te)}if(_.canvasFiles){let te=_.canvasFiles.sort();k(te),b((oe)=>{if(oe.type==="overview")return te.length>1?oe:{type:"canvas",filename:te[0]||""};if(oe.type==="canvas"&&(!oe.filename||!te.includes(oe.filename)))return{type:"canvas",filename:te[0]||""};return oe})}if(_.projectRoot)C(_.projectRoot);if(Array.isArray(_.shares))ce(_.shares);Q(!!_.shareEnabled)}).catch(()=>{})},[e]),Ue(()=>{if(!e||!r||t)return;fetch(`/api/session/${e}/revision/${r}/remote-feedback`).then((_)=>_.json()).then((_)=>{let te=ti.safeParse(_);if(!te.success)return;let oe=tl(te.data.entries);ae((Ye)=>{let ze=new Map(Ye);return ze.set(r,oe),ze})}).catch(()=>{})},[e,r,t]),Ue(()=>{if(!e)return;if(!yi){u(!0);return}let _=null,te=()=>{let oe=window.location.protocol==="https:"?"wss:":"ws:",Ye=new WebSocket(`${oe}//${window.location.host}/ws/session/${e}`);S.current=Ye,Ye.onopen=()=>{u(!0),oo?.load().catch((ze)=>console.warn(`[threads] ${Tn(ze)}`));for(let ze of T.current)Ye.send(JSON.stringify({type:"render-error",error:ze}));T.current=[]},Ye.onclose=()=>{u(!1),_=setTimeout(te,2000)},Ye.onmessage=(ze)=>{try{let Ee=JSON.parse(ze.data);if(Ee.type==="plan-updated"){let Pe=Array.isArray(Ee.revisions)?Ee.revisions:[];if(Wr(localStorage,e,Ee.currentRevision,Pe),o(Ee.currentRevision),a(Ee.currentRevision),c(null),Pe.length>0){l(Pe);let wt=Pe.find((Dt)=>Dt.revision===Ee.currentRevision);if(wt?.canvasFiles){let Dt=wt.canvasFiles.map((Cn)=>Cn.filename).sort();k(Dt);let ho=Pe.find((Cn)=>Cn.revision===Ee.currentRevision-1),Rn=Cs(wt,ho),nn=Wi(Rn);if(nn.length===1)b({type:"canvas",filename:nn[0]});else if(nn.length>1||Dt.length>1)b({type:"overview"});else b({type:"canvas",filename:Dt[0]||""})}}}if(Ee.type==="revision-updated"){if(Array.isArray(Ee.revisions)){let Pe=Ee.revisions;for(let wt of Pe)if(wt.hasFeedback)Kt(localStorage,e,wt.revision);l(Pe)}}if(Ee.type==="threads")oo?.receive(Ee.threads);if(Ee.type==="watcher-status")x(!!Ee.watching);if(Ee.type==="remote-feedback"){let Pe=Ee.revision,wt=Ee.entries||[],Dt=tl(wt);ae((ho)=>{let Rn=new Map(ho),nn=Rn.get(Pe)||[],Cn=new Set(nn.map((go)=>go.id)),cl=[...nn,...Dt.filter((go)=>!Cn.has(go.id))];return Rn.set(Pe,cl),Rn})}}catch{}}};return te(),()=>{if(_)clearTimeout(_);S.current?.close()}},[e]);let mo=En(async(_,te)=>{try{let oe=localStorage.getItem(`canvas:${e}:rev:${r}`),Ye=[],ze=[];if(oe)try{let Ee=gn(JSON.parse(oe));Ye=(Ee?.annotations??[]).filter((Pe)=>Pe.source!=="remote"),ze=Qa((Ee?.responses??[]).map(([,Pe])=>Pe))}catch{}await vi({author:te,revision:r,annotations:Ye,generalNote:_,...ze.length>0?{responses:ze}:{}}),Kt(localStorage,e,r),f(!0),K({kind:"success",message:"Feedback submitted. The canvas author will see it shortly."})}catch(oe){K({kind:"error",message:`Failed to submit feedback: ${Tn(oe)}`})}},[e,r]),Ps=En(async(_,te)=>{if(t){let oe=Ss();if(!oe){N(_),V(!0);return}await mo(_,oe);return}if(S.current?.readyState===WebSocket.OPEN)S.current.send(JSON.stringify({type:"submit",feedback:_,annotations:te}))},[t,mo]);if(!e)return v("div",{className:"flex items-center justify-center h-screen text-text-tertiary font-body",children:"No session selected."},void 0,!1,void 0,this);return v(Gr.Provider,{value:ki,children:v(sl.Provider,{value:e,children:v(dr.Provider,{value:xe,children:v(Ve.Provider,{value:{currentRevision:n,selectedRevision:r,revisions:s,setSelectedRevision:a,isReadOnly:Ms,compareRevision:i,setCompareRevision:c,agentWatching:h},children:v(Qo,{sessionId:e,revision:r,isReadOnly:Ms,draftPhase:Ls,remoteAnnotations:W.get(r),canvasFiles:g,children:v(ot.Provider,{value:{activeView:m,setActiveView:Is,openFiles:w,closeFile:ll,canvasFiles:g},children:v(Cp.Provider,{value:{setActiveView:Is},children:v("div",{className:"min-h-screen bg-bg-base",children:[v(Ip,{sessionId:e,projectRoot:E,connected:d,onMobileSidebar:()=>B(!O),collapsed:Y,onToggle:()=>me((_)=>!_)},void 0,!1,void 0,this),v(Pp,{collapsed:X,onToggle:()=>pe((_)=>!_),children:v(no,{onSubmit:Ps},void 0,!1,void 0,this)},void 0,!1,void 0,this),i!==null?v("div",{className:`${Y?"lg:ml-0":"lg:ml-60"} ${X?"lg:mr-0":"lg:mr-[var(--sidebar-width,320px)]"} transition-[margin] duration-200`,children:v($i,{initialLeft:i.left,initialRight:i.right,sessionId:e,onExit:()=>c(null)},void 0,!1,void 0,this)},void 0,!1,void 0,this):v("div",{className:`relative ${Y?"lg:ml-0":"lg:ml-60"} ${X?"lg:mr-0":"lg:mr-[var(--sidebar-width,320px)]"} transition-[margin] duration-200`,id:"plan-scroll-container",children:[v("div",{className:"lg:hidden sticky top-0 z-20 flex items-center justify-between px-4 py-2 border-b border-border-subtle bg-bg-surface",children:[v("div",{className:"flex items-center gap-2",children:[!t&&v(Ns,{currentSessionId:e,projectRoot:E},void 0,!1,void 0,this),t&&v("span",{className:"text-[11px] text-text-tertiary font-body",children:"Shared canvas"},void 0,!1,void 0,this),!t&&v("span",{className:`w-1.5 h-1.5 rounded-full ${d?"bg-accent-green":"bg-accent-red"}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("div",{className:"flex items-center gap-1",children:[v(il,{},void 0,!1,void 0,this),v("button",{onClick:()=>B(!O),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Annotations",children:v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:v("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),v(al,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),v($p,{},void 0,!1,void 0,this),m.type==="overview"&&v(Gi,{revision:r,responseBanner:De?.response?v(rl,{markdown:De.response},void 0,!1,void 0,this):void 0},void 0,!1,void 0,this),m.type==="canvas"&&g.includes(m.filename)&&v("div",{className:"relative max-w-[720px] mx-auto px-6 pt-12 pb-32",children:[ve&&v("div",{className:"absolute top-3 right-12 z-10",children:v(Zi,{onClick:()=>he(!0),hasShare:ne.some((_)=>_.revision===r),title:ne.some((_)=>_.revision===r)?"Manage share link":"Share this revision"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v("button",{onClick:()=>{let _=document.querySelector(`[data-canvas-file="${m.filename}"] .plan-content`);if(!_)return;let te=Hi(_);navigator.clipboard.writeText(te).then(()=>{let oe=document.getElementById("export-md-btn");if(oe)oe.setAttribute("data-copied","true"),setTimeout(()=>{oe.removeAttribute("data-copied")},1500)})},id:"export-md-btn",className:"group absolute top-3 right-6 p-1.5 text-text-tertiary hover:text-text-secondary transition-colors z-10",title:"Copy as Markdown",children:[v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"group-[[data-copied=true]]:hidden",children:[v("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},void 0,!1,void 0,this),v("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"hidden group-[[data-copied=true]]:block text-green-500",children:v("polyline",{points:"20 6 9 17 4 12"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g.length<=1&&De?.response&&v(rl,{markdown:De.response},void 0,!1,void 0,this),v("div",{"data-canvas-file":m.filename,children:v(Sn,{revision:r,filename:m.filename},m.filename,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.map((_)=>v("div",{style:{display:m.type==="file"&&m.path===_?void 0:"none"},children:v(qi,{path:_},void 0,!1,void 0,this)},_,!1,void 0,this))]},void 0,!0,void 0,this),O&&v("div",{className:"lg:hidden fixed inset-0 z-40 flex",children:[v("div",{className:"flex-1",onClick:()=>B(!1)},void 0,!1,void 0,this),v("div",{className:"w-80 max-w-[85vw] bg-bg-surface border-l border-border-subtle flex flex-col shadow-lg",children:[v("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border-subtle flex-shrink-0",children:[v("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:"Sidebar"},void 0,!1,void 0,this),v("button",{onClick:()=>B(!1),className:"text-text-tertiary hover:text-text-secondary w-7 h-7 flex items-center justify-center",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("div",{className:"flex-1 overflow-hidden",children:v(no,{onSubmit:Ps},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),v(Qi,{sessionId:e,revision:r,open:se,shareEnabled:ve,existingShares:ne,onClose:()=>he(!1),onShareCreated:(_)=>{ce((te)=>[...te.filter((oe)=>oe.shareId!==_.shareId),_]),K({kind:"success",message:"Share link created. Copy and send it to reviewers."})},onShareRevoked:(_)=>{ce((te)=>te.filter((oe)=>oe.shareId!==_)),K({kind:"success",message:"Share link revoked."})}},void 0,!1,void 0,this),v(Ki,{open:D,onClose:()=>{V(!1),N(null)},onSubmit:async(_)=>{let te=bi(_);if(V(!1),P!==null)await mo(P,te),N(null)}},void 0,!1,void 0,this),F&&v("div",{className:`fixed bottom-4 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-lg text-[13px] font-body font-medium flex items-center gap-2 ${F.kind==="error"?"bg-accent-red text-white":"bg-accent-green text-white"}`,children:[F.message,v("button",{onClick:()=>K(null),className:"ml-2 opacity-70 hover:opacity-100",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},`${e}:${r}:${Ls}`,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Ip({sessionId:e,projectRoot:t,connected:n,onMobileSidebar:o,collapsed:r,onToggle:a}){let s=de.isShared;return v(vr,{children:[r&&v("button",{onClick:a,className:"hidden lg:flex fixed top-3 left-3 z-20 w-7 h-7 items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors bg-bg-surface border border-border-subtle",title:"Show sidebar",children:v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},void 0,!1,void 0,this),v("line",{x1:"9",y1:"3",x2:"9",y2:"21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),v("div",{className:`hidden lg:flex w-60 flex-col fixed top-0 left-0 bottom-0 bg-bg-surface border-r border-border-subtle z-10 transition-transform duration-200 ${r?"-translate-x-full":""}`,children:[v("div",{className:"px-4 pt-4 pb-3 flex-shrink-0 border-b border-border-subtle",children:[v("div",{className:"flex items-center gap-2 mb-2",children:[v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"text-text-tertiary flex-shrink-0",children:v("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s?v("span",{className:"text-[12px] font-body text-text-secondary truncate flex-1",children:"Shared canvas"},void 0,!1,void 0,this):v(vr,{children:[v(Ns,{currentSessionId:e,projectRoot:t},void 0,!1,void 0,this),v("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${n?"bg-accent-green":"bg-accent-red"}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("button",{onClick:a,className:"ml-auto w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Hide sidebar",children:v("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v("polyline",{points:"11 17 6 12 11 7"},void 0,!1,void 0,this),v("polyline",{points:"18 17 13 12 18 7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(il,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("div",{className:"flex-1 flex flex-col overflow-hidden",children:v(ji,{embedded:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this),v("div",{className:"px-4 py-3 border-t border-border-subtle flex items-center justify-between flex-shrink-0",children:[v("span",{className:"text-[10px] text-text-tertiary font-body uppercase tracking-widest",children:"Theme"},void 0,!1,void 0,this),v(al,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Pp({children:e,collapsed:t,onToggle:n}){let[o,r]=be(()=>{let d=localStorage.getItem("canvas-sidebar-width");return d?parseInt(d,10):320}),a=ct(!1),s=ct(0),l=ct(0),i=ct(o);i.current=o;let c=En((d)=>{d.preventDefault(),a.current=!0,s.current=d.clientX,l.current=i.current;let u=(f)=>{if(!a.current)return;let h=s.current-f.clientX,x=Math.max(240,Math.min(600,l.current+h));r(x),i.current=x},p=()=>{a.current=!1,localStorage.setItem("canvas-sidebar-width",String(i.current)),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",u),document.addEventListener("mouseup",p),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);return Ue(()=>(document.documentElement.style.setProperty("--sidebar-width",`${o}px`),()=>{document.documentElement.style.removeProperty("--sidebar-width")}),[o]),v(vr,{children:[t&&v("button",{onClick:n,className:"hidden lg:flex fixed top-3 right-3 z-20 w-7 h-7 items-center justify-center rounded-md text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors bg-bg-surface border border-border-subtle",title:"Show annotations",children:v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:v("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),v("div",{className:`hidden lg:flex flex-col fixed top-0 right-0 bottom-0 bg-bg-surface border-l border-border-subtle z-10 transition-transform duration-200 ${t?"translate-x-full":""}`,style:{width:o},children:[v("div",{onMouseDown:c,className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-accent-blue/30 transition-colors z-20",style:{marginLeft:"-2px"}},void 0,!1,void 0,this),Ot.Children.map(e,(d)=>Ot.isValidElement(d)?Ot.cloneElement(d,{collapseButton:v("button",{onClick:n,className:"w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",title:"Hide annotations",children:v("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v("polyline",{points:"13 17 18 12 13 7"},void 0,!1,void 0,this),v("polyline",{points:"6 17 11 12 6 7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}):d)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function rl({markdown:e}){let[t,n]=be(!1),o=el(()=>eo(e),[e]),r=ct(null),{annotations:a,addAnnotationWithId:s,removeAnnotation:l,updateAnnotation:i,addAnnotationImage:c,removeAnnotationImage:d,activeAnnotationId:u,setActiveAnnotationId:p}=it(),[f,h]=be(null),[x,g]=be(null),k=el(()=>a.filter((S)=>S.filePath===Be),[a]),[m,b]=be(e);if(e!==m)b(e),n(!1);Ue(()=>{if(!r.current||k.length===0)return;let S=setTimeout(()=>{if(r.current)Ln(r.current,k)},50);return()=>clearTimeout(S)},[o,k.length]);let w=ct(null);if(Ue(()=>{_n(u,w.current),w.current=u},[u]),Ue(()=>{let S=r.current;if(!S)return;let T=(C)=>{let O=C.target.closest("[data-annotation-id]");if(!O)return;C.stopPropagation();let B=O.getAttribute("data-annotation-id");if(B===u)g({anchorEl:O,annId:B});else p(B)},M=(C)=>{let O=C.target.closest("[data-annotation-id]");if(O)p(O.getAttribute("data-annotation-id"))},E=(C)=>{let O=C.target.closest("[data-annotation-id]"),B=C.relatedTarget?.closest?.("[data-annotation-id]");if(O&&!B)p(null)};return S.addEventListener("click",T),S.addEventListener("mouseover",M),S.addEventListener("mouseout",E),()=>{S.removeEventListener("click",T),S.removeEventListener("mouseover",M),S.removeEventListener("mouseout",E)}},[o,u]),Ue(()=>{let S=()=>{let T=window.getSelection();if(!T||T.isCollapsed||!T.toString().trim())return;if(!r.current)return;let M=T.getRangeAt(0);if(!r.current.contains(M.startContainer))return;if(M.startContainer.parentElement?.closest?.("[data-annotation-id]"))return;let E=T.toString().trim();if(E.length<2)return;let C=M.cloneRange(),O=At(M,r.current),B=`__pending_${Date.now()}`;try{St(C,B)}catch{}window.getSelection()?.removeAllRanges();let Y=document.querySelectorAll(`[data-annotation-id="${B}"]`),me=Y[Y.length-1];if(!me)return;h({anchorEl:me,tempId:B,snippet:E,ctx:O})};return document.addEventListener("mouseup",S),()=>document.removeEventListener("mouseup",S)},[]),t)return null;let y=document.getElementById("plan-scroll-container");return v("div",{className:"mb-6 rounded-lg border border-accent-blue/20 bg-accent-blue/5 relative",children:[v("button",{onClick:()=>n(!0),className:"absolute top-2 right-2 w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-elevated transition-colors",children:v("span",{className:"text-xs",children:"✕"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v("div",{className:"px-4 py-3 pr-10",children:[v("div",{className:"flex items-center gap-2 mb-1.5",children:[v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-blue flex-shrink-0",children:v("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v("span",{className:"text-[11px] font-medium uppercase tracking-widest text-accent-blue font-body",children:"Agent Response"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("div",{ref:r,className:"prose-canvas text-sm",dangerouslySetInnerHTML:{__html:o}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),f&&v(nt,{anchorEl:f.anchorEl,scrollContainer:y,snippet:f.snippet,truncateAt:80,onAdd:(S,T)=>{let M=qe();Mn(f.tempId,M),s(M,f.snippet,S,Be,f.ctx,T),h(null)},onCancel:()=>{In(f.tempId),h(null)}},void 0,!1,void 0,this),x&&(()=>{let S=a.find((T)=>T.id===x.annId);if(!S)return null;return v(Wt,{anchorEl:x.anchorEl,scrollContainer:y,initialNote:S.note,initialImages:S.images,onUpdate:(T,M)=>{i(x.annId,T);let E=S.images||[];for(let C of M)if(!E.includes(C))c(x.annId,C);for(let C of E)if(!M.includes(C))d(x.annId,C)},onDelete:()=>{l(x.annId),p(null)},onClose:()=>g(null)},void 0,!1,void 0,this)})()]},void 0,!0,void 0,this)}function $p(){let{activeView:e,setActiveView:t,openFiles:n,closeFile:o,canvasFiles:r}=Ot.useContext(ot),a=Ot.useContext(sl),{addAnnotationWithId:s,setActiveAnnotationId:l}=it();if(!(r.length>1||n.length>0))return null;return v("div",{className:"flex items-center border-b border-border-medium bg-bg-surface overflow-x-auto sticky top-0 z-10",children:[r.length>1&&v(vr,{children:[v("button",{onClick:()=>t({type:"overview"}),className:`flex items-center gap-1.5 px-4 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${e.type==="overview"?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[v("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"opacity-60",children:v("path",{d:"M12 7L2 12l10 5 10-5-10-5z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Overview",e.type==="overview"&&v("span",{className:"absolute bottom-0 left-3 right-3 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r.map((c,d)=>{let u=c.replace(/\.jsx$/,""),p=e.type==="canvas"&&e.filename===c;return v(Ot.Fragment,{children:[v("button",{onClick:()=>t({type:"canvas",filename:c}),className:`flex items-center gap-1.5 px-4 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${p?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[u,p&&v("span",{className:"absolute bottom-0 left-3 right-3 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d<r.length-1&&v("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},c,!0,void 0,this)}),n.length>0&&v(vr,{children:[v("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this),n.map((c,d)=>{let u=c.split("/").pop()||c,p=e.type==="file"&&e.path===c;return v(Ot.Fragment,{children:[v("div",{className:"flex items-center",children:[v("button",{onClick:()=>t({type:"file",path:c}),className:`flex items-center gap-1.5 pl-3 pr-1 py-2.5 text-[13px] font-body whitespace-nowrap transition-colors relative ${p?"text-text-primary":"text-text-tertiary hover:text-text-secondary"}`,children:[v(Lt,{name:u,type:"file"},void 0,!1,void 0,this),u,p&&v("span",{className:"absolute bottom-0 left-3 right-1 h-[2px] bg-text-primary rounded-full"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v("button",{onClick:(f)=>{f.stopPropagation(),o(c)},className:"text-text-tertiary hover:text-text-secondary px-1.5 py-1 text-[10px] transition-colors rounded hover:bg-bg-input",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d<n.length-1&&v("span",{className:"w-px h-4 bg-border-medium flex-shrink-0"},void 0,!1,void 0,this)]},c,!0,void 0,this)})]},void 0,!0,void 0,this),v("div",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:e.type==="file"&&bt&&v("button",{onClick:async()=>{let c=e.path;try{let d=await fetch(`/api/file?session=${a}&path=${encodeURIComponent(c)}`),u=Mt.parse(await d.json());if("content"in u){let p=u.content.split(`
86
86
  `).slice(0,3).join(`
87
- `)+(K.content.split(`
87
+ `)+(u.content.split(`
88
88
  `).length>3?`
89
- ...`:""),O=x$();X(O,N,"",H),W(O)}}catch{}},className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-medium font-body text-text-tertiary hover:text-text-secondary whitespace-nowrap transition-colors",children:[P("span",{className:"text-[13px] leading-none",children:"+"},void 0,!1,void 0,this),"Add to context"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var t6=document.getElementById("root");if(t6)Nq(t6).render(P(zq,{},void 0,!1,void 0,this));
89
+ ...`:""),f=qe();s(f,p,"",c),l(f)}}catch{}},className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-medium font-body text-text-tertiary hover:text-text-secondary whitespace-nowrap transition-colors",children:[v("span",{className:"text-[13px] leading-none",children:"+"},void 0,!1,void 0,this),"Add to context"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ol=document.getElementById("root");if(ol)_p(ol).render(v(Lp,{},void 0,!1,void 0,this));