@waniwani/sdk 0.22.0-beta.7 → 0.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/embed.js +19 -19
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/index.js +11 -11
- package/dist/chat/index.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.d.ts +66 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react/skybridge.js +1 -1
- package/dist/mcp/react/skybridge.js.map +1 -1
- package/dist/mcp/react.js +1 -1
- package/dist/mcp/react.js.map +1 -1
- package/package.json +1 -1
package/dist/chat/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as di,b as ci,c as fi,d as pi,e as mi,f as Sr,g as hi,h as gi,i as wi,j as Ii,k as No,l as xi,m as ea,n as ta,o as Cr,p as aa,u as ya}from"../chunk-QIQG7C7A.js";import"../chunk-V3ZDECK5.js";import{useCallback as km,useEffect as Mr,useMemo as Tm,useRef as _e,useState as al}from"react";function ra(e){if(!e)return!1;let t=Array.isArray(e.content)&&e.content.length>0,a=typeof e.structuredContent=="object"&&e.structuredContent!==null&&Object.keys(e.structuredContent).length>0;return t||a}function yi(e,t){return!ra(e)&&!ra(t)?null:ra(e)?ra(t)?{...e.content||t.content?{content:[...e.content??[],...t.content??[]]}:{},...e.structuredContent||t.structuredContent?{structuredContent:{...e.structuredContent??{},...t.structuredContent??{}}}:{}}:{...e.content?{content:[...e.content]}:{},...e.structuredContent?{structuredContent:{...e.structuredContent}}:{}}:{...t?.content?{content:[...t.content]}:{},...t?.structuredContent?{structuredContent:{...t.structuredContent}}:{}}}import{forwardRef as dp,createElement as cp}from"react";var br=(...e)=>e.filter((t,a,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===a).join(" ").trim();var Li=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var Si=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,r)=>r?r.toUpperCase():a.toLowerCase());var qo=e=>{let t=Si(e);return t.charAt(0).toUpperCase()+t.slice(1)};import{forwardRef as up,createElement as vi}from"react";var Ci={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var bi=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var ki=up(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:r,className:o="",children:n,iconNode:s,...i},l)=>vi("svg",{ref:l,...Ci,width:t,height:t,stroke:e,strokeWidth:r?Number(a)*24/Number(t):a,className:br("lucide",o),...!n&&!bi(i)&&{"aria-hidden":"true"},...i},[...s.map(([u,d])=>vi(u,d)),...Array.isArray(n)?n:[n]]));var ce=(e,t)=>{let a=dp(({className:r,...o},n)=>cp(ki,{ref:n,iconNode:t,className:br(`lucide-${Li(qo(e))}`,`lucide-${e}`,r),...o}));return a.displayName=qo(e),a};var fp=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],La=ce("arrow-down",fp);var pp=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Sa=ce("arrow-up",pp);var mp=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ca=ce("check",mp);var hp=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],vt=ce("chevron-down",hp);var gp=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ba=ce("chevron-right",gp);var wp=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]],va=ce("clipboard-copy",wp);var Ip=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],ht=ce("clock",Ip);var xp=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ka=ce("file-text",xp);var yp=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],oa=ce("file",yp);var Lp=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Ta=ce("globe",Lp);var Sp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Aa=ce("image",Sp);var Cp=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],Pa=ce("loader",Cp);var bp=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],na=ce("paperclip",bp);var vp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Ra=ce("square",vp);var kp=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],qt=ce("wrench",kp);var Tp=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],kt=ce("x",Tp);var Ap=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Ea=ce("zap",Ap);import{createContext as Hp,useCallback as $p,useContext as _i,useEffect as Wp,useMemo as Ko,useRef as jp,useState as Xo}from"react";function Ho(e){if(!(typeof e!="object"||e===null))return e}function Ti(e){return Ho(e?.ui)}function $o(e){if(!e)return;let t=Ti(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let a=e["ui/resourceUri"];if(typeof a=="string"&&a.length>0)return a;let r=e["openai/outputTemplate"];if(typeof r=="string"&&r.length>0)return r}function Ma(e){return Ti(e)?.autoHeight===!0}function Wo(e){return Ho(Ho(e)?._meta)}import{createContext as Pp,useContext as Rp,useEffect as Ep,useMemo as Mp,useState as Ei}from"react";var Ai=["en","fr","es"];function sa(e){return Ai.includes(e)}function jo(e){if(e&&sa(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&sa(a))return a}let t=[];if(typeof navigator<"u"&&(navigator.language&&t.push(navigator.language),navigator.languages&&t.push(...navigator.languages)),typeof document<"u"){let a=document.documentElement.getAttribute("lang");a&&t.push(a)}for(let a of t){let r=a.toLowerCase();if(sa(r))return r;let o=r.split("-")[0];if(o&&sa(o))return o}return"en"}var vr={promptInput:{placeholder:"What would you like to know?",uploadFiles:"Upload files",uploadFilesUpTo:"Upload a document, up to {limit}",uploadFilesUpToWithPages:"Upload a document, up to {limit} and {pages} pages",stop:"Stop",submit:"Submit",removeAttachments:"Remove all attachments",removeAttachment:"Remove attachment",uploading:"Uploading\u2026",retry:"Retry",retryUpload:"Retry the upload",uploadFailed:"The upload did not finish.",dropToAttach:"Drop to attach",errorAccept:"{name} is not a file type this chat accepts.",errorTooLarge:"{name} is larger than {limit}.",errorTooMany:"You can attach up to {limit} files."},workingIndicator:{default:"On it\u2026"},reasoning:{thinking:"Thinking\u2026",thoughtBrief:"Thought for a few seconds",thoughtForSeconds:e=>`Thought for ${e} second${e===1?"":"s"}`},chainOfThought:{working:"Working on it\u2026",done:"Thought process"},tool:{copy:"Copy",copied:"Copied",request:"Request",response:"Response",error:"Error"},attachments:{attachmentFallback:"attachment",kindPdf:"PDF",kindImage:"Image",kindFile:"File",fileFallback:"file"},threadMenu:{newChat:"New chat",threadHistory:"Thread history",deleteThread:"Delete thread",noPreviousChats:"No previous chats yet.",hiddenThreads:e=>`${e} older thread${e===1?"":"s"} hidden`},chatQueue:{attachmentFallback:"(attachment)",removeFromQueue:"Remove from queue",queued:e=>`${e} queued`},poweredBy:{label:"AI agent powered by"},aiDisclaimer:{default:"can make mistakes"},exportSession:{saving:"saving...",saved:"saved",error:"error",export:"export",tooltip:"Save scenario to Waniwani"},widgetErrorBoundary:{failedToLoad:"Widget failed to load",retry:"Retry"},launcher:{prompt:"Ask anything\u2026",open:"Open chat",close:"Close chat",minimize:"Minimize"}};var Pi={promptInput:{placeholder:"\xBFQu\xE9 te gustar\xEDa saber?",uploadFiles:"Subir archivos",uploadFilesUpTo:"Subir un documento, hasta {limit}",uploadFilesUpToWithPages:"Subir un documento, hasta {limit} y {pages} p\xE1ginas",stop:"Detener",submit:"Enviar",removeAttachments:"Eliminar todos los archivos adjuntos",removeAttachment:"Quitar archivo",uploading:"Subiendo\u2026",retry:"Reintentar",retryUpload:"Reintentar la subida",uploadFailed:"La subida no se complet\xF3.",dropToAttach:"Suelta para adjuntar",errorAccept:"{name} no es un tipo de archivo que acepte este chat.",errorTooLarge:"{name} supera {limit}.",errorTooMany:"Puedes adjuntar hasta {limit} archivos."},workingIndicator:{default:"Un momento\u2026"},reasoning:{thinking:"Pensando\u2026",thoughtBrief:"Pensado durante unos segundos",thoughtForSeconds:e=>`Pensado durante ${e} segundo${e===1?"":"s"}`},chainOfThought:{working:"Estoy en ello\u2026",done:"Razonamiento"},tool:{copy:"Copiar",copied:"Copiado",request:"Solicitud",response:"Respuesta",error:"Error"},attachments:{attachmentFallback:"adjunto",kindPdf:"PDF",kindImage:"Imagen",kindFile:"Archivo",fileFallback:"archivo"},threadMenu:{newChat:"Nueva conversaci\xF3n",threadHistory:"Historial",deleteThread:"Eliminar conversaci\xF3n",noPreviousChats:"A\xFAn no hay conversaciones anteriores.",hiddenThreads:e=>`${e} conversaci\xF3n${e===1?"":"es"} anterior${e===1?"":"es"} oculta${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(adjunto)",removeFromQueue:"Quitar de la cola",queued:e=>`${e} en cola`},poweredBy:{label:"Agente IA con tecnolog\xEDa de"},aiDisclaimer:{default:"puede cometer errores"},exportSession:{saving:"guardando...",saved:"guardado",error:"error",export:"exportar",tooltip:"Guardar escenario en Waniwani"},widgetErrorBoundary:{failedToLoad:"No se pudo cargar el widget",retry:"Reintentar"},launcher:{prompt:"Pregunta lo que quieras\u2026",open:"Abrir chat",close:"Cerrar chat",minimize:"Minimizar"}};var Ri={promptInput:{placeholder:"Que souhaitez-vous savoir ?",uploadFiles:"Importer des fichiers",uploadFilesUpTo:"Joindre un document, jusqu'\xE0 {limit}",uploadFilesUpToWithPages:"Envoyer un document, jusqu'\xE0 {limit} et {pages} pages",stop:"Arr\xEAter",submit:"Envoyer",removeAttachments:"Supprimer toutes les pi\xE8ces jointes",removeAttachment:"Retirer la pi\xE8ce jointe",uploading:"Envoi en cours\u2026",retry:"R\xE9essayer",retryUpload:"R\xE9essayer l'envoi",uploadFailed:"L'envoi ne s'est pas termin\xE9.",dropToAttach:"D\xE9posez pour joindre",errorAccept:"{name} n'est pas un type de fichier accept\xE9 par ce chat.",errorTooLarge:"{name} d\xE9passe {limit}.",errorTooMany:"Vous pouvez joindre jusqu'\xE0 {limit} fichiers."},workingIndicator:{default:"Un instant\u2026"},reasoning:{thinking:"R\xE9flexion\u2026",thoughtBrief:"R\xE9flexion pendant quelques secondes",thoughtForSeconds:e=>`R\xE9flexion pendant ${e} seconde${e===1?"":"s"}`},chainOfThought:{working:"Je m'en occupe\u2026",done:"Raisonnement"},tool:{copy:"Copier",copied:"Copi\xE9",request:"Requ\xEAte",response:"R\xE9ponse",error:"Erreur"},attachments:{attachmentFallback:"pi\xE8ce jointe",kindPdf:"PDF",kindImage:"Image",kindFile:"Fichier",fileFallback:"fichier"},threadMenu:{newChat:"Nouvelle conversation",threadHistory:"Historique",deleteThread:"Supprimer la conversation",noPreviousChats:"Aucune conversation pr\xE9c\xE9dente.",hiddenThreads:e=>`${e} conversation${e===1?"":"s"} plus ancienne${e===1?"":"s"} masqu\xE9e${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(pi\xE8ce jointe)",removeFromQueue:"Retirer de la file",queued:e=>`${e} en attente`},poweredBy:{label:"Agent IA propuls\xE9 par"},aiDisclaimer:{default:"peut faire des erreurs"},exportSession:{saving:"enregistrement...",saved:"enregistr\xE9",error:"erreur",export:"exporter",tooltip:"Enregistrer le sc\xE9nario dans Waniwani"},widgetErrorBoundary:{failedToLoad:"\xC9chec du chargement du widget",retry:"R\xE9essayer"},launcher:{prompt:"Posez votre question\u2026",open:"Ouvrir le chat",close:"Fermer le chat",minimize:"R\xE9duire"}};var zo={en:vr,fr:Ri,es:Pi};import{jsx as Dp}from"react/jsx-runtime";var Mi=Pp(null);function Fp(e,t){if(!t)return e;let a={...e};for(let r of Object.keys(e)){let o=e[r],n=t[r];n&&typeof o=="object"&&(a[r]={...o,...n})}return a}function Vo({children:e,locale:t,messages:a}){let r=!!(t&&_p(t)),o=r?t:"en",[n,s]=Ei(o),[i,l]=Ei(r);Ep(()=>{s(jo(t)),l(!0)},[t]);let u=Mp(()=>{let d=zo[n]??zo["en"];return{locale:n,t:Fp(d,a),ready:i}},[n,a,i]);return Dp(Mi.Provider,{value:u,children:e})}function _p(e){return e==="en"||e==="fr"||e==="es"}function te(){let e=Rp(Mi);return e||{locale:"en",t:vr,ready:!0}}function Go(e,t){let a=Date.now()-e;if(a<6e4)try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"narrow"}).format(0,"second")}catch{return"just now"}let r,o;a<60*6e4?(r=-Math.floor(a/6e4),o="minute"):a<1440*6e4?(r=-Math.floor(a/(60*6e4)),o="hour"):(r=-Math.floor(a/(1440*6e4)),o="day");try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"short"}).format(r,o)}catch{return`${Math.abs(r)}${o==="minute"?"m":o==="hour"?"h":"d"} ago`}}var Bp=ci({prefix:"ww"});function P(...e){return Bp(di(e))}import{jsx as Op}from"react/jsx-runtime";var it=({className:e,variant:t="default",size:a="default",type:r="button",...o})=>Op("button",{type:r,className:P("ww:inline-flex ww:cursor-pointer ww:items-center ww:justify-center ww:rounded-md ww:font-medium ww:transition-colors ww:disabled:pointer-events-none ww:disabled:opacity-50",t==="default"&&"ww:bg-primary ww:text-primary-foreground ww:hover:bg-primary/90",t==="outline"&&"ww:border ww:border-border ww:bg-background ww:hover:bg-accent ww:hover:text-accent-foreground",t==="ghost"&&"ww:hover:bg-accent ww:hover:text-accent-foreground",a==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",a==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",a==="icon"&&"ww:size-9 ww:!rounded-full",a==="icon-sm"&&"ww:size-7 ww:!rounded-full",e),...o});import{memo as Up}from"react";import{jsx as qp}from"react/jsx-runtime";var Np=({as:e="span",className:t,duration:a=2,style:r,children:o,...n})=>{let s={backgroundImage:"linear-gradient(90deg, var(--ww-color-muted-foreground) 0%, var(--ww-color-muted-foreground) 40%, var(--ww-color-foreground) 50%, var(--ww-color-muted-foreground) 60%, var(--ww-color-muted-foreground) 100%)",backgroundSize:"250% 100%",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent",animation:`ww-shimmer ${a}s linear infinite`,...r};return qp(e,{"data-waniwani-shimmer":"",className:P("ww:inline-block",t),style:s,...n,children:o})},et=Up(Np);et.displayName="Shimmer";import{Fragment as Fi,jsx as ge,jsxs as Ht}from"react/jsx-runtime";function zp(e,t=80){if(e==null)return String(e);if(typeof e!="object")return String(e).slice(0,t);if(Array.isArray(e))return`Array(${e.length})`;let a=JSON.stringify(e);if(a.length<=t)return a;let r=Object.entries(e),o=[],n=t-2;for(let[s,i]of r){if(n<=8)break;let l=s.length>4?`${s.slice(0,4)}\u2026`:s,u;typeof i=="string"?u=i.length>2?`'${i.slice(0,1)}\u2026`:`'${i}'`:Array.isArray(i)?u=`Array(${i.length})`:typeof i=="object"&&i!==null?u="{\u2026}":u=String(i);let d=`${l}\u2009${u}`;o.push(d),n-=d.length+3}return`{${o.join(", ")}}`}function Vp({text:e,className:t}){let{t:a}=te(),[r,o]=Xo(!1),n=jp(null);Wp(()=>()=>{n.current&&clearTimeout(n.current)},[]);let s=$p(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>o(!1),2e3)}catch{}},[e]);return ge(it,{variant:"ghost",size:"sm",onClick:s,className:P("ww:h-auto ww:gap-1 ww:px-1.5 ww:py-0.5 ww:text-xs ww:text-muted-foreground ww:hover:text-foreground",t),children:r?Ht(Fi,{children:[ge(Ca,{className:"ww:size-3.5"}),ge("span",{children:a.tool.copied})]}):Ht(Fi,{children:[ge(va,{className:"ww:size-3.5"}),ge("span",{children:a.tool.copy})]})})}function Di({data:e,label:t,className:a,...r}){let[o,n]=Xo(!1),s=Ko(()=>JSON.stringify(e,null,2),[e]),i=zp(e);return Ht("div",{className:P("ww:rounded-lg ww:bg-tool-card",a),...r,children:[Ht("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[ge("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),ge(Vp,{text:s})]}),Ht("button",{type:"button",onClick:()=>n(l=>!l),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[ge(ba,{className:P("ww:mt-0.5 ww:size-3.5 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-150",o&&"ww:rotate-90")}),o?ge("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:ge("code",{children:s})}):ge("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:i})]})]})}var Jo=Hp({open:!1,toggle:()=>{}});function Bi({className:e,defaultOpen:t=!1,children:a,...r}){let[o,n]=Xo(t);return ge(Jo.Provider,{value:{open:o,toggle:()=>n(s=>!s)},children:ge("div",{className:P("ww:mb-4 ww:w-full",e),"data-state":o?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...r,children:a})})}function Oi({className:e,title:t,state:a,...r}){let{open:o,toggle:n}=_i(Jo),s=a==="input-available"||a==="input-streaming",i=t??"";return Ht("button",{type:"button",onClick:n,className:P("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),"aria-expanded":o,...r,children:[ge(qt,{className:"ww:size-4 ww:shrink-0"}),ge("span",{className:"ww:truncate",children:s?ge(et,{duration:1.6,children:i}):i}),ge(vt,{className:P("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function Ui({className:e,title:t,state:a,...r}){let o=a==="input-available"||a==="input-streaming",n=t??"";return ge("div",{className:P("ww:mb-4 ww:flex ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...r,children:ge("span",{className:"ww:truncate",children:o?ge(et,{duration:1.6,children:n}):n})})}function Ni({className:e,children:t,...a}){let{open:r}=_i(Jo);return ge("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:ge("div",{className:"ww:min-h-0 ww:overflow-hidden",children:ge("div",{className:P("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...a,children:t})})})}function Qo({className:e,input:t,debug:a,...r}){let{t:o}=te(),n=Ko(()=>{if(!a&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:s,...i}=t;return i}return t},[t,a]);return ge(Di,{data:n,label:o.tool.request,className:e,...r})}function Fa(e,t,a){if(e){let r=$o(a?.[e]?._meta);if(r)return r}return $o(Wo(t))}function qi(e,t,a){return e&&Ma(a?.[e]?._meta)?!0:Ma(Wo(t))}function Yo({className:e,output:t,errorText:a,debug:r,...o}){let{t:n}=te(),s=Ko(()=>{if(!r&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:i,...l}=t;return l}return t},[t,r]);return t||a?a?Ht("div",{className:P("ww:space-y-2",e),...o,children:[ge("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:n.tool.error}),ge("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):ge(Di,{data:s,label:n.tool.response,className:e,...o}):null}var Hi=typeof performance>"u"?0:performance.now(),$i=typeof window<"u"&&!!window.WaniWani?.chat;function tt(e,t,a){let[r,o=""]=e.split("?"),n=r.replace(/\/$/,""),s=new URLSearchParams(o);if(a)for(let[l,u]of Object.entries(a))s.set(l,u);let i=s.toString();return`${n}${t}${i?`?${i}`:""}`}var Gp="/api/mcp/";function kr(e,t){let[a=""]=e.split("?"),r="",o=a;try{let n=new URL(a);r=n.origin,o=n.pathname}catch{if(!a.startsWith("/"))return null}return o.startsWith(Gp)?`${r}${t}`:null}function Kp(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function lt(...e){Kp()&&console.log("[Waniwani]",...e)}var Zo="waniwani-visitor-id";function Xp(){try{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,a=>a.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}}catch{}return`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ge(){try{let t=localStorage.getItem(Zo);if(t)return t}catch{}let e=Xp();try{localStorage.setItem(Zo,e)}catch{}return e}function en(e){let t=typeof e=="string"?e.trim():"";if(!t)return Ge();try{localStorage.setItem(Zo,t)}catch{}return t}function Jp(e){return e!=null&&typeof e.then=="function"}function tn(e){let t=!1,a=()=>{t=!0};if(e==null)return a;let r;try{r=typeof e=="function"?e():e}catch{return a}return Jp(r)?r.then(o=>{t||en(o??"")},()=>{}):en(r??""),a}var Qp="waniwani-memory";var Ke="threads",Tr="by_memoryUserId",Yp="by_updatedAt";var ji="memoryUserId",Wi="waniwani-memory-user-id",an=null;function rn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Zp(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(Ke)){let a=e.createObjectStore(Ke,{keyPath:"threadId"});a.createIndex(Tr,"memoryUserId",{unique:!1}),a.createIndex(Yp,"updatedAt",{unique:!1})}}async function on(){return new Promise((e,t)=>{let a=indexedDB.open(Qp,2);a.onupgradeneeded=r=>{Zp(a.result,r.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function em(){return on()}async function tm(e){return new Promise((t,a)=>{let n=e.transaction("ids","readonly").objectStore("ids").get(ji);n.onsuccess=()=>t(typeof n.result=="string"?n.result:null),n.onerror=()=>a(n.error)})}async function am(e,t){return new Promise((a,r)=>{let s=e.transaction("ids","readwrite").objectStore("ids").put(t,ji);s.onsuccess=()=>a(),s.onerror=()=>r(s.error)})}async function rm(){if(typeof indexedDB>"u")return null;try{let e=await em();try{let t=await tm(e);if(t)return t;let a=rn();return await am(e,a),a}finally{e.close()}}catch{return null}}function om(){try{let e=localStorage.getItem(Wi);if(e)return e;let t=rn();return localStorage.setItem(Wi,t),t}catch{return null}}async function zi(){let e=await rm();if(e)return e;let t=om();return t||(an||(an=rn()),an)}function Vi(e,t){return e.match(t)?.[1]??null}function nm(e){let t=[["Edge",/Edg(?:e|A|iOS)?\/(\S+)/],["Opera",/(?:OPR|Opera)\/(\S+)/],["Samsung Internet",/SamsungBrowser\/(\S+)/],["Firefox",/Firefox\/(\S+)/],["Chrome",/Chrome\/(\S+)/],["Safari",/Version\/(\S+).*Safari/]];for(let[a,r]of t){let o=Vi(e,r);if(o)return{name:a,version:o}}return null}function sm(e){let t=[["iOS",/(?:iPhone|iPad|iPod).+?OS (\d+[_.\d]*)/],["Android",/Android (\d+[.\d]*)/],["macOS",/Mac OS X (\d+[_.\d]*)/],["Windows",/Windows NT (\d+[.\d]*)/],["ChromeOS",/CrOS \S+ (\d+[.\d]*)/],["Linux",/Linux/]];for(let[a,r]of t){let o=Vi(e,r);if(o)return{name:a,version:o.replace(/_/g,".")};if(a==="Linux"&&r.test(e))return{name:a,version:""}}return null}function im(e){return typeof navigator<"u"&&"userAgentData"in navigator&&navigator.userAgentData?.mobile?"mobile":/iPad|tablet|PlayBook/i.test(e)?"tablet":/Mobi|Android.*Mobile|iPhone|iPod/i.test(e)?"mobile":"desktop"}async function _a(){let e=navigator.userAgent,t=Ge(),a=await zi();return{userAgent:e,browser:nm(e),os:sm(e),deviceType:im(e),language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,colorDepth:screen.colorDepth,devicePixelRatio:window.devicePixelRatio??1,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,connectionType:navigator.connection?.effectiveType??"unknown",referrer:document.referrer,visitorId:t,memoryUserId:a}}var lm="0.22.0-beta.7",um=40,dm=10,cm=6e5;function sn(){return typeof performance>"u"?0:performance.now()}function ln(e,t){let a={};return{metrics:a,has:r=>r in a,set(r,o){a[r]=o},mark(r,o=sn()){if(!(r in a)){a[r]=o-t;try{performance.mark(`waniwani:${e}:${r}`,{startTime:o})}catch{}}}}}function fm(e){let t={};for(let[a,r]of Object.entries(e)){if(Object.keys(t).length>=um)break;if(!Number.isFinite(r))continue;let o=Math.round(r);o<0||o>cm||(t[a]=o)}return t}function pm(e){let t={};for(let[a,r]of Object.entries(e)){if(Object.keys(t).length>=dm)break;(typeof r=="string"||typeof r=="boolean")&&(t[a]=r)}return t}function mm(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function Pr(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function hm(e,t,a,r){return{kind:e,sdkVersion:lm,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Ge(),pageHost:window.location.hostname,connection:mm(),tags:pm(a),metrics:fm(r)}}var nn,Ar=[];function Rr(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";nn=t;let a=Ar;if(Ar=[],t)for(let r of a)r()}function Er(e,t,a,r){let{api:o,token:n}=t;if(!(typeof window>"u"||!o||!n||nn===!1))try{let s=hm(e,t,a,r),i=()=>{lt("timing",s),fetch(tt(o,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s),keepalive:!0}).catch(()=>{})};nn?i():Ar.length<20&&Ar.push(i)}catch{}}var gt=ln("boot",0),Gi;function $t(e,t){gt.mark(e,t)}function Da(e){Gi??=e}var gm=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,wm=/\/embed\.js(\?|$)/;function Im(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&>.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&>.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)gm.test(a.name)?(gt.mark("bundleStart",a.startTime),gt.mark("bundleEnd",a.responseEnd)):wm.test(a.name)&&(gt.mark("loaderStart",a.startTime),gt.mark("loaderEnd",a.responseEnd))}function xm(){if($i)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function Ki(e){Im(),gt.mark("bundleExecuted",Hi),Er("boot",e,{configSource:Gi,mode:e.mode,secondSdk:xm()},gt.metrics)}var ym=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function Xi(e){let t=ln("turn",sn());t.set("turnIndex",e);let a=!1;return{mark:r=>t.mark(r),instrument(r){if(!r.ok||!r.body||typeof TransformStream>"u")return r;try{let o=new TextDecoder,n=r.body.pipeThrough(new TransformStream({transform(s,i){t.mark("firstChunk");let l=o.decode(s,{stream:!0});for(let[u,d]of ym)!t.has(d)&&l.includes(u)&&t.mark(d);i.enqueue(s)}}));return new Response(n,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return r}},report(r,o){a||(a=!0,Er("turn",r,o,t.metrics))}}}function Lm(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function Ji(e,t){let a=ln("widget",sn()),r=!1;return{mark:o=>a.mark(o),has:o=>a.has(o),report(o,n){r||(r=!0,a.set("retries",n),t({widget:Lm(e),outcome:o,metrics:a.metrics}))}}}import{createContext as Sm,useContext as Cm,useEffect as bm,useRef as Qi}from"react";var Yi=Sm(()=>{});function Zi(){return Cm(Yi)}var el=Yi.Provider;function vm(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function tl(e){let t=Qi(e);t.current=e;let a=Qi(!1);bm(()=>{if(!e.painted||a.current)return;a.current=!0;let r=requestAnimationFrame(()=>{let o=t.current;$t(o.paintMark),vm(()=>Ki(o))});return()=>cancelAnimationFrame(r)},[e.painted])}import{jsx as Nm}from"react/jsx-runtime";var Am="/api/mcp/resource",Pm=500,Rm=0,Em=16,Mm="2026-01-26",Fm=300,_m=3e3,Dm=3,Bm=2e3;function Om(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Um(e,t,a){return Fa(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function Ba({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:r=Am,chatSessionId:o,isDark:n=!1,className:s,autoHeight:i=!1,onOpenLink:l,onFollowUp:u,onCallTool:d,onDisplayModeChange:c,isFullscreen:p=!1,toolDefinitions:f}){let m=_e(null),y=_e(t),S=_e(a),L=_e({width:0,height:0}),C=_e(null),I=_e(!1),x=_e(0),v=_e("inline"),[q,N]=al(Rm),[V,G]=al(void 0),Q=_e(l),O=_e(u),re=_e(d),K=_e(c),J=_e(o),X=_e(f);y.current=t,S.current=a,Q.current=l,O.current=u,re.current=d,K.current=c,J.current=o,X.current=f;let R=km(k=>i?Math.max(k+Em,0):Math.min(Math.max(k,50),Pm),[i]),b=Tm(()=>{let k=r.includes("?")?"&":"?";return`${r}${k}uri=${encodeURIComponent(e)}`},[r,e]),D=Zi(),ae=_e(null),oe=_e(void 0);Mr(()=>{let k=Ji(e,D);return ae.current=k,()=>{clearTimeout(oe.current),k.has("initialized")||k.report("timeout",x.current),ae.current=null}},[e,D]);let Re=_e(n);Re.current=n;let Ne=_e(p);return Mr(()=>{Ne.current=p,L.current.height=-1,C.current&&(C.current.cancel(),C.current=null)},[p]),Mr(()=>{if(!I.current)return;let k=m.current;k?.contentWindow&&k.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:n?"dark":"light"}},"*")},[n]),Mr(()=>{let k=m.current;if(!k)return;let H=!1,$=!1,ne=null,me=null,Ie=setTimeout(()=>{if(H||$||x.current>=Dm)return;x.current+=1;let W=new URL(k.src);W.searchParams.set("_retry",String(x.current)),k.src=W.toString()},_m),fe=W=>{k.contentWindow?.postMessage(W,"*")},Z=W=>{if(H||W.source!==k.contentWindow)return;let se=W.data;if(!se||typeof se!="object"||se.jsonrpc!=="2.0")return;let xe=se.method,ie=se.id;if(xe==="ui/initialize"&&ie!=null){$=!0,ae.current?.mark("initialize"),clearTimeout(Ie),fe({jsonrpc:"2.0",id:ie,result:{protocolVersion:se.params?.protocolVersion??Mm,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:Re.current?"dark":"light",displayMode:v.current}}});return}if(xe==="ui/notifications/initialized"){I.current=!0,ae.current?.mark("initialized"),oe.current=setTimeout(()=>ae.current?.report("ok",x.current),Bm);let le=y.current,ee=S.current,ue=ee._meta&&typeof ee._meta=="object"?ee._meta:null,Y=Om(J.current),he=ue&&typeof ue.waniwani=="object"&&ue.waniwani!==null?ue.waniwani:null,T=he||Y?{...he??{},...Y?{sessionId:Y}:{}}:void 0,ye=ue||T?{...ue??{},...T?{waniwani:T}:{}}:void 0;fe({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:le}});let _=ee.content??[{type:"text",text:JSON.stringify(ee)}];fe({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:_,structuredContent:ee.structuredContent,_meta:ye,meta:ye}});return}if(xe==="ui/notifications/size-changed"){clearTimeout(oe.current),ae.current?.mark("firstSize"),ae.current?.report("ok",x.current);let le=se.params,ee=typeof le?.height=="number"?le.height:void 0,ue=typeof le?.width=="number"?le.width:void 0,Y=L.current,he=ee!==void 0&&ee!==Y.height,T=ue!==void 0&&ue!==Y.width;if(!he&&!T)return;if(he&&ee!==void 0){if(Y.height=ee,Ne.current)return;let ye=R(ee),_=k.getBoundingClientRect().height;if(C.current&&(C.current.cancel(),C.current=null),N(ye),k.animate&&Math.abs(_-ye)>2){let M=k.animate([{height:`${_}px`},{height:`${ye}px`}],{duration:Fm,easing:"ease-out",fill:"forwards"});C.current=M,M.onfinish=()=>{C.current===M&&(M.cancel(),C.current=null)}}}T&&i&&ue!==void 0&&(Y.width=ue,G(ue));return}if(xe==="ui/open-link"&&ie!=null){let le=se.params?.url;typeof le=="string"&&(Q.current?Q.current(le):window.open(le,"_blank","noopener,noreferrer")),fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="ui/message"&&ie!=null){if(O.current&&se.params){let le=se.params,ee=ne;if(ne=null,me){clearTimeout(me.timer);let ue=me.text;me=null;let Y=(le.content??[]).map(he=>he.text??"").join("").trim();le={...le,content:[{type:"text",text:`${Y}
|
|
2
|
+
import{a as di,b as ci,c as fi,d as pi,e as mi,f as Sr,g as hi,h as gi,i as wi,j as Ii,k as No,l as xi,m as ea,n as ta,o as Cr,p as aa,u as ya}from"../chunk-QIQG7C7A.js";import"../chunk-V3ZDECK5.js";import{useCallback as Tm,useEffect as Mr,useMemo as Am,useRef as _e,useState as al}from"react";function ra(e){if(!e)return!1;let t=Array.isArray(e.content)&&e.content.length>0,a=typeof e.structuredContent=="object"&&e.structuredContent!==null&&Object.keys(e.structuredContent).length>0;return t||a}function yi(e,t){return!ra(e)&&!ra(t)?null:ra(e)?ra(t)?{...e.content||t.content?{content:[...e.content??[],...t.content??[]]}:{},...e.structuredContent||t.structuredContent?{structuredContent:{...e.structuredContent??{},...t.structuredContent??{}}}:{}}:{...e.content?{content:[...e.content]}:{},...e.structuredContent?{structuredContent:{...e.structuredContent}}:{}}:{...t?.content?{content:[...t.content]}:{},...t?.structuredContent?{structuredContent:{...t.structuredContent}}:{}}}import{forwardRef as dp,createElement as cp}from"react";var br=(...e)=>e.filter((t,a,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===a).join(" ").trim();var Li=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var Si=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,r)=>r?r.toUpperCase():a.toLowerCase());var qo=e=>{let t=Si(e);return t.charAt(0).toUpperCase()+t.slice(1)};import{forwardRef as up,createElement as vi}from"react";var Ci={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var bi=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var ki=up(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:r,className:o="",children:n,iconNode:s,...i},l)=>vi("svg",{ref:l,...Ci,width:t,height:t,stroke:e,strokeWidth:r?Number(a)*24/Number(t):a,className:br("lucide",o),...!n&&!bi(i)&&{"aria-hidden":"true"},...i},[...s.map(([u,d])=>vi(u,d)),...Array.isArray(n)?n:[n]]));var ce=(e,t)=>{let a=dp(({className:r,...o},n)=>cp(ki,{ref:n,iconNode:t,className:br(`lucide-${Li(qo(e))}`,`lucide-${e}`,r),...o}));return a.displayName=qo(e),a};var fp=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],La=ce("arrow-down",fp);var pp=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Sa=ce("arrow-up",pp);var mp=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ca=ce("check",mp);var hp=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],vt=ce("chevron-down",hp);var gp=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ba=ce("chevron-right",gp);var wp=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]],va=ce("clipboard-copy",wp);var Ip=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],ht=ce("clock",Ip);var xp=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ka=ce("file-text",xp);var yp=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],oa=ce("file",yp);var Lp=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Ta=ce("globe",Lp);var Sp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Aa=ce("image",Sp);var Cp=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],Pa=ce("loader",Cp);var bp=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],na=ce("paperclip",bp);var vp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Ra=ce("square",vp);var kp=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],qt=ce("wrench",kp);var Tp=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],kt=ce("x",Tp);var Ap=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Ea=ce("zap",Ap);import{createContext as Hp,useCallback as $p,useContext as _i,useEffect as Wp,useMemo as Ko,useRef as jp,useState as Xo}from"react";function Ho(e){if(!(typeof e!="object"||e===null))return e}function Ti(e){return Ho(e?.ui)}function $o(e){if(!e)return;let t=Ti(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let a=e["ui/resourceUri"];if(typeof a=="string"&&a.length>0)return a;let r=e["openai/outputTemplate"];if(typeof r=="string"&&r.length>0)return r}function Ma(e){return Ti(e)?.autoHeight===!0}function Wo(e){return Ho(Ho(e)?._meta)}import{createContext as Pp,useContext as Rp,useEffect as Ep,useMemo as Mp,useState as Ei}from"react";var Ai=["en","fr","es"];function sa(e){return Ai.includes(e)}function jo(e){if(e&&sa(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&sa(a))return a}let t=[];if(typeof navigator<"u"&&(navigator.language&&t.push(navigator.language),navigator.languages&&t.push(...navigator.languages)),typeof document<"u"){let a=document.documentElement.getAttribute("lang");a&&t.push(a)}for(let a of t){let r=a.toLowerCase();if(sa(r))return r;let o=r.split("-")[0];if(o&&sa(o))return o}return"en"}var vr={promptInput:{placeholder:"What would you like to know?",uploadFiles:"Upload files",uploadFilesUpTo:"Upload a document, up to {limit}",uploadFilesUpToWithPages:"Upload a document, up to {limit} and {pages} pages",stop:"Stop",submit:"Submit",removeAttachments:"Remove all attachments",removeAttachment:"Remove attachment",uploading:"Uploading\u2026",retry:"Retry",retryUpload:"Retry the upload",uploadFailed:"The upload did not finish.",dropToAttach:"Drop to attach",errorAccept:"{name} is not a file type this chat accepts.",errorTooLarge:"{name} is larger than {limit}.",errorTooMany:"You can attach up to {limit} files."},workingIndicator:{default:"On it\u2026"},reasoning:{thinking:"Thinking\u2026",thoughtBrief:"Thought for a few seconds",thoughtForSeconds:e=>`Thought for ${e} second${e===1?"":"s"}`},chainOfThought:{working:"Working on it\u2026",done:"Thought process"},tool:{copy:"Copy",copied:"Copied",request:"Request",response:"Response",error:"Error"},attachments:{attachmentFallback:"attachment",kindPdf:"PDF",kindImage:"Image",kindFile:"File",fileFallback:"file"},threadMenu:{newChat:"New chat",threadHistory:"Thread history",deleteThread:"Delete thread",noPreviousChats:"No previous chats yet.",hiddenThreads:e=>`${e} older thread${e===1?"":"s"} hidden`},chatQueue:{attachmentFallback:"(attachment)",removeFromQueue:"Remove from queue",queued:e=>`${e} queued`},poweredBy:{label:"AI agent powered by"},aiDisclaimer:{default:"can make mistakes"},exportSession:{saving:"saving...",saved:"saved",error:"error",export:"export",tooltip:"Save scenario to Waniwani"},widgetErrorBoundary:{failedToLoad:"Widget failed to load",retry:"Retry"},launcher:{prompt:"Ask anything\u2026",open:"Open chat",close:"Close chat",minimize:"Minimize"}};var Pi={promptInput:{placeholder:"\xBFQu\xE9 te gustar\xEDa saber?",uploadFiles:"Subir archivos",uploadFilesUpTo:"Subir un documento, hasta {limit}",uploadFilesUpToWithPages:"Subir un documento, hasta {limit} y {pages} p\xE1ginas",stop:"Detener",submit:"Enviar",removeAttachments:"Eliminar todos los archivos adjuntos",removeAttachment:"Quitar archivo",uploading:"Subiendo\u2026",retry:"Reintentar",retryUpload:"Reintentar la subida",uploadFailed:"La subida no se complet\xF3.",dropToAttach:"Suelta para adjuntar",errorAccept:"{name} no es un tipo de archivo que acepte este chat.",errorTooLarge:"{name} supera {limit}.",errorTooMany:"Puedes adjuntar hasta {limit} archivos."},workingIndicator:{default:"Un momento\u2026"},reasoning:{thinking:"Pensando\u2026",thoughtBrief:"Pensado durante unos segundos",thoughtForSeconds:e=>`Pensado durante ${e} segundo${e===1?"":"s"}`},chainOfThought:{working:"Estoy en ello\u2026",done:"Razonamiento"},tool:{copy:"Copiar",copied:"Copiado",request:"Solicitud",response:"Respuesta",error:"Error"},attachments:{attachmentFallback:"adjunto",kindPdf:"PDF",kindImage:"Imagen",kindFile:"Archivo",fileFallback:"archivo"},threadMenu:{newChat:"Nueva conversaci\xF3n",threadHistory:"Historial",deleteThread:"Eliminar conversaci\xF3n",noPreviousChats:"A\xFAn no hay conversaciones anteriores.",hiddenThreads:e=>`${e} conversaci\xF3n${e===1?"":"es"} anterior${e===1?"":"es"} oculta${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(adjunto)",removeFromQueue:"Quitar de la cola",queued:e=>`${e} en cola`},poweredBy:{label:"Agente IA con tecnolog\xEDa de"},aiDisclaimer:{default:"puede cometer errores"},exportSession:{saving:"guardando...",saved:"guardado",error:"error",export:"exportar",tooltip:"Guardar escenario en Waniwani"},widgetErrorBoundary:{failedToLoad:"No se pudo cargar el widget",retry:"Reintentar"},launcher:{prompt:"Pregunta lo que quieras\u2026",open:"Abrir chat",close:"Cerrar chat",minimize:"Minimizar"}};var Ri={promptInput:{placeholder:"Que souhaitez-vous savoir ?",uploadFiles:"Importer des fichiers",uploadFilesUpTo:"Joindre un document, jusqu'\xE0 {limit}",uploadFilesUpToWithPages:"Envoyer un document, jusqu'\xE0 {limit} et {pages} pages",stop:"Arr\xEAter",submit:"Envoyer",removeAttachments:"Supprimer toutes les pi\xE8ces jointes",removeAttachment:"Retirer la pi\xE8ce jointe",uploading:"Envoi en cours\u2026",retry:"R\xE9essayer",retryUpload:"R\xE9essayer l'envoi",uploadFailed:"L'envoi ne s'est pas termin\xE9.",dropToAttach:"D\xE9posez pour joindre",errorAccept:"{name} n'est pas un type de fichier accept\xE9 par ce chat.",errorTooLarge:"{name} d\xE9passe {limit}.",errorTooMany:"Vous pouvez joindre jusqu'\xE0 {limit} fichiers."},workingIndicator:{default:"Un instant\u2026"},reasoning:{thinking:"R\xE9flexion\u2026",thoughtBrief:"R\xE9flexion pendant quelques secondes",thoughtForSeconds:e=>`R\xE9flexion pendant ${e} seconde${e===1?"":"s"}`},chainOfThought:{working:"Je m'en occupe\u2026",done:"Raisonnement"},tool:{copy:"Copier",copied:"Copi\xE9",request:"Requ\xEAte",response:"R\xE9ponse",error:"Erreur"},attachments:{attachmentFallback:"pi\xE8ce jointe",kindPdf:"PDF",kindImage:"Image",kindFile:"Fichier",fileFallback:"fichier"},threadMenu:{newChat:"Nouvelle conversation",threadHistory:"Historique",deleteThread:"Supprimer la conversation",noPreviousChats:"Aucune conversation pr\xE9c\xE9dente.",hiddenThreads:e=>`${e} conversation${e===1?"":"s"} plus ancienne${e===1?"":"s"} masqu\xE9e${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(pi\xE8ce jointe)",removeFromQueue:"Retirer de la file",queued:e=>`${e} en attente`},poweredBy:{label:"Agent IA propuls\xE9 par"},aiDisclaimer:{default:"peut faire des erreurs"},exportSession:{saving:"enregistrement...",saved:"enregistr\xE9",error:"erreur",export:"exporter",tooltip:"Enregistrer le sc\xE9nario dans Waniwani"},widgetErrorBoundary:{failedToLoad:"\xC9chec du chargement du widget",retry:"R\xE9essayer"},launcher:{prompt:"Posez votre question\u2026",open:"Ouvrir le chat",close:"Fermer le chat",minimize:"R\xE9duire"}};var zo={en:vr,fr:Ri,es:Pi};import{jsx as Dp}from"react/jsx-runtime";var Mi=Pp(null);function Fp(e,t){if(!t)return e;let a={...e};for(let r of Object.keys(e)){let o=e[r],n=t[r];n&&typeof o=="object"&&(a[r]={...o,...n})}return a}function Vo({children:e,locale:t,messages:a}){let r=!!(t&&_p(t)),o=r?t:"en",[n,s]=Ei(o),[i,l]=Ei(r);Ep(()=>{s(jo(t)),l(!0)},[t]);let u=Mp(()=>{let d=zo[n]??zo["en"];return{locale:n,t:Fp(d,a),ready:i}},[n,a,i]);return Dp(Mi.Provider,{value:u,children:e})}function _p(e){return e==="en"||e==="fr"||e==="es"}function te(){let e=Rp(Mi);return e||{locale:"en",t:vr,ready:!0}}function Go(e,t){let a=Date.now()-e;if(a<6e4)try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"narrow"}).format(0,"second")}catch{return"just now"}let r,o;a<60*6e4?(r=-Math.floor(a/6e4),o="minute"):a<1440*6e4?(r=-Math.floor(a/(60*6e4)),o="hour"):(r=-Math.floor(a/(1440*6e4)),o="day");try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"short"}).format(r,o)}catch{return`${Math.abs(r)}${o==="minute"?"m":o==="hour"?"h":"d"} ago`}}var Bp=ci({prefix:"ww"});function P(...e){return Bp(di(e))}import{jsx as Op}from"react/jsx-runtime";var it=({className:e,variant:t="default",size:a="default",type:r="button",...o})=>Op("button",{type:r,className:P("ww:inline-flex ww:cursor-pointer ww:items-center ww:justify-center ww:rounded-md ww:font-medium ww:transition-colors ww:disabled:pointer-events-none ww:disabled:opacity-50",t==="default"&&"ww:bg-primary ww:text-primary-foreground ww:hover:bg-primary/90",t==="outline"&&"ww:border ww:border-border ww:bg-background ww:hover:bg-accent ww:hover:text-accent-foreground",t==="ghost"&&"ww:hover:bg-accent ww:hover:text-accent-foreground",a==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",a==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",a==="icon"&&"ww:size-9 ww:!rounded-full",a==="icon-sm"&&"ww:size-7 ww:!rounded-full",e),...o});import{memo as Up}from"react";import{jsx as qp}from"react/jsx-runtime";var Np=({as:e="span",className:t,duration:a=2,style:r,children:o,...n})=>{let s={backgroundImage:"linear-gradient(90deg, var(--ww-color-muted-foreground) 0%, var(--ww-color-muted-foreground) 40%, var(--ww-color-foreground) 50%, var(--ww-color-muted-foreground) 60%, var(--ww-color-muted-foreground) 100%)",backgroundSize:"250% 100%",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent",animation:`ww-shimmer ${a}s linear infinite`,...r};return qp(e,{"data-waniwani-shimmer":"",className:P("ww:inline-block",t),style:s,...n,children:o})},et=Up(Np);et.displayName="Shimmer";import{Fragment as Fi,jsx as ge,jsxs as Ht}from"react/jsx-runtime";function zp(e,t=80){if(e==null)return String(e);if(typeof e!="object")return String(e).slice(0,t);if(Array.isArray(e))return`Array(${e.length})`;let a=JSON.stringify(e);if(a.length<=t)return a;let r=Object.entries(e),o=[],n=t-2;for(let[s,i]of r){if(n<=8)break;let l=s.length>4?`${s.slice(0,4)}\u2026`:s,u;typeof i=="string"?u=i.length>2?`'${i.slice(0,1)}\u2026`:`'${i}'`:Array.isArray(i)?u=`Array(${i.length})`:typeof i=="object"&&i!==null?u="{\u2026}":u=String(i);let d=`${l}\u2009${u}`;o.push(d),n-=d.length+3}return`{${o.join(", ")}}`}function Vp({text:e,className:t}){let{t:a}=te(),[r,o]=Xo(!1),n=jp(null);Wp(()=>()=>{n.current&&clearTimeout(n.current)},[]);let s=$p(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>o(!1),2e3)}catch{}},[e]);return ge(it,{variant:"ghost",size:"sm",onClick:s,className:P("ww:h-auto ww:gap-1 ww:px-1.5 ww:py-0.5 ww:text-xs ww:text-muted-foreground ww:hover:text-foreground",t),children:r?Ht(Fi,{children:[ge(Ca,{className:"ww:size-3.5"}),ge("span",{children:a.tool.copied})]}):Ht(Fi,{children:[ge(va,{className:"ww:size-3.5"}),ge("span",{children:a.tool.copy})]})})}function Di({data:e,label:t,className:a,...r}){let[o,n]=Xo(!1),s=Ko(()=>JSON.stringify(e,null,2),[e]),i=zp(e);return Ht("div",{className:P("ww:rounded-lg ww:bg-tool-card",a),...r,children:[Ht("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[ge("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),ge(Vp,{text:s})]}),Ht("button",{type:"button",onClick:()=>n(l=>!l),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[ge(ba,{className:P("ww:mt-0.5 ww:size-3.5 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-150",o&&"ww:rotate-90")}),o?ge("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:ge("code",{children:s})}):ge("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:i})]})]})}var Jo=Hp({open:!1,toggle:()=>{}});function Bi({className:e,defaultOpen:t=!1,children:a,...r}){let[o,n]=Xo(t);return ge(Jo.Provider,{value:{open:o,toggle:()=>n(s=>!s)},children:ge("div",{className:P("ww:mb-4 ww:w-full",e),"data-state":o?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...r,children:a})})}function Oi({className:e,title:t,state:a,...r}){let{open:o,toggle:n}=_i(Jo),s=a==="input-available"||a==="input-streaming",i=t??"";return Ht("button",{type:"button",onClick:n,className:P("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),"aria-expanded":o,...r,children:[ge(qt,{className:"ww:size-4 ww:shrink-0"}),ge("span",{className:"ww:truncate",children:s?ge(et,{duration:1.6,children:i}):i}),ge(vt,{className:P("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function Ui({className:e,title:t,state:a,...r}){let o=a==="input-available"||a==="input-streaming",n=t??"";return ge("div",{className:P("ww:mb-4 ww:flex ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...r,children:ge("span",{className:"ww:truncate",children:o?ge(et,{duration:1.6,children:n}):n})})}function Ni({className:e,children:t,...a}){let{open:r}=_i(Jo);return ge("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:ge("div",{className:"ww:min-h-0 ww:overflow-hidden",children:ge("div",{className:P("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...a,children:t})})})}function Gp(e,t){if(t||typeof e!="object"||e===null||Array.isArray(e))return e;let{_meta:a,telemetry:r,...o}=e;return o}function Qo({className:e,input:t,debug:a,...r}){let{t:o}=te(),n=Ko(()=>Gp(t,a),[t,a]);return ge(Di,{data:n,label:o.tool.request,className:e,...r})}function Fa(e,t,a){if(e){let r=$o(a?.[e]?._meta);if(r)return r}return $o(Wo(t))}function qi(e,t,a){return e&&Ma(a?.[e]?._meta)?!0:Ma(Wo(t))}function Yo({className:e,output:t,errorText:a,debug:r,...o}){let{t:n}=te(),s=Ko(()=>{if(!r&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:i,...l}=t;return l}return t},[t,r]);return t||a?a?Ht("div",{className:P("ww:space-y-2",e),...o,children:[ge("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:n.tool.error}),ge("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):ge(Di,{data:s,label:n.tool.response,className:e,...o}):null}var Hi=typeof performance>"u"?0:performance.now(),$i=typeof window<"u"&&!!window.WaniWani?.chat;function tt(e,t,a){let[r,o=""]=e.split("?"),n=r.replace(/\/$/,""),s=new URLSearchParams(o);if(a)for(let[l,u]of Object.entries(a))s.set(l,u);let i=s.toString();return`${n}${t}${i?`?${i}`:""}`}var Kp="/api/mcp/";function kr(e,t){let[a=""]=e.split("?"),r="",o=a;try{let n=new URL(a);r=n.origin,o=n.pathname}catch{if(!a.startsWith("/"))return null}return o.startsWith(Kp)?`${r}${t}`:null}function Xp(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function lt(...e){Xp()&&console.log("[Waniwani]",...e)}var Zo="waniwani-visitor-id";function Jp(){try{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,a=>a.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}}catch{}return`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ge(){try{let t=localStorage.getItem(Zo);if(t)return t}catch{}let e=Jp();try{localStorage.setItem(Zo,e)}catch{}return e}function en(e){let t=typeof e=="string"?e.trim():"";if(!t)return Ge();try{localStorage.setItem(Zo,t)}catch{}return t}function Qp(e){return e!=null&&typeof e.then=="function"}function tn(e){let t=!1,a=()=>{t=!0};if(e==null)return a;let r;try{r=typeof e=="function"?e():e}catch{return a}return Qp(r)?r.then(o=>{t||en(o??"")},()=>{}):en(r??""),a}var Yp="waniwani-memory";var Ke="threads",Tr="by_memoryUserId",Zp="by_updatedAt";var ji="memoryUserId",Wi="waniwani-memory-user-id",an=null;function rn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function em(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(Ke)){let a=e.createObjectStore(Ke,{keyPath:"threadId"});a.createIndex(Tr,"memoryUserId",{unique:!1}),a.createIndex(Zp,"updatedAt",{unique:!1})}}async function on(){return new Promise((e,t)=>{let a=indexedDB.open(Yp,2);a.onupgradeneeded=r=>{em(a.result,r.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function tm(){return on()}async function am(e){return new Promise((t,a)=>{let n=e.transaction("ids","readonly").objectStore("ids").get(ji);n.onsuccess=()=>t(typeof n.result=="string"?n.result:null),n.onerror=()=>a(n.error)})}async function rm(e,t){return new Promise((a,r)=>{let s=e.transaction("ids","readwrite").objectStore("ids").put(t,ji);s.onsuccess=()=>a(),s.onerror=()=>r(s.error)})}async function om(){if(typeof indexedDB>"u")return null;try{let e=await tm();try{let t=await am(e);if(t)return t;let a=rn();return await rm(e,a),a}finally{e.close()}}catch{return null}}function nm(){try{let e=localStorage.getItem(Wi);if(e)return e;let t=rn();return localStorage.setItem(Wi,t),t}catch{return null}}async function zi(){let e=await om();if(e)return e;let t=nm();return t||(an||(an=rn()),an)}function Vi(e,t){return e.match(t)?.[1]??null}function sm(e){let t=[["Edge",/Edg(?:e|A|iOS)?\/(\S+)/],["Opera",/(?:OPR|Opera)\/(\S+)/],["Samsung Internet",/SamsungBrowser\/(\S+)/],["Firefox",/Firefox\/(\S+)/],["Chrome",/Chrome\/(\S+)/],["Safari",/Version\/(\S+).*Safari/]];for(let[a,r]of t){let o=Vi(e,r);if(o)return{name:a,version:o}}return null}function im(e){let t=[["iOS",/(?:iPhone|iPad|iPod).+?OS (\d+[_.\d]*)/],["Android",/Android (\d+[.\d]*)/],["macOS",/Mac OS X (\d+[_.\d]*)/],["Windows",/Windows NT (\d+[.\d]*)/],["ChromeOS",/CrOS \S+ (\d+[.\d]*)/],["Linux",/Linux/]];for(let[a,r]of t){let o=Vi(e,r);if(o)return{name:a,version:o.replace(/_/g,".")};if(a==="Linux"&&r.test(e))return{name:a,version:""}}return null}function lm(e){return typeof navigator<"u"&&"userAgentData"in navigator&&navigator.userAgentData?.mobile?"mobile":/iPad|tablet|PlayBook/i.test(e)?"tablet":/Mobi|Android.*Mobile|iPhone|iPod/i.test(e)?"mobile":"desktop"}async function _a(){let e=navigator.userAgent,t=Ge(),a=await zi();return{userAgent:e,browser:sm(e),os:im(e),deviceType:lm(e),language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,colorDepth:screen.colorDepth,devicePixelRatio:window.devicePixelRatio??1,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,connectionType:navigator.connection?.effectiveType??"unknown",referrer:document.referrer,visitorId:t,memoryUserId:a}}var um="0.22.1",dm=40,cm=10,fm=6e5;function sn(){return typeof performance>"u"?0:performance.now()}function ln(e,t){let a={};return{metrics:a,has:r=>r in a,set(r,o){a[r]=o},mark(r,o=sn()){if(!(r in a)){a[r]=o-t;try{performance.mark(`waniwani:${e}:${r}`,{startTime:o})}catch{}}}}}function pm(e){let t={};for(let[a,r]of Object.entries(e)){if(Object.keys(t).length>=dm)break;if(!Number.isFinite(r))continue;let o=Math.round(r);o<0||o>fm||(t[a]=o)}return t}function mm(e){let t={};for(let[a,r]of Object.entries(e)){if(Object.keys(t).length>=cm)break;(typeof r=="string"||typeof r=="boolean")&&(t[a]=r)}return t}function hm(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function Pr(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function gm(e,t,a,r){return{kind:e,sdkVersion:um,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Ge(),pageHost:window.location.hostname,connection:hm(),tags:mm(a),metrics:pm(r)}}var nn,Ar=[];function Rr(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";nn=t;let a=Ar;if(Ar=[],t)for(let r of a)r()}function Er(e,t,a,r){let{api:o,token:n}=t;if(!(typeof window>"u"||!o||!n||nn===!1))try{let s=gm(e,t,a,r),i=()=>{lt("timing",s),fetch(tt(o,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s),keepalive:!0}).catch(()=>{})};nn?i():Ar.length<20&&Ar.push(i)}catch{}}var gt=ln("boot",0),Gi;function $t(e,t){gt.mark(e,t)}function Da(e){Gi??=e}var wm=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,Im=/\/embed\.js(\?|$)/;function xm(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&>.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&>.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)wm.test(a.name)?(gt.mark("bundleStart",a.startTime),gt.mark("bundleEnd",a.responseEnd)):Im.test(a.name)&&(gt.mark("loaderStart",a.startTime),gt.mark("loaderEnd",a.responseEnd))}function ym(){if($i)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function Ki(e){xm(),gt.mark("bundleExecuted",Hi),Er("boot",e,{configSource:Gi,mode:e.mode,secondSdk:ym()},gt.metrics)}var Lm=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function Xi(e){let t=ln("turn",sn());t.set("turnIndex",e);let a=!1;return{mark:r=>t.mark(r),instrument(r){if(!r.ok||!r.body||typeof TransformStream>"u")return r;try{let o=new TextDecoder,n=r.body.pipeThrough(new TransformStream({transform(s,i){t.mark("firstChunk");let l=o.decode(s,{stream:!0});for(let[u,d]of Lm)!t.has(d)&&l.includes(u)&&t.mark(d);i.enqueue(s)}}));return new Response(n,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return r}},report(r,o){a||(a=!0,Er("turn",r,o,t.metrics))}}}function Sm(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function Ji(e,t){let a=ln("widget",sn()),r=!1;return{mark:o=>a.mark(o),has:o=>a.has(o),report(o,n){r||(r=!0,a.set("retries",n),t({widget:Sm(e),outcome:o,metrics:a.metrics}))}}}import{createContext as Cm,useContext as bm,useEffect as vm,useRef as Qi}from"react";var Yi=Cm(()=>{});function Zi(){return bm(Yi)}var el=Yi.Provider;function km(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function tl(e){let t=Qi(e);t.current=e;let a=Qi(!1);vm(()=>{if(!e.painted||a.current)return;a.current=!0;let r=requestAnimationFrame(()=>{let o=t.current;$t(o.paintMark),km(()=>Ki(o))});return()=>cancelAnimationFrame(r)},[e.painted])}import{jsx as qm}from"react/jsx-runtime";var Pm="/api/mcp/resource",Rm=500,Em=0,Mm=16,Fm="2026-01-26",_m=300,Dm=3e3,Bm=3,Om=2e3;function Um(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Nm(e,t,a){return Fa(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function Ba({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:r=Pm,chatSessionId:o,isDark:n=!1,className:s,autoHeight:i=!1,onOpenLink:l,onFollowUp:u,onCallTool:d,onDisplayModeChange:c,isFullscreen:p=!1,toolDefinitions:f}){let m=_e(null),y=_e(t),S=_e(a),L=_e({width:0,height:0}),C=_e(null),I=_e(!1),x=_e(0),v=_e("inline"),[q,N]=al(Em),[V,G]=al(void 0),Q=_e(l),O=_e(u),re=_e(d),K=_e(c),J=_e(o),X=_e(f);y.current=t,S.current=a,Q.current=l,O.current=u,re.current=d,K.current=c,J.current=o,X.current=f;let R=Tm(k=>i?Math.max(k+Mm,0):Math.min(Math.max(k,50),Rm),[i]),b=Am(()=>{let k=r.includes("?")?"&":"?";return`${r}${k}uri=${encodeURIComponent(e)}`},[r,e]),D=Zi(),ae=_e(null),oe=_e(void 0);Mr(()=>{let k=Ji(e,D);return ae.current=k,()=>{clearTimeout(oe.current),k.has("initialized")||k.report("timeout",x.current),ae.current=null}},[e,D]);let Re=_e(n);Re.current=n;let Ne=_e(p);return Mr(()=>{Ne.current=p,L.current.height=-1,C.current&&(C.current.cancel(),C.current=null)},[p]),Mr(()=>{if(!I.current)return;let k=m.current;k?.contentWindow&&k.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:n?"dark":"light"}},"*")},[n]),Mr(()=>{let k=m.current;if(!k)return;let H=!1,$=!1,ne=null,me=null,Ie=setTimeout(()=>{if(H||$||x.current>=Bm)return;x.current+=1;let W=new URL(k.src);W.searchParams.set("_retry",String(x.current)),k.src=W.toString()},Dm),fe=W=>{k.contentWindow?.postMessage(W,"*")},Z=W=>{if(H||W.source!==k.contentWindow)return;let se=W.data;if(!se||typeof se!="object"||se.jsonrpc!=="2.0")return;let xe=se.method,ie=se.id;if(xe==="ui/initialize"&&ie!=null){$=!0,ae.current?.mark("initialize"),clearTimeout(Ie),fe({jsonrpc:"2.0",id:ie,result:{protocolVersion:se.params?.protocolVersion??Fm,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:Re.current?"dark":"light",displayMode:v.current}}});return}if(xe==="ui/notifications/initialized"){I.current=!0,ae.current?.mark("initialized"),oe.current=setTimeout(()=>ae.current?.report("ok",x.current),Om);let le=y.current,ee=S.current,ue=ee._meta&&typeof ee._meta=="object"?ee._meta:null,Y=Um(J.current),he=ue&&typeof ue.waniwani=="object"&&ue.waniwani!==null?ue.waniwani:null,T=he||Y?{...he??{},...Y?{sessionId:Y}:{}}:void 0,ye=ue||T?{...ue??{},...T?{waniwani:T}:{}}:void 0;fe({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:le}});let _=ee.content??[{type:"text",text:JSON.stringify(ee)}];fe({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:_,structuredContent:ee.structuredContent,_meta:ye,meta:ye}});return}if(xe==="ui/notifications/size-changed"){clearTimeout(oe.current),ae.current?.mark("firstSize"),ae.current?.report("ok",x.current);let le=se.params,ee=typeof le?.height=="number"?le.height:void 0,ue=typeof le?.width=="number"?le.width:void 0,Y=L.current,he=ee!==void 0&&ee!==Y.height,T=ue!==void 0&&ue!==Y.width;if(!he&&!T)return;if(he&&ee!==void 0){if(Y.height=ee,Ne.current)return;let ye=R(ee),_=k.getBoundingClientRect().height;if(C.current&&(C.current.cancel(),C.current=null),N(ye),k.animate&&Math.abs(_-ye)>2){let M=k.animate([{height:`${_}px`},{height:`${ye}px`}],{duration:_m,easing:"ease-out",fill:"forwards"});C.current=M,M.onfinish=()=>{C.current===M&&(M.cancel(),C.current=null)}}}T&&i&&ue!==void 0&&(Y.width=ue,G(ue));return}if(xe==="ui/open-link"&&ie!=null){let le=se.params?.url;typeof le=="string"&&(Q.current?Q.current(le):window.open(le,"_blank","noopener,noreferrer")),fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="ui/message"&&ie!=null){if(O.current&&se.params){let le=se.params,ee=ne;if(ne=null,me){clearTimeout(me.timer);let ue=me.text;me=null;let Y=(le.content??[]).map(he=>he.text??"").join("").trim();le={...le,content:[{type:"text",text:`${Y}
|
|
3
3
|
|
|
4
|
-
${ue}`}]}}O.current({...le,...ee?{modelContext:ee}:{}})}fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="ui/update-model-context"&&ie!=null){ne=yi(ne,se.params),fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="tools/call"&&ie!=null){let le=re.current;if(!le){fe({jsonrpc:"2.0",id:ie,error:{code:-32601,message:"tools/call not supported"}});return}let ee=se.params?.name;le({name:ee,arguments:se.params?.arguments??{}}).then(ue=>{fe({jsonrpc:"2.0",id:ie,result:ue});let Y=ue.content?.map(he=>he.text??"").join("").trim();Y&&Um(ee,ue,X.current)&&(me&&clearTimeout(me.timer),me={text:Y,timer:setTimeout(()=>{if(H)return;let he=ne;ne=null,me=null,O.current?.({role:"user",content:[{type:"text",text:Y}],...he?{modelContext:he}:{}})},500)})}).catch(ue=>{let Y=ue instanceof Error?ue.message:"Tool call failed";fe({jsonrpc:"2.0",id:ie,error:{code:-32e3,message:Y}})});return}if(xe==="ui/request-display-mode"&&ie!=null){let le=se.params?.mode,ee=le==="fullscreen"||le==="inline"||le==="pip"?le:"inline";v.current=ee,fe({jsonrpc:"2.0",id:ie,result:{mode:ee}}),fe({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:ee}}),K.current?.(ee);return}if(xe==="ui/resource-teardown"&&ie!=null){fe({jsonrpc:"2.0",id:ie,result:{}});return}xe==="ping"&&ie!=null&&fe({jsonrpc:"2.0",id:ie,result:{}})};return window.addEventListener("message",Z),()=>{H=!0,clearTimeout(Ie),me&&clearTimeout(me.timer),window.removeEventListener("message",Z)}},[i,R]),Nm("iframe",{ref:m,src:b,onLoad:()=>ae.current?.mark("iframeLoad"),sandbox:"allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox",className:P(!p&&"ww:rounded-md ww:border ww:border-border",s),style:{height:p?"100%":q,minWidth:p||!V?void 0:`min(${V}px, 100%)`,width:"100%",border:"none",colorScheme:n?"dark":"auto"},title:"MCP App"})}import{useCallback as qm,useEffect as un,useState as Hm}from"react";import{jsx as dn,jsxs as Wm}from"react/jsx-runtime";var rl=672,ol=32;function $m({widget:e,onCallTool:t,toolsEndpoint:a,headers:r,resourceEndpoint:o,onClose:n,isDark:s=!1}){let[i,l]=Hm(null);un(()=>{let f=()=>l({width:window.innerWidth,height:window.innerHeight});return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]);let u=e?.preview===!0;un(()=>{if(!e||!u)return;let f=m=>{m.key==="Escape"&&n()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,u,n]),un(()=>{if(!e)return;let f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=f}},[e]);let d=qm(async f=>{if(t)return t(f);if(!a)throw new Error("webmcp overlay needs onCallTool");let m=await fetch(a,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify({action:"call",...f})});if(!m.ok)throw new Error(`webmcp tool call failed: ${m.status}`);return await m.json()},[t,a,r]);if(!e)return null;let c=i?Math.min(rl,i.width-ol):rl,p=i?i.height-ol:void 0;return Wm("div",{role:"dialog","aria-modal":"true","aria-label":"Waniwani",className:P("ww:fixed ww:inset-0 ww:z-[2147483000] ww:flex ww:items-center ww:justify-center ww:bg-black/45 ww:backdrop-blur-md",s&&"dark"),children:[u&&dn("button",{type:"button","aria-label":"Close",onClick:n,className:"ww:absolute ww:inset-0 ww:h-full ww:w-full ww:cursor-pointer ww:border-none ww:bg-transparent ww:p-0"}),dn("div",{className:"ww:relative ww:overflow-auto ww:rounded-2xl ww:bg-background ww:shadow-2xl",style:{width:c,maxHeight:p},children:dn(Ba,{resourceUri:e.viewUri,resourceEndpoint:o,toolInput:e.data,toolResult:e.result,autoHeight:Ma(e.result._meta),isDark:s,onCallTool:d,onOpenLink:f=>window.open(f,"_blank","noopener")},`${o}|${e.viewUri}`)})]})}import{forwardRef as rc,useCallback as rr,useEffect as It,useImperativeHandle as Rx,useRef as Dt,useState as vo}from"react";var Oa=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,a)=>(a&=63,a<36?t+=a.toString(36):a<62?t+=(a-26).toString(36).toUpperCase():a>62?t+="-":t+="_",t),"");import{createContext as Km,useCallback as je,useContext as Xm,useEffect as Ua,useMemo as Jm,useRef as Tt,useState as pn}from"react";var Wt=new Map;function nl(e,t){if(Wt.has(e)){URL.revokeObjectURL(t);return}for(Wt.set(e,t);Wt.size>20;){let a=Wt.keys().next();if(a.done)return;let r=Wt.get(a.value);Wt.delete(a.value),r&&URL.revokeObjectURL(r)}}function sl(e){return Wt.get(e)}import{useState as jm}from"react";import{jsx as De,jsxs as cn}from"react/jsx-runtime";var il=({files:e,className:t,...a})=>e.length===0?null:De("div",{className:P("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((r,o)=>De(zm,{file:r},o))});function zm({file:e}){let{t}=te();return e.mediaType?.startsWith("image/")&&e.url?De("img",{src:e.url,alt:e.filename??t.attachments.attachmentFallback,className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):cn("span",{className:"ww:inline-flex ww:items-center ww:gap-1.5 ww:rounded ww:bg-background/20 ww:px-2 ww:py-1 ww:text-xs",children:[De(oa,{className:"ww:size-3 ww:shrink-0"}),De("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??t.attachments.fileFallback})]})}function ll(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function Vm({mediaType:e}){return e.startsWith("image/")?De(Aa,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?De(ka,{className:"ww:size-5 ww:text-muted-foreground"}):De(oa,{className:"ww:size-5 ww:text-muted-foreground"})}function fn({filename:e,mediaType:t,previewUrl:a,subtitle:r,tone:o="default",children:n,className:s}){let{t:i}=te(),l=ll(t,i);return cn("li",{"aria-label":`${e}, ${l}`,className:P("ww:relative ww:flex ww:w-60 ww:max-w-full ww:cursor-default ww:items-center ww:gap-2.5 ww:overflow-hidden ww:rounded-xl ww:border ww:bg-background ww:p-2.5",o==="error"?"ww:border-destructive/50":"ww:border-border",s),children:[De("span",{className:"ww:flex ww:size-10 ww:shrink-0 ww:items-center ww:justify-center ww:overflow-hidden ww:rounded-xl ww:bg-muted",children:a?De("img",{alt:"",className:"ww:size-full ww:object-cover ww:object-center",src:a}):De(Vm,{mediaType:t})}),cn("span",{className:"ww:flex ww:min-w-0 ww:flex-col",children:[De("span",{className:"ww:truncate ww:font-medium ww:text-sm",title:e,children:e}),De("span",{className:P("ww:truncate ww:text-xs",o==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:r??l})]}),n]})}function ul(e){if(typeof e!="object"||e===null)return[];let t=e.documents;return Array.isArray(t)?t.filter(a=>typeof a=="object"&&a!==null&&typeof a.documentId=="string"&&typeof a.filename=="string"&&typeof a.mediaType=="string"):[]}var dl=({documents:e,className:t,...a})=>e.length===0?null:De("ul",{className:P("ww:flex ww:list-none ww:flex-wrap ww:items-end ww:justify-end ww:gap-2 ww:p-0",t),...a,children:e.map((r,o)=>De(Gm,{document:r},`${r.documentId}-${o}`))});function Gm({document:e}){let{t}=te(),[a,r]=jm(!1),o=e.mediaType.startsWith("image/")?sl(e.documentId):void 0;return o&&!a?De("li",{children:De("img",{alt:`${e.filename}, ${ll(e.mediaType,t)}`,className:"ww:max-h-80 ww:max-w-72 ww:rounded-xl ww:border ww:border-border ww:object-contain",onError:()=>r(!0),src:o,title:e.filename})}):De(fn,{filename:e.filename,mediaType:e.mediaType})}import{jsx as Ee,jsxs as _r}from"react/jsx-runtime";var Qm=async e=>{try{let a=await(await fetch(e)).blob();return new Promise(r=>{let o=new FileReader;o.onloadend=()=>r(o.result),o.onerror=()=>r(null),o.readAsDataURL(a)})}catch{return null}},Ym=(e,t)=>{if(!t)return!0;let a=t.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean);if(a.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return a.some(n=>n.startsWith(".")?o.endsWith(n):n.endsWith("/*")?r.startsWith(n.slice(0,-1)):r===n)},fl=Km(null),Fr=()=>{let e=Xm(fl);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},pl=({className:e,accept:t,multiple:a,globalDrop:r,maxFiles:o,maxFileSize:n,maxPdfPages:s,attachmentsEnabled:i=!0,upload:l,onDiscard:u,onError:d,onSubmit:c,children:p,...f})=>{let{t:m,locale:y}=te(),S=Tt(null),L=Tt(null),[C,I]=pn([]),x=Tt(C),v=Tt(new Map),q=Tt(l),N=Tt(d),V=Tt(u);Ua(()=>{q.current=l,N.current=d,V.current=u},[l,d,u]);let G=je(k=>{x.current=k,I(k)},[]),Q=je(()=>{S.current?.click()},[]),O=je((k,H)=>{G(x.current.map($=>$.id===k?{...$,...H}:$))},[G]),re=je((k,H)=>{let $=q.current;if(!$)return;let ne=new AbortController,me=$(H,ne.signal,Ie=>{O(k,{progress:Ie})}).then(Ie=>(O(k,{status:"ready",progress:1,documentId:Ie.documentId,error:void 0}),Ie)).catch(Ie=>{if(ne.signal.aborted)return null;let fe=Ie instanceof Error?Ie.message:m.promptInput.uploadFailed;return O(k,{status:"failed",error:fe}),N.current?.({code:"upload_failed",message:fe}),null});v.current.set(k,{file:H,controller:ne,done:me})},[O,m]),K=je(k=>{let H=[...k];if(!i||H.length===0)return;let $=(W,se)=>N.current?.({code:W,message:se}),ne=[];for(let W of H){if(!Ym(W,t)){$("accept",m.promptInput.errorAccept.replace("{name}",W.name));continue}if(n&&W.size>n){$("max_file_size",m.promptInput.errorTooLarge.replace("{name}",W.name).replace("{limit}",ml(n,y)));continue}ne.push(W)}if(ne.length===0)return;let me=typeof o=="number"?Math.max(0,o-x.current.length):void 0,Ie=typeof me=="number"?ne.slice(0,me):ne;if(Ie.length<ne.length&&$("max_files",m.promptInput.errorTooMany.replace("{limit}",String(o))),Ie.length===0)return;let fe=!!q.current,Z=Ie.map(W=>({file:W,item:{filename:W.name,id:Oa(),mediaType:W.type,type:"file",url:URL.createObjectURL(W),status:fe?"uploading":"ready",progress:0}}));G([...x.current,...Z.map(W=>W.item)]);for(let W of Z)re(W.item.id,W.file)},[o,n,t,i,re,G,m,y]),J=je(k=>{let H=v.current.get(k);H&&(O(k,{status:"uploading",progress:0,error:void 0}),re(k,H.file))},[O,re]),X=je((k,H)=>{v.current.get(k.id)?.controller.abort(),v.current.delete(k.id),k.url&&(!H&&!!k.documentId&&!!k.mediaType?.startsWith("image/")&&k.documentId?nl(k.documentId,k.url):URL.revokeObjectURL(k.url)),H&&k.documentId&&V.current?.({documentId:k.documentId,filename:k.filename??"",mediaType:k.mediaType??""})},[]),R=je(k=>{let H=x.current.find($=>$.id===k);H&&X(H,!0),G(x.current.filter($=>$.id!==k))},[X,G]),b=je(()=>{for(let k of x.current)X(k,!0);G([])},[X,G]),D=Tt(i);Ua(()=>{let k=D.current;D.current=i,k&&!i&&b()},[i,b]);let ae=je(()=>{for(let k of x.current)X(k,!1);G([])},[X,G]);Ua(()=>()=>{for(let k of x.current)v.current.get(k.id)?.controller.abort(),k.url&&URL.revokeObjectURL(k.url)},[]);let oe=je(k=>{k.currentTarget.files&&K(k.currentTarget.files),k.currentTarget.value=""},[K]);Ua(()=>{if(!r)return;let k=$=>{$.dataTransfer?.types?.includes("Files")&&$.preventDefault()},H=$=>{$.dataTransfer?.types?.includes("Files")&&$.preventDefault(),$.dataTransfer?.files&&$.dataTransfer.files.length>0&&K($.dataTransfer.files)};return document.addEventListener("dragover",k),document.addEventListener("drop",H),()=>{document.removeEventListener("dragover",k),document.removeEventListener("drop",H)}},[K,r]);let Re=je(async k=>{k.preventDefault();let H=k.currentTarget,$=new FormData(H).get("message")||"",ne=new Map;for(;ne.size<v.current.size;)await Promise.all([...v.current.entries()].filter(([Z])=>!ne.has(Z)).map(async([Z,W])=>{ne.set(Z,await W.done)}));for(let Z of ne.keys())v.current.has(Z)||ne.delete(Z);if([...ne.values()].some(Z=>Z===null)){N.current?.({code:"upload_failed",message:m.promptInput.uploadFailed});return}let me=[...ne.values()].filter(Z=>Z!==null),Ie=q.current?[]:x.current,fe=await Promise.all(Ie.map(async({id:Z,status:W,progress:se,error:xe,...ie})=>{if(ie.url?.startsWith("blob:")){let le=await Qm(ie.url);return{...ie,url:le??ie.url}}return ie}));try{let Z=c({documents:me,files:fe,text:$},k);Z instanceof Promise&&await Z,H.reset(),ae()}catch{}},[c,ae,m]),Ne=Jm(()=>({add:K,clear:b,files:C,openFileDialog:Q,remove:R,retry:J,maxFileSize:n,maxPdfPages:s}),[C,K,R,J,b,Q,n,s]);return _r(fl.Provider,{value:Ne,children:[Ee("input",{accept:t,"aria-label":m.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:oe,ref:S,title:m.promptInput.uploadFiles,type:"file"}),Ee("form",{className:P("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:Re,ref:L,...f,children:p})]})},cl=1024*1024;function ml(e,t){let a=e>=cl;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/cl:Math.max(1,e/1024))}var hl=({onChange:e,onKeyDown:t,className:a,placeholder:r,...o})=>{let{t:n}=te(),s=Fr(),[i,l]=pn(!1),u=r??n.promptInput.placeholder,d=je(p=>{if(t?.(p),!p.defaultPrevented){if(p.key==="Enter"){if(i||p.nativeEvent.isComposing||p.shiftKey)return;p.preventDefault();let{form:f}=p.currentTarget;if(f?.querySelector('[data-submit-blocked="true"]')||f?.querySelector('button[type="submit"]')?.disabled)return;f?.requestSubmit()}if(p.key==="Backspace"&&p.currentTarget.value===""&&s.files.length>0){p.preventDefault();let f=s.files.at(-1);f&&s.remove(f.id)}}},[t,i,s]),c=je(p=>{let f=p.clipboardData?.items;if(!f)return;let m=[];for(let y of f)if(y.kind==="file"){let S=y.getAsFile();S&&m.push(S)}m.length>0&&(p.preventDefault(),s.add(m))},[s]);return Ee("textarea",{className:P("ww:field-sizing-content ww:max-h-48 ww:min-h-0 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-2 ww:text-base ww:sm:text-sm ww:outline-none ww:placeholder:text-muted-foreground",a),name:"message",onCompositionEnd:()=>l(!1),onCompositionStart:()=>l(!0),onKeyDown:d,onPaste:c,placeholder:u,onChange:e,...o})},gl=({className:e,status:t,onStop:a,onClick:r,children:o,disabled:n,...s})=>{let{t:i}=te(),l=t==="submitted"||t==="streaming",u=l&&a!==void 0,d=Ee(Sa,{className:"ww:size-4"});t==="submitted"?d=Ee(Pa,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(d=Ee(Ra,{className:"ww:size-4"}));let c=je(p=>{if(l&&a){p.preventDefault(),a();return}r?.(p)},[l,a,r]);return Ee(it,{"aria-label":l?i.promptInput.stop:i.promptInput.submit,className:P("ww:bg-foreground ww:text-background ww:hover:bg-foreground ww:rounded-full",e),"data-submit-blocked":n?"true":void 0,disabled:u?!1:n,onClick:c,size:"icon-sm",type:u?"button":"submit",variant:"ghost",...s,children:o??d})},wl=({className:e,children:t,...a})=>{let{t:r,locale:o}=te(),n=Fr();if(n.files.length>0)return _r(it,{className:P("ww:group ww:relative",e),onClick:()=>n.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":r.promptInput.removeAttachments,...a,children:[Ee("span",{className:"ww:flex ww:size-5 ww:items-center ww:justify-center ww:rounded-full ww:bg-primary ww:text-[10px] ww:font-medium ww:text-primary-foreground ww:transition-opacity ww:group-hover:opacity-0",children:n.files.length}),Ee(kt,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let i=n.maxFileSize?(n.maxPdfPages?r.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(n.maxPdfPages)):r.promptInput.uploadFilesUpTo).replace("{limit}",ml(n.maxFileSize,o)):r.promptInput.uploadFiles;return Ee(it,{"aria-label":i,className:P(e),title:i,onClick:()=>n.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??Ee(na,{className:"ww:size-4"})})},Il=({className:e,...t})=>{let a=Fr();return a.files.length===0?null:Ee("ul",{className:P("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(r=>Ee(Zm,{file:r},r.id))})};function Zm({file:e}){let{t}=te(),a=Fr(),r=e.status==="failed",o=e.status==="uploading";return _r(fn,{filename:e.filename??t.attachments.fileFallback,mediaType:e.mediaType??"",previewUrl:e.mediaType?.startsWith("image/")?e.url:void 0,subtitle:r?e.error:o?t.promptInput.uploading:void 0,tone:r?"error":"default",children:[r?Ee("button",{"aria-label":t.promptInput.retryUpload,className:"ww:ml-auto ww:shrink-0 ww:text-destructive ww:text-xs ww:underline ww:underline-offset-2",onClick:()=>a.retry(e.id),type:"button",children:t.promptInput.retry}):null,Ee("button",{"aria-label":t.promptInput.removeAttachment,className:P("ww:shrink-0 ww:rounded-full ww:p-1 ww:opacity-60 ww:transition-opacity hover:ww:bg-muted hover:ww:opacity-100",r?null:"ww:ml-auto"),onClick:()=>a.remove(e.id),type:"button",children:Ee(kt,{className:"ww:size-3.5"})}),o?Ee("span",{"aria-hidden":!0,className:"ww:absolute ww:bottom-0 ww:left-0 ww:h-0.5 ww:bg-primary ww:transition-[width] ww:duration-200",style:{width:`${Math.round(e.progress*100)}%`}}):null]})}var xl=({enabled:e=!0})=>{let{t}=te(),[a,r]=pn(!1);return Ua(()=>{if(!e)return;let o=0,n=u=>!!u.dataTransfer?.types?.includes("Files"),s=u=>{n(u)&&(o+=1,r(!0))},i=u=>{n(u)&&(o=Math.max(0,o-1),o===0&&r(!1))},l=()=>{o=0,r(!1)};return document.addEventListener("dragenter",s),document.addEventListener("dragleave",i),document.addEventListener("drop",l),()=>{document.removeEventListener("dragenter",s),document.removeEventListener("dragleave",i),document.removeEventListener("drop",l)}},[e]),e&&a?Ee("div",{className:"ww:pointer-events-none ww:absolute ww:inset-0 ww:z-50 ww:flex ww:items-center ww:justify-center ww:rounded-2xl ww:border-2 ww:border-primary ww:border-dashed ww:bg-background/85",children:_r("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[Ee(na,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};import{jsx as eh}from"react/jsx-runtime";function yl({text:e}){let{t}=te();return e===!1?null:eh("span",{className:"ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70",children:e||t.aiDisclaimer.default})}import{memo as th,useCallback as ah}from"react";import{jsx as la}from"react/jsx-runtime";var Ll=({className:e,...t})=>la("div",{className:P("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),Sl=({className:e,...t})=>la("li",{className:P("ww:group ww:flex ww:items-center ww:gap-2 ww:rounded-md ww:px-2 ww:py-1 ww:text-sm ww:transition-colors ww:hover:bg-muted",e),...t}),Cl=({className:e,...t})=>la("span",{className:P("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),bl=({className:e,...t})=>la("span",{className:P("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),vl=({className:e,...t})=>la("div",{className:P("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),kl=({className:e,...t})=>la(it,{className:P("ww:size-auto ww:rounded ww:p-1 ww:text-muted-foreground ww:hover:bg-muted-foreground/10 ww:hover:text-foreground",e),size:"icon",type:"button",variant:"ghost",...t});import{jsx as At,jsxs as Pl}from"react/jsx-runtime";var Tl=th(({message:e,onRemove:t})=>{let{t:a}=te(),r=ah(()=>t(e.id),[t,e.id]);return Pl(Sl,{children:[At(Cl,{}),At(bl,{children:e.text||a.chatQueue.attachmentFallback}),At(vl,{children:At(kl,{"aria-label":a.chatQueue.removeFromQueue,onClick:r,children:At(kt,{className:"ww:size-3"})})})]})});Tl.displayName="ChatQueueItem";function Al({queuedMessages:e,onRemove:t,className:a}){let{t:r}=te();return e.length===0?null:Pl(Ll,{className:P("ww:border-t ww:border-border",a),children:[At("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:r.chatQueue.queued(e.length)}),At("ul",{children:e.map(o=>At(Tl,{message:o,onRemove:t},o.id))})]})}import{createContext as ch,useCallback as fh,useContext as ph,useEffect as mh,useMemo as hh,useState as wn}from"react";import{createContext as rh,memo as gn,useCallback as oh,useContext as nh,useEffect as mn,useMemo as sh,useRef as Rl,useState as hn}from"react";import{Fragment as uh,jsx as at,jsxs as dh}from"react/jsx-runtime";var El=rh(null);function Ml(){let e=nh(El);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var ih=1e3,lh=1e3,Na=gn(({className:e,isStreaming:t=!1,open:a,defaultOpen:r,onOpenChange:o,duration:n,children:s,...i})=>{let l=r??t,u=r===!1,d=a!==void 0,[c,p]=hn(l),f=d?a:c,m=oh(N=>{d||p(N),o?.(N)},[d,o]),[y,S]=hn(void 0),L=n??y,C=Rl(t),[I,x]=hn(!1),v=Rl(null);mn(()=>{t?(C.current=!0,v.current===null&&(v.current=Date.now())):v.current!==null&&(S(Math.ceil((Date.now()-v.current)/lh)),v.current=null)},[t]),mn(()=>{t&&!f&&!u&&m(!0)},[t,f,u,m]),mn(()=>{if(C.current&&!t&&f&&!I){let N=setTimeout(()=>{m(!1),x(!0)},ih);return()=>clearTimeout(N)}},[t,f,I,m]);let q=sh(()=>({isStreaming:t,isOpen:f,setIsOpen:m,duration:L}),[t,f,m,L]);return at(El.Provider,{value:q,children:at("div",{className:P("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":f?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...i,children:s})})});Na.displayName="Reasoning";var qa=gn(({className:e,children:t,getThinkingMessage:a,hideIcon:r=!1,onClick:o,...n})=>{let{t:s}=te(),{isStreaming:i,isOpen:l,duration:u,setIsOpen:d}=Ml(),p=a??((f,m)=>f||m===0?at(et,{duration:1.6,children:s.reasoning.thinking}):m===void 0?at("span",{children:s.reasoning.thoughtBrief}):at("span",{children:s.reasoning.thoughtForSeconds(m)}));return at("button",{type:"button","aria-expanded":l,onClick:f=>{d(!l),o?.(f)},className:P("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),...n,children:t??dh(uh,{children:[!r&&at(ht,{className:"ww:size-4 ww:shrink-0"}),p(i,u)]})})});qa.displayName="ReasoningTrigger";var Ha=gn(({className:e,children:t,...a})=>{let{isOpen:r}=Ml();return at("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:at("div",{className:"ww:min-h-0 ww:overflow-hidden",children:at("div",{className:P("ww:text-sm ww:text-muted-foreground",e),...a,children:at(ya,{children:t})})})})});Ha.displayName="ReasoningContent";import{jsx as Le,jsxs as Pt}from"react/jsx-runtime";var gh=500,Fl=ch(null);function _l(){let e=ph(Fl);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function Dl({className:e,isWorking:t=!1,activeStep:a,open:r,defaultOpen:o=!1,onOpenChange:n,children:s,...i}){let l=r!==void 0,[u,d]=wn(o),c=l?r:u,p=fh(S=>{l||d(S),n?.(S)},[l,n]),[f,m]=wn(!t);mh(()=>{if(t){m(!1);return}let S=setTimeout(()=>m(!0),gh);return()=>clearTimeout(S)},[t]);let y=hh(()=>({open:c,setOpen:p,isWorking:t,settled:f,activeStep:a}),[c,p,t,f,a]);return Le(Fl.Provider,{value:y,children:Le("div",{className:P("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":c?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...i,children:s})})}function Bl({className:e,label:t,workingLabel:a,children:r,...o}){let{open:n,setOpen:s,isWorking:i,settled:l,activeStep:u}=_l();if(!l){let d=u?.icon,c=u?.label??a??t??"";return Le("div",{className:P("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground",e),children:Pt("span",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-1.5",style:{animation:"ww-fade-in 0.25s ease-out"},children:[d&&Le(d,{className:P("ww:size-4 ww:shrink-0",i&&"ww:animate-pulse")}),Le("span",{className:"ww:truncate",children:i?Le(et,{duration:2.6,children:c}):c})]},c)})}return Pt("button",{type:"button",onClick:()=>s(!n),"aria-expanded":n,className:P("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),style:{animation:"ww-fade-in 0.25s ease-out"},...o,children:[Le("span",{className:"ww:truncate",children:r??t}),Le(vt,{className:P("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",n&&"ww:rotate-180")})]})}function Ol({className:e,children:t,...a}){let{open:r}=_l();return Le("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:Le("div",{className:"ww:min-h-0 ww:overflow-hidden",children:Le("div",{className:P("ww:flex ww:flex-col",e),...a,children:t})})})}function Ul({icon:e,isLast:t,running:a,error:r}){return Pt("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[Le("span",{className:"ww:flex ww:h-5 ww:items-center",children:Le(e,{className:P("ww:size-4 ww:shrink-0",r?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&Le("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function In({className:e,icon:t,title:a,state:r,isLast:o=!1,children:n,...s}){let i=r==="input-available"||r==="input-streaming",l=r==="output-error",u=n!=null,[d,c]=wn(!1),p=a??"",f=i?Le(et,{duration:1.6,children:p}):Le("span",{className:"ww:truncate",children:p});return Pt("div",{className:P("ww:flex ww:gap-2",e),...s,children:[Le(Ul,{icon:t,isLast:o,running:i,error:l}),Pt("div",{className:P("ww:min-w-0 ww:flex-1",!o&&"ww:pb-3"),children:[u?Pt("button",{type:"button",onClick:()=>c(m=>!m),"aria-expanded":d,className:"ww:flex ww:w-full ww:items-center ww:gap-1.5 ww:text-left ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",children:[f,Le(vt,{className:P("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",d&&"ww:rotate-180")})]}):Le("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:f}),u&&Le("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",d?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:Le("div",{className:"ww:min-h-0 ww:overflow-hidden",children:Le("div",{className:"ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",children:n})})})]})]})}function Nl({isStreaming:e=!1,isLast:t=!1,children:a}){return Pt("div",{className:"ww:flex ww:gap-2",children:[Le(Ul,{icon:ht,isLast:t,running:e}),Le("div",{className:P("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:Pt(Na,{isStreaming:e,className:"ww:mb-0",children:[Le(qa,{hideIcon:!0}),Le(Ha,{children:a})]})})]})}var Oe={carriageReturn:-5,lineFeed:-4,carriageReturnLineFeed:-3,horizontalTab:-2,virtualSpace:-1,eof:null,nul:0,soh:1,stx:2,etx:3,eot:4,enq:5,ack:6,bel:7,bs:8,ht:9,lf:10,vt:11,ff:12,cr:13,so:14,si:15,dle:16,dc1:17,dc2:18,dc3:19,dc4:20,nak:21,syn:22,etb:23,can:24,em:25,sub:26,esc:27,fs:28,gs:29,rs:30,us:31,space:32,exclamationMark:33,quotationMark:34,numberSign:35,dollarSign:36,percentSign:37,ampersand:38,apostrophe:39,leftParenthesis:40,rightParenthesis:41,asterisk:42,plusSign:43,comma:44,dash:45,dot:46,slash:47,digit0:48,digit1:49,digit2:50,digit3:51,digit4:52,digit5:53,digit6:54,digit7:55,digit8:56,digit9:57,colon:58,semicolon:59,lessThan:60,equalsTo:61,greaterThan:62,questionMark:63,atSign:64,uppercaseA:65,uppercaseB:66,uppercaseC:67,uppercaseD:68,uppercaseE:69,uppercaseF:70,uppercaseG:71,uppercaseH:72,uppercaseI:73,uppercaseJ:74,uppercaseK:75,uppercaseL:76,uppercaseM:77,uppercaseN:78,uppercaseO:79,uppercaseP:80,uppercaseQ:81,uppercaseR:82,uppercaseS:83,uppercaseT:84,uppercaseU:85,uppercaseV:86,uppercaseW:87,uppercaseX:88,uppercaseY:89,uppercaseZ:90,leftSquareBracket:91,backslash:92,rightSquareBracket:93,caret:94,underscore:95,graveAccent:96,lowercaseA:97,lowercaseB:98,lowercaseC:99,lowercaseD:100,lowercaseE:101,lowercaseF:102,lowercaseG:103,lowercaseH:104,lowercaseI:105,lowercaseJ:106,lowercaseK:107,lowercaseL:108,lowercaseM:109,lowercaseN:110,lowercaseO:111,lowercaseP:112,lowercaseQ:113,lowercaseR:114,lowercaseS:115,lowercaseT:116,lowercaseU:117,lowercaseV:118,lowercaseW:119,lowercaseX:120,lowercaseY:121,lowercaseZ:122,leftCurlyBrace:123,verticalBar:124,rightCurlyBrace:125,tilde:126,del:127,byteOrderMarker:65279,replacementCharacter:65533};var ut={attentionSideAfter:2,attentionSideBefore:1,atxHeadingOpeningFenceSizeMax:6,autolinkDomainSizeMax:63,autolinkSchemeSizeMax:32,cdataOpeningString:"CDATA[",characterGroupPunctuation:2,characterGroupWhitespace:1,characterReferenceDecimalSizeMax:7,characterReferenceHexadecimalSizeMax:6,characterReferenceNamedSizeMax:31,codeFencedSequenceSizeMin:3,contentTypeContent:"content",contentTypeDocument:"document",contentTypeFlow:"flow",contentTypeString:"string",contentTypeText:"text",hardBreakPrefixSizeMin:2,htmlBasic:6,htmlCdata:5,htmlComment:2,htmlComplete:7,htmlDeclaration:4,htmlInstruction:3,htmlRawSizeMax:8,htmlRaw:1,linkResourceDestinationBalanceMax:32,linkReferenceSizeMax:999,listItemValueSizeMax:10,numericBaseDecimal:10,numericBaseHexadecimal:16,tabSize:4,thematicBreakMarkerCountMin:3,v8MaxSafeChunkSize:1e4};var Xe={data:"data",whitespace:"whitespace",lineEnding:"lineEnding",lineEndingBlank:"lineEndingBlank",linePrefix:"linePrefix",lineSuffix:"lineSuffix",atxHeading:"atxHeading",atxHeadingSequence:"atxHeadingSequence",atxHeadingText:"atxHeadingText",autolink:"autolink",autolinkEmail:"autolinkEmail",autolinkMarker:"autolinkMarker",autolinkProtocol:"autolinkProtocol",characterEscape:"characterEscape",characterEscapeValue:"characterEscapeValue",characterReference:"characterReference",characterReferenceMarker:"characterReferenceMarker",characterReferenceMarkerNumeric:"characterReferenceMarkerNumeric",characterReferenceMarkerHexadecimal:"characterReferenceMarkerHexadecimal",characterReferenceValue:"characterReferenceValue",codeFenced:"codeFenced",codeFencedFence:"codeFencedFence",codeFencedFenceSequence:"codeFencedFenceSequence",codeFencedFenceInfo:"codeFencedFenceInfo",codeFencedFenceMeta:"codeFencedFenceMeta",codeFlowValue:"codeFlowValue",codeIndented:"codeIndented",codeText:"codeText",codeTextData:"codeTextData",codeTextPadding:"codeTextPadding",codeTextSequence:"codeTextSequence",content:"content",definition:"definition",definitionDestination:"definitionDestination",definitionDestinationLiteral:"definitionDestinationLiteral",definitionDestinationLiteralMarker:"definitionDestinationLiteralMarker",definitionDestinationRaw:"definitionDestinationRaw",definitionDestinationString:"definitionDestinationString",definitionLabel:"definitionLabel",definitionLabelMarker:"definitionLabelMarker",definitionLabelString:"definitionLabelString",definitionMarker:"definitionMarker",definitionTitle:"definitionTitle",definitionTitleMarker:"definitionTitleMarker",definitionTitleString:"definitionTitleString",emphasis:"emphasis",emphasisSequence:"emphasisSequence",emphasisText:"emphasisText",escapeMarker:"escapeMarker",hardBreakEscape:"hardBreakEscape",hardBreakTrailing:"hardBreakTrailing",htmlFlow:"htmlFlow",htmlFlowData:"htmlFlowData",htmlText:"htmlText",htmlTextData:"htmlTextData",image:"image",label:"label",labelText:"labelText",labelLink:"labelLink",labelImage:"labelImage",labelMarker:"labelMarker",labelImageMarker:"labelImageMarker",labelEnd:"labelEnd",link:"link",paragraph:"paragraph",reference:"reference",referenceMarker:"referenceMarker",referenceString:"referenceString",resource:"resource",resourceDestination:"resourceDestination",resourceDestinationLiteral:"resourceDestinationLiteral",resourceDestinationLiteralMarker:"resourceDestinationLiteralMarker",resourceDestinationRaw:"resourceDestinationRaw",resourceDestinationString:"resourceDestinationString",resourceMarker:"resourceMarker",resourceTitle:"resourceTitle",resourceTitleMarker:"resourceTitleMarker",resourceTitleString:"resourceTitleString",setextHeading:"setextHeading",setextHeadingText:"setextHeadingText",setextHeadingLine:"setextHeadingLine",setextHeadingLineSequence:"setextHeadingLineSequence",strong:"strong",strongSequence:"strongSequence",strongText:"strongText",thematicBreak:"thematicBreak",thematicBreakSequence:"thematicBreakSequence",blockQuote:"blockQuote",blockQuotePrefix:"blockQuotePrefix",blockQuoteMarker:"blockQuoteMarker",blockQuotePrefixWhitespace:"blockQuotePrefixWhitespace",listOrdered:"listOrdered",listUnordered:"listUnordered",listItemIndent:"listItemIndent",listItemMarker:"listItemMarker",listItemPrefix:"listItemPrefix",listItemPrefixWhitespace:"listItemPrefixWhitespace",listItemValue:"listItemValue",chunkDocument:"chunkDocument",chunkContent:"chunkContent",chunkFlow:"chunkFlow",chunkText:"chunkText",chunkString:"chunkString"};function ql(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}function Hl(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}function $l(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e>=94192&&e<=94198||e>=94208&&e<=101589||e>=101631&&e<=101662||e>=101760&&e<=101874||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128728||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129674||e>=129678&&e<=129734||e===129736||e>=129741&&e<=129756||e>=129759&&e<=129770||e>=129775&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}function Wl(e){return ql(e)?"ambiguous":Hl(e)?"fullwidth":e===8361||e>=65377&&e<=65470||e>=65474&&e<=65479||e>=65482&&e<=65487||e>=65490&&e<=65495||e>=65498&&e<=65500||e>=65512&&e<=65518?"halfwidth":e>=32&&e<=126||e===162||e===163||e===165||e===166||e===172||e===175||e>=10214&&e<=10221||e===10629||e===10630?"narrow":$l(e)?"wide":"neutral"}function wh(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}function jl(e){return wh(e),Wl(e)}var Ih=Object.defineProperty,xh=(e,t,a)=>t in e?Ih(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,yh=(e,t,a)=>xh(e,typeof t!="symbol"?t+"":t,a);function Lh(e){return/^\p{Emoji_Presentation}/u.test(String.fromCodePoint(e))}function Sh(e){if(!e||e<4352)return!1;switch(jl(e)){case"fullwidth":case"halfwidth":return!0;case"wide":return!Lh(e);case"narrow":return!1;case"ambiguous":return 917760<=e&&e<=917999?null:!1;case"neutral":return/^\p{sc=Hangul}/u.test(String.fromCodePoint(e))}}function Ch(e,t){return t!==65025||!e||e<8216?!1:e===8216||e===8217||e===8220||e===8221}function bh(e){return e!==null&&e>=65024&&e<=65038}var vh=zl(/\p{P}|\p{S}/u),kh=zl(/\s/);function zl(e){return t;function t(a){return a!==null&&a>-1&&e.test(String.fromCodePoint(a))}}var Je;(e=>{e.spaceOrPunctuation=3,e.cjk=4096,e.cjkPunctuation=4098,e.ivs=8192,e.cjkOrIvs=12288,e.nonEmojiGeneralUseVS=16384,e.variationSelector=24576,e.ivsToCjkRightShift=1})(Je||(Je={}));function Rt(e){if(e===Oe.eof||xi(e)||kh(e))return ut.characterGroupWhitespace;let t=0;if(e>=4352){if(bh(e))return Je.nonEmojiGeneralUseVS;switch(Sh(e)){case null:return Je.ivs;case!0:t|=Je.cjk;break}}return vh(e)&&(t|=ut.characterGroupPunctuation),t}function Dr(e,t,a){if(!Ah(e))return e;let r=t(),o=Rt(r);return!r||jt(o)?e:Ch(r,a)?Je.cjkPunctuation:Th(o)}function Th(e){return e&~Je.ivs}function jt(e){return!!(e&ut.characterGroupWhitespace)}function ua(e){return(e&Je.cjkPunctuation)===ut.characterGroupPunctuation}function $a(e){return!!(e&Je.cjk)}function Vl(e){return e===Je.ivs}function Gl(e){return!!(e&Je.cjkOrIvs)}function Ah(e){return e===Je.nonEmojiGeneralUseVS}function xn(e){return!!(e&Je.spaceOrPunctuation)}function Br(e){return!!(e&&e>=55296&&e<=56319)}function Or(e){return!!(e&&e>=56320&&e<=57343)}function Ur(e,t,a){if(t._bufferIndex<2)return e;let o=a({start:{...t,_bufferIndex:t._bufferIndex-2},end:t}).codePointAt(0);return o&&o>=65536?o:e}function Ph(e,t,a){let r=e>=65536?2:1;if(t._bufferIndex<1+r)return null;let o=t._bufferIndex-r-2,n=a({start:{...t,_bufferIndex:o>=0?o:0},end:{...t,_bufferIndex:t._bufferIndex-r}}),s=n.charCodeAt(n.length-1);if(Number.isNaN(s))return null;if(n.length<2||s<56320||57343<s)return s;let i=n.codePointAt(0);return i&&i>=65536?i:s}var Nr=class{constructor(e,t,a){this.previousCode=e,this.nowPoint=t,this.sliceSerialize=a,yh(this,"cachedValue")}value(){return this.cachedValue===void 0&&(this.cachedValue=Ph(this.previousCode,this.nowPoint,this.sliceSerialize)),this.cachedValue}};function qr(e,t,a){let r=a({start:t,end:{...t,_bufferIndex:t._bufferIndex+2}}).codePointAt(0);return r&&r>=65536?r:e}var yn={name:"attention",resolveAll:Rh,tokenize:Eh};function Rh(e,t){let a=-1,r,o,n,s,i,l,u,d;for(;++a<e.length;)if(e[a][0]==="enter"&&e[a][1].type==="attentionSequence"&&e[a][1]._close){for(r=a;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[a][1]).charCodeAt(0)){if((e[r][1]._close||e[a][1]._open)&&(e[a][1].end.offset-e[a][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[a][1].end.offset-e[a][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[a][1].end.offset-e[a][1].start.offset>1?2:1;let c={...e[r][1].end},p={...e[a][1].start};Kl(c,-l),Kl(p,l),s={type:l>1?Xe.strongSequence:Xe.emphasisSequence,start:c,end:{...e[r][1].end}},i={type:l>1?Xe.strongSequence:Xe.emphasisSequence,start:{...e[a][1].start},end:p},n={type:l>1?Xe.strongText:Xe.emphasisText,start:{...e[r][1].end},end:{...e[a][1].start}},o={type:l>1?Xe.strong:Xe.emphasis,start:{...s.start},end:{...i.end}},e[r][1].end={...s.start},e[a][1].start={...i.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=ta(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=ta(u,[["enter",o,t],["enter",s,t],["exit",s,t],["enter",n,t]]),t.parser.constructs.insideSpan.null,u=ta(u,Cr(t.parser.constructs.insideSpan.null,e.slice(r+1,a),t)),u=ta(u,[["exit",n,t],["enter",i,t],["exit",i,t],["exit",o,t]]),e[a][1].end.offset-e[a][1].start.offset?(d=2,u=ta(u,[["enter",e[a][1],t],["exit",e[a][1],t]])):d=0,ea(e,r-1,a-r+3,u),a=r+u.length-d-2;break}}for(a=-1;++a<e.length;)e[a][1].type==="attentionSequence"&&(e[a][1].type="data");return e}function Eh(e,t){let a=this.parser.constructs.attentionMarkers.null,{now:r,sliceSerialize:o,previous:n}=this,s=Or(n)?Ur(n,r(),o):n,i=Rt(s),l=new Nr(s,r(),o),u=Dr(i,l.value.bind(l),s),d;return c;function c(f){return f===Oe.asterisk||Oe.underscore,d=f,e.enter("attentionSequence"),p(f)}function p(f){if(f===d)return e.consume(f),p;let m=e.exit("attentionSequence"),y=Br(f)?qr(f,r(),o):f,S=Rt(y);let L=ua(u),C=L||jt(u),I=ua(S),x=I||jt(S),v=Gl(u),q=!x||I&&(C||v)||a.includes(f),N=!C||L&&(x||$a(S))||a.includes(s);return m._open=!!(d===Oe.asterisk?q:q&&(xn(u)||!N)),m._close=!!(d===Oe.asterisk?N:N&&(xn(S)||!q)),t(f)}}function Kl(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}function Xl(){return{text:{[Oe.asterisk]:yn,[Oe.underscore]:yn},insideSpan:{null:[yn]}}}function Jl(){let e=this.data();(e.micromarkExtensions||(e.micromarkExtensions=[])).push(Xl())}function Ql(e){let a=(e||{}).singleTilde,r={name:"strikethrough",tokenize:n,resolveAll:o};return a==null&&(a=!0),{text:{[Oe.tilde]:r},insideSpan:{null:[r]},attentionMarkers:{null:[Oe.tilde]}};function o(s,i){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";let d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},p=[["enter",d,i],["enter",s[u][1],i],["exit",s[u][1],i],["enter",c,i]],f=i.parser.constructs.insideSpan.null;f&&ea(p,p.length,0,Cr(f,s.slice(u+1,l),i)),ea(p,p.length,0,[["exit",c,i],["enter",s[l][1],i],["exit",s[l][1],i],["exit",d,i]]),ea(s,u-1,l-u+3,p),l=u+p.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type=Xe.data);return s}function n(s,i,l){let{now:u,sliceSerialize:d,previous:c}=this,p=Or(c)?Ur(c,u(),d):c,f=Rt(p),m=new Nr(p,u(),d),y=Dr(f,m.value.bind(m),p),S=this.events,L=0;return C;function C(x){return Oe.tilde,p===Oe.tilde&&S[S.length-1][1].type!==Xe.characterEscape?l(x):(s.enter("strikethroughSequenceTemporary"),I(x))}function I(x){let v=Rt(p);if(x===Oe.tilde)return L>1?l(x):(s.consume(x),L++,I);if(L<2&&!a)return l(x);let q=s.exit("strikethroughSequenceTemporary"),N=Br(x)?qr(x,u(),d):x,V=Rt(N),Q=ua(y)||jt(y),re=ua(V)||jt(V),K=$a(y)||Vl(v);return q._open=!re||V===ut.attentionSideAfter&&(Q||K),q._close=!Q||v===ut.attentionSideAfter&&(re||$a(V)),i(x)}}}function Yl(e){let t=this.data();(t.micromarkExtensions||(t.micromarkExtensions=[])).push(Ql(e))}var Mh=new Set(["\u3002","\uFF0E","\uFF0C","\u3001","\uFF1F","\uFF01","\uFF1A","\uFF1B","\uFF08","\uFF09","\u3010","\u3011","\u300C","\u300D","\u300E","\u300F","\u3008","\u3009","\u300A","\u300B"]),Fh=/^(https?:\/\/|mailto:|www\.)/i,_h=e=>{if(e.children.length!==1)return!1;let t=e.children[0];return t.type==="text"&&t.value===e.url},Dh=e=>{let t=0;for(let a of e){if(Mh.has(a))return t;t+=a.length}return null},Bh=(e,t)=>({...t,url:e,children:[{type:"text",value:e}]}),Oh=e=>({type:"text",value:e}),Uh=()=>e=>{fi(e,"link",(t,a,r)=>{if(!r||typeof a!="number"||!_h(t)||!Fh.test(t.url))return;let o=Dh(t.url);if(o===null||o===0)return;let n=t.url.slice(0,o),s=t.url.slice(o),i=Bh(n,t),l=Oh(s);return r.children.splice(a,1,i,l),a+1})};function Nh(){let e=[Jl],t=[Uh,Yl],a=[...e,...t];return{name:"cjk",type:"cjk",remarkPluginsBefore:e,remarkPluginsAfter:t,remarkPlugins:a}}var Ln=Nh();var ve=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function qh(e){return En(e)}function En(e){return Array.isArray(e)?Hh(e):e instanceof RegExp?e:typeof e=="object"?$h(e):e}function Hh(e){let t=[];for(let a=0,r=e.length;a<r;a++)t[a]=En(e[a]);return t}function $h(e){let t={};for(let a in e)t[a]=En(e[a]);return t}function iu(e,...t){return t.forEach(a=>{for(let r in a)e[r]=a[r]}),e}function lu(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?lu(e.substring(0,e.length-1)):e.substr(~t+1)}var Sn=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Hr=class{static hasCaptures(e){return e===null?!1:(Sn.lastIndex=0,Sn.test(e))}static replaceCaptures(e,t,a){return e.replace(Sn,(r,o,n,s)=>{let i=a[parseInt(o||n,10)];if(i){let l=t.substring(i.start,i.end);for(;l[0]===".";)l=l.substring(1);switch(s){case"downcase":return l.toLowerCase();case"upcase":return l.toUpperCase();default:return l}}else return r})}};function uu(e,t){return e<t?-1:e>t?1:0}function du(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let a=e.length,r=t.length;if(a===r){for(let o=0;o<a;o++){let n=uu(e[o],t[o]);if(n!==0)return n}return 0}return a-r}function Zl(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function cu(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var fu=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},za=class{constructor(e,t,a){this._colorMap=e,this._defaults=t,this._root=a}static createFromRawTheme(e,t){return this.createFromParsedTheme(zh(e),t)}static createFromParsedTheme(e,t){return Gh(e,t)}_cachedMatchRoot=new fu(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(o=>Wh(e.parent,o.parentScopes));return r?new pu(r.fontStyle,r.foreground,r.background):null}},Cn=class $r{constructor(t,a){this.parent=t,this.scopeName=a}static push(t,a){for(let r of a)t=new $r(t,r);return t}static from(...t){let a=null;for(let r=0;r<t.length;r++)a=new $r(a,t[r]);return a}push(t){return new $r(this,t)}getSegments(){let t=this,a=[];for(;t;)a.push(t.scopeName),t=t.parent;return a.reverse(),a}toString(){return this.getSegments().join(" ")}extends(t){return this===t?!0:this.parent===null?!1:this.parent.extends(t)}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push(r.scopeName),r=r.parent;return r===t?a.reverse():void 0}};function Wh(e,t){if(t.length===0)return!0;for(let a=0;a<t.length;a++){let r=t[a],o=!1;if(r===">"){if(a===t.length-1)return!1;r=t[++a],o=!0}for(;e&&!jh(e.scopeName,r);){if(o)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function jh(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var pu=class{constructor(e,t,a){this.fontStyle=e,this.foregroundId=t,this.backgroundId=a}};function zh(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,a=[],r=0;for(let o=0,n=t.length;o<n;o++){let s=t[o];if(!s.settings)continue;let i;if(typeof s.scope=="string"){let c=s.scope;c=c.replace(/^[,]+/,""),c=c.replace(/[,]+$/,""),i=c.split(",")}else Array.isArray(s.scope)?i=s.scope:i=[""];let l=-1;if(typeof s.settings.fontStyle=="string"){l=0;let c=s.settings.fontStyle.split(" ");for(let p=0,f=c.length;p<f;p++)switch(c[p]){case"italic":l=l|1;break;case"bold":l=l|2;break;case"underline":l=l|4;break;case"strikethrough":l=l|8;break}}let u=null;typeof s.settings.foreground=="string"&&Zl(s.settings.foreground)&&(u=s.settings.foreground);let d=null;typeof s.settings.background=="string"&&Zl(s.settings.background)&&(d=s.settings.background);for(let c=0,p=i.length;c<p;c++){let m=i[c].trim().split(" "),y=m[m.length-1],S=null;m.length>1&&(S=m.slice(0,m.length-1),S.reverse()),a[r++]=new Vh(y,S,o,l,u,d)}}return a}var Vh=class{constructor(e,t,a,r,o,n){this.scope=e,this.parentScopes=t,this.index=a,this.fontStyle=r,this.foreground=o,this.background=n}},Ue=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(Ue||{});function Gh(e,t){e.sort((l,u)=>{let d=uu(l.scope,u.scope);return d!==0||(d=du(l.parentScopes,u.parentScopes),d!==0)?d:l.index-u.index});let a=0,r="#000000",o="#ffffff";for(;e.length>=1&&e[0].scope==="";){let l=e.shift();l.fontStyle!==-1&&(a=l.fontStyle),l.foreground!==null&&(r=l.foreground),l.background!==null&&(o=l.background)}let n=new Kh(t),s=new pu(a,n.getId(r),n.getId(o)),i=new Jh(new vn(0,null,-1,0,0),[]);for(let l=0,u=e.length;l<u;l++){let d=e[l];i.insert(0,d.scope,d.parentScopes,d.fontStyle,n.getId(d.foreground),n.getId(d.background))}return new za(n,s,i)}var Kh=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,a=e.length;t<a;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw new Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},Xh=Object.freeze([]),vn=class mu{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(t,a,r,o,n){this.scopeDepth=t,this.parentScopes=a||Xh,this.fontStyle=r,this.foreground=o,this.background=n}clone(){return new mu(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(t){let a=[];for(let r=0,o=t.length;r<o;r++)a[r]=t[r].clone();return a}acceptOverwrite(t,a,r,o){this.scopeDepth>t?console.log("how did this happen?"):this.scopeDepth=t,a!==-1&&(this.fontStyle=a),r!==0&&(this.foreground=r),o!==0&&(this.background=o)}},Jh=class kn{constructor(t,a=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=a}_rulesWithParentScopes;static _cmpBySpecificity(t,a){if(t.scopeDepth!==a.scopeDepth)return a.scopeDepth-t.scopeDepth;let r=0,o=0;for(;t.parentScopes[r]===">"&&r++,a.parentScopes[o]===">"&&o++,!(r>=t.parentScopes.length||o>=a.parentScopes.length);){let n=a.parentScopes[o].length-t.parentScopes[r].length;if(n!==0)return n;r++,o++}return a.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),o,n;if(r===-1?(o=t,n=""):(o=t.substring(0,r),n=t.substring(r+1)),this._children.hasOwnProperty(o))return this._children[o].match(n)}let a=this._rulesWithParentScopes.concat(this._mainRule);return a.sort(kn._cmpBySpecificity),a}insert(t,a,r,o,n,s){if(a===""){this._doInsertHere(t,r,o,n,s);return}let i=a.indexOf("."),l,u;i===-1?(l=a,u=""):(l=a.substring(0,i),u=a.substring(i+1));let d;this._children.hasOwnProperty(l)?d=this._children[l]:(d=new kn(this._mainRule.clone(),vn.cloneArr(this._rulesWithParentScopes)),this._children[l]=d),d.insert(t+1,u,r,o,n,s)}_doInsertHere(t,a,r,o,n){if(a===null){this._mainRule.acceptOverwrite(t,r,o,n);return}for(let s=0,i=this._rulesWithParentScopes.length;s<i;s++){let l=this._rulesWithParentScopes[s];if(du(l.parentScopes,a)===0){l.acceptOverwrite(t,r,o,n);return}}r===-1&&(r=this._mainRule.fontStyle),o===0&&(o=this._mainRule.foreground),n===0&&(n=this._mainRule.background),this._rulesWithParentScopes.push(new vn(t,a,r,o,n))}},Vt=class Ye{static toBinaryStr(t){return t.toString(2).padStart(32,"0")}static print(t){let a=Ye.getLanguageId(t),r=Ye.getTokenType(t),o=Ye.getFontStyle(t),n=Ye.getForeground(t),s=Ye.getBackground(t);console.log({languageId:a,tokenType:r,fontStyle:o,foreground:n,background:s})}static getLanguageId(t){return(t&255)>>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,a,r,o,n,s,i){let l=Ye.getLanguageId(t),u=Ye.getTokenType(t),d=Ye.containsBalancedBrackets(t)?1:0,c=Ye.getFontStyle(t),p=Ye.getForeground(t),f=Ye.getBackground(t);return a!==0&&(l=a),r!==8&&(u=r),o!==null&&(d=o?1:0),n!==-1&&(c=n),s!==0&&(p=s),i!==0&&(f=i),(l<<0|u<<8|d<<10|c<<11|p<<15|f<<24)>>>0}};function jr(e,t){let a=[],r=Qh(e),o=r.next();for(;o!==null;){let l=0;if(o.length===2&&o.charAt(1)===":"){switch(o.charAt(0)){case"R":l=1;break;case"L":l=-1;break;default:console.log(`Unknown priority ${o} in scope selector`)}o=r.next()}let u=s();if(a.push({matcher:u,priority:l}),o!==",")break;o=r.next()}return a;function n(){if(o==="-"){o=r.next();let l=n();return u=>!!l&&!l(u)}if(o==="("){o=r.next();let l=i();return o===")"&&(o=r.next()),l}if(eu(o)){let l=[];do l.push(o),o=r.next();while(eu(o));return u=>t(l,u)}return null}function s(){let l=[],u=n();for(;u;)l.push(u),u=n();return d=>l.every(c=>c(d))}function i(){let l=[],u=s();for(;u&&(l.push(u),o==="|"||o===",");){do o=r.next();while(o==="|"||o===",");u=s()}return d=>l.some(c=>c(d))}}function eu(e){return!!e&&!!e.match(/[\w\.:]+/)}function Qh(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,a=t.exec(e);return{next:()=>{if(!a)return null;let r=a[0];return a=t.exec(e),r}}}function hu(e){typeof e.dispose=="function"&&e.dispose()}var Va=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},Yh=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},Zh=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},eg=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Va(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new Zh;for(let a of e)tg(a,this.initialScopeName,this.repo,t);for(let a of t.references)if(a instanceof Va){if(this.seenFullScopeRequests.has(a.scopeName))continue;this.seenFullScopeRequests.add(a.scopeName),this.Q.push(a)}else{if(this.seenFullScopeRequests.has(a.scopeName)||this.seenPartialScopeRequests.has(a.toKey()))continue;this.seenPartialScopeRequests.add(a.toKey()),this.Q.push(a)}}};function tg(e,t,a,r){let o=a.lookup(e.scopeName);if(!o){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let n=a.lookup(t);e instanceof Va?Wr({baseGrammar:n,selfGrammar:o},r):Tn(e.ruleName,{baseGrammar:n,selfGrammar:o,repository:o.repository},r);let s=a.injections(e.scopeName);if(s)for(let i of s)r.add(new Va(i))}function Tn(e,t,a){if(t.repository&&t.repository[e]){let r=t.repository[e];zr([r],t,a)}}function Wr(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&zr(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&zr(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function zr(e,t,a){for(let r of e){if(a.visitedRule.has(r))continue;a.visitedRule.add(r);let o=r.repository?iu({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&zr(r.patterns,{...t,repository:o},a);let n=r.include;if(!n)continue;let s=gu(n);switch(s.kind){case 0:Wr({...t,selfGrammar:t.baseGrammar},a);break;case 1:Wr(t,a);break;case 2:Tn(s.ruleName,{...t,repository:o},a);break;case 3:case 4:let i=s.scopeName===t.selfGrammar.scopeName?t.selfGrammar:s.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(i){let l={baseGrammar:t.baseGrammar,selfGrammar:i,repository:o};s.kind===4?Tn(s.ruleName,l,a):Wr(l,a)}else s.kind===4?a.add(new Yh(s.scopeName,s.ruleName)):a.add(new Va(s.scopeName));break}}}var ag=class{kind=0},rg=class{kind=1},og=class{constructor(e){this.ruleName=e}kind=2},ng=class{constructor(e){this.scopeName=e}kind=3},sg=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function gu(e){if(e==="$base")return new ag;if(e==="$self")return new rg;let t=e.indexOf("#");if(t===-1)return new ng(e);if(t===0)return new og(e.substring(1));{let a=e.substring(0,t),r=e.substring(t+1);return new sg(a,r)}}var ig=/\\(\d+)/,tu=/\\(\d+)/g;var lg=-1,wu=-2;var Xa=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,a,r){this.$location=e,this.id=t,this._name=a||null,this._nameIsCapturing=Hr.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Hr.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${lu(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Hr.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Hr.replaceCaptures(this._contentName,e,t)}},ug=class extends Xa{retokenizeCapturedWithRuleId;constructor(e,t,a,r,o){super(e,t,a,r),this.retokenizeCapturedWithRuleId=o}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,a,r){throw new Error("Not supported!")}},dg=class extends Xa{_match;captures;_cachedCompiledPatterns;constructor(e,t,a,r,o){super(e,t,a,null),this._match=new Ga(r,this.id),this.captures=o,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ka,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},au=class extends Xa{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,o){super(e,t,a,r),this.patterns=o.patterns,this.hasMissingPatterns=o.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let a of this.patterns)e.getRule(a).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ka,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},An=class extends Xa{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,o,n,s,i,l,u){super(e,t,a,r),this._begin=new Ga(o,this.id),this.beginCaptures=n,this._end=new Ga(s||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=i,this.applyEndPatternLast=l||!1,this.patterns=u.patterns,this.hasMissingPatterns=u.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,a,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ka;for(let a of this.patterns)e.getRule(a).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Vr=class extends Xa{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,a,r,o,n,s,i,l){super(e,t,a,r),this._begin=new Ga(o,this.id),this.beginCaptures=n,this.whileCaptures=i,this._while=new Ga(s,wu),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ka;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,a,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,a,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Ka,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},Iu=class qe{static createCaptureRule(t,a,r,o,n){return t.registerRule(s=>new ug(a,s,r,o,n))}static getCompiledRuleId(t,a,r){return t.id||a.registerRule(o=>{if(t.id=o,t.match)return new dg(t.$vscodeTextmateLocation,t.id,t.name,t.match,qe._compileCaptures(t.captures,a,r));if(typeof t.begin>"u"){t.repository&&(r=iu({},r,t.repository));let n=t.patterns;return typeof n>"u"&&t.include&&(n=[{include:t.include}]),new au(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,qe._compilePatterns(n,a,r))}return t.while?new Vr(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,qe._compileCaptures(t.beginCaptures||t.captures,a,r),t.while,qe._compileCaptures(t.whileCaptures||t.captures,a,r),qe._compilePatterns(t.patterns,a,r)):new An(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,qe._compileCaptures(t.beginCaptures||t.captures,a,r),t.end,qe._compileCaptures(t.endCaptures||t.captures,a,r),t.applyEndPatternLast,qe._compilePatterns(t.patterns,a,r))}),t.id}static _compileCaptures(t,a,r){let o=[];if(t){let n=0;for(let s in t){if(s==="$vscodeTextmateLocation")continue;let i=parseInt(s,10);i>n&&(n=i)}for(let s=0;s<=n;s++)o[s]=null;for(let s in t){if(s==="$vscodeTextmateLocation")continue;let i=parseInt(s,10),l=0;t[s].patterns&&(l=qe.getCompiledRuleId(t[s],a,r)),o[i]=qe.createCaptureRule(a,t[s].$vscodeTextmateLocation,t[s].name,t[s].contentName,l)}}return o}static _compilePatterns(t,a,r){let o=[];if(t)for(let n=0,s=t.length;n<s;n++){let i=t[n],l=-1;if(i.include){let u=gu(i.include);switch(u.kind){case 0:case 1:l=qe.getCompiledRuleId(r[i.include],a,r);break;case 2:let d=r[u.ruleName];d&&(l=qe.getCompiledRuleId(d,a,r));break;case 3:case 4:let c=u.scopeName,p=u.kind===4?u.ruleName:null,f=a.getExternalGrammar(c,r);if(f)if(p){let m=f.repository[p];m&&(l=qe.getCompiledRuleId(m,a,f.repository))}else l=qe.getCompiledRuleId(f.repository.$self,a,f.repository);break}}else l=qe.getCompiledRuleId(i,a,r);if(l!==-1){let u=a.getRule(l),d=!1;if((u instanceof au||u instanceof An||u instanceof Vr)&&u.hasMissingPatterns&&u.patterns.length===0&&(d=!0),d)continue;o.push(l)}}return{patterns:o,hasMissingPatterns:(t?t.length:0)!==o.length}}},Ga=class xu{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(t,a){if(t&&typeof t=="string"){let r=t.length,o=0,n=[],s=!1;for(let i=0;i<r;i++)if(t.charAt(i)==="\\"&&i+1<r){let u=t.charAt(i+1);u==="z"?(n.push(t.substring(o,i)),n.push("$(?!\\n)(?<!\\n)"),o=i+2):(u==="A"||u==="G")&&(s=!0),i++}this.hasAnchor=s,o===0?this.source=t:(n.push(t.substring(o,r)),this.source=n.join(""))}else this.hasAnchor=!1,this.source=t;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=a,typeof this.source=="string"?this.hasBackReferences=ig.test(this.source):this.hasBackReferences=!1}clone(){return new xu(this.source,this.ruleId)}setSource(t){this.source!==t&&(this.source=t,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(t,a){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=a.map(o=>t.substring(o.start,o.end));return tu.lastIndex=0,this.source.replace(tu,(o,n)=>cu(r[parseInt(n,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],a=[],r=[],o=[],n,s,i,l;for(n=0,s=this.source.length;n<s;n++)i=this.source.charAt(n),t[n]=i,a[n]=i,r[n]=i,o[n]=i,i==="\\"&&n+1<s&&(l=this.source.charAt(n+1),l==="A"?(t[n+1]="\uFFFF",a[n+1]="\uFFFF",r[n+1]="A",o[n+1]="A"):l==="G"?(t[n+1]="\uFFFF",a[n+1]="G",r[n+1]="\uFFFF",o[n+1]="G"):(t[n+1]=l,a[n+1]=l,r[n+1]=l,o[n+1]=l),n++);return{A0_G0:t.join(""),A0_G1:a.join(""),A1_G0:r.join(""),A1_G1:o.join("")}}resolveAnchors(t,a){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:t?a?this._anchorCache.A1_G1:this._anchorCache.A1_G0:a?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Ka=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(a=>a.source);this._cached=new ru(e,t,this._items.map(a=>a.ruleId))}return this._cached}compileAG(e,t,a){return this._hasAnchors?t?a?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G0):a?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,a){let r=this._items.map(o=>o.resolveAnchors(t,a));return new ru(e,r,this._items.map(o=>o.ruleId))}},ru=class{constructor(e,t,a){this.regExps=t,this.rules=a,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,a=this.rules.length;t<a;t++)e.push(" - "+this.rules[t]+": "+this.regExps[t]);return e.join(`
|
|
5
|
-
`)}findNextMatchSync(e,t,a){let r=this.scanner.findNextMatchSync(e,t,a);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},bn=class{constructor(e,t){this.languageId=e,this.tokenType=t}},
|
|
6
|
-
`;let n=this.createOnigString(e),s=n.content.length,i=new Cg(a,e,this._tokenTypeMatchers,this.balancedBracketSelectors),l=Lu(this,n,o,0,t,i,!0,r);return hu(n),{lineLength:s,lineTokens:i,ruleStack:l.stack,stoppedEarly:l.stoppedEarly}}};function su(e,t){return e=qh(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var ja=class dt{constructor(t,a,r){this.parent=t,this.scopePath=a,this.tokenAttributes=r}static fromExtension(t,a){let r=t,o=t?.scopePath??null;for(let n of a)o=Cn.push(o,n.scopeNames),r=new dt(r,o,n.encodedTokenAttributes);return r}static createRoot(t,a){return new dt(null,new Cn(null,t),a)}static createRootAndLookUpScopeName(t,a,r){let o=r.getMetadataForScope(t),n=new Cn(null,t),s=r.themeProvider.themeMatch(n),i=dt.mergeAttributes(a,o,s);return new dt(null,n,i)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return dt.equals(this,t)}static equals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.scopeName!==a.scopeName||t.tokenAttributes!==a.tokenAttributes)return!1;t=t.parent,a=a.parent}while(!0)}static mergeAttributes(t,a,r){let o=-1,n=0,s=0;return r!==null&&(o=r.fontStyle,n=r.foregroundId,s=r.backgroundId),Vt.set(t,a.languageId,a.tokenType,null,o,n,s)}pushAttributed(t,a){if(t===null)return this;if(t.indexOf(" ")===-1)return dt._pushAttributed(this,t,a);let r=t.split(/ /g),o=this;for(let n of r)o=dt._pushAttributed(o,n,a);return o}static _pushAttributed(t,a,r){let o=r.getMetadataForScope(a),n=t.scopePath.push(a),s=r.themeProvider.themeMatch(n),i=dt.mergeAttributes(t.tokenAttributes,o,s);return new dt(t,n,i)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?a.reverse():void 0}},Rn=class zt{constructor(t,a,r,o,n,s,i,l){this.parent=t,this.ruleId=a,this.beginRuleCapturedEOL=n,this.endRule=s,this.nameScopesList=i,this.contentNameScopesList=l,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=o}_stackElementBrand=void 0;static NULL=new zt(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:zt._equals(this,t)}static _equals(t,a){return t===a?!0:this._structuralEquals(t,a)?ja.equals(t.contentNameScopesList,a.contentNameScopesList):!1}static _structuralEquals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.depth!==a.depth||t.ruleId!==a.ruleId||t.endRule!==a.endRule)return!1;t=t.parent,a=a.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){zt._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,a,r,o,n,s,i){return new zt(this,t,a,r,o,n,s,i)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,a){return this.parent&&(a=this.parent._writeString(t,a)),t[a++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,a}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new zt(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let a=this;for(;a&&a._enterPos===t._enterPos;){if(a.ruleId===t.ruleId)return!0;a=a.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,a){let r=ja.fromExtension(t?.nameScopesList??null,a.nameScopesList);return new zt(t,a.ruleId,a.enterPos??-1,a.anchorPos??-1,a.beginRuleCapturedEOL,a.endRule,r,ja.fromExtension(r,a.contentNameScopesList))}},Sg=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(a=>a==="*"?(this.allowAny=!0,[]):jr(a,Gr).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(a=>jr(a,Gr).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Cg=class{constructor(e,t,a,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=a,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,o=!1;if(this.balancedBracketSelectors?.matchesAlways&&(o=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let n=e?.getScopeNames()??[];for(let s of this._tokenTypeOverrides)s.matcher(n)&&(r=Vt.set(r,0,s.type,null,-1,0,0));this.balancedBracketSelectors&&(o=this.balancedBracketSelectors.match(n))}if(o&&(r=Vt.set(r,0,8,o,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let a=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:a}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let a=new Uint32Array(this._binaryTokens.length);for(let r=0,o=this._binaryTokens.length;r<o;r++)a[r]=this._binaryTokens[r];return a}},bg=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,a,r,o){if(!this._grammars.has(e)){let n=this._rawGrammars.get(e);if(!n)return null;this._grammars.set(e,xg(e,n,t,a,r,o,this,this._onigLib))}return this._grammars.get(e)}},bu=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new bg(za.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(za.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,a){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:a})}loadGrammarWithConfiguration(e,t,a){return this._loadGrammar(e,t,a.embeddedLanguages,a.tokenTypes,new Sg(a.balancedBracketSelectors||[],a.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,a,r,o){let n=new eg(this._syncRegistry,e);for(;n.Q.length>0;)n.Q.map(s=>this._loadSingleGrammar(s.scopeName)),n.processQueue();return this._grammarForScopeName(e,t,a,r,o)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let a=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,a)}}addGrammar(e,t=[],a=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,a,r)}_grammarForScopeName(e,t=0,a=null,r=null,o=null){return this._syncRegistry.grammarForScopeName(e,t,a,r,o)}},Kr=Rn.NULL;var vg=/["&'<>`]/g,kg=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Tg=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,Ag=/[|\\{}()[\]^$+*?.]/g,vu=new WeakMap;function ku(e,t){if(e=e.replace(t.subset?Pg(t.subset):vg,r),t.subset||t.escapeOnly)return e;return e.replace(kg,a).replace(Tg,r);function a(o,n,s){return t.format((o.charCodeAt(0)-55296)*1024+o.charCodeAt(1)-56320+65536,s.charCodeAt(n+2),t)}function r(o,n,s){return t.format(o.charCodeAt(0),s.charCodeAt(n+1),t)}}function Pg(e){let t=vu.get(e);return t||(t=Rg(e),vu.set(e,t)),t}function Rg(e){let t=[],a=-1;for(;++a<e.length;)t.push(e[a].replace(Ag,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}var Eg=/[\dA-Fa-f]/;function Tu(e,t,a){let r="&#x"+e.toString(16).toUpperCase();return a&&t&&!Eg.test(String.fromCharCode(t))?r:r+";"}var Mg=/\d/;function Au(e,t,a){let r="&#"+String(e);return a&&t&&!Mg.test(String.fromCharCode(t))?r:r+";"}var Pu=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var Xr={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var Ru=["cent","copy","divide","gt","lt","not","para","times"];var Eu={}.hasOwnProperty,Mn={},Jr;for(Jr in Xr)Eu.call(Xr,Jr)&&(Mn[Xr[Jr]]=Jr);var Fg=/[^\dA-Za-z]/;function Mu(e,t,a,r){let o=String.fromCharCode(e);if(Eu.call(Mn,o)){let n=Mn[o],s="&"+n;return a&&Pu.includes(n)&&!Ru.includes(n)&&(!r||t&&t!==61&&Fg.test(String.fromCharCode(t)))?s:s+";"}return""}function Fu(e,t,a){let r=Tu(e,t,a.omitOptionalSemicolons),o;if((a.useNamedReferences||a.useShortestReferences)&&(o=Mu(e,t,a.omitOptionalSemicolons,a.attribute)),(a.useShortestReferences||!o)&&a.useShortestReferences){let n=Au(e,t,a.omitOptionalSemicolons);n.length<r.length&&(r=n)}return o&&(!a.useShortestReferences||o.length<r.length)?o:r}function wt(e,t){return ku(e,Object.assign({format:Fu},t))}var _g=/^>|^->|<!--|-->|--!>|<!-$/g,Dg=[">"],Bg=["<",">"];function _u(e,t,a,r){return r.settings.bogusComments?"<?"+wt(e.value,Object.assign({},r.settings.characterReferences,{subset:Dg}))+">":"<!--"+e.value.replace(_g,o)+"-->";function o(n){return wt(n,Object.assign({},r.settings.characterReferences,{subset:Bg}))}}function Du(e,t,a,r){return"<!"+(r.settings.upperDoctype?"DOCTYPE":"doctype")+(r.settings.tightDoctype?"":" ")+"html>"}var Pe=Bu(1),Fn=Bu(-1),Og=[];function Bu(e){return t;function t(a,r,o){let n=a?a.children:Og,s=(r||0)+e,i=n[s];if(!o)for(;i&&aa(i);)s+=e,i=n[s];return i}}var Ug={}.hasOwnProperty;function Qr(e){return t;function t(a,r,o){return Ug.call(e,a.tagName)&&e[a.tagName](a,r,o)}}var Ja=Qr({body:qg,caption:_n,colgroup:_n,dd:jg,dt:Wg,head:_n,html:Ng,li:$g,optgroup:zg,option:Vg,p:Hg,rp:Ou,rt:Ou,tbody:Kg,td:Uu,tfoot:Xg,th:Uu,thead:Gg,tr:Jg});function _n(e,t,a){let r=Pe(a,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&aa(r.value.charAt(0)))}function Ng(e,t,a){let r=Pe(a,t);return!r||r.type!=="comment"}function qg(e,t,a){let r=Pe(a,t);return!r||r.type!=="comment"}function Hg(e,t,a){let r=Pe(a,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!a||!(a.type==="element"&&(a.tagName==="a"||a.tagName==="audio"||a.tagName==="del"||a.tagName==="ins"||a.tagName==="map"||a.tagName==="noscript"||a.tagName==="video"))}function $g(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="li"}function Wg(e,t,a){let r=Pe(a,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function jg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function Ou(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function zg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function Vg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function Gg(e,t,a){let r=Pe(a,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Kg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Xg(e,t,a){return!Pe(a,t)}function Jg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="tr"}function Uu(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var Nu=Qr({body:Zg,colgroup:ew,head:Yg,html:Qg,tbody:tw});function Qg(e){let t=Pe(e,-1);return!t||t.type!=="comment"}function Yg(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let a=e.children[0];return!a||a.type==="element"}function Zg(e){let t=Pe(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&aa(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function ew(e,t,a){let r=Fn(a,t),o=Pe(e,-1,!0);return a&&r&&r.type==="element"&&r.tagName==="colgroup"&&Ja(r,a.children.indexOf(r),a)?!1:!!(o&&o.type==="element"&&o.tagName==="col")}function tw(e,t,a){let r=Fn(a,t),o=Pe(e,-1);return a&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&Ja(r,a.children.indexOf(r),a)?!1:!!(o&&o.type==="element"&&o.tagName==="tr")}var Yr={name:[[`
|
|
4
|
+
${ue}`}]}}O.current({...le,...ee?{modelContext:ee}:{}})}fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="ui/update-model-context"&&ie!=null){ne=yi(ne,se.params),fe({jsonrpc:"2.0",id:ie,result:{}});return}if(xe==="tools/call"&&ie!=null){let le=re.current;if(!le){fe({jsonrpc:"2.0",id:ie,error:{code:-32601,message:"tools/call not supported"}});return}let ee=se.params?.name;le({name:ee,arguments:se.params?.arguments??{}}).then(ue=>{fe({jsonrpc:"2.0",id:ie,result:ue});let Y=ue.content?.map(he=>he.text??"").join("").trim();Y&&Nm(ee,ue,X.current)&&(me&&clearTimeout(me.timer),me={text:Y,timer:setTimeout(()=>{if(H)return;let he=ne;ne=null,me=null,O.current?.({role:"user",content:[{type:"text",text:Y}],...he?{modelContext:he}:{}})},500)})}).catch(ue=>{let Y=ue instanceof Error?ue.message:"Tool call failed";fe({jsonrpc:"2.0",id:ie,error:{code:-32e3,message:Y}})});return}if(xe==="ui/request-display-mode"&&ie!=null){let le=se.params?.mode,ee=le==="fullscreen"||le==="inline"||le==="pip"?le:"inline";v.current=ee,fe({jsonrpc:"2.0",id:ie,result:{mode:ee}}),fe({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:ee}}),K.current?.(ee);return}if(xe==="ui/resource-teardown"&&ie!=null){fe({jsonrpc:"2.0",id:ie,result:{}});return}xe==="ping"&&ie!=null&&fe({jsonrpc:"2.0",id:ie,result:{}})};return window.addEventListener("message",Z),()=>{H=!0,clearTimeout(Ie),me&&clearTimeout(me.timer),window.removeEventListener("message",Z)}},[i,R]),qm("iframe",{ref:m,src:b,onLoad:()=>ae.current?.mark("iframeLoad"),sandbox:"allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox",className:P(!p&&"ww:rounded-md ww:border ww:border-border",s),style:{height:p?"100%":q,minWidth:p||!V?void 0:`min(${V}px, 100%)`,width:"100%",border:"none",colorScheme:n?"dark":"auto"},title:"MCP App"})}import{useCallback as Hm,useEffect as un,useState as $m}from"react";import{jsx as dn,jsxs as jm}from"react/jsx-runtime";var rl=672,ol=32;function Wm({widget:e,onCallTool:t,toolsEndpoint:a,headers:r,resourceEndpoint:o,onClose:n,isDark:s=!1}){let[i,l]=$m(null);un(()=>{let f=()=>l({width:window.innerWidth,height:window.innerHeight});return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]);let u=e?.preview===!0;un(()=>{if(!e||!u)return;let f=m=>{m.key==="Escape"&&n()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,u,n]),un(()=>{if(!e)return;let f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=f}},[e]);let d=Hm(async f=>{if(t)return t(f);if(!a)throw new Error("webmcp overlay needs onCallTool");let m=await fetch(a,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify({action:"call",...f})});if(!m.ok)throw new Error(`webmcp tool call failed: ${m.status}`);return await m.json()},[t,a,r]);if(!e)return null;let c=i?Math.min(rl,i.width-ol):rl,p=i?i.height-ol:void 0;return jm("div",{role:"dialog","aria-modal":"true","aria-label":"Waniwani",className:P("ww:fixed ww:inset-0 ww:z-[2147483000] ww:flex ww:items-center ww:justify-center ww:bg-black/45 ww:backdrop-blur-md",s&&"dark"),children:[u&&dn("button",{type:"button","aria-label":"Close",onClick:n,className:"ww:absolute ww:inset-0 ww:h-full ww:w-full ww:cursor-pointer ww:border-none ww:bg-transparent ww:p-0"}),dn("div",{className:"ww:relative ww:overflow-auto ww:rounded-2xl ww:bg-background ww:shadow-2xl",style:{width:c,maxHeight:p},children:dn(Ba,{resourceUri:e.viewUri,resourceEndpoint:o,toolInput:e.data,toolResult:e.result,autoHeight:Ma(e.result._meta),isDark:s,onCallTool:d,onOpenLink:f=>window.open(f,"_blank","noopener")},`${o}|${e.viewUri}`)})]})}import{forwardRef as rc,useCallback as rr,useEffect as It,useImperativeHandle as Ex,useRef as Dt,useState as vo}from"react";var Oa=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,a)=>(a&=63,a<36?t+=a.toString(36):a<62?t+=(a-26).toString(36).toUpperCase():a>62?t+="-":t+="_",t),"");import{createContext as Xm,useCallback as je,useContext as Jm,useEffect as Ua,useMemo as Qm,useRef as Tt,useState as pn}from"react";var Wt=new Map;function nl(e,t){if(Wt.has(e)){URL.revokeObjectURL(t);return}for(Wt.set(e,t);Wt.size>20;){let a=Wt.keys().next();if(a.done)return;let r=Wt.get(a.value);Wt.delete(a.value),r&&URL.revokeObjectURL(r)}}function sl(e){return Wt.get(e)}import{useState as zm}from"react";import{jsx as De,jsxs as cn}from"react/jsx-runtime";var il=({files:e,className:t,...a})=>e.length===0?null:De("div",{className:P("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((r,o)=>De(Vm,{file:r},o))});function Vm({file:e}){let{t}=te();return e.mediaType?.startsWith("image/")&&e.url?De("img",{src:e.url,alt:e.filename??t.attachments.attachmentFallback,className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):cn("span",{className:"ww:inline-flex ww:items-center ww:gap-1.5 ww:rounded ww:bg-background/20 ww:px-2 ww:py-1 ww:text-xs",children:[De(oa,{className:"ww:size-3 ww:shrink-0"}),De("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??t.attachments.fileFallback})]})}function ll(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function Gm({mediaType:e}){return e.startsWith("image/")?De(Aa,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?De(ka,{className:"ww:size-5 ww:text-muted-foreground"}):De(oa,{className:"ww:size-5 ww:text-muted-foreground"})}function fn({filename:e,mediaType:t,previewUrl:a,subtitle:r,tone:o="default",children:n,className:s}){let{t:i}=te(),l=ll(t,i);return cn("li",{"aria-label":`${e}, ${l}`,className:P("ww:relative ww:flex ww:w-60 ww:max-w-full ww:cursor-default ww:items-center ww:gap-2.5 ww:overflow-hidden ww:rounded-xl ww:border ww:bg-background ww:p-2.5",o==="error"?"ww:border-destructive/50":"ww:border-border",s),children:[De("span",{className:"ww:flex ww:size-10 ww:shrink-0 ww:items-center ww:justify-center ww:overflow-hidden ww:rounded-xl ww:bg-muted",children:a?De("img",{alt:"",className:"ww:size-full ww:object-cover ww:object-center",src:a}):De(Gm,{mediaType:t})}),cn("span",{className:"ww:flex ww:min-w-0 ww:flex-col",children:[De("span",{className:"ww:truncate ww:font-medium ww:text-sm",title:e,children:e}),De("span",{className:P("ww:truncate ww:text-xs",o==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:r??l})]}),n]})}function ul(e){if(typeof e!="object"||e===null)return[];let t=e.documents;return Array.isArray(t)?t.filter(a=>typeof a=="object"&&a!==null&&typeof a.documentId=="string"&&typeof a.filename=="string"&&typeof a.mediaType=="string"):[]}var dl=({documents:e,className:t,...a})=>e.length===0?null:De("ul",{className:P("ww:flex ww:list-none ww:flex-wrap ww:items-end ww:justify-end ww:gap-2 ww:p-0",t),...a,children:e.map((r,o)=>De(Km,{document:r},`${r.documentId}-${o}`))});function Km({document:e}){let{t}=te(),[a,r]=zm(!1),o=e.mediaType.startsWith("image/")?sl(e.documentId):void 0;return o&&!a?De("li",{children:De("img",{alt:`${e.filename}, ${ll(e.mediaType,t)}`,className:"ww:max-h-80 ww:max-w-72 ww:rounded-xl ww:border ww:border-border ww:object-contain",onError:()=>r(!0),src:o,title:e.filename})}):De(fn,{filename:e.filename,mediaType:e.mediaType})}import{jsx as Ee,jsxs as _r}from"react/jsx-runtime";var Ym=async e=>{try{let a=await(await fetch(e)).blob();return new Promise(r=>{let o=new FileReader;o.onloadend=()=>r(o.result),o.onerror=()=>r(null),o.readAsDataURL(a)})}catch{return null}},Zm=(e,t)=>{if(!t)return!0;let a=t.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean);if(a.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return a.some(n=>n.startsWith(".")?o.endsWith(n):n.endsWith("/*")?r.startsWith(n.slice(0,-1)):r===n)},fl=Xm(null),Fr=()=>{let e=Jm(fl);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},pl=({className:e,accept:t,multiple:a,globalDrop:r,maxFiles:o,maxFileSize:n,maxPdfPages:s,attachmentsEnabled:i=!0,upload:l,onDiscard:u,onError:d,onSubmit:c,children:p,...f})=>{let{t:m,locale:y}=te(),S=Tt(null),L=Tt(null),[C,I]=pn([]),x=Tt(C),v=Tt(new Map),q=Tt(l),N=Tt(d),V=Tt(u);Ua(()=>{q.current=l,N.current=d,V.current=u},[l,d,u]);let G=je(k=>{x.current=k,I(k)},[]),Q=je(()=>{S.current?.click()},[]),O=je((k,H)=>{G(x.current.map($=>$.id===k?{...$,...H}:$))},[G]),re=je((k,H)=>{let $=q.current;if(!$)return;let ne=new AbortController,me=$(H,ne.signal,Ie=>{O(k,{progress:Ie})}).then(Ie=>(O(k,{status:"ready",progress:1,documentId:Ie.documentId,error:void 0}),Ie)).catch(Ie=>{if(ne.signal.aborted)return null;let fe=Ie instanceof Error?Ie.message:m.promptInput.uploadFailed;return O(k,{status:"failed",error:fe}),N.current?.({code:"upload_failed",message:fe}),null});v.current.set(k,{file:H,controller:ne,done:me})},[O,m]),K=je(k=>{let H=[...k];if(!i||H.length===0)return;let $=(W,se)=>N.current?.({code:W,message:se}),ne=[];for(let W of H){if(!Zm(W,t)){$("accept",m.promptInput.errorAccept.replace("{name}",W.name));continue}if(n&&W.size>n){$("max_file_size",m.promptInput.errorTooLarge.replace("{name}",W.name).replace("{limit}",ml(n,y)));continue}ne.push(W)}if(ne.length===0)return;let me=typeof o=="number"?Math.max(0,o-x.current.length):void 0,Ie=typeof me=="number"?ne.slice(0,me):ne;if(Ie.length<ne.length&&$("max_files",m.promptInput.errorTooMany.replace("{limit}",String(o))),Ie.length===0)return;let fe=!!q.current,Z=Ie.map(W=>({file:W,item:{filename:W.name,id:Oa(),mediaType:W.type,type:"file",url:URL.createObjectURL(W),status:fe?"uploading":"ready",progress:0}}));G([...x.current,...Z.map(W=>W.item)]);for(let W of Z)re(W.item.id,W.file)},[o,n,t,i,re,G,m,y]),J=je(k=>{let H=v.current.get(k);H&&(O(k,{status:"uploading",progress:0,error:void 0}),re(k,H.file))},[O,re]),X=je((k,H)=>{v.current.get(k.id)?.controller.abort(),v.current.delete(k.id),k.url&&(!H&&!!k.documentId&&!!k.mediaType?.startsWith("image/")&&k.documentId?nl(k.documentId,k.url):URL.revokeObjectURL(k.url)),H&&k.documentId&&V.current?.({documentId:k.documentId,filename:k.filename??"",mediaType:k.mediaType??""})},[]),R=je(k=>{let H=x.current.find($=>$.id===k);H&&X(H,!0),G(x.current.filter($=>$.id!==k))},[X,G]),b=je(()=>{for(let k of x.current)X(k,!0);G([])},[X,G]),D=Tt(i);Ua(()=>{let k=D.current;D.current=i,k&&!i&&b()},[i,b]);let ae=je(()=>{for(let k of x.current)X(k,!1);G([])},[X,G]);Ua(()=>()=>{for(let k of x.current)v.current.get(k.id)?.controller.abort(),k.url&&URL.revokeObjectURL(k.url)},[]);let oe=je(k=>{k.currentTarget.files&&K(k.currentTarget.files),k.currentTarget.value=""},[K]);Ua(()=>{if(!r)return;let k=$=>{$.dataTransfer?.types?.includes("Files")&&$.preventDefault()},H=$=>{$.dataTransfer?.types?.includes("Files")&&$.preventDefault(),$.dataTransfer?.files&&$.dataTransfer.files.length>0&&K($.dataTransfer.files)};return document.addEventListener("dragover",k),document.addEventListener("drop",H),()=>{document.removeEventListener("dragover",k),document.removeEventListener("drop",H)}},[K,r]);let Re=je(async k=>{k.preventDefault();let H=k.currentTarget,$=new FormData(H).get("message")||"",ne=new Map;for(;ne.size<v.current.size;)await Promise.all([...v.current.entries()].filter(([Z])=>!ne.has(Z)).map(async([Z,W])=>{ne.set(Z,await W.done)}));for(let Z of ne.keys())v.current.has(Z)||ne.delete(Z);if([...ne.values()].some(Z=>Z===null)){N.current?.({code:"upload_failed",message:m.promptInput.uploadFailed});return}let me=[...ne.values()].filter(Z=>Z!==null),Ie=q.current?[]:x.current,fe=await Promise.all(Ie.map(async({id:Z,status:W,progress:se,error:xe,...ie})=>{if(ie.url?.startsWith("blob:")){let le=await Ym(ie.url);return{...ie,url:le??ie.url}}return ie}));try{let Z=c({documents:me,files:fe,text:$},k);Z instanceof Promise&&await Z,H.reset(),ae()}catch{}},[c,ae,m]),Ne=Qm(()=>({add:K,clear:b,files:C,openFileDialog:Q,remove:R,retry:J,maxFileSize:n,maxPdfPages:s}),[C,K,R,J,b,Q,n,s]);return _r(fl.Provider,{value:Ne,children:[Ee("input",{accept:t,"aria-label":m.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:oe,ref:S,title:m.promptInput.uploadFiles,type:"file"}),Ee("form",{className:P("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:Re,ref:L,...f,children:p})]})},cl=1024*1024;function ml(e,t){let a=e>=cl;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/cl:Math.max(1,e/1024))}var hl=({onChange:e,onKeyDown:t,className:a,placeholder:r,...o})=>{let{t:n}=te(),s=Fr(),[i,l]=pn(!1),u=r??n.promptInput.placeholder,d=je(p=>{if(t?.(p),!p.defaultPrevented){if(p.key==="Enter"){if(i||p.nativeEvent.isComposing||p.shiftKey)return;p.preventDefault();let{form:f}=p.currentTarget;if(f?.querySelector('[data-submit-blocked="true"]')||f?.querySelector('button[type="submit"]')?.disabled)return;f?.requestSubmit()}if(p.key==="Backspace"&&p.currentTarget.value===""&&s.files.length>0){p.preventDefault();let f=s.files.at(-1);f&&s.remove(f.id)}}},[t,i,s]),c=je(p=>{let f=p.clipboardData?.items;if(!f)return;let m=[];for(let y of f)if(y.kind==="file"){let S=y.getAsFile();S&&m.push(S)}m.length>0&&(p.preventDefault(),s.add(m))},[s]);return Ee("textarea",{className:P("ww:field-sizing-content ww:max-h-48 ww:min-h-0 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-2 ww:text-base ww:sm:text-sm ww:outline-none ww:placeholder:text-muted-foreground",a),name:"message",onCompositionEnd:()=>l(!1),onCompositionStart:()=>l(!0),onKeyDown:d,onPaste:c,placeholder:u,onChange:e,...o})},gl=({className:e,status:t,onStop:a,onClick:r,children:o,disabled:n,...s})=>{let{t:i}=te(),l=t==="submitted"||t==="streaming",u=l&&a!==void 0,d=Ee(Sa,{className:"ww:size-4"});t==="submitted"?d=Ee(Pa,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(d=Ee(Ra,{className:"ww:size-4"}));let c=je(p=>{if(l&&a){p.preventDefault(),a();return}r?.(p)},[l,a,r]);return Ee(it,{"aria-label":l?i.promptInput.stop:i.promptInput.submit,className:P("ww:bg-foreground ww:text-background ww:hover:bg-foreground ww:rounded-full",e),"data-submit-blocked":n?"true":void 0,disabled:u?!1:n,onClick:c,size:"icon-sm",type:u?"button":"submit",variant:"ghost",...s,children:o??d})},wl=({className:e,children:t,...a})=>{let{t:r,locale:o}=te(),n=Fr();if(n.files.length>0)return _r(it,{className:P("ww:group ww:relative",e),onClick:()=>n.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":r.promptInput.removeAttachments,...a,children:[Ee("span",{className:"ww:flex ww:size-5 ww:items-center ww:justify-center ww:rounded-full ww:bg-primary ww:text-[10px] ww:font-medium ww:text-primary-foreground ww:transition-opacity ww:group-hover:opacity-0",children:n.files.length}),Ee(kt,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let i=n.maxFileSize?(n.maxPdfPages?r.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(n.maxPdfPages)):r.promptInput.uploadFilesUpTo).replace("{limit}",ml(n.maxFileSize,o)):r.promptInput.uploadFiles;return Ee(it,{"aria-label":i,className:P(e),title:i,onClick:()=>n.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??Ee(na,{className:"ww:size-4"})})},Il=({className:e,...t})=>{let a=Fr();return a.files.length===0?null:Ee("ul",{className:P("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(r=>Ee(eh,{file:r},r.id))})};function eh({file:e}){let{t}=te(),a=Fr(),r=e.status==="failed",o=e.status==="uploading";return _r(fn,{filename:e.filename??t.attachments.fileFallback,mediaType:e.mediaType??"",previewUrl:e.mediaType?.startsWith("image/")?e.url:void 0,subtitle:r?e.error:o?t.promptInput.uploading:void 0,tone:r?"error":"default",children:[r?Ee("button",{"aria-label":t.promptInput.retryUpload,className:"ww:ml-auto ww:shrink-0 ww:text-destructive ww:text-xs ww:underline ww:underline-offset-2",onClick:()=>a.retry(e.id),type:"button",children:t.promptInput.retry}):null,Ee("button",{"aria-label":t.promptInput.removeAttachment,className:P("ww:shrink-0 ww:rounded-full ww:p-1 ww:opacity-60 ww:transition-opacity hover:ww:bg-muted hover:ww:opacity-100",r?null:"ww:ml-auto"),onClick:()=>a.remove(e.id),type:"button",children:Ee(kt,{className:"ww:size-3.5"})}),o?Ee("span",{"aria-hidden":!0,className:"ww:absolute ww:bottom-0 ww:left-0 ww:h-0.5 ww:bg-primary ww:transition-[width] ww:duration-200",style:{width:`${Math.round(e.progress*100)}%`}}):null]})}var xl=({enabled:e=!0})=>{let{t}=te(),[a,r]=pn(!1);return Ua(()=>{if(!e)return;let o=0,n=u=>!!u.dataTransfer?.types?.includes("Files"),s=u=>{n(u)&&(o+=1,r(!0))},i=u=>{n(u)&&(o=Math.max(0,o-1),o===0&&r(!1))},l=()=>{o=0,r(!1)};return document.addEventListener("dragenter",s),document.addEventListener("dragleave",i),document.addEventListener("drop",l),()=>{document.removeEventListener("dragenter",s),document.removeEventListener("dragleave",i),document.removeEventListener("drop",l)}},[e]),e&&a?Ee("div",{className:"ww:pointer-events-none ww:absolute ww:inset-0 ww:z-50 ww:flex ww:items-center ww:justify-center ww:rounded-2xl ww:border-2 ww:border-primary ww:border-dashed ww:bg-background/85",children:_r("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[Ee(na,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};import{jsx as th}from"react/jsx-runtime";function yl({text:e}){let{t}=te();return e===!1?null:th("span",{className:"ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70",children:e||t.aiDisclaimer.default})}import{memo as ah,useCallback as rh}from"react";import{jsx as la}from"react/jsx-runtime";var Ll=({className:e,...t})=>la("div",{className:P("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),Sl=({className:e,...t})=>la("li",{className:P("ww:group ww:flex ww:items-center ww:gap-2 ww:rounded-md ww:px-2 ww:py-1 ww:text-sm ww:transition-colors ww:hover:bg-muted",e),...t}),Cl=({className:e,...t})=>la("span",{className:P("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),bl=({className:e,...t})=>la("span",{className:P("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),vl=({className:e,...t})=>la("div",{className:P("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),kl=({className:e,...t})=>la(it,{className:P("ww:size-auto ww:rounded ww:p-1 ww:text-muted-foreground ww:hover:bg-muted-foreground/10 ww:hover:text-foreground",e),size:"icon",type:"button",variant:"ghost",...t});import{jsx as At,jsxs as Pl}from"react/jsx-runtime";var Tl=ah(({message:e,onRemove:t})=>{let{t:a}=te(),r=rh(()=>t(e.id),[t,e.id]);return Pl(Sl,{children:[At(Cl,{}),At(bl,{children:e.text||a.chatQueue.attachmentFallback}),At(vl,{children:At(kl,{"aria-label":a.chatQueue.removeFromQueue,onClick:r,children:At(kt,{className:"ww:size-3"})})})]})});Tl.displayName="ChatQueueItem";function Al({queuedMessages:e,onRemove:t,className:a}){let{t:r}=te();return e.length===0?null:Pl(Ll,{className:P("ww:border-t ww:border-border",a),children:[At("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:r.chatQueue.queued(e.length)}),At("ul",{children:e.map(o=>At(Tl,{message:o,onRemove:t},o.id))})]})}import{createContext as fh,useCallback as ph,useContext as mh,useEffect as hh,useMemo as gh,useState as wn}from"react";import{createContext as oh,memo as gn,useCallback as nh,useContext as sh,useEffect as mn,useMemo as ih,useRef as Rl,useState as hn}from"react";import{Fragment as dh,jsx as at,jsxs as ch}from"react/jsx-runtime";var El=oh(null);function Ml(){let e=sh(El);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var lh=1e3,uh=1e3,Na=gn(({className:e,isStreaming:t=!1,open:a,defaultOpen:r,onOpenChange:o,duration:n,children:s,...i})=>{let l=r??t,u=r===!1,d=a!==void 0,[c,p]=hn(l),f=d?a:c,m=nh(N=>{d||p(N),o?.(N)},[d,o]),[y,S]=hn(void 0),L=n??y,C=Rl(t),[I,x]=hn(!1),v=Rl(null);mn(()=>{t?(C.current=!0,v.current===null&&(v.current=Date.now())):v.current!==null&&(S(Math.ceil((Date.now()-v.current)/uh)),v.current=null)},[t]),mn(()=>{t&&!f&&!u&&m(!0)},[t,f,u,m]),mn(()=>{if(C.current&&!t&&f&&!I){let N=setTimeout(()=>{m(!1),x(!0)},lh);return()=>clearTimeout(N)}},[t,f,I,m]);let q=ih(()=>({isStreaming:t,isOpen:f,setIsOpen:m,duration:L}),[t,f,m,L]);return at(El.Provider,{value:q,children:at("div",{className:P("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":f?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...i,children:s})})});Na.displayName="Reasoning";var qa=gn(({className:e,children:t,getThinkingMessage:a,hideIcon:r=!1,onClick:o,...n})=>{let{t:s}=te(),{isStreaming:i,isOpen:l,duration:u,setIsOpen:d}=Ml(),p=a??((f,m)=>f||m===0?at(et,{duration:1.6,children:s.reasoning.thinking}):m===void 0?at("span",{children:s.reasoning.thoughtBrief}):at("span",{children:s.reasoning.thoughtForSeconds(m)}));return at("button",{type:"button","aria-expanded":l,onClick:f=>{d(!l),o?.(f)},className:P("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),...n,children:t??ch(dh,{children:[!r&&at(ht,{className:"ww:size-4 ww:shrink-0"}),p(i,u)]})})});qa.displayName="ReasoningTrigger";var Ha=gn(({className:e,children:t,...a})=>{let{isOpen:r}=Ml();return at("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:at("div",{className:"ww:min-h-0 ww:overflow-hidden",children:at("div",{className:P("ww:text-sm ww:text-muted-foreground",e),...a,children:at(ya,{children:t})})})})});Ha.displayName="ReasoningContent";import{jsx as Le,jsxs as Pt}from"react/jsx-runtime";var wh=500,Fl=fh(null);function _l(){let e=mh(Fl);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function Dl({className:e,isWorking:t=!1,activeStep:a,open:r,defaultOpen:o=!1,onOpenChange:n,children:s,...i}){let l=r!==void 0,[u,d]=wn(o),c=l?r:u,p=ph(S=>{l||d(S),n?.(S)},[l,n]),[f,m]=wn(!t);hh(()=>{if(t){m(!1);return}let S=setTimeout(()=>m(!0),wh);return()=>clearTimeout(S)},[t]);let y=gh(()=>({open:c,setOpen:p,isWorking:t,settled:f,activeStep:a}),[c,p,t,f,a]);return Le(Fl.Provider,{value:y,children:Le("div",{className:P("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":c?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...i,children:s})})}function Bl({className:e,label:t,workingLabel:a,children:r,...o}){let{open:n,setOpen:s,isWorking:i,settled:l,activeStep:u}=_l();if(!l){let d=u?.icon,c=u?.label??a??t??"";return Le("div",{className:P("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground",e),children:Pt("span",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-1.5",style:{animation:"ww-fade-in 0.25s ease-out"},children:[d&&Le(d,{className:P("ww:size-4 ww:shrink-0",i&&"ww:animate-pulse")}),Le("span",{className:"ww:truncate",children:i?Le(et,{duration:2.6,children:c}):c})]},c)})}return Pt("button",{type:"button",onClick:()=>s(!n),"aria-expanded":n,className:P("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),style:{animation:"ww-fade-in 0.25s ease-out"},...o,children:[Le("span",{className:"ww:truncate",children:r??t}),Le(vt,{className:P("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",n&&"ww:rotate-180")})]})}function Ol({className:e,children:t,...a}){let{open:r}=_l();return Le("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",r?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:Le("div",{className:"ww:min-h-0 ww:overflow-hidden",children:Le("div",{className:P("ww:flex ww:flex-col",e),...a,children:t})})})}function Ul({icon:e,isLast:t,running:a,error:r}){return Pt("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[Le("span",{className:"ww:flex ww:h-5 ww:items-center",children:Le(e,{className:P("ww:size-4 ww:shrink-0",r?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&Le("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function In({className:e,icon:t,title:a,state:r,isLast:o=!1,children:n,...s}){let i=r==="input-available"||r==="input-streaming",l=r==="output-error",u=n!=null,[d,c]=wn(!1),p=a??"",f=i?Le(et,{duration:1.6,children:p}):Le("span",{className:"ww:truncate",children:p});return Pt("div",{className:P("ww:flex ww:gap-2",e),...s,children:[Le(Ul,{icon:t,isLast:o,running:i,error:l}),Pt("div",{className:P("ww:min-w-0 ww:flex-1",!o&&"ww:pb-3"),children:[u?Pt("button",{type:"button",onClick:()=>c(m=>!m),"aria-expanded":d,className:"ww:flex ww:w-full ww:items-center ww:gap-1.5 ww:text-left ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",children:[f,Le(vt,{className:P("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",d&&"ww:rotate-180")})]}):Le("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:f}),u&&Le("div",{className:P("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",d?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:Le("div",{className:"ww:min-h-0 ww:overflow-hidden",children:Le("div",{className:"ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",children:n})})})]})]})}function Nl({isStreaming:e=!1,isLast:t=!1,children:a}){return Pt("div",{className:"ww:flex ww:gap-2",children:[Le(Ul,{icon:ht,isLast:t,running:e}),Le("div",{className:P("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:Pt(Na,{isStreaming:e,className:"ww:mb-0",children:[Le(qa,{hideIcon:!0}),Le(Ha,{children:a})]})})]})}var Oe={carriageReturn:-5,lineFeed:-4,carriageReturnLineFeed:-3,horizontalTab:-2,virtualSpace:-1,eof:null,nul:0,soh:1,stx:2,etx:3,eot:4,enq:5,ack:6,bel:7,bs:8,ht:9,lf:10,vt:11,ff:12,cr:13,so:14,si:15,dle:16,dc1:17,dc2:18,dc3:19,dc4:20,nak:21,syn:22,etb:23,can:24,em:25,sub:26,esc:27,fs:28,gs:29,rs:30,us:31,space:32,exclamationMark:33,quotationMark:34,numberSign:35,dollarSign:36,percentSign:37,ampersand:38,apostrophe:39,leftParenthesis:40,rightParenthesis:41,asterisk:42,plusSign:43,comma:44,dash:45,dot:46,slash:47,digit0:48,digit1:49,digit2:50,digit3:51,digit4:52,digit5:53,digit6:54,digit7:55,digit8:56,digit9:57,colon:58,semicolon:59,lessThan:60,equalsTo:61,greaterThan:62,questionMark:63,atSign:64,uppercaseA:65,uppercaseB:66,uppercaseC:67,uppercaseD:68,uppercaseE:69,uppercaseF:70,uppercaseG:71,uppercaseH:72,uppercaseI:73,uppercaseJ:74,uppercaseK:75,uppercaseL:76,uppercaseM:77,uppercaseN:78,uppercaseO:79,uppercaseP:80,uppercaseQ:81,uppercaseR:82,uppercaseS:83,uppercaseT:84,uppercaseU:85,uppercaseV:86,uppercaseW:87,uppercaseX:88,uppercaseY:89,uppercaseZ:90,leftSquareBracket:91,backslash:92,rightSquareBracket:93,caret:94,underscore:95,graveAccent:96,lowercaseA:97,lowercaseB:98,lowercaseC:99,lowercaseD:100,lowercaseE:101,lowercaseF:102,lowercaseG:103,lowercaseH:104,lowercaseI:105,lowercaseJ:106,lowercaseK:107,lowercaseL:108,lowercaseM:109,lowercaseN:110,lowercaseO:111,lowercaseP:112,lowercaseQ:113,lowercaseR:114,lowercaseS:115,lowercaseT:116,lowercaseU:117,lowercaseV:118,lowercaseW:119,lowercaseX:120,lowercaseY:121,lowercaseZ:122,leftCurlyBrace:123,verticalBar:124,rightCurlyBrace:125,tilde:126,del:127,byteOrderMarker:65279,replacementCharacter:65533};var ut={attentionSideAfter:2,attentionSideBefore:1,atxHeadingOpeningFenceSizeMax:6,autolinkDomainSizeMax:63,autolinkSchemeSizeMax:32,cdataOpeningString:"CDATA[",characterGroupPunctuation:2,characterGroupWhitespace:1,characterReferenceDecimalSizeMax:7,characterReferenceHexadecimalSizeMax:6,characterReferenceNamedSizeMax:31,codeFencedSequenceSizeMin:3,contentTypeContent:"content",contentTypeDocument:"document",contentTypeFlow:"flow",contentTypeString:"string",contentTypeText:"text",hardBreakPrefixSizeMin:2,htmlBasic:6,htmlCdata:5,htmlComment:2,htmlComplete:7,htmlDeclaration:4,htmlInstruction:3,htmlRawSizeMax:8,htmlRaw:1,linkResourceDestinationBalanceMax:32,linkReferenceSizeMax:999,listItemValueSizeMax:10,numericBaseDecimal:10,numericBaseHexadecimal:16,tabSize:4,thematicBreakMarkerCountMin:3,v8MaxSafeChunkSize:1e4};var Xe={data:"data",whitespace:"whitespace",lineEnding:"lineEnding",lineEndingBlank:"lineEndingBlank",linePrefix:"linePrefix",lineSuffix:"lineSuffix",atxHeading:"atxHeading",atxHeadingSequence:"atxHeadingSequence",atxHeadingText:"atxHeadingText",autolink:"autolink",autolinkEmail:"autolinkEmail",autolinkMarker:"autolinkMarker",autolinkProtocol:"autolinkProtocol",characterEscape:"characterEscape",characterEscapeValue:"characterEscapeValue",characterReference:"characterReference",characterReferenceMarker:"characterReferenceMarker",characterReferenceMarkerNumeric:"characterReferenceMarkerNumeric",characterReferenceMarkerHexadecimal:"characterReferenceMarkerHexadecimal",characterReferenceValue:"characterReferenceValue",codeFenced:"codeFenced",codeFencedFence:"codeFencedFence",codeFencedFenceSequence:"codeFencedFenceSequence",codeFencedFenceInfo:"codeFencedFenceInfo",codeFencedFenceMeta:"codeFencedFenceMeta",codeFlowValue:"codeFlowValue",codeIndented:"codeIndented",codeText:"codeText",codeTextData:"codeTextData",codeTextPadding:"codeTextPadding",codeTextSequence:"codeTextSequence",content:"content",definition:"definition",definitionDestination:"definitionDestination",definitionDestinationLiteral:"definitionDestinationLiteral",definitionDestinationLiteralMarker:"definitionDestinationLiteralMarker",definitionDestinationRaw:"definitionDestinationRaw",definitionDestinationString:"definitionDestinationString",definitionLabel:"definitionLabel",definitionLabelMarker:"definitionLabelMarker",definitionLabelString:"definitionLabelString",definitionMarker:"definitionMarker",definitionTitle:"definitionTitle",definitionTitleMarker:"definitionTitleMarker",definitionTitleString:"definitionTitleString",emphasis:"emphasis",emphasisSequence:"emphasisSequence",emphasisText:"emphasisText",escapeMarker:"escapeMarker",hardBreakEscape:"hardBreakEscape",hardBreakTrailing:"hardBreakTrailing",htmlFlow:"htmlFlow",htmlFlowData:"htmlFlowData",htmlText:"htmlText",htmlTextData:"htmlTextData",image:"image",label:"label",labelText:"labelText",labelLink:"labelLink",labelImage:"labelImage",labelMarker:"labelMarker",labelImageMarker:"labelImageMarker",labelEnd:"labelEnd",link:"link",paragraph:"paragraph",reference:"reference",referenceMarker:"referenceMarker",referenceString:"referenceString",resource:"resource",resourceDestination:"resourceDestination",resourceDestinationLiteral:"resourceDestinationLiteral",resourceDestinationLiteralMarker:"resourceDestinationLiteralMarker",resourceDestinationRaw:"resourceDestinationRaw",resourceDestinationString:"resourceDestinationString",resourceMarker:"resourceMarker",resourceTitle:"resourceTitle",resourceTitleMarker:"resourceTitleMarker",resourceTitleString:"resourceTitleString",setextHeading:"setextHeading",setextHeadingText:"setextHeadingText",setextHeadingLine:"setextHeadingLine",setextHeadingLineSequence:"setextHeadingLineSequence",strong:"strong",strongSequence:"strongSequence",strongText:"strongText",thematicBreak:"thematicBreak",thematicBreakSequence:"thematicBreakSequence",blockQuote:"blockQuote",blockQuotePrefix:"blockQuotePrefix",blockQuoteMarker:"blockQuoteMarker",blockQuotePrefixWhitespace:"blockQuotePrefixWhitespace",listOrdered:"listOrdered",listUnordered:"listUnordered",listItemIndent:"listItemIndent",listItemMarker:"listItemMarker",listItemPrefix:"listItemPrefix",listItemPrefixWhitespace:"listItemPrefixWhitespace",listItemValue:"listItemValue",chunkDocument:"chunkDocument",chunkContent:"chunkContent",chunkFlow:"chunkFlow",chunkText:"chunkText",chunkString:"chunkString"};function ql(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}function Hl(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}function $l(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e>=94192&&e<=94198||e>=94208&&e<=101589||e>=101631&&e<=101662||e>=101760&&e<=101874||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128728||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129674||e>=129678&&e<=129734||e===129736||e>=129741&&e<=129756||e>=129759&&e<=129770||e>=129775&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}function Wl(e){return ql(e)?"ambiguous":Hl(e)?"fullwidth":e===8361||e>=65377&&e<=65470||e>=65474&&e<=65479||e>=65482&&e<=65487||e>=65490&&e<=65495||e>=65498&&e<=65500||e>=65512&&e<=65518?"halfwidth":e>=32&&e<=126||e===162||e===163||e===165||e===166||e===172||e===175||e>=10214&&e<=10221||e===10629||e===10630?"narrow":$l(e)?"wide":"neutral"}function Ih(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}function jl(e){return Ih(e),Wl(e)}var xh=Object.defineProperty,yh=(e,t,a)=>t in e?xh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,Lh=(e,t,a)=>yh(e,typeof t!="symbol"?t+"":t,a);function Sh(e){return/^\p{Emoji_Presentation}/u.test(String.fromCodePoint(e))}function Ch(e){if(!e||e<4352)return!1;switch(jl(e)){case"fullwidth":case"halfwidth":return!0;case"wide":return!Sh(e);case"narrow":return!1;case"ambiguous":return 917760<=e&&e<=917999?null:!1;case"neutral":return/^\p{sc=Hangul}/u.test(String.fromCodePoint(e))}}function bh(e,t){return t!==65025||!e||e<8216?!1:e===8216||e===8217||e===8220||e===8221}function vh(e){return e!==null&&e>=65024&&e<=65038}var kh=zl(/\p{P}|\p{S}/u),Th=zl(/\s/);function zl(e){return t;function t(a){return a!==null&&a>-1&&e.test(String.fromCodePoint(a))}}var Je;(e=>{e.spaceOrPunctuation=3,e.cjk=4096,e.cjkPunctuation=4098,e.ivs=8192,e.cjkOrIvs=12288,e.nonEmojiGeneralUseVS=16384,e.variationSelector=24576,e.ivsToCjkRightShift=1})(Je||(Je={}));function Rt(e){if(e===Oe.eof||xi(e)||Th(e))return ut.characterGroupWhitespace;let t=0;if(e>=4352){if(vh(e))return Je.nonEmojiGeneralUseVS;switch(Ch(e)){case null:return Je.ivs;case!0:t|=Je.cjk;break}}return kh(e)&&(t|=ut.characterGroupPunctuation),t}function Dr(e,t,a){if(!Ph(e))return e;let r=t(),o=Rt(r);return!r||jt(o)?e:bh(r,a)?Je.cjkPunctuation:Ah(o)}function Ah(e){return e&~Je.ivs}function jt(e){return!!(e&ut.characterGroupWhitespace)}function ua(e){return(e&Je.cjkPunctuation)===ut.characterGroupPunctuation}function $a(e){return!!(e&Je.cjk)}function Vl(e){return e===Je.ivs}function Gl(e){return!!(e&Je.cjkOrIvs)}function Ph(e){return e===Je.nonEmojiGeneralUseVS}function xn(e){return!!(e&Je.spaceOrPunctuation)}function Br(e){return!!(e&&e>=55296&&e<=56319)}function Or(e){return!!(e&&e>=56320&&e<=57343)}function Ur(e,t,a){if(t._bufferIndex<2)return e;let o=a({start:{...t,_bufferIndex:t._bufferIndex-2},end:t}).codePointAt(0);return o&&o>=65536?o:e}function Rh(e,t,a){let r=e>=65536?2:1;if(t._bufferIndex<1+r)return null;let o=t._bufferIndex-r-2,n=a({start:{...t,_bufferIndex:o>=0?o:0},end:{...t,_bufferIndex:t._bufferIndex-r}}),s=n.charCodeAt(n.length-1);if(Number.isNaN(s))return null;if(n.length<2||s<56320||57343<s)return s;let i=n.codePointAt(0);return i&&i>=65536?i:s}var Nr=class{constructor(e,t,a){this.previousCode=e,this.nowPoint=t,this.sliceSerialize=a,Lh(this,"cachedValue")}value(){return this.cachedValue===void 0&&(this.cachedValue=Rh(this.previousCode,this.nowPoint,this.sliceSerialize)),this.cachedValue}};function qr(e,t,a){let r=a({start:t,end:{...t,_bufferIndex:t._bufferIndex+2}}).codePointAt(0);return r&&r>=65536?r:e}var yn={name:"attention",resolveAll:Eh,tokenize:Mh};function Eh(e,t){let a=-1,r,o,n,s,i,l,u,d;for(;++a<e.length;)if(e[a][0]==="enter"&&e[a][1].type==="attentionSequence"&&e[a][1]._close){for(r=a;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[a][1]).charCodeAt(0)){if((e[r][1]._close||e[a][1]._open)&&(e[a][1].end.offset-e[a][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[a][1].end.offset-e[a][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[a][1].end.offset-e[a][1].start.offset>1?2:1;let c={...e[r][1].end},p={...e[a][1].start};Kl(c,-l),Kl(p,l),s={type:l>1?Xe.strongSequence:Xe.emphasisSequence,start:c,end:{...e[r][1].end}},i={type:l>1?Xe.strongSequence:Xe.emphasisSequence,start:{...e[a][1].start},end:p},n={type:l>1?Xe.strongText:Xe.emphasisText,start:{...e[r][1].end},end:{...e[a][1].start}},o={type:l>1?Xe.strong:Xe.emphasis,start:{...s.start},end:{...i.end}},e[r][1].end={...s.start},e[a][1].start={...i.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=ta(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=ta(u,[["enter",o,t],["enter",s,t],["exit",s,t],["enter",n,t]]),t.parser.constructs.insideSpan.null,u=ta(u,Cr(t.parser.constructs.insideSpan.null,e.slice(r+1,a),t)),u=ta(u,[["exit",n,t],["enter",i,t],["exit",i,t],["exit",o,t]]),e[a][1].end.offset-e[a][1].start.offset?(d=2,u=ta(u,[["enter",e[a][1],t],["exit",e[a][1],t]])):d=0,ea(e,r-1,a-r+3,u),a=r+u.length-d-2;break}}for(a=-1;++a<e.length;)e[a][1].type==="attentionSequence"&&(e[a][1].type="data");return e}function Mh(e,t){let a=this.parser.constructs.attentionMarkers.null,{now:r,sliceSerialize:o,previous:n}=this,s=Or(n)?Ur(n,r(),o):n,i=Rt(s),l=new Nr(s,r(),o),u=Dr(i,l.value.bind(l),s),d;return c;function c(f){return f===Oe.asterisk||Oe.underscore,d=f,e.enter("attentionSequence"),p(f)}function p(f){if(f===d)return e.consume(f),p;let m=e.exit("attentionSequence"),y=Br(f)?qr(f,r(),o):f,S=Rt(y);let L=ua(u),C=L||jt(u),I=ua(S),x=I||jt(S),v=Gl(u),q=!x||I&&(C||v)||a.includes(f),N=!C||L&&(x||$a(S))||a.includes(s);return m._open=!!(d===Oe.asterisk?q:q&&(xn(u)||!N)),m._close=!!(d===Oe.asterisk?N:N&&(xn(S)||!q)),t(f)}}function Kl(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}function Xl(){return{text:{[Oe.asterisk]:yn,[Oe.underscore]:yn},insideSpan:{null:[yn]}}}function Jl(){let e=this.data();(e.micromarkExtensions||(e.micromarkExtensions=[])).push(Xl())}function Ql(e){let a=(e||{}).singleTilde,r={name:"strikethrough",tokenize:n,resolveAll:o};return a==null&&(a=!0),{text:{[Oe.tilde]:r},insideSpan:{null:[r]},attentionMarkers:{null:[Oe.tilde]}};function o(s,i){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";let d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},p=[["enter",d,i],["enter",s[u][1],i],["exit",s[u][1],i],["enter",c,i]],f=i.parser.constructs.insideSpan.null;f&&ea(p,p.length,0,Cr(f,s.slice(u+1,l),i)),ea(p,p.length,0,[["exit",c,i],["enter",s[l][1],i],["exit",s[l][1],i],["exit",d,i]]),ea(s,u-1,l-u+3,p),l=u+p.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type=Xe.data);return s}function n(s,i,l){let{now:u,sliceSerialize:d,previous:c}=this,p=Or(c)?Ur(c,u(),d):c,f=Rt(p),m=new Nr(p,u(),d),y=Dr(f,m.value.bind(m),p),S=this.events,L=0;return C;function C(x){return Oe.tilde,p===Oe.tilde&&S[S.length-1][1].type!==Xe.characterEscape?l(x):(s.enter("strikethroughSequenceTemporary"),I(x))}function I(x){let v=Rt(p);if(x===Oe.tilde)return L>1?l(x):(s.consume(x),L++,I);if(L<2&&!a)return l(x);let q=s.exit("strikethroughSequenceTemporary"),N=Br(x)?qr(x,u(),d):x,V=Rt(N),Q=ua(y)||jt(y),re=ua(V)||jt(V),K=$a(y)||Vl(v);return q._open=!re||V===ut.attentionSideAfter&&(Q||K),q._close=!Q||v===ut.attentionSideAfter&&(re||$a(V)),i(x)}}}function Yl(e){let t=this.data();(t.micromarkExtensions||(t.micromarkExtensions=[])).push(Ql(e))}var Fh=new Set(["\u3002","\uFF0E","\uFF0C","\u3001","\uFF1F","\uFF01","\uFF1A","\uFF1B","\uFF08","\uFF09","\u3010","\u3011","\u300C","\u300D","\u300E","\u300F","\u3008","\u3009","\u300A","\u300B"]),_h=/^(https?:\/\/|mailto:|www\.)/i,Dh=e=>{if(e.children.length!==1)return!1;let t=e.children[0];return t.type==="text"&&t.value===e.url},Bh=e=>{let t=0;for(let a of e){if(Fh.has(a))return t;t+=a.length}return null},Oh=(e,t)=>({...t,url:e,children:[{type:"text",value:e}]}),Uh=e=>({type:"text",value:e}),Nh=()=>e=>{fi(e,"link",(t,a,r)=>{if(!r||typeof a!="number"||!Dh(t)||!_h.test(t.url))return;let o=Bh(t.url);if(o===null||o===0)return;let n=t.url.slice(0,o),s=t.url.slice(o),i=Oh(n,t),l=Uh(s);return r.children.splice(a,1,i,l),a+1})};function qh(){let e=[Jl],t=[Nh,Yl],a=[...e,...t];return{name:"cjk",type:"cjk",remarkPluginsBefore:e,remarkPluginsAfter:t,remarkPlugins:a}}var Ln=qh();var ve=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Hh(e){return En(e)}function En(e){return Array.isArray(e)?$h(e):e instanceof RegExp?e:typeof e=="object"?Wh(e):e}function $h(e){let t=[];for(let a=0,r=e.length;a<r;a++)t[a]=En(e[a]);return t}function Wh(e){let t={};for(let a in e)t[a]=En(e[a]);return t}function iu(e,...t){return t.forEach(a=>{for(let r in a)e[r]=a[r]}),e}function lu(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?lu(e.substring(0,e.length-1)):e.substr(~t+1)}var Sn=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Hr=class{static hasCaptures(e){return e===null?!1:(Sn.lastIndex=0,Sn.test(e))}static replaceCaptures(e,t,a){return e.replace(Sn,(r,o,n,s)=>{let i=a[parseInt(o||n,10)];if(i){let l=t.substring(i.start,i.end);for(;l[0]===".";)l=l.substring(1);switch(s){case"downcase":return l.toLowerCase();case"upcase":return l.toUpperCase();default:return l}}else return r})}};function uu(e,t){return e<t?-1:e>t?1:0}function du(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let a=e.length,r=t.length;if(a===r){for(let o=0;o<a;o++){let n=uu(e[o],t[o]);if(n!==0)return n}return 0}return a-r}function Zl(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function cu(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var fu=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},za=class{constructor(e,t,a){this._colorMap=e,this._defaults=t,this._root=a}static createFromRawTheme(e,t){return this.createFromParsedTheme(Vh(e),t)}static createFromParsedTheme(e,t){return Kh(e,t)}_cachedMatchRoot=new fu(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(o=>jh(e.parent,o.parentScopes));return r?new pu(r.fontStyle,r.foreground,r.background):null}},Cn=class $r{constructor(t,a){this.parent=t,this.scopeName=a}static push(t,a){for(let r of a)t=new $r(t,r);return t}static from(...t){let a=null;for(let r=0;r<t.length;r++)a=new $r(a,t[r]);return a}push(t){return new $r(this,t)}getSegments(){let t=this,a=[];for(;t;)a.push(t.scopeName),t=t.parent;return a.reverse(),a}toString(){return this.getSegments().join(" ")}extends(t){return this===t?!0:this.parent===null?!1:this.parent.extends(t)}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push(r.scopeName),r=r.parent;return r===t?a.reverse():void 0}};function jh(e,t){if(t.length===0)return!0;for(let a=0;a<t.length;a++){let r=t[a],o=!1;if(r===">"){if(a===t.length-1)return!1;r=t[++a],o=!0}for(;e&&!zh(e.scopeName,r);){if(o)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function zh(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var pu=class{constructor(e,t,a){this.fontStyle=e,this.foregroundId=t,this.backgroundId=a}};function Vh(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,a=[],r=0;for(let o=0,n=t.length;o<n;o++){let s=t[o];if(!s.settings)continue;let i;if(typeof s.scope=="string"){let c=s.scope;c=c.replace(/^[,]+/,""),c=c.replace(/[,]+$/,""),i=c.split(",")}else Array.isArray(s.scope)?i=s.scope:i=[""];let l=-1;if(typeof s.settings.fontStyle=="string"){l=0;let c=s.settings.fontStyle.split(" ");for(let p=0,f=c.length;p<f;p++)switch(c[p]){case"italic":l=l|1;break;case"bold":l=l|2;break;case"underline":l=l|4;break;case"strikethrough":l=l|8;break}}let u=null;typeof s.settings.foreground=="string"&&Zl(s.settings.foreground)&&(u=s.settings.foreground);let d=null;typeof s.settings.background=="string"&&Zl(s.settings.background)&&(d=s.settings.background);for(let c=0,p=i.length;c<p;c++){let m=i[c].trim().split(" "),y=m[m.length-1],S=null;m.length>1&&(S=m.slice(0,m.length-1),S.reverse()),a[r++]=new Gh(y,S,o,l,u,d)}}return a}var Gh=class{constructor(e,t,a,r,o,n){this.scope=e,this.parentScopes=t,this.index=a,this.fontStyle=r,this.foreground=o,this.background=n}},Ue=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(Ue||{});function Kh(e,t){e.sort((l,u)=>{let d=uu(l.scope,u.scope);return d!==0||(d=du(l.parentScopes,u.parentScopes),d!==0)?d:l.index-u.index});let a=0,r="#000000",o="#ffffff";for(;e.length>=1&&e[0].scope==="";){let l=e.shift();l.fontStyle!==-1&&(a=l.fontStyle),l.foreground!==null&&(r=l.foreground),l.background!==null&&(o=l.background)}let n=new Xh(t),s=new pu(a,n.getId(r),n.getId(o)),i=new Qh(new vn(0,null,-1,0,0),[]);for(let l=0,u=e.length;l<u;l++){let d=e[l];i.insert(0,d.scope,d.parentScopes,d.fontStyle,n.getId(d.foreground),n.getId(d.background))}return new za(n,s,i)}var Xh=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,a=e.length;t<a;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw new Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},Jh=Object.freeze([]),vn=class mu{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(t,a,r,o,n){this.scopeDepth=t,this.parentScopes=a||Jh,this.fontStyle=r,this.foreground=o,this.background=n}clone(){return new mu(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(t){let a=[];for(let r=0,o=t.length;r<o;r++)a[r]=t[r].clone();return a}acceptOverwrite(t,a,r,o){this.scopeDepth>t?console.log("how did this happen?"):this.scopeDepth=t,a!==-1&&(this.fontStyle=a),r!==0&&(this.foreground=r),o!==0&&(this.background=o)}},Qh=class kn{constructor(t,a=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=a}_rulesWithParentScopes;static _cmpBySpecificity(t,a){if(t.scopeDepth!==a.scopeDepth)return a.scopeDepth-t.scopeDepth;let r=0,o=0;for(;t.parentScopes[r]===">"&&r++,a.parentScopes[o]===">"&&o++,!(r>=t.parentScopes.length||o>=a.parentScopes.length);){let n=a.parentScopes[o].length-t.parentScopes[r].length;if(n!==0)return n;r++,o++}return a.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),o,n;if(r===-1?(o=t,n=""):(o=t.substring(0,r),n=t.substring(r+1)),this._children.hasOwnProperty(o))return this._children[o].match(n)}let a=this._rulesWithParentScopes.concat(this._mainRule);return a.sort(kn._cmpBySpecificity),a}insert(t,a,r,o,n,s){if(a===""){this._doInsertHere(t,r,o,n,s);return}let i=a.indexOf("."),l,u;i===-1?(l=a,u=""):(l=a.substring(0,i),u=a.substring(i+1));let d;this._children.hasOwnProperty(l)?d=this._children[l]:(d=new kn(this._mainRule.clone(),vn.cloneArr(this._rulesWithParentScopes)),this._children[l]=d),d.insert(t+1,u,r,o,n,s)}_doInsertHere(t,a,r,o,n){if(a===null){this._mainRule.acceptOverwrite(t,r,o,n);return}for(let s=0,i=this._rulesWithParentScopes.length;s<i;s++){let l=this._rulesWithParentScopes[s];if(du(l.parentScopes,a)===0){l.acceptOverwrite(t,r,o,n);return}}r===-1&&(r=this._mainRule.fontStyle),o===0&&(o=this._mainRule.foreground),n===0&&(n=this._mainRule.background),this._rulesWithParentScopes.push(new vn(t,a,r,o,n))}},Vt=class Ye{static toBinaryStr(t){return t.toString(2).padStart(32,"0")}static print(t){let a=Ye.getLanguageId(t),r=Ye.getTokenType(t),o=Ye.getFontStyle(t),n=Ye.getForeground(t),s=Ye.getBackground(t);console.log({languageId:a,tokenType:r,fontStyle:o,foreground:n,background:s})}static getLanguageId(t){return(t&255)>>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,a,r,o,n,s,i){let l=Ye.getLanguageId(t),u=Ye.getTokenType(t),d=Ye.containsBalancedBrackets(t)?1:0,c=Ye.getFontStyle(t),p=Ye.getForeground(t),f=Ye.getBackground(t);return a!==0&&(l=a),r!==8&&(u=r),o!==null&&(d=o?1:0),n!==-1&&(c=n),s!==0&&(p=s),i!==0&&(f=i),(l<<0|u<<8|d<<10|c<<11|p<<15|f<<24)>>>0}};function jr(e,t){let a=[],r=Yh(e),o=r.next();for(;o!==null;){let l=0;if(o.length===2&&o.charAt(1)===":"){switch(o.charAt(0)){case"R":l=1;break;case"L":l=-1;break;default:console.log(`Unknown priority ${o} in scope selector`)}o=r.next()}let u=s();if(a.push({matcher:u,priority:l}),o!==",")break;o=r.next()}return a;function n(){if(o==="-"){o=r.next();let l=n();return u=>!!l&&!l(u)}if(o==="("){o=r.next();let l=i();return o===")"&&(o=r.next()),l}if(eu(o)){let l=[];do l.push(o),o=r.next();while(eu(o));return u=>t(l,u)}return null}function s(){let l=[],u=n();for(;u;)l.push(u),u=n();return d=>l.every(c=>c(d))}function i(){let l=[],u=s();for(;u&&(l.push(u),o==="|"||o===",");){do o=r.next();while(o==="|"||o===",");u=s()}return d=>l.some(c=>c(d))}}function eu(e){return!!e&&!!e.match(/[\w\.:]+/)}function Yh(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,a=t.exec(e);return{next:()=>{if(!a)return null;let r=a[0];return a=t.exec(e),r}}}function hu(e){typeof e.dispose=="function"&&e.dispose()}var Va=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},Zh=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},eg=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},tg=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Va(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new eg;for(let a of e)ag(a,this.initialScopeName,this.repo,t);for(let a of t.references)if(a instanceof Va){if(this.seenFullScopeRequests.has(a.scopeName))continue;this.seenFullScopeRequests.add(a.scopeName),this.Q.push(a)}else{if(this.seenFullScopeRequests.has(a.scopeName)||this.seenPartialScopeRequests.has(a.toKey()))continue;this.seenPartialScopeRequests.add(a.toKey()),this.Q.push(a)}}};function ag(e,t,a,r){let o=a.lookup(e.scopeName);if(!o){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let n=a.lookup(t);e instanceof Va?Wr({baseGrammar:n,selfGrammar:o},r):Tn(e.ruleName,{baseGrammar:n,selfGrammar:o,repository:o.repository},r);let s=a.injections(e.scopeName);if(s)for(let i of s)r.add(new Va(i))}function Tn(e,t,a){if(t.repository&&t.repository[e]){let r=t.repository[e];zr([r],t,a)}}function Wr(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&zr(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&zr(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function zr(e,t,a){for(let r of e){if(a.visitedRule.has(r))continue;a.visitedRule.add(r);let o=r.repository?iu({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&zr(r.patterns,{...t,repository:o},a);let n=r.include;if(!n)continue;let s=gu(n);switch(s.kind){case 0:Wr({...t,selfGrammar:t.baseGrammar},a);break;case 1:Wr(t,a);break;case 2:Tn(s.ruleName,{...t,repository:o},a);break;case 3:case 4:let i=s.scopeName===t.selfGrammar.scopeName?t.selfGrammar:s.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(i){let l={baseGrammar:t.baseGrammar,selfGrammar:i,repository:o};s.kind===4?Tn(s.ruleName,l,a):Wr(l,a)}else s.kind===4?a.add(new Zh(s.scopeName,s.ruleName)):a.add(new Va(s.scopeName));break}}}var rg=class{kind=0},og=class{kind=1},ng=class{constructor(e){this.ruleName=e}kind=2},sg=class{constructor(e){this.scopeName=e}kind=3},ig=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function gu(e){if(e==="$base")return new rg;if(e==="$self")return new og;let t=e.indexOf("#");if(t===-1)return new sg(e);if(t===0)return new ng(e.substring(1));{let a=e.substring(0,t),r=e.substring(t+1);return new ig(a,r)}}var lg=/\\(\d+)/,tu=/\\(\d+)/g;var ug=-1,wu=-2;var Xa=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,a,r){this.$location=e,this.id=t,this._name=a||null,this._nameIsCapturing=Hr.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Hr.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${lu(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Hr.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Hr.replaceCaptures(this._contentName,e,t)}},dg=class extends Xa{retokenizeCapturedWithRuleId;constructor(e,t,a,r,o){super(e,t,a,r),this.retokenizeCapturedWithRuleId=o}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,a,r){throw new Error("Not supported!")}},cg=class extends Xa{_match;captures;_cachedCompiledPatterns;constructor(e,t,a,r,o){super(e,t,a,null),this._match=new Ga(r,this.id),this.captures=o,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ka,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},au=class extends Xa{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,o){super(e,t,a,r),this.patterns=o.patterns,this.hasMissingPatterns=o.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let a of this.patterns)e.getRule(a).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ka,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},An=class extends Xa{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,a,r,o,n,s,i,l,u){super(e,t,a,r),this._begin=new Ga(o,this.id),this.beginCaptures=n,this._end=new Ga(s||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=i,this.applyEndPatternLast=l||!1,this.patterns=u.patterns,this.hasMissingPatterns=u.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,a,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ka;for(let a of this.patterns)e.getRule(a).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Vr=class extends Xa{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,a,r,o,n,s,i,l){super(e,t,a,r),this._begin=new Ga(o,this.id),this.beginCaptures=n,this.whileCaptures=i,this._while=new Ga(s,wu),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,a,r){return this._getCachedCompiledPatterns(e).compileAG(e,a,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ka;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,a,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,a,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Ka,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},Iu=class qe{static createCaptureRule(t,a,r,o,n){return t.registerRule(s=>new dg(a,s,r,o,n))}static getCompiledRuleId(t,a,r){return t.id||a.registerRule(o=>{if(t.id=o,t.match)return new cg(t.$vscodeTextmateLocation,t.id,t.name,t.match,qe._compileCaptures(t.captures,a,r));if(typeof t.begin>"u"){t.repository&&(r=iu({},r,t.repository));let n=t.patterns;return typeof n>"u"&&t.include&&(n=[{include:t.include}]),new au(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,qe._compilePatterns(n,a,r))}return t.while?new Vr(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,qe._compileCaptures(t.beginCaptures||t.captures,a,r),t.while,qe._compileCaptures(t.whileCaptures||t.captures,a,r),qe._compilePatterns(t.patterns,a,r)):new An(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,qe._compileCaptures(t.beginCaptures||t.captures,a,r),t.end,qe._compileCaptures(t.endCaptures||t.captures,a,r),t.applyEndPatternLast,qe._compilePatterns(t.patterns,a,r))}),t.id}static _compileCaptures(t,a,r){let o=[];if(t){let n=0;for(let s in t){if(s==="$vscodeTextmateLocation")continue;let i=parseInt(s,10);i>n&&(n=i)}for(let s=0;s<=n;s++)o[s]=null;for(let s in t){if(s==="$vscodeTextmateLocation")continue;let i=parseInt(s,10),l=0;t[s].patterns&&(l=qe.getCompiledRuleId(t[s],a,r)),o[i]=qe.createCaptureRule(a,t[s].$vscodeTextmateLocation,t[s].name,t[s].contentName,l)}}return o}static _compilePatterns(t,a,r){let o=[];if(t)for(let n=0,s=t.length;n<s;n++){let i=t[n],l=-1;if(i.include){let u=gu(i.include);switch(u.kind){case 0:case 1:l=qe.getCompiledRuleId(r[i.include],a,r);break;case 2:let d=r[u.ruleName];d&&(l=qe.getCompiledRuleId(d,a,r));break;case 3:case 4:let c=u.scopeName,p=u.kind===4?u.ruleName:null,f=a.getExternalGrammar(c,r);if(f)if(p){let m=f.repository[p];m&&(l=qe.getCompiledRuleId(m,a,f.repository))}else l=qe.getCompiledRuleId(f.repository.$self,a,f.repository);break}}else l=qe.getCompiledRuleId(i,a,r);if(l!==-1){let u=a.getRule(l),d=!1;if((u instanceof au||u instanceof An||u instanceof Vr)&&u.hasMissingPatterns&&u.patterns.length===0&&(d=!0),d)continue;o.push(l)}}return{patterns:o,hasMissingPatterns:(t?t.length:0)!==o.length}}},Ga=class xu{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(t,a){if(t&&typeof t=="string"){let r=t.length,o=0,n=[],s=!1;for(let i=0;i<r;i++)if(t.charAt(i)==="\\"&&i+1<r){let u=t.charAt(i+1);u==="z"?(n.push(t.substring(o,i)),n.push("$(?!\\n)(?<!\\n)"),o=i+2):(u==="A"||u==="G")&&(s=!0),i++}this.hasAnchor=s,o===0?this.source=t:(n.push(t.substring(o,r)),this.source=n.join(""))}else this.hasAnchor=!1,this.source=t;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=a,typeof this.source=="string"?this.hasBackReferences=lg.test(this.source):this.hasBackReferences=!1}clone(){return new xu(this.source,this.ruleId)}setSource(t){this.source!==t&&(this.source=t,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(t,a){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=a.map(o=>t.substring(o.start,o.end));return tu.lastIndex=0,this.source.replace(tu,(o,n)=>cu(r[parseInt(n,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],a=[],r=[],o=[],n,s,i,l;for(n=0,s=this.source.length;n<s;n++)i=this.source.charAt(n),t[n]=i,a[n]=i,r[n]=i,o[n]=i,i==="\\"&&n+1<s&&(l=this.source.charAt(n+1),l==="A"?(t[n+1]="\uFFFF",a[n+1]="\uFFFF",r[n+1]="A",o[n+1]="A"):l==="G"?(t[n+1]="\uFFFF",a[n+1]="G",r[n+1]="\uFFFF",o[n+1]="G"):(t[n+1]=l,a[n+1]=l,r[n+1]=l,o[n+1]=l),n++);return{A0_G0:t.join(""),A0_G1:a.join(""),A1_G0:r.join(""),A1_G1:o.join("")}}resolveAnchors(t,a){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:t?a?this._anchorCache.A1_G1:this._anchorCache.A1_G0:a?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Ka=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(a=>a.source);this._cached=new ru(e,t,this._items.map(a=>a.ruleId))}return this._cached}compileAG(e,t,a){return this._hasAnchors?t?a?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A1_G0):a?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,a)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,a){let r=this._items.map(o=>o.resolveAnchors(t,a));return new ru(e,r,this._items.map(o=>o.ruleId))}},ru=class{constructor(e,t,a){this.regExps=t,this.rules=a,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,a=this.rules.length;t<a;t++)e.push(" - "+this.rules[t]+": "+this.regExps[t]);return e.join(`
|
|
5
|
+
`)}findNextMatchSync(e,t,a){let r=this.scanner.findNextMatchSync(e,t,a);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},bn=class{constructor(e,t){this.languageId=e,this.tokenType=t}},fg=class Pn{_defaultAttributes;_embeddedLanguagesMatcher;constructor(t,a){this._defaultAttributes=new bn(t,8),this._embeddedLanguagesMatcher=new pg(Object.entries(a||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?Pn._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new bn(0,0);_getBasicScopeAttributes=new fu(t=>{let a=this._scopeToLanguage(t),r=this._toStandardTokenType(t);return new bn(a,r)});_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let a=t.match(Pn.STANDARD_TOKEN_TYPE_REGEXP);if(!a)return 8;switch(a[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},pg=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([a,r])=>cu(a));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},mk={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},yu=!1,ou=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function Lu(e,t,a,r,o,n,s,i){let l=t.content.length,u=!1,d=-1;if(s){let f=mg(e,t,a,r,o,n);o=f.stack,r=f.linePos,a=f.isFirstLine,d=f.anchorPosition}let c=Date.now();for(;!u;){if(i!==0&&Date.now()-c>i)return new ou(o,!0);p()}return new ou(o,!1);function p(){let f=hg(e,t,a,r,o,d);if(!f){n.produce(o,l),u=!0;return}let m=f.captureIndices,y=f.matchedRuleId,S=m&&m.length>0?m[0].end>r:!1;if(y===ug){let L=o.getRule(e);n.produce(o,m[0].start),o=o.withContentNameScopesList(o.nameScopesList),Wa(e,t,a,o,n,L.endCaptures,m),n.produce(o,m[0].end);let C=o;if(o=o.parent,d=C.getAnchorPos(),!S&&C.getEnterPos()===r){o=C,n.produce(o,l),u=!0;return}}else{let L=e.getRule(y);n.produce(o,m[0].start);let C=o,I=L.getName(t.content,m),x=o.contentNameScopesList.pushAttributed(I,e);if(o=o.push(y,r,d,m[0].end===l,null,x,x),L instanceof An){let v=L;Wa(e,t,a,o,n,v.beginCaptures,m),n.produce(o,m[0].end),d=m[0].end;let q=v.getContentName(t.content,m),N=x.pushAttributed(q,e);if(o=o.withContentNameScopesList(N),v.endHasBackReferences&&(o=o.withEndRule(v.getEndWithResolvedBackReferences(t.content,m))),!S&&C.hasSameRuleAs(o)){o=o.pop(),n.produce(o,l),u=!0;return}}else if(L instanceof Vr){let v=L;Wa(e,t,a,o,n,v.beginCaptures,m),n.produce(o,m[0].end),d=m[0].end;let q=v.getContentName(t.content,m),N=x.pushAttributed(q,e);if(o=o.withContentNameScopesList(N),v.whileHasBackReferences&&(o=o.withEndRule(v.getWhileWithResolvedBackReferences(t.content,m))),!S&&C.hasSameRuleAs(o)){o=o.pop(),n.produce(o,l),u=!0;return}}else if(Wa(e,t,a,o,n,L.captures,m),n.produce(o,m[0].end),o=o.pop(),!S){o=o.safePop(),n.produce(o,l),u=!0;return}}m[0].end>r&&(r=m[0].end,a=!1)}}function mg(e,t,a,r,o,n){let s=o.beginRuleCapturedEOL?0:-1,i=[];for(let l=o;l;l=l.pop()){let u=l.getRule(e);u instanceof Vr&&i.push({rule:u,stack:l})}for(let l=i.pop();l;l=i.pop()){let{ruleScanner:u,findOptions:d}=Ig(l.rule,e,l.stack.endRule,a,r===s),c=u.findNextMatchSync(t,r,d);if(c){if(c.ruleId!==wu){o=l.stack.pop();break}c.captureIndices&&c.captureIndices.length&&(n.produce(l.stack,c.captureIndices[0].start),Wa(e,t,a,l.stack,n,l.rule.whileCaptures,c.captureIndices),n.produce(l.stack,c.captureIndices[0].end),s=c.captureIndices[0].end,c.captureIndices[0].end>r&&(r=c.captureIndices[0].end,a=!1))}else{o=l.stack.pop();break}}return{stack:o,linePos:r,anchorPosition:s,isFirstLine:a}}function hg(e,t,a,r,o,n){let s=gg(e,t,a,r,o,n),i=e.getInjections();if(i.length===0)return s;let l=wg(i,e,t,a,r,o,n);if(!l)return s;if(!s)return l;let u=s.captureIndices[0].start,d=l.captureIndices[0].start;return d<u||l.priorityMatch&&d===u?l:s}function gg(e,t,a,r,o,n){let s=o.getRule(e),{ruleScanner:i,findOptions:l}=Su(s,e,o.endRule,a,r===n),u=i.findNextMatchSync(t,r,l);return u?{captureIndices:u.captureIndices,matchedRuleId:u.ruleId}:null}function wg(e,t,a,r,o,n,s){let i=Number.MAX_VALUE,l=null,u,d=0,c=n.contentNameScopesList.getScopeNames();for(let p=0,f=e.length;p<f;p++){let m=e[p];if(!m.matcher(c))continue;let y=t.getRule(m.ruleId),{ruleScanner:S,findOptions:L}=Su(y,t,null,r,o===s),C=S.findNextMatchSync(a,o,L);if(!C)continue;let I=C.captureIndices[0].start;if(!(I>=i)&&(i=I,l=C.captureIndices,u=C.ruleId,d=m.priority,i===o))break}return l?{priorityMatch:d===-1,captureIndices:l,matchedRuleId:u}:null}function Su(e,t,a,r,o){if(yu){let s=e.compile(t,a),i=Cu(r,o);return{ruleScanner:s,findOptions:i}}return{ruleScanner:e.compileAG(t,a,r,o),findOptions:0}}function Ig(e,t,a,r,o){if(yu){let s=e.compileWhile(t,a),i=Cu(r,o);return{ruleScanner:s,findOptions:i}}return{ruleScanner:e.compileWhileAG(t,a,r,o),findOptions:0}}function Cu(e,t){let a=0;return e||(a|=1),t||(a|=4),a}function Wa(e,t,a,r,o,n,s){if(n.length===0)return;let i=t.content,l=Math.min(n.length,s.length),u=[],d=s[0].end;for(let c=0;c<l;c++){let p=n[c];if(p===null)continue;let f=s[c];if(f.length===0)continue;if(f.start>d)break;for(;u.length>0&&u[u.length-1].endPos<=f.start;)o.produceFromScopes(u[u.length-1].scopes,u[u.length-1].endPos),u.pop();if(u.length>0?o.produceFromScopes(u[u.length-1].scopes,f.start):o.produce(r,f.start),p.retokenizeCapturedWithRuleId){let y=p.getName(i,s),S=r.contentNameScopesList.pushAttributed(y,e),L=p.getContentName(i,s),C=S.pushAttributed(L,e),I=r.push(p.retokenizeCapturedWithRuleId,f.start,-1,!1,null,S,C),x=e.createOnigString(i.substring(0,f.end));Lu(e,x,a&&f.start===0,f.start,I,o,!1,0),hu(x);continue}let m=p.getName(i,s);if(m!==null){let S=(u.length>0?u[u.length-1].scopes:r.contentNameScopesList).pushAttributed(m,e);u.push(new xg(S,f.end))}}for(;u.length>0;)o.produceFromScopes(u[u.length-1].scopes,u[u.length-1].endPos),u.pop()}var xg=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function yg(e,t,a,r,o,n,s,i){return new Sg(e,t,a,r,o,n,s,i)}function nu(e,t,a,r,o){let n=jr(t,Gr),s=Iu.getCompiledRuleId(a,r,o.repository);for(let i of n)e.push({debugSelector:t,matcher:i.matcher,ruleId:s,grammar:o,priority:i.priority})}function Gr(e,t){if(t.length<e.length)return!1;let a=0;return e.every(r=>{for(let o=a;o<t.length;o++)if(Lg(t[o],r))return a=o+1,!0;return!1})}function Lg(e,t){if(!e)return!1;if(e===t)return!0;let a=t.length;return e.length>a&&e.substr(0,a)===t&&e[a]==="."}var Sg=class{constructor(e,t,a,r,o,n,s,i){if(this._rootScopeName=e,this.balancedBracketSelectors=n,this._onigLib=i,this._basicScopeAttributesProvider=new fg(a,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=s,this._grammar=su(t,null),this._injections=null,this._tokenTypeMatchers=[],o)for(let l of Object.keys(o)){let u=jr(l,Gr);for(let d of u)this._tokenTypeMatchers.push({matcher:d.matcher,type:o[l]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:o=>o===this._rootScopeName?this._grammar:this.getExternalGrammar(o),injections:o=>this._grammarRepository.injections(o)},t=[],a=this._rootScopeName,r=e.lookup(a);if(r){let o=r.injections;if(o)for(let s in o)nu(t,s,o[s],this,r);let n=this._grammarRepository.injections(a);n&&n.forEach(s=>{let i=this.getExternalGrammar(s);if(i){let l=i.injectionSelector;l&&nu(t,l,i,this,i)}})}return t.sort((o,n)=>o.priority-n.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,a=e(t);return this._ruleId2desc[t]=a,a}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let a=this._grammarRepository.lookup(e);if(a)return this._includedGrammars[e]=su(a,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,a=0){let r=this._tokenize(e,t,!1,a);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,a=0){let r=this._tokenize(e,t,!0,a);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,a,r){this._rootId===-1&&(this._rootId=Iu.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let o;if(!t||t===Rn.NULL){o=!0;let u=this._basicScopeAttributesProvider.getDefaultAttributes(),d=this.themeProvider.getDefaults(),c=Vt.set(0,u.languageId,u.tokenType,null,d.fontStyle,d.foregroundId,d.backgroundId),p=this.getRule(this._rootId).getName(null,null),f;p?f=ja.createRootAndLookUpScopeName(p,c,this):f=ja.createRoot("unknown",c),t=new Rn(null,this._rootId,-1,-1,!1,null,f,f)}else o=!1,t.reset();e=e+`
|
|
6
|
+
`;let n=this.createOnigString(e),s=n.content.length,i=new bg(a,e,this._tokenTypeMatchers,this.balancedBracketSelectors),l=Lu(this,n,o,0,t,i,!0,r);return hu(n),{lineLength:s,lineTokens:i,ruleStack:l.stack,stoppedEarly:l.stoppedEarly}}};function su(e,t){return e=Hh(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var ja=class dt{constructor(t,a,r){this.parent=t,this.scopePath=a,this.tokenAttributes=r}static fromExtension(t,a){let r=t,o=t?.scopePath??null;for(let n of a)o=Cn.push(o,n.scopeNames),r=new dt(r,o,n.encodedTokenAttributes);return r}static createRoot(t,a){return new dt(null,new Cn(null,t),a)}static createRootAndLookUpScopeName(t,a,r){let o=r.getMetadataForScope(t),n=new Cn(null,t),s=r.themeProvider.themeMatch(n),i=dt.mergeAttributes(a,o,s);return new dt(null,n,i)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return dt.equals(this,t)}static equals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.scopeName!==a.scopeName||t.tokenAttributes!==a.tokenAttributes)return!1;t=t.parent,a=a.parent}while(!0)}static mergeAttributes(t,a,r){let o=-1,n=0,s=0;return r!==null&&(o=r.fontStyle,n=r.foregroundId,s=r.backgroundId),Vt.set(t,a.languageId,a.tokenType,null,o,n,s)}pushAttributed(t,a){if(t===null)return this;if(t.indexOf(" ")===-1)return dt._pushAttributed(this,t,a);let r=t.split(/ /g),o=this;for(let n of r)o=dt._pushAttributed(o,n,a);return o}static _pushAttributed(t,a,r){let o=r.getMetadataForScope(a),n=t.scopePath.push(a),s=r.themeProvider.themeMatch(n),i=dt.mergeAttributes(t.tokenAttributes,o,s);return new dt(t,n,i)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let a=[],r=this;for(;r&&r!==t;)a.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?a.reverse():void 0}},Rn=class zt{constructor(t,a,r,o,n,s,i,l){this.parent=t,this.ruleId=a,this.beginRuleCapturedEOL=n,this.endRule=s,this.nameScopesList=i,this.contentNameScopesList=l,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=o}_stackElementBrand=void 0;static NULL=new zt(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:zt._equals(this,t)}static _equals(t,a){return t===a?!0:this._structuralEquals(t,a)?ja.equals(t.contentNameScopesList,a.contentNameScopesList):!1}static _structuralEquals(t,a){do{if(t===a||!t&&!a)return!0;if(!t||!a||t.depth!==a.depth||t.ruleId!==a.ruleId||t.endRule!==a.endRule)return!1;t=t.parent,a=a.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){zt._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,a,r,o,n,s,i){return new zt(this,t,a,r,o,n,s,i)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,a){return this.parent&&(a=this.parent._writeString(t,a)),t[a++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,a}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new zt(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let a=this;for(;a&&a._enterPos===t._enterPos;){if(a.ruleId===t.ruleId)return!0;a=a.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,a){let r=ja.fromExtension(t?.nameScopesList??null,a.nameScopesList);return new zt(t,a.ruleId,a.enterPos??-1,a.anchorPos??-1,a.beginRuleCapturedEOL,a.endRule,r,ja.fromExtension(r,a.contentNameScopesList))}},Cg=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(a=>a==="*"?(this.allowAny=!0,[]):jr(a,Gr).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(a=>jr(a,Gr).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},bg=class{constructor(e,t,a,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=a,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,o=!1;if(this.balancedBracketSelectors?.matchesAlways&&(o=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let n=e?.getScopeNames()??[];for(let s of this._tokenTypeOverrides)s.matcher(n)&&(r=Vt.set(r,0,s.type,null,-1,0,0));this.balancedBracketSelectors&&(o=this.balancedBracketSelectors.match(n))}if(o&&(r=Vt.set(r,0,8,o,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let a=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:a}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let a=new Uint32Array(this._binaryTokens.length);for(let r=0,o=this._binaryTokens.length;r<o;r++)a[r]=this._binaryTokens[r];return a}},vg=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,a,r,o){if(!this._grammars.has(e)){let n=this._rawGrammars.get(e);if(!n)return null;this._grammars.set(e,yg(e,n,t,a,r,o,this,this._onigLib))}return this._grammars.get(e)}},bu=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new vg(za.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(za.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,a){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:a})}loadGrammarWithConfiguration(e,t,a){return this._loadGrammar(e,t,a.embeddedLanguages,a.tokenTypes,new Cg(a.balancedBracketSelectors||[],a.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,a,r,o){let n=new tg(this._syncRegistry,e);for(;n.Q.length>0;)n.Q.map(s=>this._loadSingleGrammar(s.scopeName)),n.processQueue();return this._grammarForScopeName(e,t,a,r,o)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let a=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,a)}}addGrammar(e,t=[],a=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,a,r)}_grammarForScopeName(e,t=0,a=null,r=null,o=null){return this._syncRegistry.grammarForScopeName(e,t,a,r,o)}},Kr=Rn.NULL;var kg=/["&'<>`]/g,Tg=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Ag=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,Pg=/[|\\{}()[\]^$+*?.]/g,vu=new WeakMap;function ku(e,t){if(e=e.replace(t.subset?Rg(t.subset):kg,r),t.subset||t.escapeOnly)return e;return e.replace(Tg,a).replace(Ag,r);function a(o,n,s){return t.format((o.charCodeAt(0)-55296)*1024+o.charCodeAt(1)-56320+65536,s.charCodeAt(n+2),t)}function r(o,n,s){return t.format(o.charCodeAt(0),s.charCodeAt(n+1),t)}}function Rg(e){let t=vu.get(e);return t||(t=Eg(e),vu.set(e,t)),t}function Eg(e){let t=[],a=-1;for(;++a<e.length;)t.push(e[a].replace(Pg,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}var Mg=/[\dA-Fa-f]/;function Tu(e,t,a){let r="&#x"+e.toString(16).toUpperCase();return a&&t&&!Mg.test(String.fromCharCode(t))?r:r+";"}var Fg=/\d/;function Au(e,t,a){let r="&#"+String(e);return a&&t&&!Fg.test(String.fromCharCode(t))?r:r+";"}var Pu=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var Xr={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var Ru=["cent","copy","divide","gt","lt","not","para","times"];var Eu={}.hasOwnProperty,Mn={},Jr;for(Jr in Xr)Eu.call(Xr,Jr)&&(Mn[Xr[Jr]]=Jr);var _g=/[^\dA-Za-z]/;function Mu(e,t,a,r){let o=String.fromCharCode(e);if(Eu.call(Mn,o)){let n=Mn[o],s="&"+n;return a&&Pu.includes(n)&&!Ru.includes(n)&&(!r||t&&t!==61&&_g.test(String.fromCharCode(t)))?s:s+";"}return""}function Fu(e,t,a){let r=Tu(e,t,a.omitOptionalSemicolons),o;if((a.useNamedReferences||a.useShortestReferences)&&(o=Mu(e,t,a.omitOptionalSemicolons,a.attribute)),(a.useShortestReferences||!o)&&a.useShortestReferences){let n=Au(e,t,a.omitOptionalSemicolons);n.length<r.length&&(r=n)}return o&&(!a.useShortestReferences||o.length<r.length)?o:r}function wt(e,t){return ku(e,Object.assign({format:Fu},t))}var Dg=/^>|^->|<!--|-->|--!>|<!-$/g,Bg=[">"],Og=["<",">"];function _u(e,t,a,r){return r.settings.bogusComments?"<?"+wt(e.value,Object.assign({},r.settings.characterReferences,{subset:Bg}))+">":"<!--"+e.value.replace(Dg,o)+"-->";function o(n){return wt(n,Object.assign({},r.settings.characterReferences,{subset:Og}))}}function Du(e,t,a,r){return"<!"+(r.settings.upperDoctype?"DOCTYPE":"doctype")+(r.settings.tightDoctype?"":" ")+"html>"}var Pe=Bu(1),Fn=Bu(-1),Ug=[];function Bu(e){return t;function t(a,r,o){let n=a?a.children:Ug,s=(r||0)+e,i=n[s];if(!o)for(;i&&aa(i);)s+=e,i=n[s];return i}}var Ng={}.hasOwnProperty;function Qr(e){return t;function t(a,r,o){return Ng.call(e,a.tagName)&&e[a.tagName](a,r,o)}}var Ja=Qr({body:Hg,caption:_n,colgroup:_n,dd:zg,dt:jg,head:_n,html:qg,li:Wg,optgroup:Vg,option:Gg,p:$g,rp:Ou,rt:Ou,tbody:Xg,td:Uu,tfoot:Jg,th:Uu,thead:Kg,tr:Qg});function _n(e,t,a){let r=Pe(a,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&aa(r.value.charAt(0)))}function qg(e,t,a){let r=Pe(a,t);return!r||r.type!=="comment"}function Hg(e,t,a){let r=Pe(a,t);return!r||r.type!=="comment"}function $g(e,t,a){let r=Pe(a,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!a||!(a.type==="element"&&(a.tagName==="a"||a.tagName==="audio"||a.tagName==="del"||a.tagName==="ins"||a.tagName==="map"||a.tagName==="noscript"||a.tagName==="video"))}function Wg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="li"}function jg(e,t,a){let r=Pe(a,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function zg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function Ou(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function Vg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function Gg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function Kg(e,t,a){let r=Pe(a,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Xg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Jg(e,t,a){return!Pe(a,t)}function Qg(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&r.tagName==="tr"}function Uu(e,t,a){let r=Pe(a,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var Nu=Qr({body:ew,colgroup:tw,head:Zg,html:Yg,tbody:aw});function Yg(e){let t=Pe(e,-1);return!t||t.type!=="comment"}function Zg(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let a=e.children[0];return!a||a.type==="element"}function ew(e){let t=Pe(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&aa(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function tw(e,t,a){let r=Fn(a,t),o=Pe(e,-1,!0);return a&&r&&r.type==="element"&&r.tagName==="colgroup"&&Ja(r,a.children.indexOf(r),a)?!1:!!(o&&o.type==="element"&&o.tagName==="col")}function aw(e,t,a){let r=Fn(a,t),o=Pe(e,-1);return a&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&Ja(r,a.children.indexOf(r),a)?!1:!!(o&&o.type==="element"&&o.tagName==="tr")}var Yr={name:[[`
|
|
7
7
|
\f\r &/=>`.split(""),`
|
|
8
8
|
\f\r "&'/=>\``.split("")],[`\0
|
|
9
9
|
\f\r "&'/<=>`.split(""),`\0
|
|
@@ -11,16 +11,16 @@ ${ue}`}]}}O.current({...le,...ee?{modelContext:ee}:{}})}fe({jsonrpc:"2.0",id:ie,
|
|
|
11
11
|
\f\r &>`.split(""),`\0
|
|
12
12
|
\f\r "&'<=>\``.split("")],[`\0
|
|
13
13
|
\f\r "&'<=>\``.split(""),`\0
|
|
14
|
-
\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function qu(e,t,a,r){let o=r.schema,n=o.space==="svg"?!1:r.settings.omitOptionalTags,s=o.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),i=[],l;o.space==="html"&&e.tagName==="svg"&&(r.schema=Sr);let u=aw(r,e.properties),d=r.all(o.space==="html"&&e.tagName==="template"?e.content:e);return r.schema=o,d&&(s=!1),(u||!n||!Nu(e,t,a))&&(i.push("<",e.tagName,u?" "+u:""),s&&(o.space==="svg"||r.settings.closeSelfClosing)&&(l=u.charAt(u.length-1),(!r.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&i.push(" "),i.push("/")),i.push(">")),i.push(d),!s&&(!n||!Ja(e,t,a))&&i.push("</"+e.tagName+">"),i.join("")}function aw(e,t){let a=[],r=-1,o;if(t){for(o in t)if(t[o]!==null&&t[o]!==void 0){let n=rw(e,o,t[o]);n&&a.push(n)}}for(;++r<a.length;){let n=e.settings.tightAttributes?a[r].charAt(a[r].length-1):void 0;r!==a.length-1&&n!=='"'&&n!=="'"&&(a[r]+=" ")}return a.join("")}function rw(e,t,a){let r=pi(e.schema,t),o=e.settings.allowParseErrors&&e.schema.space==="html"?0:1,n=e.settings.allowDangerousCharacters?0:1,s=e.quote,i;if(r.overloadedBoolean&&(a===r.attribute||a==="")?a=!0:(r.boolean||r.overloadedBoolean)&&(typeof a!="string"||a===r.attribute||a==="")&&(a=!!a),a==null||a===!1||typeof a=="number"&&Number.isNaN(a))return"";let l=wt(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Yr.name[o][n]}));return a===!0||(a=Array.isArray(a)?(r.commaSeparated?hi:gi)(a,{padLeft:!e.settings.tightCommaSeparatedLists}):String(a),e.settings.collapseEmptyAttributes&&!a)?l:(e.settings.preferUnquoted&&(i=wt(a,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Yr.unquoted[o][n]}))),i!==a&&(e.settings.quoteSmart&&No(a,s)>No(a,e.alternative)&&(s=e.alternative),i=s+wt(a,Object.assign({},e.settings.characterReferences,{subset:(s==="'"?Yr.single:Yr.double)[o][n],attribute:!0}))+s),l+(i&&"="+i))}var ow=["<","&"];function Zr(e,t,a,r){return a&&a.type==="element"&&(a.tagName==="script"||a.tagName==="style")?e.value:wt(e.value,Object.assign({},r.settings.characterReferences,{subset:ow}))}function Hu(e,t,a,r){return r.settings.allowDangerousHtml?e.value:Zr(e,t,a,r)}function $u(e,t,a,r){return r.all(e)}var Wu=wi("type",{invalid:nw,unknown:sw,handlers:{comment:_u,doctype:Du,element:qu,raw:Hu,root:$u,text:Zr}});function nw(e){throw new Error("Expected node, not `"+e+"`")}function sw(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var iw={},lw={},uw=[];function Dn(e,t){let a=t||iw,r=a.quote||'"',o=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:dw,all:cw,settings:{omitOptionalTags:a.omitOptionalTags||!1,allowParseErrors:a.allowParseErrors||!1,allowDangerousCharacters:a.allowDangerousCharacters||!1,quoteSmart:a.quoteSmart||!1,preferUnquoted:a.preferUnquoted||!1,tightAttributes:a.tightAttributes||!1,upperDoctype:a.upperDoctype||!1,tightDoctype:a.tightDoctype||!1,bogusComments:a.bogusComments||!1,tightCommaSeparatedLists:a.tightCommaSeparatedLists||!1,tightSelfClosing:a.tightSelfClosing||!1,collapseEmptyAttributes:a.collapseEmptyAttributes||!1,allowDangerousHtml:a.allowDangerousHtml||!1,voids:a.voids||Ii,characterReferences:a.characterReferences||lw,closeSelfClosing:a.closeSelfClosing||!1,closeEmptyElements:a.closeEmptyElements||!1},schema:a.space==="svg"?Sr:mi,quote:r,alternative:o}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function dw(e,t,a){return Wu(e,t,a,this)}function cw(e){let t=[],a=e&&e.children||uw,r=-1;for(;++r<a.length;)t[r]=this.one(a[r],r,e);return t.join("")}function eo(e,t){let a=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[o,n]of Object.entries(t?.colorReplacements||{}))typeof n=="string"?a[o]=n:o===r&&Object.assign(a,n);return a}function Mt(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function fw(e){return Array.isArray(e)?e:[e]}async function Ju(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function Hn(e){return!e||["plaintext","txt","text","plain"].includes(e)}function Qu(e){return e==="ansi"||Hn(e)}function $n(e){return e==="none"}function Yu(e){return $n(e)}function Zu(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class=="string"&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let a=Array.isArray(t)?t:t.split(/\s+/g);for(let r of a)r&&!e.properties.class.includes(r)&&e.properties.class.push(r);return e}function no(e,t=!1){if(e.length===0)return[["",0]];let a=e.split(/(\r?\n)/g),r=0,o=[];for(let n=0;n<a.length;n+=2){let s=t?a[n]+(a[n+1]||""):a[n];o.push([s,r]),r+=a[n].length,r+=a[n+1]?.length||0}return o}function pw(e){let t=no(e,!0).map(([o])=>o);function a(o){if(o===e.length)return{line:t.length-1,character:t[t.length-1].length};let n=o,s=0;for(let i of t){if(n<i.length)break;n-=i.length,s++}return{line:s,character:n}}function r(o,n){let s=0;for(let i=0;i<o;i++)s+=t[i].length;return s+=n,s}return{lines:t,indexToPos:a,posToIndex:r}}function ed(e,t,a){let r=new Set;for(let n of e.matchAll(/:?lang=["']([^"']+)["']/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/\\begin\{([\w-]+)\}/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let s=n[1].toLowerCase().trim(),i=s.includes("/")?s.split("/").pop():s;i&&r.add(i)}if(!a)return Array.from(r);let o=a.getBundledLanguages();return Array.from(r).filter(n=>n&&o[n])}var Wn="light-dark()",mw=["color","background-color"];function hw(e,t){let a=0,r=[];for(let o of t)o>a&&r.push({...e,content:e.content.slice(a,o),offset:e.offset+a}),a=o;return a<e.content.length&&r.push({...e,content:e.content.slice(a),offset:e.offset+a}),r}function gw(e,t){let a=Array.from(t instanceof Set?t:new Set(t)).sort((r,o)=>r-o);return a.length?e.map(r=>r.flatMap(o=>{let n=a.filter(s=>o.offset<s&&s<o.offset+o.content.length).map(s=>s-o.offset).sort((s,i)=>s-i);return n.length?hw(o,n):o})):e}function ww(e,t,a,r,o="css-vars"){let n={content:e.content,explanation:e.explanation,offset:e.offset},s=t.map(d=>to(e.variants[d])),i=new Set(s.flatMap(d=>Object.keys(d))),l={},u=(d,c)=>{let p=c==="color"?"":c==="background-color"?"-bg":`-${c}`;return a+t[d]+(c==="color"?"":p)};return s.forEach((d,c)=>{for(let p of i){let f=d[p]||"inherit";if(c===0&&r&&mw.includes(p))if(r===Wn&&s.length>1){let m=t.findIndex(C=>C==="light"),y=t.findIndex(C=>C==="dark");if(m===-1||y===-1)throw new ve('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let S=s[m][p]||"inherit",L=s[y][p]||"inherit";l[p]=`light-dark(${S}, ${L})`,o==="css-vars"&&(l[u(c,p)]=f)}else l[p]=f;else o==="css-vars"&&(l[u(c,p)]=f)}}),n.htmlStyle=l,n}function to(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&Ue.Italic&&(t["font-style"]="italic"),e.fontStyle&Ue.Bold&&(t["font-weight"]="bold");let a=[];e.fontStyle&Ue.Underline&&a.push("underline"),e.fontStyle&Ue.Strikethrough&&a.push("line-through"),a.length&&(t["text-decoration"]=a.join(" "))}return t}function Un(e){return typeof e=="string"?e:Object.entries(e).map(([t,a])=>`${t}:${a}`).join(";")}var td=new WeakMap;function so(e,t){td.set(e,t)}function Ya(e){return td.get(e)}var da=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,a){return new e(Object.fromEntries(fw(a).map(r=>[r,Kr])),t)}constructor(...t){if(t.length===2){let[a,r]=t;this.lang=r,this._stacks=a}else{let[a,r,o]=t;this.lang=r,this._stacks={[o]:a}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return Iw(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Iw(e){let t=[],a=new Set;function r(o){if(a.has(o))return;a.add(o);let n=o?.nameScopesList?.scopeName;n&&t.push(n),o.parent&&r(o.parent)}return r(e),t}function xw(e,t){if(!(e instanceof da))throw new ve("Invalid grammar state");return e.getInternalStack(t)}function yw(){let e=new WeakMap;function t(a){if(!e.has(a.meta)){let r=function(s){if(typeof s=="number"){if(s<0||s>a.source.length)throw new ve(`Invalid decoration offset: ${s}. Code length: ${a.source.length}`);return{...o.indexToPos(s),offset:s}}else{let i=o.lines[s.line];if(i===void 0)throw new ve(`Invalid decoration position ${JSON.stringify(s)}. Lines length: ${o.lines.length}`);let l=s.character;if(l<0&&(l=i.length+l),l<0||l>i.length)throw new ve(`Invalid decoration position ${JSON.stringify(s)}. Line ${s.line} length: ${i.length}`);return{...s,character:l,offset:o.posToIndex(s.line,l)}}},o=pw(a.source),n=(a.options.decorations||[]).map(s=>({...s,start:r(s.start),end:r(s.end)}));Lw(n),e.set(a.meta,{decorations:n,converter:o,source:a.source})}return e.get(a.meta)}return{name:"shiki:decorations",tokens(a){if(!this.options.decorations?.length)return;let o=t(this).decorations.flatMap(s=>[s.start.offset,s.end.offset]);return gw(a,o)},code(a){if(!this.options.decorations?.length)return;let r=t(this),o=Array.from(a.children).filter(d=>d.type==="element"&&d.tagName==="span");if(o.length!==r.converter.lines.length)throw new ve(`Number of lines in code element (${o.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);function n(d,c,p,f){let m=o[d],y="",S=-1,L=-1;if(c===0&&(S=0),p===0&&(L=0),p===Number.POSITIVE_INFINITY&&(L=m.children.length),S===-1||L===-1)for(let I=0;I<m.children.length;I++)y+=ad(m.children[I]),S===-1&&y.length===c&&(S=I+1),L===-1&&y.length===p&&(L=I+1);if(S===-1)throw new ve(`Failed to find start index for decoration ${JSON.stringify(f.start)}`);if(L===-1)throw new ve(`Failed to find end index for decoration ${JSON.stringify(f.end)}`);let C=m.children.slice(S,L);if(!f.alwaysWrap&&C.length===m.children.length)i(m,f,"line");else if(!f.alwaysWrap&&C.length===1&&C[0].type==="element")i(C[0],f,"token");else{let I={type:"element",tagName:"span",properties:{},children:C};i(I,f,"wrapper"),m.children.splice(S,C.length,I)}}function s(d,c){o[d]=i(o[d],c,"line")}function i(d,c,p){let f=c.properties||{},m=c.transform||(y=>y);return d.tagName=c.tagName||"span",d.properties={...d.properties,...f,class:d.properties.class},c.properties?.class&&Zu(d,c.properties.class),d=m(d,p)||d,d}let l=[],u=r.decorations.sort((d,c)=>c.start.offset-d.start.offset||d.end.offset-c.end.offset);for(let d of u){let{start:c,end:p}=d;if(c.line===p.line)n(c.line,c.character,p.character,d);else if(c.line<p.line){n(c.line,c.character,Number.POSITIVE_INFINITY,d);for(let f=c.line+1;f<p.line;f++)l.unshift(()=>s(f,d));n(p.line,0,p.character,d)}}l.forEach(d=>d())}}}function Lw(e){for(let t=0;t<e.length;t++){let a=e[t];if(a.start.offset>a.end.offset)throw new ve(`Invalid decoration range: ${JSON.stringify(a.start)} - ${JSON.stringify(a.end)}`);for(let r=t+1;r<e.length;r++){let o=e[r],n=a.start.offset<=o.start.offset&&o.start.offset<a.end.offset,s=a.start.offset<o.end.offset&&o.end.offset<=a.end.offset,i=o.start.offset<=a.start.offset&&a.start.offset<o.end.offset,l=o.start.offset<a.end.offset&&a.end.offset<=o.end.offset;if(n||s||i||l){if(n&&s||i&&l||i&&a.start.offset===a.end.offset||s&&o.start.offset===o.end.offset)continue;throw new ve(`Decorations ${JSON.stringify(a.start)} and ${JSON.stringify(o.start)} intersect.`)}}}}function ad(e){return e.type==="text"?e.value:e.type==="element"?e.children.map(ad).join(""):""}var Sw=[yw()];function ao(e){let t=Cw(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...Sw]}function Cw(e){let t=[],a=[],r=[];for(let o of e)switch(o.enforce){case"pre":t.push(o);break;case"post":a.push(o);break;default:r.push(o)}return{pre:t,post:a,normal:r}}var Gt=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],Bn={1:"bold",2:"dim",3:"italic",4:"underline",7:"reverse",8:"hidden",9:"strikethrough"};function bw(e,t){let a=e.indexOf("\x1B",t);if(a!==-1&&e[a+1]==="["){let r=e.indexOf("m",a);if(r!==-1)return{sequence:e.substring(a+2,r).split(";"),startPosition:a,position:r+1}}return{position:e.length}}function ju(e){let t=e.shift();if(t==="2"){let a=e.splice(0,3).map(r=>Number.parseInt(r));return a.length!==3||a.some(r=>Number.isNaN(r))?void 0:{type:"rgb",rgb:a}}else if(t==="5"){let a=e.shift();if(a)return{type:"table",index:Number(a)}}}function vw(e){let t=[];for(;e.length>0;){let a=e.shift();if(!a)continue;let r=Number.parseInt(a);if(!Number.isNaN(r))if(r===0)t.push({type:"resetAll"});else if(r<=9)Bn[r]&&t.push({type:"setDecoration",value:Bn[r]});else if(r<=29){let o=Bn[r-20];o&&(t.push({type:"resetDecoration",value:o}),o==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(r<=37)t.push({type:"setForegroundColor",value:{type:"named",name:Gt[r-30]}});else if(r===38){let o=ju(e);o&&t.push({type:"setForegroundColor",value:o})}else if(r===39)t.push({type:"resetForegroundColor"});else if(r<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:Gt[r-40]}});else if(r===48){let o=ju(e);o&&t.push({type:"setBackgroundColor",value:o})}else r===49?t.push({type:"resetBackgroundColor"}):r===53?t.push({type:"setDecoration",value:"overline"}):r===55?t.push({type:"resetDecoration",value:"overline"}):r>=90&&r<=97?t.push({type:"setForegroundColor",value:{type:"named",name:Gt[r-90+8]}}):r>=100&&r<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:Gt[r-100+8]}})}return t}function kw(){let e=null,t=null,a=new Set;return{parse(r){let o=[],n=0;do{let s=bw(r,n),i=s.sequence?r.substring(n,s.startPosition):r.substring(n);if(i.length>0&&o.push({value:i,foreground:e,background:t,decorations:new Set(a)}),s.sequence){let l=vw(s.sequence);for(let u of l)u.type==="resetAll"?(e=null,t=null,a.clear()):u.type==="resetForegroundColor"?e=null:u.type==="resetBackgroundColor"?t=null:u.type==="resetDecoration"&&a.delete(u.value);for(let u of l)u.type==="setForegroundColor"?e=u.value:u.type==="setBackgroundColor"?t=u.value:u.type==="setDecoration"&&a.add(u.value)}n=s.position}while(n<r.length);return o}}}var Tw={black:"#000000",red:"#bb0000",green:"#00bb00",yellow:"#bbbb00",blue:"#0000bb",magenta:"#ff00ff",cyan:"#00bbbb",white:"#eeeeee",brightBlack:"#555555",brightRed:"#ff5555",brightGreen:"#00ff00",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"};function Aw(e=Tw){function t(i){return e[i]}function a(i){return`#${i.map(l=>Math.max(0,Math.min(l,255)).toString(16).padStart(2,"0")).join("")}`}let r;function o(){if(r)return r;r=[];for(let u=0;u<Gt.length;u++)r.push(t(Gt[u]));let i=[0,95,135,175,215,255];for(let u=0;u<6;u++)for(let d=0;d<6;d++)for(let c=0;c<6;c++)r.push(a([i[u],i[d],i[c]]));let l=8;for(let u=0;u<24;u++,l+=10)r.push(a([l,l,l]));return r}function n(i){return o()[i]}function s(i){switch(i.type){case"named":return t(i.name);case"rgb":return a(i.rgb);case"table":return n(i.index)}}return{value:s}}var Pw={black:"#000000",red:"#cd3131",green:"#0DBC79",yellow:"#E5E510",blue:"#2472C8",magenta:"#BC3FBC",cyan:"#11A8CD",white:"#E5E5E5",brightBlack:"#666666",brightRed:"#F14C4C",brightGreen:"#23D18B",brightYellow:"#F5F543",brightBlue:"#3B8EEA",brightMagenta:"#D670D6",brightCyan:"#29B8DB",brightWhite:"#FFFFFF"};function Rw(e,t,a){let r=eo(e,a),o=no(t),n=Object.fromEntries(Gt.map(l=>{let u=`terminal.ansi${l[0].toUpperCase()}${l.substring(1)}`,d=e.colors?.[u];return[l,d||Pw[l]]})),s=Aw(n),i=kw();return o.map(l=>i.parse(l[0]).map(u=>{let d,c;u.decorations.has("reverse")?(d=u.background?s.value(u.background):e.bg,c=u.foreground?s.value(u.foreground):e.fg):(d=u.foreground?s.value(u.foreground):e.fg,c=u.background?s.value(u.background):void 0),d=Mt(d,r),c=Mt(c,r),u.decorations.has("dim")&&(d=Ew(d));let p=Ue.None;return u.decorations.has("bold")&&(p|=Ue.Bold),u.decorations.has("italic")&&(p|=Ue.Italic),u.decorations.has("underline")&&(p|=Ue.Underline),u.decorations.has("strikethrough")&&(p|=Ue.Strikethrough),{content:u.value,offset:l[1],color:d,bgColor:c,fontStyle:p}}))}function Ew(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let r=t[1];if(r.length===8){let o=Math.round(Number.parseInt(r.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${r.slice(0,6)}${o}`}else{if(r.length===6)return`#${r}80`;if(r.length===4){let o=r[0],n=r[1],s=r[2],i=r[3],l=Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,"0");return`#${o}${o}${n}${n}${s}${s}${l}`}else if(r.length===3){let o=r[0],n=r[1],s=r[2];return`#${o}${o}${n}${n}${s}${s}80`}}}let a=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return a?`var(${a[1]}-dim)`:e}function jn(e,t,a={}){let{theme:r=e.getLoadedThemes()[0]}=a,o=e.resolveLangAlias(a.lang||"text");if(Hn(o)||$n(r))return no(t).map(l=>[{content:l[0],offset:l[1]}]);let{theme:n,colorMap:s}=e.setTheme(r);if(o==="ansi")return Rw(n,t,a);let i=e.getLanguage(a.lang||"text");if(a.grammarState){if(a.grammarState.lang!==i.name)throw new ve(`Grammar state language "${a.grammarState.lang}" does not match highlight language "${i.name}"`);if(!a.grammarState.themes.includes(n.name))throw new ve(`Grammar state themes "${a.grammarState.themes}" do not contain highlight theme "${n.name}"`)}return Fw(t,i,n,s,a)}function Mw(...e){if(e.length===2)return Ya(e[1]);let[t,a,r={}]=e,{lang:o="text",theme:n=t.getLoadedThemes()[0]}=r;if(Hn(o)||$n(n))throw new ve("Plain language does not have grammar state");if(o==="ansi")throw new ve("ANSI language does not have grammar state");let{theme:s,colorMap:i}=t.setTheme(n),l=t.getLanguage(o);return new da(zn(a,l,s,i,r).stateStack,l.name,s.name)}function Fw(e,t,a,r,o){let n=zn(e,t,a,r,o),s=new da(n.stateStack,t.name,a.name);return so(n.tokens,s),n.tokens}function zn(e,t,a,r,o){let n=eo(a,o),{tokenizeMaxLineLength:s=0,tokenizeTimeLimit:i=500}=o,l=no(e),u=o.grammarState?xw(o.grammarState,a.name)??Kr:o.grammarContextCode!=null?zn(o.grammarContextCode,t,a,r,{...o,grammarState:void 0,grammarContextCode:void 0}).stateStack:Kr,d=[],c=[];for(let p=0,f=l.length;p<f;p++){let[m,y]=l[p];if(m===""){d=[],c.push([]);continue}if(s>0&&m.length>=s){d=[],c.push([{content:m,offset:y,color:"",fontStyle:0}]);continue}let S,L,C;o.includeExplanation&&(S=t.tokenizeLine(m,u,i),L=S.tokens,C=0);let I=t.tokenizeLine2(m,u,i),x=I.tokens.length/2;for(let v=0;v<x;v++){let q=I.tokens[2*v],N=v+1<x?I.tokens[2*v+2]:m.length;if(q===N)continue;let V=I.tokens[2*v+1],G=Mt(r[Vt.getForeground(V)],n),Q=Vt.getFontStyle(V),O={content:m.substring(q,N),offset:y+q,color:G,fontStyle:Q};if(o.includeExplanation){let re=[];if(o.includeExplanation!=="scopeName")for(let J of a.settings){let X;switch(typeof J.scope){case"string":X=J.scope.split(/,/).map(R=>R.trim());break;case"object":X=J.scope;break;default:continue}re.push({settings:J,selectors:X.map(R=>R.split(/ /))})}O.explanation=[];let K=0;for(;q+K<N;){let J=L[C],X=m.substring(J.startIndex,J.endIndex);K+=X.length,O.explanation.push({content:X,scopes:o.includeExplanation==="scopeName"?_w(J.scopes):Dw(re,J.scopes)}),C+=1}}d.push(O)}c.push(d),d=[],u=I.ruleStack}return{tokens:c,stateStack:u}}function _w(e){return e.map(t=>({scopeName:t}))}function Dw(e,t){let a=[];for(let r=0,o=t.length;r<o;r++){let n=t[r];a[r]={scopeName:n,themeMatches:Ow(e,n,t.slice(0,r))}}return a}function zu(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]==="."}function Bw(e,t,a){if(!zu(e[e.length-1],t))return!1;let r=e.length-2,o=a.length-1;for(;r>=0&&o>=0;)zu(e[r],a[o])&&(r-=1),o-=1;return r===-1}function Ow(e,t,a){let r=[];for(let{selectors:o,settings:n}of e)for(let s of o)if(Bw(s,t,a)){r.push(n);break}return r}function rd(e,t,a){let r=Object.entries(a.themes).filter(l=>l[1]).map(l=>({color:l[0],theme:l[1]})),o=r.map(l=>{let u=jn(e,t,{...a,theme:l.theme}),d=Ya(u),c=typeof l.theme=="string"?l.theme:l.theme.name;return{tokens:u,state:d,theme:c}}),n=Uw(...o.map(l=>l.tokens)),s=n[0].map((l,u)=>l.map((d,c)=>{let p={content:d.content,variants:{},offset:d.offset};return"includeExplanation"in a&&a.includeExplanation&&(p.explanation=d.explanation),n.forEach((f,m)=>{let{content:y,explanation:S,offset:L,...C}=f[u][c];p.variants[r[m].color]=C}),p})),i=o[0].state?new da(Object.fromEntries(o.map(l=>[l.theme,l.state?.getInternalStack(l.theme)])),o[0].state.lang):void 0;return i&&so(s,i),s}function Uw(...e){let t=e.map(()=>[]),a=e.length;for(let r=0;r<e[0].length;r++){let o=e.map(l=>l[r]),n=t.map(()=>[]);t.forEach((l,u)=>l.push(n[u]));let s=o.map(()=>0),i=o.map(l=>l[0]);for(;i.every(l=>l);){let l=Math.min(...i.map(u=>u.content.length));for(let u=0;u<a;u++){let d=i[u];d.content.length===l?(n[u].push(d),s[u]+=1,i[u]=o[u][s[u]]):(n[u].push({...d,content:d.content.slice(0,l)}),i[u]={...d,content:d.content.slice(l),offset:d.offset+l})}}}return t}function ro(e,t,a){let r,o,n,s,i,l;if("themes"in a){let{defaultColor:u="light",cssVariablePrefix:d="--shiki-",colorsRendering:c="css-vars"}=a,p=Object.entries(a.themes).filter(L=>L[1]).map(L=>({color:L[0],theme:L[1]})).sort((L,C)=>L.color===u?-1:C.color===u?1:0);if(p.length===0)throw new ve("`themes` option must not be empty");let f=rd(e,t,a);if(l=Ya(f),u&&Wn!==u&&!p.find(L=>L.color===u))throw new ve(`\`themes\` option must contain the defaultColor key \`${u}\``);let m=p.map(L=>e.getTheme(L.theme)),y=p.map(L=>L.color);n=f.map(L=>L.map(C=>ww(C,y,d,u,c))),l&&so(n,l);let S=p.map(L=>eo(L.theme,a));o=Vu(p,m,S,d,u,"fg",c),r=Vu(p,m,S,d,u,"bg",c),s=`shiki-themes ${m.map(L=>L.name).join(" ")}`,i=u?void 0:[o,r].join(";")}else if("theme"in a){let u=eo(a.theme,a);n=jn(e,t,a);let d=e.getTheme(a.theme);r=Mt(d.bg,u),o=Mt(d.fg,u),s=d.name,l=Ya(n)}else throw new ve("Invalid options, either `theme` or `themes` must be provided");return{tokens:n,fg:o,bg:r,themeName:s,rootStyle:i,grammarState:l}}function Vu(e,t,a,r,o,n,s){return e.map((i,l)=>{let u=Mt(t[l][n],a[l])||"inherit",d=`${r+i.color}${n==="bg"?"-bg":""}:${u}`;if(l===0&&o){if(o===Wn&&e.length>1){let c=e.findIndex(y=>y.color==="light"),p=e.findIndex(y=>y.color==="dark");if(c===-1||p===-1)throw new ve('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let f=Mt(t[c][n],a[c])||"inherit",m=Mt(t[p][n],a[p])||"inherit";return`light-dark(${f}, ${m});${d}`}return u}return s==="css-vars"?d:null}).filter(i=>!!i).join(";")}function oo(e,t,a,r={meta:{},options:a,codeToHast:(o,n)=>oo(e,o,n),codeToTokens:(o,n)=>ro(e,o,n)}){let o=t;for(let m of ao(a))o=m.preprocess?.call(r,o,a)||o;let{tokens:n,fg:s,bg:i,themeName:l,rootStyle:u,grammarState:d}=ro(e,o,a),{mergeWhitespaces:c=!0,mergeSameStyleTokens:p=!1}=a;c===!0?n=qw(n):c==="never"&&(n=Hw(n)),p&&(n=$w(n));let f={...r,get source(){return o}};for(let m of ao(a))n=m.tokens?.call(f,n)||n;return Nw(n,{...a,fg:s,bg:i,themeName:l,rootStyle:a.rootStyle===!1?!1:a.rootStyle??u},f,d)}function Nw(e,t,a,r=Ya(e)){let o=ao(t),n=[],s={type:"root",children:[]},{structure:i="classic",tabindex:l="0"}=t,u={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?u.style=t.rootStyle:u.style=`background-color:${t.bg};color:${t.fg}`),l!==!1&&l!=null&&(u.tabindex=l.toString());for(let[y,S]of Object.entries(t.meta||{}))y.startsWith("_")||(u[y]=S);let d={type:"element",tagName:"pre",properties:u,children:[],data:t.data},c={type:"element",tagName:"code",properties:{},children:n},p=[],f={...a,structure:i,addClassToHast:Zu,get source(){return a.source},get tokens(){return e},get options(){return t},get root(){return s},get pre(){return d},get code(){return c},get lines(){return p}};if(e.forEach((y,S)=>{S&&(i==="inline"?s.children.push({type:"element",tagName:"br",properties:{},children:[]}):i==="classic"&&n.push({type:"text",value:`
|
|
15
|
-
`}));let L={type:"element",tagName:"span",properties:{class:"line"},children:[]},C=0;for(let I of y){let x={type:"element",tagName:"span",properties:{...I.htmlAttrs},children:[{type:"text",value:I.content}]},v=Un(I.htmlStyle||to(I));v&&(x.properties.style=v);for(let q of o)x=q?.span?.call(f,x,S+1,C,L,I)||x;i==="inline"?s.children.push(x):i==="classic"&&L.children.push(x),C+=I.content.length}if(i==="classic"){for(let I of o)L=I?.line?.call(f,L,S+1)||L;p.push(L),n.push(L)}else i==="inline"&&p.push(L)}),i==="classic"){for(let y of o)c=y?.code?.call(f,c)||c;d.children.push(c);for(let y of o)d=y?.pre?.call(f,d)||d;s.children.push(d)}else if(i==="inline"){let y=[],S={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let I of s.children)I.type==="element"&&I.tagName==="br"?(y.push(S),S={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(I.type==="element"||I.type==="text")&&S.children.push(I);y.push(S);let C={type:"element",tagName:"code",properties:{},children:y};for(let I of o)C=I?.code?.call(f,C)||C;s.children=[];for(let I=0;I<C.children.length;I++){I>0&&s.children.push({type:"element",tagName:"br",properties:{},children:[]});let x=C.children[I];x.type==="element"&&s.children.push(...x.children)}}let m=s;for(let y of o)m=y?.root?.call(f,m)||m;return r&&so(m,r),m}function qw(e){return e.map(t=>{let a=[],r="",o;return t.forEach((n,s)=>{let l=!(n.fontStyle&&(n.fontStyle&Ue.Underline||n.fontStyle&Ue.Strikethrough));l&&n.content.match(/^\s+$/)&&t[s+1]?(o===void 0&&(o=n.offset),r+=n.content):r?(l?a.push({...n,offset:o,content:r+n.content}):a.push({content:r,offset:o},n),o=void 0,r=""):a.push(n)}),a})}function Hw(e){return e.map(t=>t.flatMap(a=>{if(a.content.match(/^\s+$/))return a;let r=a.content.match(/^(\s*)(.*?)(\s*)$/);if(!r)return a;let[,o,n,s]=r;if(!o&&!s)return a;let i=[{...a,offset:a.offset+o.length,content:n}];return o&&i.unshift({content:o,offset:a.offset}),s&&i.push({content:s,offset:a.offset+o.length+n.length}),i}))}function $w(e){return e.map(t=>{let a=[];for(let r of t){if(a.length===0){a.push({...r});continue}let o=a[a.length-1],n=Un(o.htmlStyle||to(o)),s=Un(r.htmlStyle||to(r)),i=o.fontStyle&&(o.fontStyle&Ue.Underline||o.fontStyle&Ue.Strikethrough),l=r.fontStyle&&(r.fontStyle&Ue.Underline||r.fontStyle&Ue.Strikethrough);!i&&!l&&n===s?o.content+=r.content:a.push({...r})}return a})}var Ww=Dn;function jw(e,t,a){let r={meta:{},options:a,codeToHast:(n,s)=>oo(e,n,s),codeToTokens:(n,s)=>ro(e,n,s)},o=Ww(oo(e,t,a,r));for(let n of ao(a))o=n.postprocess?.call(r,o,a)||o;return o}var Gu={light:"#333333",dark:"#bbbbbb"},Ku={light:"#fffffe",dark:"#1e1e1e"},Xu="__shiki_resolved";function Vn(e){if(e?.[Xu])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||="dark",t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:a,fg:r}=t;if(!a||!r){let i=t.settings?t.settings.find(l=>!l.name&&!l.scope):void 0;i?.settings?.foreground&&(r=i.settings.foreground),i?.settings?.background&&(a=i.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!a&&t?.colors?.["editor.background"]&&(a=t.colors["editor.background"]),r||(r=t.type==="light"?Gu.light:Gu.dark),a||(a=t.type==="light"?Ku.light:Ku.dark),t.fg=r,t.bg=a}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let o=0,n=new Map;function s(i){if(n.has(i))return n.get(i);o+=1;let l=`#${o.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${l}`]?s(i):(n.set(i,l),l)}t.settings=t.settings.map(i=>{let l=i.settings?.foreground&&!i.settings.foreground.startsWith("#"),u=i.settings?.background&&!i.settings.background.startsWith("#");if(!l&&!u)return i;let d={...i,settings:{...i.settings}};if(l){let c=s(i.settings.foreground);t.colorReplacements[c]=i.settings.foreground,d.settings.foreground=c}if(u){let c=s(i.settings.background);t.colorReplacements[c]=i.settings.background,d.settings.background=c}return d});for(let i of Object.keys(t.colors||{}))if((i==="editor.foreground"||i==="editor.background"||i.startsWith("terminal.ansi"))&&!t.colors[i]?.startsWith("#")){let l=s(t.colors[i]);t.colorReplacements[l]=t.colors[i],t.colors[i]=l}return Object.defineProperty(t,Xu,{enumerable:!1,writable:!1,value:!0}),t}async function od(e){return Array.from(new Set((await Promise.all(e.filter(t=>!Qu(t)).map(async t=>await Ju(t).then(a=>Array.isArray(a)?a:[a])))).flat()))}async function nd(e){return(await Promise.all(e.map(async a=>Yu(a)?null:Vn(await Ju(a))))).filter(a=>!!a)}var On=3,zw=!1;function Vw(e,t=3){if(On&&!(typeof On=="number"&&t>On)){if(zw)throw new Error(`[SHIKI DEPRECATE]: ${e}`);console.trace(`[SHIKI DEPRECATE]: ${e}`)}}var Et=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function sd(e,t){if(!t)return e;if(t[e]){let a=new Set([e]);for(;t[e];){if(e=t[e],a.has(e))throw new Et(`Circular alias \`${Array.from(a).join(" -> ")} -> ${e}\``);a.add(e)}}return e}var Nn=class extends bu{constructor(t,a,r,o={}){super(t),this._resolver=t,this._themes=a,this._langs=r,this._alias=o,this._themes.map(n=>this.loadTheme(n)),this.loadLanguages(this._langs)}_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;getTheme(t){return typeof t=="string"?this._resolvedThemes.get(t):this.loadTheme(t)}loadTheme(t){let a=Vn(t);return a.name&&(this._resolvedThemes.set(a.name,a),this._loadedThemesCache=null),a}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(t){let a=this._textmateThemeCache.get(t);a||(a=za.createFromRawTheme(t),this._textmateThemeCache.set(t,a)),this._syncRegistry.setTheme(a)}getGrammar(t){return t=sd(t,this._alias),this._resolvedGrammars.get(t)}loadLanguage(t){if(this.getGrammar(t.name))return;let a=new Set([...this._langMap.values()].filter(n=>n.embeddedLangsLazy?.includes(t.name)));this._resolver.addLanguage(t);let r={balancedBracketSelectors:t.balancedBracketSelectors||["*"],unbalancedBracketSelectors:t.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(t.scopeName,t);let o=this.loadGrammarWithConfiguration(t.scopeName,1,r);if(o.name=t.name,this._resolvedGrammars.set(t.name,o),t.aliases&&t.aliases.forEach(n=>{this._alias[n]=t.name}),this._loadedLanguagesCache=null,a.size)for(let n of a)this._resolvedGrammars.delete(n.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(n.scopeName),this._syncRegistry?._grammars?.delete(n.scopeName),this.loadLanguage(this._langMap.get(n.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(t){for(let o of t)this.resolveEmbeddedLanguages(o);let a=Array.from(this._langGraph.entries()),r=a.filter(([o,n])=>!n);if(r.length){let o=a.filter(([n,s])=>s?(s.embeddedLanguages||s.embeddedLangs)?.some(l=>r.map(([u])=>u).includes(l)):!1).filter(n=>!r.includes(n));throw new Et(`Missing languages ${r.map(([n])=>`\`${n}\``).join(", ")}, required by ${o.map(([n])=>`\`${n}\``).join(", ")}`)}for(let[o,n]of a)this._resolver.addLanguage(n);for(let[o,n]of a)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(t){this._langMap.set(t.name,t),this._langGraph.set(t.name,t);let a=t.embeddedLanguages??t.embeddedLangs;if(a)for(let r of a)this._langGraph.set(r,this._langMap.get(r))}},qn=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(t,a){this._onigLib={createOnigScanner:r=>t.createScanner(r),createOnigString:r=>t.createString(r)},a.forEach(r=>this.addLanguage(r))}get onigLib(){return this._onigLib}getLangRegistration(t){return this._langs.get(t)}loadGrammar(t){return this._scopeToLang.get(t)}addLanguage(t){this._langs.set(t.name,t),t.aliases&&t.aliases.forEach(a=>{this._langs.set(a,t)}),this._scopeToLang.set(t.scopeName,t),t.injectTo&&t.injectTo.forEach(a=>{this._injections.get(a)||this._injections.set(a,[]),this._injections.get(a).push(t.scopeName)})}getInjections(t){let a=t.split("."),r=[];for(let o=1;o<=a.length;o++){let n=a.slice(0,o).join(".");r=[...r,...this._injections.get(n)||[]]}return r}},Qa=0;function Gw(e){Qa+=1,e.warnings!==!1&&Qa>=10&&Qa%10===0&&console.warn(`[Shiki] ${Qa} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new Et("`engine` option is required for synchronous mode");let a=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(Vn),o=new qn(e.engine,a),n=new Nn(o,r,a,e.langAlias),s;function i(I){return sd(I,e.langAlias)}function l(I){L();let x=n.getGrammar(typeof I=="string"?I:I.name);if(!x)throw new Et(`Language \`${I}\` not found, you may need to load it first`);return x}function u(I){if(I==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};L();let x=n.getTheme(I);if(!x)throw new Et(`Theme \`${I}\` not found, you may need to load it first`);return x}function d(I){L();let x=u(I);s!==I&&(n.setTheme(x),s=I);let v=n.getColorMap();return{theme:x,colorMap:v}}function c(){return L(),n.getLoadedThemes()}function p(){return L(),n.getLoadedLanguages()}function f(...I){L(),n.loadLanguages(I.flat(1))}async function m(...I){return f(await od(I))}function y(...I){L();for(let x of I.flat(1))n.loadTheme(x)}async function S(...I){return L(),y(await nd(I))}function L(){if(t)throw new Et("Shiki instance has been disposed")}function C(){t||(t=!0,n.dispose(),Qa-=1)}return{setTheme:d,getTheme:u,getLanguage:l,getLoadedThemes:c,getLoadedLanguages:p,resolveLangAlias:i,loadLanguage:m,loadLanguageSync:f,loadTheme:S,loadThemeSync:y,dispose:C,[Symbol.dispose]:C}}async function Kw(e){e.engine||Vw("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,a,r]=await Promise.all([nd(e.themes||[]),od(e.langs||[]),e.engine]);return Gw({...e,themes:t,langs:a,engine:r})}async function Xw(e){let t=await Kw(e);return{getLastGrammarState:(...a)=>Mw(t,...a),codeToTokensBase:(a,r)=>jn(t,a,r),codeToTokensWithThemes:(a,r)=>rd(t,a,r),codeToTokens:(a,r)=>ro(t,a,r),codeToHast:(a,r)=>oo(t,a,r),codeToHtml:(a,r)=>jw(t,a,r),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function id(e){let t=e.langs,a=e.themes,r=e.engine;async function o(n){function s(c){if(typeof c=="string"){if(c=n.langAlias?.[c]||c,Qu(c))return[];let p=t[c];if(!p)throw new ve(`Language \`${c}\` is not included in this bundle. You may want to load it from external source.`);return p}return c}function i(c){if(Yu(c))return"none";if(typeof c=="string"){let p=a[c];if(!p)throw new ve(`Theme \`${c}\` is not included in this bundle. You may want to load it from external source.`);return p}return c}let l=(n.themes??[]).map(c=>i(c)),u=(n.langs??[]).map(c=>s(c)),d=await Xw({engine:n.engine??r(),...n,themes:l,langs:u});return{...d,loadLanguage(...c){return d.loadLanguage(...c.map(s))},loadTheme(...c){return d.loadTheme(...c.map(i))},getBundledLanguages(){return t},getBundledThemes(){return a}}}return o}function Jw(e){let t;async function a(r={}){if(t){let o=await t;return await Promise.all([o.loadTheme(...r.themes||[]),o.loadLanguage(...r.langs||[])]),o}else{t=e({...r,themes:[],langs:[]});let o=await t;return await Promise.all([o.loadTheme(...r.themes||[]),o.loadLanguage(...r.langs||[])]),o}}return a}function ld(e,t){let a=Jw(e);async function r(o,n){let s=await a({langs:[n.lang],themes:"theme"in n?[n.theme]:Object.values(n.themes)}),i=await t?.guessEmbeddedLanguages?.(o,n.lang,s);return i&&await s.loadLanguage(...i),s}return{getSingletonHighlighter(o){return a(o)},async codeToHtml(o,n){return(await r(o,n)).codeToHtml(o,n)},async codeToHast(o,n){return(await r(o,n)).codeToHast(o,n)},async codeToTokens(o,n){return(await r(o,n)).codeToTokens(o,n)},async codeToTokensBase(o,n){return(await r(o,n)).codeToTokensBase(o,n)},async codeToTokensWithThemes(o,n){return(await r(o,n)).codeToTokensWithThemes(o,n)},async getLastGrammarState(o,n){return(await a({langs:[n.lang],themes:[n.theme]})).getLastGrammarState(o,n)}}}var Gn=[{id:"abap",name:"ABAP",import:(()=>import("../abap-KGVIZMDC.js"))},{id:"actionscript-3",name:"ActionScript",import:(()=>import("../actionscript-3-2UHK5QYP.js"))},{id:"ada",name:"Ada",import:(()=>import("../ada-JKTWR5BV.js"))},{id:"angular-html",name:"Angular HTML",import:(()=>import("../angular-html-PU3MXNBE.js"))},{id:"angular-ts",name:"Angular TypeScript",import:(()=>import("../angular-ts-WMZKXXGP.js"))},{id:"apache",name:"Apache Conf",import:(()=>import("../apache-MPGFGQFB.js"))},{id:"apex",name:"Apex",import:(()=>import("../apex-BOAZL66Z.js"))},{id:"apl",name:"APL",import:(()=>import("../apl-YU3KF3Y6.js"))},{id:"applescript",name:"AppleScript",import:(()=>import("../applescript-C4CJ3STL.js"))},{id:"ara",name:"Ara",import:(()=>import("../ara-FSFFBRSD.js"))},{id:"asciidoc",name:"AsciiDoc",aliases:["adoc"],import:(()=>import("../asciidoc-QQK2LANG.js"))},{id:"asm",name:"Assembly",import:(()=>import("../asm-X43A2VYW.js"))},{id:"astro",name:"Astro",import:(()=>import("../astro-BMSTTQT4.js"))},{id:"awk",name:"AWK",import:(()=>import("../awk-4Z3PRTF7.js"))},{id:"ballerina",name:"Ballerina",import:(()=>import("../ballerina-JCXSJ2QD.js"))},{id:"bat",name:"Batch File",aliases:["batch"],import:(()=>import("../bat-XFWR7RMZ.js"))},{id:"beancount",name:"Beancount",import:(()=>import("../beancount-7BBDB4BH.js"))},{id:"berry",name:"Berry",aliases:["be"],import:(()=>import("../berry-PQ2BEJIZ.js"))},{id:"bibtex",name:"BibTeX",import:(()=>import("../bibtex-J2PAB23I.js"))},{id:"bicep",name:"Bicep",import:(()=>import("../bicep-TNKT6R3W.js"))},{id:"blade",name:"Blade",import:(()=>import("../blade-YKL22AM4.js"))},{id:"bsl",name:"1C (Enterprise)",aliases:["1c"],import:(()=>import("../bsl-PQW6E45S.js"))},{id:"c",name:"C",import:(()=>import("../c-PZBJFNXE.js"))},{id:"c3",name:"C3",import:(()=>import("../c3-GP7XYHE6.js"))},{id:"cadence",name:"Cadence",aliases:["cdc"],import:(()=>import("../cadence-NABGDHKY.js"))},{id:"cairo",name:"Cairo",import:(()=>import("../cairo-WQSC2GLN.js"))},{id:"clarity",name:"Clarity",import:(()=>import("../clarity-NXNSINKX.js"))},{id:"clojure",name:"Clojure",aliases:["clj"],import:(()=>import("../clojure-Y57BKRMA.js"))},{id:"cmake",name:"CMake",import:(()=>import("../cmake-LVMEA3JZ.js"))},{id:"cobol",name:"COBOL",import:(()=>import("../cobol-YD3RINFS.js"))},{id:"codeowners",name:"CODEOWNERS",import:(()=>import("../codeowners-JYHOTXQS.js"))},{id:"codeql",name:"CodeQL",aliases:["ql"],import:(()=>import("../codeql-IWWSYR3L.js"))},{id:"coffee",name:"CoffeeScript",aliases:["coffeescript"],import:(()=>import("../coffee-NNDQ5QXC.js"))},{id:"common-lisp",name:"Common Lisp",aliases:["lisp"],import:(()=>import("../common-lisp-JKXCDYH3.js"))},{id:"coq",name:"Coq",import:(()=>import("../coq-BEHPNP64.js"))},{id:"cpp",name:"C++",aliases:["c++"],import:(()=>import("../cpp-IALOHSZA.js"))},{id:"crystal",name:"Crystal",import:(()=>import("../crystal-AUUIRTAZ.js"))},{id:"csharp",name:"C#",aliases:["c#","cs"],import:(()=>import("../csharp-ODFBXRGA.js"))},{id:"css",name:"CSS",import:(()=>import("../css-CJGL5AVH.js"))},{id:"csv",name:"CSV",import:(()=>import("../csv-LIK4TU3Z.js"))},{id:"cue",name:"CUE",import:(()=>import("../cue-UAAEAKHI.js"))},{id:"cypher",name:"Cypher",aliases:["cql"],import:(()=>import("../cypher-SZPVUQZJ.js"))},{id:"d",name:"D",import:(()=>import("../d-VSCA3XHG.js"))},{id:"dart",name:"Dart",import:(()=>import("../dart-A4PE6FIS.js"))},{id:"dax",name:"DAX",import:(()=>import("../dax-TILIKSFB.js"))},{id:"desktop",name:"Desktop",import:(()=>import("../desktop-75KK3D55.js"))},{id:"diff",name:"Diff",import:(()=>import("../diff-HOT6P45M.js"))},{id:"docker",name:"Dockerfile",aliases:["dockerfile"],import:(()=>import("../docker-FF35TY6T.js"))},{id:"dotenv",name:"dotEnv",import:(()=>import("../dotenv-FVPPHJI3.js"))},{id:"dream-maker",name:"Dream Maker",import:(()=>import("../dream-maker-SYE3ZPSJ.js"))},{id:"edge",name:"Edge",import:(()=>import("../edge-44UF6IIM.js"))},{id:"elixir",name:"Elixir",import:(()=>import("../elixir-ZJ4WTHOY.js"))},{id:"elm",name:"Elm",import:(()=>import("../elm-5QRQXDZ6.js"))},{id:"emacs-lisp",name:"Emacs Lisp",aliases:["elisp"],import:(()=>import("../emacs-lisp-NJ4S4OHV.js"))},{id:"erb",name:"ERB",import:(()=>import("../erb-ZF7YKJP7.js"))},{id:"erlang",name:"Erlang",aliases:["erl"],import:(()=>import("../erlang-APEONNZ6.js"))},{id:"fennel",name:"Fennel",import:(()=>import("../fennel-7OCMFVPS.js"))},{id:"fish",name:"Fish",import:(()=>import("../fish-BC46ME2N.js"))},{id:"fluent",name:"Fluent",aliases:["ftl"],import:(()=>import("../fluent-MXZS6EX3.js"))},{id:"fortran-fixed-form",name:"Fortran (Fixed Form)",aliases:["f","for","f77"],import:(()=>import("../fortran-fixed-form-35BC2KX6.js"))},{id:"fortran-free-form",name:"Fortran (Free Form)",aliases:["f90","f95","f03","f08","f18"],import:(()=>import("../fortran-free-form-AXRAI2HH.js"))},{id:"fsharp",name:"F#",aliases:["f#","fs"],import:(()=>import("../fsharp-JKNSQXHD.js"))},{id:"gdresource",name:"GDResource",aliases:["tscn","tres"],import:(()=>import("../gdresource-ZMKZGPZV.js"))},{id:"gdscript",name:"GDScript",aliases:["gd"],import:(()=>import("../gdscript-HNCVXEYB.js"))},{id:"gdshader",name:"GDShader",import:(()=>import("../gdshader-XAJ4QRYP.js"))},{id:"genie",name:"Genie",import:(()=>import("../genie-HEFVQZAP.js"))},{id:"gherkin",name:"Gherkin",import:(()=>import("../gherkin-OFBRDPXX.js"))},{id:"git-commit",name:"Git Commit Message",import:(()=>import("../git-commit-ZE2M3Q5H.js"))},{id:"git-rebase",name:"Git Rebase Message",import:(()=>import("../git-rebase-3N3INGLU.js"))},{id:"gleam",name:"Gleam",import:(()=>import("../gleam-NFFQFQLP.js"))},{id:"glimmer-js",name:"Glimmer JS",aliases:["gjs"],import:(()=>import("../glimmer-js-TKADNZF5.js"))},{id:"glimmer-ts",name:"Glimmer TS",aliases:["gts"],import:(()=>import("../glimmer-ts-WFYWDU2O.js"))},{id:"glsl",name:"GLSL",import:(()=>import("../glsl-VJLRYEVJ.js"))},{id:"gn",name:"GN",import:(()=>import("../gn-UH2XQWLG.js"))},{id:"gnuplot",name:"Gnuplot",import:(()=>import("../gnuplot-K6IV6NNR.js"))},{id:"go",name:"Go",import:(()=>import("../go-BDV7RR5G.js"))},{id:"graphql",name:"GraphQL",aliases:["gql"],import:(()=>import("../graphql-NLMAEKLI.js"))},{id:"groovy",name:"Groovy",import:(()=>import("../groovy-SX7K3XGL.js"))},{id:"hack",name:"Hack",import:(()=>import("../hack-HCRIHDCF.js"))},{id:"haml",name:"Ruby Haml",import:(()=>import("../haml-335RVEQR.js"))},{id:"handlebars",name:"Handlebars",aliases:["hbs"],import:(()=>import("../handlebars-7EKNR6OR.js"))},{id:"haskell",name:"Haskell",aliases:["hs"],import:(()=>import("../haskell-P5PTJARU.js"))},{id:"haxe",name:"Haxe",import:(()=>import("../haxe-RCPSSA3N.js"))},{id:"hcl",name:"HashiCorp HCL",import:(()=>import("../hcl-AKKZAVC2.js"))},{id:"hjson",name:"Hjson",import:(()=>import("../hjson-REXV6F6N.js"))},{id:"hlsl",name:"HLSL",import:(()=>import("../hlsl-AJ7VWOVL.js"))},{id:"html",name:"HTML",import:(()=>import("../html-G4Q6FSTL.js"))},{id:"html-derivative",name:"HTML (Derivative)",import:(()=>import("../html-derivative-2AGKXLI2.js"))},{id:"http",name:"HTTP",import:(()=>import("../http-7ZVVH3VM.js"))},{id:"hurl",name:"Hurl",import:(()=>import("../hurl-B6WXEN45.js"))},{id:"hxml",name:"HXML",import:(()=>import("../hxml-5BXJCAAU.js"))},{id:"hy",name:"Hy",import:(()=>import("../hy-SB4TMFE7.js"))},{id:"imba",name:"Imba",import:(()=>import("../imba-Y64MHYWP.js"))},{id:"ini",name:"INI",aliases:["properties"],import:(()=>import("../ini-J2OP4CNW.js"))},{id:"java",name:"Java",import:(()=>import("../java-MJKJ5GPP.js"))},{id:"javascript",name:"JavaScript",aliases:["js","cjs","mjs"],import:(()=>import("../javascript-IYAGHPR6.js"))},{id:"jinja",name:"Jinja",import:(()=>import("../jinja-K2EDFFOP.js"))},{id:"jison",name:"Jison",import:(()=>import("../jison-UYDZQBN5.js"))},{id:"json",name:"JSON",import:(()=>import("../json-5V4JESJO.js"))},{id:"json5",name:"JSON5",import:(()=>import("../json5-7SHUZD3R.js"))},{id:"jsonc",name:"JSON with Comments",import:(()=>import("../jsonc-X3Z34FN3.js"))},{id:"jsonl",name:"JSON Lines",import:(()=>import("../jsonl-6I3D2HM6.js"))},{id:"jsonnet",name:"Jsonnet",import:(()=>import("../jsonnet-PZEQIBYV.js"))},{id:"jssm",name:"JSSM",aliases:["fsl"],import:(()=>import("../jssm-GJJ25IKR.js"))},{id:"jsx",name:"JSX",import:(()=>import("../jsx-NI2J427C.js"))},{id:"julia",name:"Julia",aliases:["jl"],import:(()=>import("../julia-CPV3A4MM.js"))},{id:"kdl",name:"KDL",import:(()=>import("../kdl-IA7HA2TL.js"))},{id:"kotlin",name:"Kotlin",aliases:["kt","kts"],import:(()=>import("../kotlin-CCRMGYMI.js"))},{id:"kusto",name:"Kusto",aliases:["kql"],import:(()=>import("../kusto-7DW25GYH.js"))},{id:"latex",name:"LaTeX",import:(()=>import("../latex-F2CTDTFG.js"))},{id:"lean",name:"Lean 4",aliases:["lean4"],import:(()=>import("../lean-MGJJWBTR.js"))},{id:"less",name:"Less",import:(()=>import("../less-WFSIMX5G.js"))},{id:"liquid",name:"Liquid",import:(()=>import("../liquid-YEOV5OY7.js"))},{id:"llvm",name:"LLVM IR",import:(()=>import("../llvm-CFQSEDXB.js"))},{id:"log",name:"Log file",import:(()=>import("../log-YQNML6LA.js"))},{id:"logo",name:"Logo",import:(()=>import("../logo-2PPKBL2M.js"))},{id:"lua",name:"Lua",import:(()=>import("../lua-RPAMRKNG.js"))},{id:"luau",name:"Luau",import:(()=>import("../luau-GR2DOH6N.js"))},{id:"make",name:"Makefile",aliases:["makefile"],import:(()=>import("../make-DQQEEPI4.js"))},{id:"markdown",name:"Markdown",aliases:["md"],import:(()=>import("../markdown-OC5ILZSY.js"))},{id:"marko",name:"Marko",import:(()=>import("../marko-XSB3CTWQ.js"))},{id:"matlab",name:"MATLAB",import:(()=>import("../matlab-YQY6FS4U.js"))},{id:"mdc",name:"MDC",import:(()=>import("../mdc-I5IJFJ2O.js"))},{id:"mdx",name:"MDX",import:(()=>import("../mdx-ZIH2JLVR.js"))},{id:"mermaid",name:"Mermaid",aliases:["mmd"],import:(()=>import("../mermaid-WPX56SBB.js"))},{id:"mipsasm",name:"MIPS Assembly",aliases:["mips"],import:(()=>import("../mipsasm-IDXQRZ2B.js"))},{id:"mojo",name:"Mojo",import:(()=>import("../mojo-MH7EQVOK.js"))},{id:"moonbit",name:"MoonBit",aliases:["mbt","mbti"],import:(()=>import("../moonbit-5JDFTWKE.js"))},{id:"move",name:"Move",import:(()=>import("../move-RWSXKYDY.js"))},{id:"narrat",name:"Narrat Language",aliases:["nar"],import:(()=>import("../narrat-QJUEXMVV.js"))},{id:"nextflow",name:"Nextflow",aliases:["nf"],import:(()=>import("../nextflow-2EICNZA3.js"))},{id:"nginx",name:"Nginx",import:(()=>import("../nginx-RIWAEC5Z.js"))},{id:"nim",name:"Nim",import:(()=>import("../nim-JXWLGPJS.js"))},{id:"nix",name:"Nix",import:(()=>import("../nix-XCKQVWCN.js"))},{id:"nushell",name:"nushell",aliases:["nu"],import:(()=>import("../nushell-QGW7HANA.js"))},{id:"objective-c",name:"Objective-C",aliases:["objc"],import:(()=>import("../objective-c-V7KYXFHL.js"))},{id:"objective-cpp",name:"Objective-C++",import:(()=>import("../objective-cpp-NKUEWVGU.js"))},{id:"ocaml",name:"OCaml",import:(()=>import("../ocaml-QT2CZJZN.js"))},{id:"odin",name:"Odin",import:(()=>import("../odin-MVMIXBHP.js"))},{id:"openscad",name:"OpenSCAD",aliases:["scad"],import:(()=>import("../openscad-BJDUXUUZ.js"))},{id:"pascal",name:"Pascal",import:(()=>import("../pascal-HGWEFD6L.js"))},{id:"perl",name:"Perl",import:(()=>import("../perl-HORNVRGS.js"))},{id:"php",name:"PHP",import:(()=>import("../php-JGPDZKQ3.js"))},{id:"pkl",name:"Pkl",import:(()=>import("../pkl-VA5ZK5DW.js"))},{id:"plsql",name:"PL/SQL",import:(()=>import("../plsql-J7A7YWFH.js"))},{id:"po",name:"Gettext PO",aliases:["pot","potx"],import:(()=>import("../po-5RDI65JX.js"))},{id:"polar",name:"Polar",import:(()=>import("../polar-VUJL2E7F.js"))},{id:"postcss",name:"PostCSS",import:(()=>import("../postcss-ESTB5G7N.js"))},{id:"powerquery",name:"PowerQuery",import:(()=>import("../powerquery-ODTEKQCW.js"))},{id:"powershell",name:"PowerShell",aliases:["ps","ps1"],import:(()=>import("../powershell-ZOYRAWBJ.js"))},{id:"prisma",name:"Prisma",import:(()=>import("../prisma-QHG2W5GE.js"))},{id:"prolog",name:"Prolog",import:(()=>import("../prolog-CSAPG5PH.js"))},{id:"proto",name:"Protocol Buffer 3",aliases:["protobuf"],import:(()=>import("../proto-WDNJBTSW.js"))},{id:"pug",name:"Pug",aliases:["jade"],import:(()=>import("../pug-3YFWZUJ6.js"))},{id:"puppet",name:"Puppet",import:(()=>import("../puppet-LHFWHTY3.js"))},{id:"purescript",name:"PureScript",import:(()=>import("../purescript-DUFJP4FY.js"))},{id:"python",name:"Python",aliases:["py"],import:(()=>import("../python-5ZNZSNQ2.js"))},{id:"qml",name:"QML",import:(()=>import("../qml-LTAXB6W5.js"))},{id:"qmldir",name:"QML Directory",import:(()=>import("../qmldir-7Z2ODQLM.js"))},{id:"qss",name:"Qt Style Sheets",import:(()=>import("../qss-FDFD3HQD.js"))},{id:"r",name:"R",import:(()=>import("../r-6ZOS53WN.js"))},{id:"racket",name:"Racket",import:(()=>import("../racket-7AYZPEUI.js"))},{id:"raku",name:"Raku",aliases:["perl6"],import:(()=>import("../raku-A4F6VHVG.js"))},{id:"razor",name:"ASP.NET Razor",import:(()=>import("../razor-7T4OK2LD.js"))},{id:"reg",name:"Windows Registry Script",import:(()=>import("../reg-FAPHGG66.js"))},{id:"regexp",name:"RegExp",aliases:["regex"],import:(()=>import("../regexp-5BYLYA2R.js"))},{id:"rel",name:"Rel",import:(()=>import("../rel-7DJ7HHU4.js"))},{id:"riscv",name:"RISC-V",import:(()=>import("../riscv-YIYJATFG.js"))},{id:"ron",name:"RON",import:(()=>import("../ron-HYYMCHTX.js"))},{id:"rosmsg",name:"ROS Interface",import:(()=>import("../rosmsg-FDNH6QF7.js"))},{id:"rst",name:"reStructuredText",import:(()=>import("../rst-SR6APMGO.js"))},{id:"ruby",name:"Ruby",aliases:["rb"],import:(()=>import("../ruby-IYOQSPDU.js"))},{id:"rust",name:"Rust",aliases:["rs"],import:(()=>import("../rust-V3GMJA2K.js"))},{id:"sas",name:"SAS",import:(()=>import("../sas-D3G4GB3X.js"))},{id:"sass",name:"Sass",import:(()=>import("../sass-JTO65AGR.js"))},{id:"scala",name:"Scala",import:(()=>import("../scala-4XQGFSVM.js"))},{id:"scheme",name:"Scheme",import:(()=>import("../scheme-CB7AC7IL.js"))},{id:"scss",name:"SCSS",import:(()=>import("../scss-6SKV4OGI.js"))},{id:"sdbl",name:"1C (Query)",aliases:["1c-query"],import:(()=>import("../sdbl-LKGZFJ46.js"))},{id:"shaderlab",name:"ShaderLab",aliases:["shader"],import:(()=>import("../shaderlab-K536DHEB.js"))},{id:"shellscript",name:"Shell",aliases:["bash","sh","shell","zsh"],import:(()=>import("../shellscript-LRNUKUSZ.js"))},{id:"shellsession",name:"Shell Session",aliases:["console"],import:(()=>import("../shellsession-IBQK7VWQ.js"))},{id:"smalltalk",name:"Smalltalk",import:(()=>import("../smalltalk-DQOSWAW7.js"))},{id:"solidity",name:"Solidity",import:(()=>import("../solidity-V2FMZEG4.js"))},{id:"soy",name:"Closure Templates",aliases:["closure-templates"],import:(()=>import("../soy-WHPD3NJL.js"))},{id:"sparql",name:"SPARQL",import:(()=>import("../sparql-L2VKP7YP.js"))},{id:"splunk",name:"Splunk Query Language",aliases:["spl"],import:(()=>import("../splunk-KDKHP7GC.js"))},{id:"sql",name:"SQL",import:(()=>import("../sql-UF27CALT.js"))},{id:"ssh-config",name:"SSH Config",import:(()=>import("../ssh-config-JC2DQ6ED.js"))},{id:"stata",name:"Stata",import:(()=>import("../stata-7PXCUY24.js"))},{id:"stylus",name:"Stylus",aliases:["styl"],import:(()=>import("../stylus-2L7N3EZD.js"))},{id:"surrealql",name:"SurrealQL",aliases:["surql"],import:(()=>import("../surrealql-ZY3E6XEL.js"))},{id:"svelte",name:"Svelte",import:(()=>import("../svelte-Q45XIK2A.js"))},{id:"swift",name:"Swift",import:(()=>import("../swift-XBH5HZSC.js"))},{id:"system-verilog",name:"SystemVerilog",import:(()=>import("../system-verilog-VRAUSZY3.js"))},{id:"systemd",name:"Systemd Units",import:(()=>import("../systemd-JOTSGJD4.js"))},{id:"talonscript",name:"TalonScript",aliases:["talon"],import:(()=>import("../talonscript-NNZRZKOU.js"))},{id:"tasl",name:"Tasl",import:(()=>import("../tasl-MBFZ4QNC.js"))},{id:"tcl",name:"Tcl",import:(()=>import("../tcl-4GEDCBVE.js"))},{id:"templ",name:"Templ",import:(()=>import("../templ-VI6LYHRW.js"))},{id:"terraform",name:"Terraform",aliases:["tf","tfvars"],import:(()=>import("../terraform-XTHOS4UK.js"))},{id:"tex",name:"TeX",import:(()=>import("../tex-UXMN2CV7.js"))},{id:"toml",name:"TOML",import:(()=>import("../toml-J6K55ZSV.js"))},{id:"ts-tags",name:"TypeScript with Tags",aliases:["lit"],import:(()=>import("../ts-tags-MU4UAPH3.js"))},{id:"tsv",name:"TSV",import:(()=>import("../tsv-DOUJHQDQ.js"))},{id:"tsx",name:"TSX",import:(()=>import("../tsx-G5BMVRHK.js"))},{id:"turtle",name:"Turtle",import:(()=>import("../turtle-JHJ7W6U5.js"))},{id:"twig",name:"Twig",import:(()=>import("../twig-OY2C64LG.js"))},{id:"typescript",name:"TypeScript",aliases:["ts","cts","mts"],import:(()=>import("../typescript-LMKEAHFC.js"))},{id:"typespec",name:"TypeSpec",aliases:["tsp"],import:(()=>import("../typespec-5CLTIJYY.js"))},{id:"typst",name:"Typst",aliases:["typ"],import:(()=>import("../typst-4W4Z436Z.js"))},{id:"v",name:"V",import:(()=>import("../v-Y4SBDBN7.js"))},{id:"vala",name:"Vala",import:(()=>import("../vala-UMKT2MFA.js"))},{id:"vb",name:"Visual Basic",aliases:["cmd"],import:(()=>import("../vb-DQ7A5WJU.js"))},{id:"verilog",name:"Verilog",import:(()=>import("../verilog-N6ZF7GQD.js"))},{id:"vhdl",name:"VHDL",import:(()=>import("../vhdl-BNYDT37G.js"))},{id:"viml",name:"Vim Script",aliases:["vim","vimscript"],import:(()=>import("../viml-37RMDCBC.js"))},{id:"vue",name:"Vue",import:(()=>import("../vue-M6XWA362.js"))},{id:"vue-html",name:"Vue HTML",import:(()=>import("../vue-html-ZLTZN573.js"))},{id:"vue-vine",name:"Vue Vine",import:(()=>import("../vue-vine-6JKAZ54I.js"))},{id:"vyper",name:"Vyper",aliases:["vy"],import:(()=>import("../vyper-GVXF46KD.js"))},{id:"wasm",name:"WebAssembly",import:(()=>import("../wasm-NTB4O7GL.js"))},{id:"wenyan",name:"Wenyan",aliases:["\u6587\u8A00"],import:(()=>import("../wenyan-W7WB3BC7.js"))},{id:"wgsl",name:"WGSL",import:(()=>import("../wgsl-7GTDVXHG.js"))},{id:"wikitext",name:"Wikitext",aliases:["mediawiki","wiki"],import:(()=>import("../wikitext-ASAFPAIL.js"))},{id:"wit",name:"WebAssembly Interface Types",import:(()=>import("../wit-ZBCR6544.js"))},{id:"wolfram",name:"Wolfram",aliases:["wl"],import:(()=>import("../wolfram-SZRZOETJ.js"))},{id:"xml",name:"XML",import:(()=>import("../xml-EBTJCOTU.js"))},{id:"xsl",name:"XSL",import:(()=>import("../xsl-IBYEXWDX.js"))},{id:"yaml",name:"YAML",aliases:["yml"],import:(()=>import("../yaml-GMVQNECR.js"))},{id:"zenscript",name:"ZenScript",import:(()=>import("../zenscript-O2TZFP4A.js"))},{id:"zig",name:"Zig",import:(()=>import("../zig-ZLGM7IMN.js"))}],ud=Object.fromEntries(Gn.map(e=>[e.id,e.import])),dd=Object.fromEntries(Gn.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),Za={...ud,...dd};var Qw=[{id:"andromeeda",displayName:"Andromeeda",type:"dark",import:(()=>import("../andromeeda-HAPOYWX3.js"))},{id:"aurora-x",displayName:"Aurora X",type:"dark",import:(()=>import("../aurora-x-R6WAWEBC.js"))},{id:"ayu-dark",displayName:"Ayu Dark",type:"dark",import:(()=>import("../ayu-dark-KMD4YO7F.js"))},{id:"ayu-light",displayName:"Ayu Light",type:"light",import:(()=>import("../ayu-light-2ATPDILG.js"))},{id:"ayu-mirage",displayName:"Ayu Mirage",type:"dark",import:(()=>import("../ayu-mirage-LJ7PG5AM.js"))},{id:"catppuccin-frappe",displayName:"Catppuccin Frapp\xE9",type:"dark",import:(()=>import("../catppuccin-frappe-Z4Y2POK6.js"))},{id:"catppuccin-latte",displayName:"Catppuccin Latte",type:"light",import:(()=>import("../catppuccin-latte-4TQUIKX4.js"))},{id:"catppuccin-macchiato",displayName:"Catppuccin Macchiato",type:"dark",import:(()=>import("../catppuccin-macchiato-B7YYPERT.js"))},{id:"catppuccin-mocha",displayName:"Catppuccin Mocha",type:"dark",import:(()=>import("../catppuccin-mocha-KX33VXKA.js"))},{id:"dark-plus",displayName:"Dark Plus",type:"dark",import:(()=>import("../dark-plus-LNHXUR7U.js"))},{id:"dracula",displayName:"Dracula Theme",type:"dark",import:(()=>import("../dracula-T2CMBBQ5.js"))},{id:"dracula-soft",displayName:"Dracula Theme Soft",type:"dark",import:(()=>import("../dracula-soft-SMFRNKX2.js"))},{id:"everforest-dark",displayName:"Everforest Dark",type:"dark",import:(()=>import("../everforest-dark-DBZHIUAO.js"))},{id:"everforest-light",displayName:"Everforest Light",type:"light",import:(()=>import("../everforest-light-TDAGYJUK.js"))},{id:"github-dark",displayName:"GitHub Dark",type:"dark",import:(()=>import("../github-dark-3E25TTAN.js"))},{id:"github-dark-default",displayName:"GitHub Dark Default",type:"dark",import:(()=>import("../github-dark-default-KCBFVSS5.js"))},{id:"github-dark-dimmed",displayName:"GitHub Dark Dimmed",type:"dark",import:(()=>import("../github-dark-dimmed-WRCBXEVS.js"))},{id:"github-dark-high-contrast",displayName:"GitHub Dark High Contrast",type:"dark",import:(()=>import("../github-dark-high-contrast-ET7SAHAV.js"))},{id:"github-light",displayName:"GitHub Light",type:"light",import:(()=>import("../github-light-6FNTZH5H.js"))},{id:"github-light-default",displayName:"GitHub Light Default",type:"light",import:(()=>import("../github-light-default-GGTAKNM7.js"))},{id:"github-light-high-contrast",displayName:"GitHub Light High Contrast",type:"light",import:(()=>import("../github-light-high-contrast-LHYKPR5E.js"))},{id:"gruvbox-dark-hard",displayName:"Gruvbox Dark Hard",type:"dark",import:(()=>import("../gruvbox-dark-hard-IQWZCHF7.js"))},{id:"gruvbox-dark-medium",displayName:"Gruvbox Dark Medium",type:"dark",import:(()=>import("../gruvbox-dark-medium-ARPWF4FS.js"))},{id:"gruvbox-dark-soft",displayName:"Gruvbox Dark Soft",type:"dark",import:(()=>import("../gruvbox-dark-soft-ODS6FPID.js"))},{id:"gruvbox-light-hard",displayName:"Gruvbox Light Hard",type:"light",import:(()=>import("../gruvbox-light-hard-KFA5YFDW.js"))},{id:"gruvbox-light-medium",displayName:"Gruvbox Light Medium",type:"light",import:(()=>import("../gruvbox-light-medium-MMET4L3Y.js"))},{id:"gruvbox-light-soft",displayName:"Gruvbox Light Soft",type:"light",import:(()=>import("../gruvbox-light-soft-DBZDERMK.js"))},{id:"horizon",displayName:"Horizon",type:"dark",import:(()=>import("../horizon-FSOMPXNP.js"))},{id:"houston",displayName:"Houston",type:"dark",import:(()=>import("../houston-FAQBCORN.js"))},{id:"kanagawa-dragon",displayName:"Kanagawa Dragon",type:"dark",import:(()=>import("../kanagawa-dragon-JNDVF5RJ.js"))},{id:"kanagawa-lotus",displayName:"Kanagawa Lotus",type:"light",import:(()=>import("../kanagawa-lotus-S7JK6TQ6.js"))},{id:"kanagawa-wave",displayName:"Kanagawa Wave",type:"dark",import:(()=>import("../kanagawa-wave-QJJIMVEV.js"))},{id:"laserwave",displayName:"LaserWave",type:"dark",import:(()=>import("../laserwave-YFP3EJVX.js"))},{id:"light-plus",displayName:"Light Plus",type:"light",import:(()=>import("../light-plus-NGDHCPUZ.js"))},{id:"material-theme",displayName:"Material Theme",type:"dark",import:(()=>import("../material-theme-H2BHKUKX.js"))},{id:"material-theme-darker",displayName:"Material Theme Darker",type:"dark",import:(()=>import("../material-theme-darker-VENCGWTB.js"))},{id:"material-theme-lighter",displayName:"Material Theme Lighter",type:"light",import:(()=>import("../material-theme-lighter-SDMLS22W.js"))},{id:"material-theme-ocean",displayName:"Material Theme Ocean",type:"dark",import:(()=>import("../material-theme-ocean-UHDBRLVF.js"))},{id:"material-theme-palenight",displayName:"Material Theme Palenight",type:"dark",import:(()=>import("../material-theme-palenight-3TB2BEET.js"))},{id:"min-dark",displayName:"Min Dark",type:"dark",import:(()=>import("../min-dark-CQ5WKNT7.js"))},{id:"min-light",displayName:"Min Light",type:"light",import:(()=>import("../min-light-LZRD4NPR.js"))},{id:"monokai",displayName:"Monokai",type:"dark",import:(()=>import("../monokai-WHRY6275.js"))},{id:"night-owl",displayName:"Night Owl",type:"dark",import:(()=>import("../night-owl-7PNEW2JB.js"))},{id:"night-owl-light",displayName:"Night Owl Light",type:"light",import:(()=>import("../night-owl-light-GJUYOOJR.js"))},{id:"nord",displayName:"Nord",type:"dark",import:(()=>import("../nord-EVGUMUX2.js"))},{id:"one-dark-pro",displayName:"One Dark Pro",type:"dark",import:(()=>import("../one-dark-pro-PMTR3SA7.js"))},{id:"one-light",displayName:"One Light",type:"light",import:(()=>import("../one-light-O7WH4N5X.js"))},{id:"plastic",displayName:"Plastic",type:"dark",import:(()=>import("../plastic-FBVUW6NJ.js"))},{id:"poimandres",displayName:"Poimandres",type:"dark",import:(()=>import("../poimandres-WBB7GZAD.js"))},{id:"red",displayName:"Red",type:"dark",import:(()=>import("../red-7KAMONOP.js"))},{id:"rose-pine",displayName:"Ros\xE9 Pine",type:"dark",import:(()=>import("../rose-pine-F2G5IHZD.js"))},{id:"rose-pine-dawn",displayName:"Ros\xE9 Pine Dawn",type:"light",import:(()=>import("../rose-pine-dawn-ALZ7XGH2.js"))},{id:"rose-pine-moon",displayName:"Ros\xE9 Pine Moon",type:"dark",import:(()=>import("../rose-pine-moon-D3K4SWUL.js"))},{id:"slack-dark",displayName:"Slack Dark",type:"dark",import:(()=>import("../slack-dark-YFPJODWS.js"))},{id:"slack-ochin",displayName:"Slack Ochin",type:"light",import:(()=>import("../slack-ochin-H67AWZOI.js"))},{id:"snazzy-light",displayName:"Snazzy Light",type:"light",import:(()=>import("../snazzy-light-OUVS63VK.js"))},{id:"solarized-dark",displayName:"Solarized Dark",type:"dark",import:(()=>import("../solarized-dark-2RCAVEXJ.js"))},{id:"solarized-light",displayName:"Solarized Light",type:"light",import:(()=>import("../solarized-light-XFSENHTC.js"))},{id:"synthwave-84",displayName:"Synthwave '84",type:"dark",import:(()=>import("../synthwave-84-5XXB3K6S.js"))},{id:"tokyo-night",displayName:"Tokyo Night",type:"dark",import:(()=>import("../tokyo-night-CHJCCBJH.js"))},{id:"vesper",displayName:"Vesper",type:"dark",import:(()=>import("../vesper-Y5GIEAN4.js"))},{id:"vitesse-black",displayName:"Vitesse Black",type:"dark",import:(()=>import("../vitesse-black-7TI33KHX.js"))},{id:"vitesse-dark",displayName:"Vitesse Dark",type:"dark",import:(()=>import("../vitesse-dark-FOB25MRB.js"))},{id:"vitesse-light",displayName:"Vitesse Light",type:"light",import:(()=>import("../vitesse-light-4WCNCTCO.js"))}],cd=Object.fromEntries(Qw.map(e=>[e.id,e.import]));var er=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Yw(){return 2147483648}function Zw(){return typeof performance<"u"?performance.now():Date.now()}var eI=(e,t)=>e+(t-e%t)%t;async function tI(e){let t,a,r={};function o(f){a=f,r.HEAPU8=new Uint8Array(f),r.HEAPU32=new Uint32Array(f)}function n(f,m,y){r.HEAPU8.copyWithin(f,m,m+y)}function s(f){try{return t.grow(f-a.byteLength+65535>>>16),o(t.buffer),1}catch{}}function i(f){let m=r.HEAPU8.length;f=f>>>0;let y=Yw();if(f>y)return!1;for(let S=1;S<=4;S*=2){let L=m*(1+.2/S);L=Math.min(L,f+100663296);let C=Math.min(y,eI(Math.max(f,L),65536));if(s(C))return!0}return!1}let l=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function u(f,m,y=1024){let S=m+y,L=m;for(;f[L]&&!(L>=S);)++L;if(L-m>16&&f.buffer&&l)return l.decode(f.subarray(m,L));let C="";for(;m<L;){let I=f[m++];if(!(I&128)){C+=String.fromCharCode(I);continue}let x=f[m++]&63;if((I&224)===192){C+=String.fromCharCode((I&31)<<6|x);continue}let v=f[m++]&63;if((I&240)===224?I=(I&15)<<12|x<<6|v:I=(I&7)<<18|x<<12|v<<6|f[m++]&63,I<65536)C+=String.fromCharCode(I);else{let q=I-65536;C+=String.fromCharCode(55296|q>>10,56320|q&1023)}}return C}function d(f,m){return f?u(r.HEAPU8,f,m):""}let c={emscripten_get_now:Zw,emscripten_memcpy_big:n,emscripten_resize_heap:i,fd_write:()=>0};async function p(){let m=await e({env:c,wasi_snapshot_preview1:c});t=m.memory,o(t.buffer),Object.assign(r,m),r.UTF8ToString=d}return await p(),r}var aI=Object.defineProperty,rI=(e,t,a)=>t in e?aI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,Me=(e,t,a)=>rI(e,typeof t!="symbol"?t+"":t,a),Be=null;function oI(e){throw new er(e.UTF8ToString(e.getLastOnigError()))}var lo=class e{constructor(t){Me(this,"utf16Length"),Me(this,"utf8Length"),Me(this,"utf16Value"),Me(this,"utf8Value"),Me(this,"utf16OffsetToUtf8"),Me(this,"utf8OffsetToUtf16");let a=t.length,r=e._utf8ByteLength(t),o=r!==a,n=o?new Uint32Array(a+1):null;o&&(n[a]=r);let s=o?new Uint32Array(r+1):null;o&&(s[r]=a);let i=new Uint8Array(r),l=0;for(let u=0;u<a;u++){let d=t.charCodeAt(u),c=d,p=!1;if(d>=55296&&d<=56319&&u+1<a){let f=t.charCodeAt(u+1);f>=56320&&f<=57343&&(c=(d-55296<<10)+65536|f-56320,p=!0)}o&&(n[u]=l,p&&(n[u+1]=l),c<=127?s[l+0]=u:c<=2047?(s[l+0]=u,s[l+1]=u):c<=65535?(s[l+0]=u,s[l+1]=u,s[l+2]=u):(s[l+0]=u,s[l+1]=u,s[l+2]=u,s[l+3]=u)),c<=127?i[l++]=c:c<=2047?(i[l++]=192|(c&1984)>>>6,i[l++]=128|(c&63)>>>0):c<=65535?(i[l++]=224|(c&61440)>>>12,i[l++]=128|(c&4032)>>>6,i[l++]=128|(c&63)>>>0):(i[l++]=240|(c&1835008)>>>18,i[l++]=128|(c&258048)>>>12,i[l++]=128|(c&4032)>>>6,i[l++]=128|(c&63)>>>0),p&&u++}this.utf16Length=a,this.utf8Length=r,this.utf16Value=t,this.utf8Value=i,this.utf16OffsetToUtf8=n,this.utf8OffsetToUtf16=s}static _utf8ByteLength(t){let a=0;for(let r=0,o=t.length;r<o;r++){let n=t.charCodeAt(r),s=n,i=!1;if(n>=55296&&n<=56319&&r+1<o){let l=t.charCodeAt(r+1);l>=56320&&l<=57343&&(s=(n-55296<<10)+65536|l-56320,i=!0)}s<=127?a+=1:s<=2047?a+=2:s<=65535?a+=3:a+=4,i&&r++}return a}createString(t){let a=t.omalloc(this.utf8Length);return t.HEAPU8.set(this.utf8Value,a),a}},uo=class ct{constructor(t){if(Me(this,"id",++ct.LAST_ID),Me(this,"_onigBinding"),Me(this,"content"),Me(this,"utf16Length"),Me(this,"utf8Length"),Me(this,"utf16OffsetToUtf8"),Me(this,"utf8OffsetToUtf16"),Me(this,"ptr"),!Be)throw new er("Must invoke loadWasm first.");this._onigBinding=Be,this.content=t;let a=new lo(t);this.utf16Length=a.utf16Length,this.utf8Length=a.utf8Length,this.utf16OffsetToUtf8=a.utf16OffsetToUtf8,this.utf8OffsetToUtf16=a.utf8OffsetToUtf16,this.utf8Length<1e4&&!ct._sharedPtrInUse?(ct._sharedPtr||(ct._sharedPtr=Be.omalloc(1e4)),ct._sharedPtrInUse=!0,Be.HEAPU8.set(a.utf8Value,ct._sharedPtr),this.ptr=ct._sharedPtr):this.ptr=a.createString(Be)}convertUtf8OffsetToUtf16(t){return this.utf8OffsetToUtf16?t<0?0:t>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[t]:t}convertUtf16OffsetToUtf8(t){return this.utf16OffsetToUtf8?t<0?0:t>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[t]:t}dispose(){this.ptr===ct._sharedPtr?ct._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};Me(uo,"LAST_ID",0);Me(uo,"_sharedPtr",0);Me(uo,"_sharedPtrInUse",!1);var fd=uo,Xn=class{constructor(t){if(Me(this,"_onigBinding"),Me(this,"_ptr"),!Be)throw new er("Must invoke loadWasm first.");let a=[],r=[];for(let i=0,l=t.length;i<l;i++){let u=new lo(t[i]);a[i]=u.createString(Be),r[i]=u.utf8Length}let o=Be.omalloc(4*t.length);Be.HEAPU32.set(a,o/4);let n=Be.omalloc(4*t.length);Be.HEAPU32.set(r,n/4);let s=Be.createOnigScanner(o,n,t.length);for(let i=0,l=t.length;i<l;i++)Be.ofree(a[i]);Be.ofree(n),Be.ofree(o),s===0&&oI(Be),this._onigBinding=Be,this._ptr=s}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(t,a,r){let o=0;if(typeof r=="number"&&(o=r),typeof t=="string"){t=new fd(t);let n=this._findNextMatchSync(t,a,!1,o);return t.dispose(),n}return this._findNextMatchSync(t,a,!1,o)}_findNextMatchSync(t,a,r,o){let n=this._onigBinding,s=n.findNextOnigScannerMatch(this._ptr,t.id,t.ptr,t.utf8Length,t.convertUtf16OffsetToUtf8(a),o);if(s===0)return null;let i=n.HEAPU32,l=s/4,u=i[l++],d=i[l++],c=[];for(let p=0;p<d;p++){let f=t.convertUtf8OffsetToUtf16(i[l++]),m=t.convertUtf8OffsetToUtf16(i[l++]);c[p]={start:f,end:m,length:m-f}}return{index:u,captureIndices:c}}};function nI(e){return typeof e.instantiator=="function"}function sI(e){return typeof e.default=="function"}function iI(e){return typeof e.data<"u"}function lI(e){return typeof Response<"u"&&e instanceof Response}function uI(e){return typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<"u"&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||typeof Uint32Array<"u"&&e instanceof Uint32Array}var io;function dI(e){if(io)return io;async function t(){Be=await tI(async a=>{let r=e;return r=await r,typeof r=="function"&&(r=await r(a)),typeof r=="function"&&(r=await r(a)),nI(r)?r=await r.instantiator(a):sI(r)?r=await r.default(a):(iI(r)&&(r=r.data),lI(r)?typeof WebAssembly.instantiateStreaming=="function"?r=await cI(r)(a):r=await fI(r)(a):uI(r)?r=await Kn(r)(a):r instanceof WebAssembly.Module?r=await Kn(r)(a):"default"in r&&r.default instanceof WebAssembly.Module&&(r=await Kn(r.default)(a))),"instance"in r&&(r=r.instance),"exports"in r&&(r=r.exports),r})}return io=t(),io}function Kn(e){return t=>WebAssembly.instantiate(e,t)}function cI(e){return t=>WebAssembly.instantiateStreaming(e,t)}function fI(e){return async t=>{let a=await e.arrayBuffer();return WebAssembly.instantiate(a,t)}}async function pd(e){return e&&await dI(e),{createScanner(t){return new Xn(t.map(a=>typeof a=="string"?a:a.source))},createString(t){return new fd(t)}}}var co=id({langs:Za,themes:cd,engine:()=>pd(import("../wasm-EOPKAILK.js"))}),{codeToHtml:pI,codeToHast:mI,codeToTokens:hI,codeToTokensBase:gI,codeToTokensWithThemes:wI,getSingletonHighlighter:II,getLastGrammarState:xI}=ld(co,{guessEmbeddedLanguages:ed});var md=new Set(Object.keys(Za)),Jn=new Map,Qn=new Map,ca=new Map,yI=(e,t)=>`${e}-${t[0]}-${t[1]}`,LI=(e,t,a)=>{let r=e.slice(0,100),o=e.length>100?e.slice(-100):"";return`${t}:${a[0]}:${a[1]}:${e.length}:${r}:${o}`},SI=(e,t)=>{let a=yI(e,t);if(Jn.has(a))return Jn.get(a);let r=co({themes:t,langs:[e]});return Jn.set(a,r),r};function CI(e={}){var t;let a=(t=e.themes)!=null?t:["github-light","github-dark"];return{name:"shiki",type:"code-highlighter",supportsLanguage(r){return md.has(r)},getSupportedLanguages(){return Array.from(md)},getThemes(){return a},highlight({code:r,language:o,themes:n},s){let i=LI(r,o,n);return Qn.has(i)?Qn.get(i):(s&&(ca.has(i)||ca.set(i,new Set),ca.get(i).add(s)),SI(o,n).then(l=>{let u=l.getLoadedLanguages().includes(o)?o:"text",d=l.codeToTokens(r,{lang:u,themes:{light:n[0],dark:n[1]}});Qn.set(i,d);let c=ca.get(i);if(c){for(let p of c)p(d);ca.delete(i)}}).catch(l=>{console.error("[Streamdown Code] Failed to highlight code:",l),ca.delete(i)}),null)}}}var hd=CI();import{memo as TI}from"react";import{useEffect as bI,useRef as fo,useState as vI}from"react";var kI=5,gd=400;function wd(e,t,a={}){let{msPerChar:r=kI}=a,[o,n]=vI(t?"":e),s=fo(e),i=fo(t?0:e.length),l=fo(0),u=fo(null);return(e.length<i.current||!e.startsWith(o.slice(0,i.current)))&&(i.current=t?0:e.length),s.current=e,bI(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),i.current=e.length,n(e);return}if(s.current.length-i.current>gd&&(i.current=s.current.length-gd),u.current!==null)return;let c=p=>{let f=s.current;if(i.current>=f.length){u.current=null;return}l.current===0&&(l.current=p);let m=p-l.current;if(m>=r){let y=Math.min(Math.floor(m/r),f.length-i.current);i.current+=y,n(f.slice(0,i.current)),l.current=p}u.current=requestAnimationFrame(c)};return u.current=requestAnimationFrame(c),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,r]),o}import{jsx as po}from"react/jsx-runtime";var Yn=({className:e,from:t,children:a,...r})=>po("div",{className:P("ww-message ww:group ww:flex ww:w-full",t==="user"?"ww-message-user is-user ww:ml-auto ww:flex-col ww:items-end ww:[max-width:var(--ww-msg-max-width,80%)]":"ww-message-assistant is-assistant ww:flex-col",e),...r,children:po("div",{className:P("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Zn=({children:e,className:t,...a})=>po("div",{className:P("ww-bubble ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden","ww:[font-size:var(--ww-font-size,1rem)] ww:[line-height:var(--ww-line-height,1.5)]","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:[color:var(--ww-color-user-bubble-text)] ww:group-[.is-user]:[border-radius:var(--ww-msg-radius,8px)] ww:group-[.is-user]:[padding:var(--ww-msg-pad-y,12px)_var(--ww-msg-pad-x,16px)]","ww:group-[.is-assistant]:text-foreground",t),...a,children:e}),AI={cjk:Ln,code:hd},PI={cjk:Ln},RI={enabled:!1};function EI({className:e,linkSafety:t,isStreaming:a,children:r,...o}){let s=wd(typeof r=="string"?r:"",!!a),i=typeof r=="string"?s:r;return po(ya,{className:P("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??RI,plugins:a?PI:AI,...o,children:i})}var mo=TI(EI,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);mo.displayName="MessageResponse";import{jsx as Id,jsxs as MI}from"react/jsx-runtime";function xd(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function yd(e){return e.parts.some(xd)}function Ld(e,t,a){if(t!=="submitted"&&t!=="streaming")return!1;let r=e[e.length-1];return!r||r.role!=="assistant"?!0:!r.parts.some(n=>!(!xd(n)||a?.ignoreToolParts&&"toolCallId"in n||a?.ignoreReasoningParts&&n.type==="reasoning"))}function Sd({className:e,...t}){let{t:a}=te();return MI("div",{"aria-live":"polite",className:P("ww:mb-4 ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...t,children:[Id(Ea,{className:"ww:size-4 ww:shrink-0"}),Id(et,{duration:1.6,children:a.workingIndicator.default})]})}import{jsx as tr,jsxs as FI}from"react/jsx-runtime";function Cd({icon:e,title:t,description:a,suggestions:r,onSuggestionSelect:o}){return FI("div",{className:"ww:flex ww:flex-col ww:items-center ww:justify-center ww:py-12 ww:px-6 ww:text-center ww:min-h-full",children:[e&&tr("div",{className:"ww:mb-4 ww:flex ww:items-center ww:justify-center ww:size-12 ww:rounded-xl ww:bg-foreground ww:text-background",children:e}),tr("h2",{className:"ww:text-lg ww:font-semibold ww:text-foreground",children:t}),a&&tr("p",{className:"ww:mt-1 ww:text-sm ww:text-muted-foreground ww:max-w-sm",children:a}),r&&r.length>0&&tr("div",{className:"ww:mt-6 ww:w-full ww:max-w-md ww:flex ww:flex-col ww:gap-2",children:r.map((n,s)=>tr("button",{type:"button",onClick:()=>o?.(n),className:P("ww:w-full ww:text-left ww:rounded-xl ww:border ww:border-border ww:bg-background ww:px-4 ww:py-3 ww:text-sm","ww:text-foreground ww:hover:bg-accent ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${s*50}ms`},children:n},n))})]})}import{Component as _I}from"react";import{jsx as es,jsxs as BI}from"react/jsx-runtime";function DI({onRetry:e}){let{t}=te();return BI("div",{className:"ww:flex ww:items-center ww:justify-between ww:rounded-md ww:border ww:border-border ww:bg-muted/50 ww:px-4 ww:py-3 ww:text-sm ww:text-muted-foreground",children:[es("span",{children:t.widgetErrorBoundary.failedToLoad}),es("button",{type:"button",onClick:e,className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:t.widgetErrorBoundary.retry})]})}var ho=class extends _I{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.warn("[Waniwani] Widget failed to render:",t.message)}render(){return this.state.hasError?es(DI,{onRetry:()=>this.setState({hasError:!1})}):this.props.children}};import{Fragment as OI,jsx as we,jsxs as Ft}from"react/jsx-runtime";function ts(e){return e?e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase()):"Tool"}function bd(e){return e&&/search|find|lookup|query|web|browse|google/i.test(e)?Ta:qt}function vd({messages:e,status:t,welcomeMessage:a,welcome:r,onSuggestionSelect:o,resourceEndpoint:n,chatSessionId:s,isDark:i,onFollowUp:l,onCallTool:u,onWidgetDisplayModeChange:d,fullscreenToolCallId:c,debug:p,showToolCalls:f=!0,toolDefinitions:m,messageClassNames:y}){let{t:S}=te(),L=e[e.length-1],C=e.length>0,I=c!=null,x=!I&&Ld(e,t,{ignoreToolParts:f===!1,ignoreReasoningParts:f===!1});return Ft(OI,{children:[!I&&(!C&&r?we(Cd,{...r,onSuggestionSelect:o}):a&&we(Yn,{from:"assistant",children:we(Zn,{children:we(mo,{children:a})})})),e.map(v=>{let q=v.parts.filter(R=>R.type==="text"),N=v.parts.filter(R=>R.type==="reasoning"),V=v.parts.filter(R=>R.type==="file"),G=ul(v.metadata),Q=v.parts.filter(R=>"toolCallId"in R),O=v.parts.filter(R=>R.type==="reasoning"||"toolCallId"in R),re=v===L&&v.role==="assistant",K=q.length>0,J=I?Q.some(R=>R.toolCallId===c):!1,X=f!==!1&&!J&&O.length>=2;return I&&!J?we("div",{style:{display:"none"}},v.id):v.role==="assistant"&&!yd(v)?we("div",{style:{display:"none"}},v.id):f===!1&&v.role==="assistant"&&!K&&V.length===0&&Q.every(R=>{let b="output"in R?R.output:void 0;return b===void 0||!n||!Fa(R.toolName,b,m)})?we("div",{style:{display:"none"}},v.id):Ft(Yn,{from:v.role,className:y?.message,children:[f!==!1&&!J&&!X&&N.map((R,b)=>Ft(Na,{isStreaming:R.state==="streaming",children:[we(qa,{}),we(Ha,{children:R.text})]},`reasoning-${v.id}-${b}`)),X&&(()=>{let R=O[O.length-1],b=R.type==="reasoning"?{icon:ht,label:S.reasoning.thinking}:{icon:bd(R.toolName),label:R.title??ts(R.toolName)};return Ft(Dl,{isWorking:re&&(t==="streaming"||t==="submitted"),activeStep:b,children:[we(Bl,{workingLabel:S.chainOfThought.working,label:S.chainOfThought.done}),we(Ol,{children:O.map((D,ae)=>{let oe=ae===O.length-1;if(D.type==="reasoning")return we(Nl,{isStreaming:D.state==="streaming",isLast:oe,children:D.text},`reasoning-${v.id}-${ae}`);let Re=D.title??ts(D.toolName),Ne=bd(D.toolName);if(f==="titles-only")return we(In,{icon:Ne,title:Re,state:D.state,isLast:oe},D.toolCallId);let k="output"in D?D.output:void 0;return Ft(In,{icon:Ne,title:Re,state:D.state,isLast:oe,children:[we(Qo,{input:D.input,debug:p}),k!==void 0&&we(Yo,{output:k,errorText:"errorText"in D?D.errorText:void 0,debug:p})]},D.toolCallId)})})]})})(),f!==!1&&!J&&!X&&Q.length===1&&(()=>{let R=Q[0],b=R.title??ts(R.toolName);if(f==="titles-only")return we(Ui,{title:b,state:R.state});let D="output"in R?R.output:void 0;return Ft(Bi,{children:[we(Oi,{title:b,state:R.state}),Ft(Ni,{children:[we(Qo,{input:R.input,debug:p}),D!==void 0&&we(Yo,{output:D,errorText:"errorText"in R?R.errorText:void 0,debug:p})]})]})})(),Q.map(R=>{let b="output"in R?R.output:void 0,D=Fa(R.toolName,b,m),ae=qi(R.toolName,b,m),oe=R.toolCallId===c;return D&&n&&b!==void 0?we("div",{style:oe?{position:"absolute",inset:0,zIndex:10,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--ww-color-background)"}:void 0,children:D&&n&&b!==void 0&&we(ho,{children:we(Ba,{isFullscreen:oe,resourceUri:D,toolInput:R.input??{},toolResult:{content:b.content,structuredContent:b.structuredContent,_meta:b._meta},resourceEndpoint:n,chatSessionId:s,isDark:i,autoHeight:ae,toolDefinitions:m,onFollowUp:l,onCallTool:u,onDisplayModeChange:d?Re=>d(Re,{toolCallId:R.toolCallId,resourceUri:D,toolInput:R.input??{},toolResult:{content:b.content,structuredContent:b.structuredContent,_meta:b._meta},autoHeight:ae}):void 0})})},R.toolCallId):null}),!J&&G.length>0&&we(dl,{documents:G}),!J&&we("div",{children:Ft(Zn,{className:P(v.role==="user"?y?.userBubble:y?.assistantBubble),children:[V.length>0&&we(il,{files:V}),K?q.map((R,b)=>{let D=re&&t==="streaming"&&b===q.length-1;return we(mo,{isStreaming:D,children:R.type==="text"?R.text:""},`${v.id}-${b}`)}):null]})})]},v.id)}),x&&we(Sd,{})]})}import{jsx as ar,jsxs as NI}from"react/jsx-runtime";function UI({label:e}){return NI("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[ar("title",{children:e}),ar("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),ar("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function go({onClick:e}){let{t}=te();return ar("button",{type:"button",onClick:e,title:t.threadMenu.newChat,"aria-label":t.threadMenu.newChat,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:ar(UI,{label:t.threadMenu.newChat})})}import{jsx as kd,jsxs as $I}from"react/jsx-runtime";var qI="https://app.waniwani.ai/assets/waniwani-logo.svg",HI="https://waniwani.ai";function Td(){let{t:e}=te();return $I("a",{href:HI,target:"_blank",rel:"noopener noreferrer",className:"ww:flex ww:items-center ww:gap-1.5 ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70 hover:ww:opacity-100 ww:transition-opacity",children:[kd("span",{children:e.poweredBy.label}),kd("img",{src:qI,alt:"Waniwani",width:72,height:10,"data-waniwani-logo":"",className:"ww:h-2.5 ww:w-auto"})]})}import{jsx as wo}from"react/jsx-runtime";function Ad({suggestions:e,isLoading:t,onSelect:a,align:r="start",className:o,...n}){return e.length===0&&!t?null:wo("div",{className:P("ww:px-4 ww:py-2",o),...n,children:wo("div",{className:P("ww:mx-auto ww:w-full ww:max-w-3xl ww:flex ww:flex-wrap ww:gap-2",r==="center"&&"ww:justify-center"),children:t?[0,1,2].map(s=>wo("div",{className:"ww:h-8 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+s*20}px`}},s)):e.map((s,i)=>wo("button",{type:"button",onClick:()=>a(s),className:P("ww:rounded-full ww:border ww:border-border ww:bg-accent ww:px-3.5 ww:py-1.5 ww:text-sm","ww:text-foreground ww:hover:bg-border ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${i*50}ms`},children:s},s))})})}import{useEffect as WI,useRef as jI,useState as zI}from"react";import{jsx as Fe,jsxs as fa}from"react/jsx-runtime";var Pd=20;function VI({label:e}){return fa("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[Fe("title",{children:e}),Fe("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),Fe("polyline",{points:"3 4 3 9 8 9"}),Fe("line",{x1:"12",y1:"7",x2:"12",y2:"12"}),Fe("line",{x1:"12",y1:"12",x2:"15",y2:"14"})]})}function GI({label:e}){return fa("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[Fe("title",{children:e}),Fe("polyline",{points:"3 6 5 6 21 6"}),Fe("path",{d:"M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"}),Fe("path",{d:"M10 11v6"}),Fe("path",{d:"M14 11v6"})]})}function Rd({threads:e,activeThreadId:t,onNewThread:a,onSelectThread:r,onDeleteThread:o}){let{locale:n,t:s}=te(),[i,l]=zI(!1),u=jI(null);WI(()=>{if(!i)return;let p=f=>{let m=u.current;m&&(f.composedPath().includes(m)||l(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[i]);let d=e.slice(0,Pd),c=Math.max(0,e.length-Pd);return fa("div",{ref:u,className:"ww:relative ww:flex ww:items-center ww:gap-1",children:[Fe(go,{onClick:a}),Fe("button",{type:"button",onClick:()=>l(p=>!p),title:s.threadMenu.threadHistory,"aria-label":s.threadMenu.threadHistory,"aria-expanded":i,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:Fe(VI,{label:s.threadMenu.threadHistory})}),i&&fa("div",{role:"menu",className:"ww:absolute ww:right-0 ww:top-full ww:mt-1 ww:w-72 ww:max-h-80 ww:overflow-y-auto ww:rounded-lg ww:border ww:border-border ww:bg-background ww:shadow-lg ww:z-50",children:[d.length===0&&Fe("div",{className:"ww:px-3 ww:py-3 ww:text-xs ww:text-muted-foreground",children:s.threadMenu.noPreviousChats}),d.map(p=>{let f=p.threadId===t,m=Date.parse(p.updatedAt);return fa("div",{className:`ww:flex ww:items-center ww:gap-2 ww:px-3 ww:py-2 ww:text-xs hover:ww:bg-foreground/5 ${f?"ww:bg-foreground/5":""}`,children:[fa("button",{type:"button",onClick:()=>{r(p.threadId),l(!1)},className:"ww:flex-1 ww:min-w-0 ww:text-left ww:cursor-pointer",children:[Fe("div",{className:"ww:truncate ww:text-foreground ww:font-medium",children:p.title}),Fe("div",{className:"ww:text-[10px] ww:text-muted-foreground",children:Number.isNaN(m)?"":Go(m,n)})]}),Fe("button",{type:"button",onClick:y=>{y.stopPropagation(),o(p.threadId)},title:s.threadMenu.deleteThread,"aria-label":s.threadMenu.deleteThread,className:"ww:p-1 ww:rounded ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/10 ww:transition-colors ww:cursor-pointer",children:Fe(GI,{label:s.threadMenu.deleteThread})})]},p.threadId)}),c>0&&Fe("div",{className:"ww:px-3 ww:py-2 ww:text-[10px] ww:text-muted-foreground ww:border-t ww:border-border",children:s.threadMenu.hiddenThreads(c)})]})]})}import{createContext as KI,useContext as XI}from"react";function Ed(e){let t=new Set;return{subscribe(a){return t.add(a),()=>{t.delete(a)}},emit(a){let{sessionId:r,...o}=a,n=a.name==="session.started"?a.properties.sessionId:void 0,s={...o,mode:e.mode,sessionId:Object.hasOwn(a,"sessionId")?r:n??e.getSessionId?.(),timestamp:Date.now()};for(let i of[...t])try{i(s)}catch(l){console.warn("[Waniwani] onEvent subscriber threw:",l)}}}}function Md(){return{subscribe(){return()=>{}},emit(){}}}var Fd=KI(Md());function Io(){return XI(Fd)}var _d=Fd.Provider;import{useCallback as JI,useRef as QI}from"react";function Dd(e){let t=QI(e);return t.current=e,JI(async a=>{let{api:r,headers:o,onCallTool:n,sessionId:s}=t.current;if(n)return n(a);let i=tt(r??"/api/waniwani","/tool"),l=typeof s=="string"&&s.trim().length>0?s.trim():void 0,u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",...l?{"X-Session-Id":l}:{},...o},body:JSON.stringify(a)});if(!u.ok)throw new Error(`Tool call failed: ${u.status} ${u.statusText}`);return u.json()},[])}import{useChat as lx}from"@ai-sdk/react";import{useCallback as Se,useEffect as He,useRef as Ce,useState as _t}from"react";var YI="/api/mcp/modules/documents",ZI=2e4,ex=3e5,Ze=class extends Error{code;constructor(t,a){super(a),this.name="DocumentUploadError",this.code=t}};function Bd(e,t){return kr(e,`${YI}${t}`)}function tx(e){return Bd(e,"/upload-url")}function Od(e,t){let a=new Headers(e);return new Headers(t).forEach((r,o)=>{a.set(o,r)}),a}function ax(e){let t=e?.data;if(typeof t?.documentId!="string"||typeof t.uploadUrl!="string"||!(t.documentId&&t.uploadUrl))return null;let a={};for(let[r,o]of Object.entries(t.headers??{}))typeof o=="string"&&(a[r]=o);return{documentId:t.documentId,uploadUrl:t.uploadUrl,headers:a}}function rx(e){return e===403?new Ze("upload_disabled","This agent does not accept document uploads."):e===413?new Ze("max_file_size","That file is too large."):e===422||e===400?new Ze("accept","That file type is not accepted."):new Ze("upload_failed",`The upload could not be started (${e}).`)}function ox(e){return new Promise((t,a)=>{let r=new XMLHttpRequest;r.open("PUT",e.url,!0);for(let[s,i]of Object.entries(e.headers))r.setRequestHeader(s,i);r.timeout=ex;let o=()=>r.abort();e.signal.addEventListener("abort",o,{once:!0});let n=()=>e.signal.removeEventListener("abort",o);r.upload.onprogress=s=>{s.lengthComputable&&s.total>0&&e.onProgress?.(s.loaded/s.total)},r.onload=()=>{if(n(),r.status>=200&&r.status<300||r.status===412){e.onProgress?.(1),t();return}a(new Ze("upload_failed",`The upload was rejected (${r.status}).`))},r.onerror=()=>{n(),a(new Ze("upload_failed","The upload could not be completed."))},r.ontimeout=()=>{n(),a(new Ze("upload_failed","The upload timed out."))},r.onabort=()=>{n(),a(e.signal.reason instanceof Error?e.signal.reason:new Error("aborted"))},r.send(e.file)})}async function xo(e){let t=Bd(e.api,`/${e.documentId}`);if(t)try{await fetch(t,{method:"DELETE",headers:Od(e.headers,e.uploadHeaders)})}catch{}}async function Ud(e){e.signal.throwIfAborted();let t=tx(e.api);if(!t)throw new Ze("upload_disabled","This agent does not accept document uploads.");let a=new AbortController,r=setTimeout(()=>a.abort(),ZI),o=()=>a.abort(e.signal.reason);e.signal.addEventListener("abort",o,{once:!0});let n;try{let i=Od(e.headers,e.uploadHeaders);i.set("Content-Type","application/json"),n=await fetch(t,{method:"POST",headers:i,signal:a.signal,body:JSON.stringify({filename:e.file.name,contentType:e.file.type,byteSize:e.file.size,...e.sessionId?{sessionId:e.sessionId}:{}})})}catch(i){throw e.signal.aborted?i:new Ze("upload_failed","The upload could not be started.")}finally{clearTimeout(r),e.signal.removeEventListener("abort",o)}if(!n.ok)throw rx(n.status);let s=ax(await n.json().catch(()=>null));if(e.signal.throwIfAborted(),!s)throw new Ze("upload_failed","The upload could not be started.");return await ox({url:s.uploadUrl,headers:s.headers,file:e.file,signal:e.signal,onProgress:e.onProgress}),{documentId:s.documentId,filename:e.file.name,mediaType:e.file.type}}import{DefaultChatTransport as nx,uiMessageChunkSchema as sx}from"ai";function ix(e){let t=e?.cause,a=t?.issues??t?.errors;if(!Array.isArray(a))return null;let r=a.find(o=>o.code==="invalid_union");if(!r?.errors)return null;for(let o of r.errors){if(!Array.isArray(o)||o.some(i=>(i.code==="invalid_value"||i.code==="invalid_literal")&&i.path?.[0]==="type"))continue;let s=o.filter(i=>i.code==="unrecognized_keys").flatMap(i=>i.keys??[]);if(s.length>0)return s}return null}var yo=class extends nx{processResponseStream(t){let a="",r=sx(),o=r.validate?.bind(r);return t.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({async transform(n,s){a+=n;let i=a.split(`
|
|
16
|
-
`);a=i.pop()??"";for(let l of i){let u=l.trim();if(!u.startsWith("data:"))continue;let d=u.slice(5).trim();if(d!=="[DONE]")try{let c=JSON.parse(d);if(!o){s.enqueue(c);continue}let p=await o(c);if(p.success){s.enqueue(p.value);continue}let f=ix(p.error);if(f?.length){let m={...c};for(let S of f)delete m[S];let y=await o(m);y.success&&s.enqueue(y.value)}}catch{}}}}))}};var Nd=50,qd=1e3;function Lo(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.threadId=="string"&&typeof t.memoryUserId=="string"&&typeof t.title=="string"&&Array.isArray(t.messages)&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"}async function So(e){if(typeof indexedDB>"u")return null;let t=null;try{return t=await on(),await e(t)}catch{return null}finally{try{t?.close()}catch{}}}function as(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error)})}async function rs(e){return await So(async a=>{let n=a.transaction(Ke,"readonly").objectStore(Ke).index(Tr),i=(await as(n.getAll(e))??[]).filter(Lo);return i.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),i})??[]}async function Co(e){return await So(async a=>{let o=a.transaction(Ke,"readonly").objectStore(Ke),n=await as(o.get(e));return Lo(n)?n:null})??null}async function os(e){if(!Lo(e))return;let t=e.messages.length>qd?{...e,messages:e.messages.slice(e.messages.length-qd)}:e;await So(async a=>{await new Promise((l,u)=>{let d=a.transaction(Ke,"readwrite");d.oncomplete=()=>l(),d.onerror=()=>u(d.error),d.onabort=()=>u(d.error),d.objectStore(Ke).put(t)});let r=a.transaction(Ke,"readwrite"),o=r.objectStore(Ke),n=o.index(Tr),i=(await as(n.getAll(t.memoryUserId))??[]).filter(Lo);if(i.length>Nd){i.sort((u,d)=>u.updatedAt<d.updatedAt?-1:1);let l=i.slice(0,i.length-Nd);for(let u of l)o.delete(u.threadId)}return await new Promise((l,u)=>{r.oncomplete=()=>l(),r.onerror=()=>u(r.error),r.onabort=()=>u(r.error)}),null})}async function Hd(e){await So(async t=>(await new Promise((a,r)=>{let o=t.transaction(Ke,"readwrite");o.oncomplete=()=>a(),o.onerror=()=>r(o.error),o.onabort=()=>r(o.error),o.objectStore(Ke).delete(e)}),null))}async function ns(e){return(await rs(e))[0]?.threadId??null}function $d(e){let t=e.trim();if(!t)return`Conversation on ${new Date().toISOString().slice(0,10)}`;let a=t.split(/\r?\n/,1)[0]??t;return a.length<=60?a:`${a.slice(0,60).trimEnd()}\u2026`}var ux="x-session-id",dx=250,cx=200;function Wd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Oa()}function bo(){return new Date().toISOString()}function jd(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}async function fx(e,t){let a=tt(e,"/tools"),r=await fetch(a,{method:"GET",headers:t?{...t}:void 0});if(!r.ok)throw new Error(`[Waniwani] Failed to fetch /tools: ${r.status} ${r.statusText}`);let o=await r.json();if(!o||!Array.isArray(o.tools))return{};let n={};for(let s of o.tools)s&&typeof s.name=="string"&&(n[s.name]=s);return n}function zd(e){let{api:t="/api/waniwani",headers:a,uploadHeaders:r,body:o,onMessageSent:n,onResponseReceived:s,enableThreadHistory:i=!1,activeThreadId:l,onThreadChange:u}=e,d=e.visitorId;He(()=>tn(d),[d]);let c=Io(),p=Ce(a),f=Ce(r),m=Ce(o),y=Ce(i);He(()=>{y.current=i},[i]);let S=Ce(void 0),L=Ce(void 0),C=Ce(null),[I,x]=_t(void 0),v=Ce(I),[q,N]=_t(l),V=Ce(q),[G,Q]=_t([]),[O,re]=_t(!i),K=Ce(void 0),J=Ce(void 0),X=Ce(void 0),R=Ce(void 0),b=Ce(0),D=Ce(u);He(()=>{D.current=u},[u]);let ae=Se(g=>{V.current=g,N(g),g&&(D.current?.(g),c.emit({name:"thread.changed",sessionId:v.current,properties:{threadId:g}}))},[c]),oe=Se(async()=>{if(!i)return;let g=C.current?.memoryUserId;if(!g)return;let U=await rs(g);Q(U)},[i]),Re=Se(()=>v.current,[]),Ne=Se(g=>{let U=jd(g);if(!U||v.current===U)return;let j=v.current===void 0;v.current=U,x(U),j&&c.emit({name:"session.started",properties:{sessionId:U}})},[c]),k=Se(()=>{v.current=void 0,x(void 0)},[]);He(()=>{p.current=a,f.current=r},[a,r]),He(()=>{m.current=o},[o]),He(()=>{let g=!1,U=b.current;return(async()=>{try{let de=await _a();if(g)return;C.current=de}catch{}if(!i)return;let j=C.current?.memoryUserId;if(!j){re(!0);return}try{let de=l??await ns(j);if(g||U!==b.current)return;if(de){let be=await Co(de);if(g||U!==b.current)return;be&&be.memoryUserId===j&&(V.current=be.threadId,N(be.threadId),K.current=be.createdAt,J.current=be.title,be.sessionId&&(v.current=be.sessionId,x(be.sessionId)),ye(be.messages))}await oe()}finally{g||re(!0)}})(),()=>{g=!0}},[]);let H=Ce(null),$=Se(g=>{let U=m.current?.[g];return typeof U=="string"?U:void 0},[]),ne=Se(()=>({api:t,token:Pr(p.current),channelId:$("channelId"),sessionId:v.current}),[t,$]),me=Se(g=>{let U=H.current;H.current=null,U?.report(ne(),{mode:$("mode"),outcome:g})},[ne,$]),Ie=Se(g=>{let U=typeof g=="object"&&g!==null&&!Array.isArray(g)?g:void 0,j=C.current?.memoryUserId,de=C.current?.language,be={};return j&&(be.memoryUserId=j),de&&(be.locale=de),Object.keys(be).length>0||U?{...be,...U??{}}:void 0},[]),fe=Se(()=>{let g=V.current;return g||(g=Wd(),K.current=bo(),J.current=void 0,ae(g)),g},[ae]),Z=Ce(new yo({api:t,headers:()=>({...p.current}),body:()=>{let g={...m.current??{}},U=Object.hasOwn(g,"sessionId"),j=jd(g.sessionId);if(j)Ne(j),g.sessionId=j;else if(U)k(),delete g.sessionId;else{let Uo=Re();Uo&&(g.sessionId=Uo)}ra(S.current)&&(g.modelContext=S.current),L.current?.length&&(g.documents=L.current);let de=C.current,be=Ge();de&&(g.visitorContext={timezone:de.timezone,language:de.language,languages:de.languages,deviceType:de.deviceType,referrer:de.referrer,visitorId:be});let Ae=typeof g.visitor=="object"&&g.visitor!==null?g.visitor:{},lp=typeof Ae.client=="object"&&Ae.client!==null?Ae.client:{};g.visitor={...Ae,id:be,client:{...lp,...de&&{memoryUserId:de.memoryUserId}}};let ui=Ie(g.extra);return ui&&(g.extra=ui),y.current&&(Object.hasOwn(g,"threadId")?typeof g.threadId=="string"&&(V.current=g.threadId):g.threadId=fe()),g},fetch:(async(g,U)=>{let j=H.current;j?.mark("requestStart");try{let de=await fetch(g,U);return S.current=void 0,Ne(de.headers.get(ux)),j?j.instrument(de):de}finally{L.current=void 0}})})),W=Ce(e.transport?.({fallback:Z.current,headers:()=>p.current,body:()=>{let g=Ie(m.current?.extra);return{channelId:$("channelId"),visitor:{id:Ge()},...g?{extra:g}:{}}},threadHistory:()=>y.current,threadId:()=>y.current?fe():void 0,hasMessages:()=>z.current.length>0,takeTurnInput:()=>{let g=L.current;return L.current=void 0,S.current=void 0,g?.length?{documents:g}:{}},onSession:Ne})??Z.current),se=Ce(null),xe=Ce(null),ie=Ce({}),[le,ee]=_t(0),ue=e.skipRemoteConfig===!0,Y=Se(async()=>{if(!ue)try{let g=await fx(t,p.current);ie.current=g,ee(U=>U+1)}catch(g){console.warn("[Waniwani] Failed to fetch tool definitions:",g instanceof Error?g.message:g)}},[t,ue]);He(()=>{Y()},[Y]);let{messages:he,sendMessage:T,setMessages:ye,status:_,stop:M}=lx({messages:e.initialMessages,transport:W.current,onFinish({message:g,isAbort:U,isDisconnect:j,isError:de}){H.current?.mark("streamEnd"),me(U||j||de?"error":"ok"),s?.(),!U&&!j&&!de&&c.emit({name:"message.received"}),se.current&&(xe.current=g)},onError(g){me("error"),console.warn("[Waniwani] Chat error:",g.message),c.emit({name:"chat.error",properties:{message:g.message.slice(0,cx)}}),se.current&&(se.current.reject(g),se.current=null)}}),z=Ce(he);He(()=>{z.current=he},[he]);let E=W.current.keepsSession?.()??!1,w=Ce(!1);He(()=>{!E||w.current||z.current.length>0||(w.current=!0,W.current.restore?.().then(g=>{g.length>0&&z.current.length===0&&ye(g)}).catch(()=>{}))},[E]),He(()=>{let g=W.current;return()=>g.dispose?.()},[]);let A=Se(()=>{H.current=Xi(z.current.filter(g=>g.role==="user").length+1)},[]),[F,pe]=_t(!1),nt=Se(async()=>{pe(!0);try{await M();let g=v.current;if(!g)return;await fetch(tt(t,"/cancel"),{method:"POST",headers:{"Content-Type":"application/json",...p.current},body:JSON.stringify({sessionId:g})})}catch{}finally{pe(!1)}},[t,M]),st=Ce(i);He(()=>{if(!i||st.current||(st.current=!0,z.current.length>0))return;let g=!1,U=b.current;return re(!1),(async()=>{try{let j=C.current;if(!j)try{j=await _a(),C.current=j}catch{}let de=j?.memoryUserId;if(!de||g||U!==b.current){g||re(!0);return}let be=l??await ns(de);if(g||U!==b.current)return;if(be){let Ae=await Co(be);if(g||U!==b.current)return;Ae&&Ae.memoryUserId===de&&(V.current=Ae.threadId,N(Ae.threadId),K.current=Ae.createdAt,J.current=Ae.title,Ae.sessionId&&(v.current=Ae.sessionId,x(Ae.sessionId)),ye(Ae.messages))}await oe()}finally{g||re(!0)}})(),()=>{g=!0}},[i]),He(()=>{if(_==="ready"&&se.current&&xe.current){let g=se.current,U=xe.current;se.current=null,xe.current=null,g.resolve(U)}},[_]);let[wr,St]=_t(""),oi=typeof d!="function",ni=wr.length>0;He(()=>{oi&&ni&&W.current.prepare?.()},[oi,ni]);let[Ct,Ir]=_t([]),Bo=Ce([]);Bo.current=Ct;let xa=_==="submitted"||_==="streaming",xr=Se(g=>{for(let U of g)for(let j of U.documents??[])xo({documentId:j.documentId,api:t,headers:p.current,uploadHeaders:f.current})},[t]),bt=Se(()=>{xr(Bo.current),Ir([])},[xr]),Yf=Se(g=>{let U=Bo.current.find(j=>j.id===g);U&&xr([U]),Ir(j=>j.filter(de=>de.id!==g))},[xr]),Zf=xa&&Ct.length>0,ep=Se(g=>{let U=!!g.text?.trim(),j=!!(g.files?.length||g.documents?.length);if(U||j){if(xa){if(Ct.length>0)return;Ir(de=>[...de,{id:Oa(),text:g.text||"",files:g.files??[],documents:g.documents??[],modelContext:g.modelContext}]),St("");return}A(),S.current=g.modelContext,L.current=g.documents,T({text:g.text||"",files:g.files,...g.documents?.length&&{metadata:{documents:g.documents}}}),n?.(g.text||""),c.emit({name:"message.sent"}),St("")}},[T,n,xa,Ct.length,c,A]),tp=Se(g=>new Promise((U,j)=>{se.current={resolve:U,reject:j},A(),T({text:g}),n?.(g),c.emit({name:"message.sent"})}),[T,n,c,A]);He(()=>{if(_!=="ready"||F||Ct.length===0)return;let[g,...U]=Ct;Ir(U),A(),S.current=g.modelContext,L.current=g.documents,T({text:g.text,files:g.files.length>0?g.files:void 0,...g.documents.length>0&&{metadata:{documents:g.documents}}}),n?.(g.text),c.emit({name:"message.sent"})},[_,F,T,n,Ct,c,A]);let ap=Se(()=>{W.current.reset?.(),ye([]),bt(),k(),St(""),ie.current={},ee(g=>g+1),Y()},[ye,k,Y,bt]),yr=Se(()=>{if(!y.current)return;let g=C.current?.memoryUserId,U=V.current,j=z.current;if(!(!g||!U||j.length===0)){if(K.current||(K.current=bo()),!J.current){let de=j.find(Ae=>Ae.role==="user"),be=de?de.parts.map(Ae=>"text"in Ae&&typeof Ae.text=="string"?Ae.text:"").join(" "):"";J.current=$d(be)}return{threadId:U,memoryUserId:g,title:J.current,messages:j,sessionId:v.current,createdAt:K.current,updatedAt:bo()}}},[]),si=Se(async()=>{let g=yr();g&&(await os(g),await oe())},[yr,oe]);He(()=>{if(i&&O&&!(_==="submitted"||_==="streaming")&&he.length!==0)return X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{X.current=void 0;let g=si().finally(()=>{R.current===g&&(R.current=void 0)});R.current=g},dx),()=>{X.current&&clearTimeout(X.current)}},[i,O,he,_,si]);let Lr=Se(()=>{let g=R.current,U=X.current,j=U?yr():void 0;return U&&(clearTimeout(U),X.current=void 0),(async()=>{g&&await g,j&&(await os(j),await oe())})()},[yr,oe]),rp=Se(()=>{b.current+=1,Lr(),W.current.dispose?.(),ye([]),bt(),k(),St("");let g=Wd();return K.current=bo(),J.current=void 0,ae(g),oe(),g},[ye,k,ae,oe,Lr,bt]),Oo=Se(async g=>{b.current+=1;let U=b.current;if(await Lr(),U!==b.current)return;let j=await Co(g);U===b.current&&j&&(W.current.dispose?.(),j.sessionId?(v.current=j.sessionId,x(j.sessionId)):k(),ae(j.threadId),K.current=j.createdAt,J.current=j.title,ye(j.messages),bt(),St(""))},[ye,k,ae,Lr,bt]),op=Se(async g=>{if(V.current===g){b.current+=1,X.current&&(clearTimeout(X.current),X.current=void 0);let U=R.current;U&&await U}await Hd(g),W.current.forget?.(g),await oe(),V.current===g&&(W.current.dispose?.(),ye([]),bt(),k(),St(""),V.current=void 0,N(void 0),K.current=void 0,J.current=void 0)},[ye,k,oe,bt]);He(()=>{i&&O&&l!==void 0&&l!==V.current&&Oo(l)},[l,i,O,Oo]);let np=Se(g=>{St(g.target.value)},[]),ii=he[he.length-1],li=he.length>0,sp=xa&&(!li||ii.role==="user"),ip=ie.current;return{messages:he,status:_,text:wr,setText:St,handleSubmit:ep,handleTextChange:np,isLoading:xa,showLoaderBubble:sp,lastMessage:ii,hasMessages:li,sendMessage:T,sendMessageAndWait:tp,stop:nt,reset:ap,queuedMessages:Ct,queueFull:Zf,removeQueuedMessage:Yf,sessionId:I,toolDefinitions:ip,refreshToolDefinitions:Y,threads:G,activeThreadId:q,isThreadHistoryReady:O,startNewThread:rp,switchThread:Oo,deleteThread:op,keepsSession:E}}import{useCallback as Vd,useEffect as px,useState as mx}from"react";var hx=6e3;function Gd(e){let{api:t,headers:a,uploadHeaders:r,sessionId:o,documentUpload:n,allowAttachments:s}=e,[i,l]=mx(null),u=Vd((p,f,m)=>Ud({file:p,api:t,headers:a,uploadHeaders:r,sessionId:o,signal:f,onProgress:m}),[t,a,r,o]),d=Vd(p=>{xo({documentId:p.documentId,api:t,headers:a,uploadHeaders:r})},[t,a,r]);px(()=>{if(!i)return;let p=setTimeout(()=>l(null),hx);return()=>clearTimeout(p)},[i]);let c=n?.enabled??!1;return{enabled:n?n.enabled:!!s,accept:n?.accept.join(","),maxFileSize:n?.maxBytes,maxPdfPages:n?.maxPdfPages,maxFiles:n?.maxFiles,upload:c?u:void 0,onDiscard:c?d:void 0,error:i,reportError:l}}import{useCallback as wx,useEffect as ls,useMemo as us,useRef as Ix,useState as Qd}from"react";function pa(e){return e.map(t=>({id:null,text:t}))}function ss(e){let{flow:t,followup:a,page:r,channel:o}=e;return t!==null?{origin:"flow",suggestions:t}:a?.length?{origin:"followup",suggestions:a}:r?.length?{origin:"page",suggestions:r}:o?.length?{origin:"channel",suggestions:o}:null}var is="waniwani/suggestions";function ma(e){return typeof e=="object"&&e!==null}function Kd(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function gx(e){if(!ma(e)||!("toolCallId"in e)||!("output"in e))return null;let t=e.output;if(!ma(t)||!ma(t._meta))return null;let a=t._meta[is];return!ma(a)||!Kd(a.suggestions)?null:a.suggestions}function Xd(e){let t=null;for(let a of e.parts){let r=gx(a);r!==null&&(t=r)}return t}function Jd(e){for(let t of e.parts){if(!ma(t)||t.type!=="data-suggestions")continue;let a=t.data;if(ma(a)&&Kd(a.suggestions)&&a.suggestions.length>0)return a.suggestions}return null}function xx(e){return"page"in e||"channel"in e}function yx(e){return typeof e!="object"||e===null?{}:xx(e)?{rungs:e}:{initial:e.initial}}function Yd(e){let{messages:t,status:a,suggestions:r}=e,o=r!==!1,{rungs:n,initial:s}=yx(r),i=us(()=>({page:null,channel:pa(s??[])}),[s]),l=n??i,u=us(()=>o?ss({flow:null,followup:null,...l}):null,[o,l]),d=us(()=>u?.suggestions.map(I=>I.text)??[],[u]),[c,p]=Qd(d),[f,m]=Qd(u?.origin??"channel"),y=Ix(a),S=wx(()=>{p([])},[]),L=t.length>0;ls(()=>{L||(p(d),m(u?.origin??"channel"))},[d,u,L]);let C=t[t.length-1];return ls(()=>{C?.role==="user"&&S()},[C,S]),ls(()=>{let I=y.current;if(y.current=a,I!=="streaming"||a!=="ready"||!o)return;let x=[...t].reverse().find(V=>V.role==="assistant");if(!x)return;let v=Xd(x),q=Jd(x),N=ss({flow:v===null?null:pa(v),followup:q===null?null:pa(q),page:null,channel:null});p(N?N.suggestions.map(V=>V.text):[]),m(N?.origin??"channel")},[a,o,t]),{suggestions:c,source:f,isLoading:!1,clear:S}}import{useEffect as Lx,useRef as Sx,useState as Cx}from"react";var bx=80,vx=50,kx=15e3,Zd=500;function ec(e,t=!0){let[a,r]=Cx(""),o=Sx(void 0);return Lx(()=>{if(!t){r("");return}let n=0,s=!1,i=!1,l=()=>{i||(s?(n--,r(e.slice(0,n)),n<=0?(s=!1,o.current=setTimeout(l,Zd)):o.current=setTimeout(l,vx)):(n++,r(e.slice(0,n)),n>=e.length?(s=!0,o.current=setTimeout(l,kx)):o.current=setTimeout(l,bx)))};return o.current=setTimeout(l,Zd),()=>{i=!0,clearTimeout(o.current)}},[e,t]),a}function tc(e,t){let a=t?.Authorization,r=typeof a=="string"&&a.startsWith("Bearer ")?a.slice(7):null;return tt(e,"/resource",r?{token:r}:void 0)}var ac={primaryColor:"#6366f1",primaryForeground:"#1f2937",backgroundColor:"#ffffff",textColor:"#1f2937",mutedColor:"#6b7280",borderColor:"#e5e7eb",borderWidth:0,boxShadow:"none",assistantBubbleColor:"#f3f4f6",userBubbleColor:"#f4f4f4",inputBackgroundColor:"#f9fafb",borderRadius:16,messageBorderRadius:8,fontFamily:"system-ui, -apple-system, 'Segoe UI', sans-serif",headerBackgroundColor:"#ffffff",headerTextColor:"#1f2937",statusColor:"#22c55e",toolCardColor:"#f4f4f5",userBubbleTextColor:"#1f2937",assistantBubbleTextColor:"#1f2937",messagePaddingX:16,messagePaddingY:12,messageMaxWidth:"80%",fontSize:16,lineHeight:"1.5",glassTint:"transparent",glassTintStrength:"0"},Tx={backgroundColor:"#212121",headerBackgroundColor:"#1e1e1e",headerTextColor:"#ececec",textColor:"#ececec",primaryForeground:"#ffffff",mutedColor:"#8e8ea0",borderColor:"#444444",assistantBubbleColor:"#2f2f2f",userBubbleColor:"#303030",inputBackgroundColor:"#2f2f2f",primaryColor:"#6366f1",statusColor:"#22c55e",toolCardColor:"#262626",userBubbleTextColor:"#ffffff",assistantBubbleTextColor:"#ececec"},Ax={primaryColor:["--ww-primary","--ww-color-primary"],primaryForeground:["--ww-primary-fg","--ww-color-primary-foreground"],backgroundColor:["--ww-bg","--ww-color-background"],textColor:["--ww-text","--ww-color-foreground","--ww-color-accent-foreground"],mutedColor:["--ww-muted","--ww-color-muted-foreground"],borderColor:["--ww-border","--ww-color-border"],borderWidth:["--ww-border-width"],boxShadow:["--ww-shadow"],assistantBubbleColor:["--ww-assistant-bubble","--ww-color-accent"],userBubbleColor:["--ww-user-bubble"],inputBackgroundColor:["--ww-input-bg","--ww-color-input"],borderRadius:["--ww-radius"],messageBorderRadius:["--ww-msg-radius"],fontFamily:["--ww-font"],headerBackgroundColor:["--ww-header-bg"],headerTextColor:["--ww-header-text"],statusColor:["--ww-status"],toolCardColor:["--ww-tool-card","--ww-color-tool-card"],userBubbleTextColor:["--ww-user-bubble-text"],assistantBubbleTextColor:["--ww-assistant-bubble-text"],messagePaddingX:["--ww-msg-pad-x"],messagePaddingY:["--ww-msg-pad-y"],messageMaxWidth:["--ww-msg-max-width"],fontSize:["--ww-font-size"],lineHeight:["--ww-line-height"],glassTint:["--ww-glass-tint"],glassTintStrength:["--ww-glass-tint-opacity"]};function Px(e){return{...ac,...e}}function ds(e){let t={};for(let[a,r]of Object.entries(Ax)){let o=e[a];if(o===void 0)continue;let n=typeof o=="number"?`${o}px`:String(o);for(let s of r)t[s]=n}return t}import{jsx as ke,jsxs as xt}from"react/jsx-runtime";var cs=rc(function(t,a){let{locale:r,messages:o}=t;return ke(Vo,{locale:r,messages:o,children:ke(Ex,{...t,ref:a})})}),Ex=rc(function(t,a){let{t:r,ready:o}=te(),{appearance:n,className:s,classNames:i,allowAttachments:l=!1,documentUpload:u,welcomeMessage:d,welcome:c,placeholder:p=r.promptInput.placeholder,triggerEvent:f="triggerDemoRequest",api:m,mcp:y,debug:S=!1,readOnly:L=!1,title:C,headerActions:I,hideHeader:x=!1,enableThreadHistory:v=!1,showToolCalls:q=!0,initializing:N=!1,onScreen:V=!0,disclaimer:G}=t,Q=n?.theme,O=n?.variables,re=n?.assistantBubble??!1,K=O?ds(O):{},[J,X]=vo(!1);It(()=>{if(Q!=="auto"||typeof window>"u")return;let w=window.matchMedia("(prefers-color-scheme: dark)");X(w.matches);let A=()=>X(w.matches);return w.addEventListener("change",A),()=>w.removeEventListener("change",A)},[Q]);let R=Q==="dark"||Q==="auto"&&J,b=zd({...t,api:m}),D=Io(),ae=Dd({...t,api:m,sessionId:b.sessionId,onCallTool:y?.onCallTool}),oe=y?.resourceEndpoint??tc(m,t.headers),Re=Dt({});Re.current={api:m,token:Pr(t.headers),channelId:typeof t.body?.channelId=="string"?t.body.channelId:void 0,sessionId:b.sessionId};let Ne=rr(w=>{Er("widget",Re.current,{widget:w.widget,outcome:w.outcome},w.metrics)},[]),k=ec(p,!b.text),H=Gd({api:m,headers:t.headers,uploadHeaders:t.uploadHeaders,sessionId:b.sessionId,documentUpload:u,allowAttachments:l}),[$,ne]=vo(null),[me,Ie]=vo(null),fe=Dt(null),Z=Dt(null),W=Dt(null),se=Dt(null),[xe,ie]=vo(!0),le=Dt(xe);le.current=xe;let ee=rr(()=>{let w=fe.current;if(!w)return;let A=w.querySelector("textarea");A&&A.focus()},[]),ue=rr((w="smooth")=>{let A=Z.current;A&&A.scrollTo({top:A.scrollHeight,behavior:w})},[]);It(()=>{let w=se.current,A=Z.current;if(!w||!A)return;let F=new IntersectionObserver(([pe])=>ie(pe.isIntersecting),{root:A,rootMargin:"0px 0px 200px 0px",threshold:0});return F.observe(w),()=>F.disconnect()},[]),It(()=>{let w=Z.current;if(!w)return;let A=F=>{let nt=(F.target instanceof Element?F.target:null)?.closest("a");nt?.href&&D.emit({name:"link.clicked",properties:{url:nt.href}})};return w.addEventListener("click",A),()=>w.removeEventListener("click",A)},[D]),It(()=>{(b.messages[b.messages.length-1]?.role==="user"||le.current)&&ue("smooth")},[b.messages.length,b.messages[b.messages.length-1]]),It(()=>{ue("auto")},[ue]),It(()=>{if(typeof ResizeObserver>"u")return;let w=Z.current,A=W.current;if(!w&&!A)return;let F=w?.scrollHeight??0,pe=w?.clientHeight??0,nt=new ResizeObserver(()=>{let st=Z.current;if(!st)return;let wr=st.scrollTop+pe>=F-5;F=st.scrollHeight,pe=st.clientHeight,wr&&ue("auto")});return w&&nt.observe(w),A&&nt.observe(A),()=>nt.disconnect()},[ue]);let Y=Yd({messages:b.messages,status:b.status,suggestions:t.suggestions}),he=Dt(null);It(()=>{let w=Y.suggestions;!V||w.length===0||he.current===w||(he.current=w,D.emit({name:"suggestions.shown",properties:{texts:w,origin:Y.source}}))},[Y.suggestions,Y.source,D,V]);let T=c?.suggestions,ye=Dt(null);It(()=>{!V||b.messages.length>0||!T?.length||ye.current===T||(ye.current=T,D.emit({name:"suggestions.shown",properties:{texts:T,origin:"channel"}}))},[T,b.messages.length,D,V]);let _=rr(w=>{let A=w.content.map(F=>F.text??"").join("").trim();A&&b.handleSubmit({text:A,files:[],modelContext:w.modelContext})},[b.handleSubmit]),M=rr(w=>{let A=Y.suggestions.indexOf(w),F=A>=0?A:c?.suggestions?.indexOf(w)??-1,pe=A>=0?Y.source:"channel";D.emit({name:"suggestion.clicked",properties:{text:w,index:F,origin:pe}}),Y.clear(),b.handleSubmit({text:w,files:[]})},[Y.suggestions,Y.source,Y.clear,b.handleSubmit,c,D]);Rx(a,()=>({sendMessage:w=>{b.handleSubmit({text:w,files:[]}),ee()},sendMessageAndWait:w=>b.sendMessageAndWait(w),reset:b.reset,focus:ee,get messages(){return b.messages},get sessionId(){return b.sessionId}}),[b.handleSubmit,b.sendMessageAndWait,b.reset,b.messages,b.sessionId,ee]),It(()=>{if(!f)return;let w=A=>{let F=A.detail,pe=typeof F?.message=="string"?F.message:void 0;pe&&b.handleSubmit({text:pe,files:[]}),ee()};return window.addEventListener(f,w),()=>window.removeEventListener(f,w)},[f,b.handleSubmit,ee]);let z=!x&&!!(C||v||b.keepsSession||I),E=N||!o;return xt("div",{ref:fe,style:{...K,maxHeight:"inherit",...$&&me?{height:me}:{},opacity:E?0:1,transition:"opacity 220ms ease-out"},"data-waniwani-chat":"","data-waniwani-layout":"embed","data-assistant-bubble":re?"true":void 0,"data-color-scheme":Q==="auto"?"auto":void 0,...E?{"data-waniwani-initializing":""}:{},...R?{"data-waniwani-dark":""}:{},className:P("ww:relative ww:w-full ww:h-full ww:flex ww:flex-col ww:bg-background ww:text-foreground ww:font-[family-name:var(--ww-font)] ww:overflow-hidden",Q==="dark"&&"dark",s,i?.root),children:[z&&xt("div",{className:P("ww-header ww:shrink-0 ww:flex ww:items-center ww:gap-2 ww:pl-4 ww:pr-3 ww:py-3 ww:border-b ww:border-border",i?.header),style:{backgroundColor:"var(--ww-color-card-header)",color:"var(--ww-color-card-header-foreground)"},children:[C&&ke("div",{className:"ww:text-sm ww:font-semibold ww:truncate ww:flex-1 ww:min-w-0",children:C}),!C&&ke("div",{className:"ww:flex-1"}),!v&&b.keepsSession&&ke(go,{onClick:b.reset}),v&&ke(Rd,{threads:b.threads,activeThreadId:b.activeThreadId,onNewThread:b.startNewThread,onSelectThread:w=>{b.switchThread(w)},onDeleteThread:w=>{b.deleteThread(w)}}),I]}),xt("div",{ref:Z,className:P("ww:relative ww:flex-1 ww:min-h-0",$?"ww:overflow-hidden":"ww:overflow-y-auto"),children:[xt("div",{ref:W,className:P("ww:mx-auto ww:w-full ww:max-w-3xl ww:px-4 ww:py-6 ww:flex ww:flex-col ww:gap-6",$&&"ww:!py-0"),children:[ke(el,{value:Ne,children:ke(vd,{messages:b.messages,status:b.status,welcomeMessage:d,welcome:c,onSuggestionSelect:M,resourceEndpoint:oe,chatSessionId:b.sessionId,isDark:R,onFollowUp:_,onCallTool:ae,fullscreenToolCallId:$,debug:S,showToolCalls:q,toolDefinitions:b.toolDefinitions,messageClassNames:{message:i?.message,userBubble:i?.userBubble,assistantBubble:i?.assistantBubble},onWidgetDisplayModeChange:(w,A)=>{if(w==="fullscreen"){let F=fe.current?.getBoundingClientRect().height??0;Ie(F>0?F:null),ne(A.toolCallId)}else Ie(null),ne(null)}})}),ke("div",{ref:se,"aria-hidden":!0,style:{height:1}})]}),!xe&&!$&&ke("div",{className:"ww:sticky ww:bottom-2 ww:flex ww:justify-center ww:pointer-events-none",children:ke(it,{type:"button",onClick:()=>ue("smooth"),size:"icon",variant:"outline",className:"ww:rounded-full ww:shadow ww:pointer-events-auto","aria-label":"Scroll to latest",children:ke(La,{className:"ww:size-4"})})})]}),!L&&xt("div",{className:"ww:shrink-0 ww:bg-background",style:$?{display:"none"}:void 0,children:[ke(Ad,{suggestions:Y.suggestions,isLoading:Y.isLoading,onSelect:M}),ke(Al,{queuedMessages:b.queuedMessages,onRemove:b.removeQueuedMessage}),ke("div",{className:"ww:px-4 ww:pb-2 ww:pt-2",children:xt("div",{className:"ww:mx-auto ww:w-full ww:max-w-3xl",children:[xt(pl,{onSubmit:b.handleSubmit,attachmentsEnabled:H.enabled,globalDrop:H.enabled,multiple:H.enabled,accept:H.accept,maxFileSize:H.maxFileSize,maxPdfPages:H.maxPdfPages,maxFiles:H.maxFiles,upload:H.upload,onDiscard:H.onDiscard,onError:H.reportError,className:P("ww-input ww:rounded-2xl ww:border-border ww:bg-input",i?.input),children:[ke(xl,{enabled:H.enabled}),H.enabled&&ke(Il,{className:"ww:px-4 ww:pt-3"}),xt("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-4 ww:pr-3 ww:py-2.5",children:[H.enabled&&ke(wl,{}),ke(hl,{onChange:b.handleTextChange,value:b.text,placeholder:k,className:"ww:min-h-0 ww:py-1 ww:px-0"}),ke(gl,{status:b.status,disabled:b.queueFull,onStop:b.stop})]})]}),H.error&&ke("output",{className:"ww:block ww:pt-1.5 ww:text-center ww:text-destructive ww:text-xs",children:H.error.message}),xt("div",{className:"ww:pt-2 ww:pb-1 ww:flex ww:flex-nowrap ww:justify-center ww:items-center ww:gap-1.5",children:[ke(Td,{}),ke(yl,{text:G})]})]})})]})]})});import{forwardRef as NS,useEffect as Do,useImperativeHandle as qS,useMemo as ai,useRef as ri,useState as Xf}from"react";var Mx="https://app.waniwani.ai/api/mcp/chat",Fx={api:Mx};function _x(){if(typeof document>"u")return null;if(document.currentScript instanceof HTMLScriptElement)return document.currentScript;let e=document.querySelector("script[src][data-token]");if(e instanceof HTMLScriptElement)return e;let t=document.querySelectorAll("script[src]");for(let a of t)if(a instanceof HTMLScriptElement&&/embed/i.test(a.src))return a;return null}function Dx(){let e=_x();if(!e)return{};let t=D=>e.getAttribute(D)??void 0,a=D=>{let ae=e.getAttribute(D);if(ae==null)return;let oe=ae.trim().toLowerCase();if(oe==="true"||oe==="1"||oe==="")return!0;if(oe==="false"||oe==="0")return!1},r={},o=t("data-api");o&&(r.api=o);let n=t("data-token");n&&(r.token=n);let s=t("data-visitor-id");s&&(r.visitorId=s);let i=t("data-title");i&&(r.title=i);let l=t("data-welcome-message");l&&(r.welcomeMessage=l);let u=t("data-placeholder");u&&(r.placeholder=u);let d=t("data-mcp-server-url");d&&(r.mcpServerUrl=d);let c=t("data-webmcp");c&&(r.webmcp={enabled:c!=="false"&&c!=="off"});let p=t("data-channel-id");if(p&&(r.channelId=p),t("data-show-tool-calls")?.trim().toLowerCase()==="titles-only")r.showToolCalls="titles-only";else{let D=a("data-show-tool-calls");D!==void 0&&(r.showToolCalls=D)}let m=t("data-css");m&&(r.css=m);let y=t("data-suggestions");y&&(r.suggestions=y.split(",").map(D=>D.trim()).filter(Boolean));let S=a("data-enable-thread-history");S!==void 0&&(r.enableThreadHistory=S);let L=a("data-disable-page-view");L!==void 0&&(r.disablePageView=L);let C=a("data-hide-header");C!==void 0&&(r.hideHeader=C);let I=t("data-theme");(I==="light"||I==="dark"||I==="auto")&&(r.appearance={...r.appearance,theme:I});let x=a("data-assistant-bubble");x!==void 0&&(r.appearance={...r.appearance,assistantBubble:x});let v=t("data-locale");(v==="en"||v==="fr"||v==="es")&&(r.locale=v);let q=t("data-mode");(q==="inline"||q==="floating"||q==="composer"||q==="off")&&(r.mode=q);let N={},V=t("data-composer-variant")?.trim().toLowerCase();(V==="glow"||V==="outline")&&(N.variant=V);let G=t("data-composer-size")?.trim().toLowerCase();(G==="sm"||G==="md"||G==="lg")&&(N.size=G);let Q=a("data-composer-suggestions");Q!==void 0&&(N.showSuggestions=Q);let O=t("data-composer-align")?.trim().toLowerCase();(O==="start"||O==="center")&&(N.align=O);let re=a("data-composer-trigger");re!==void 0&&(N.trigger=re);let K=a("data-composer-mobile-trigger");K!==void 0&&(N.mobileTrigger=K),Object.keys(N).length>0&&(r.composer=N);let J=t("data-height");J&&(r.height=J);let X=t("data-launcher-text");X&&(r.launcherText=X);let R=t("data-appear-delay");if(R!==void 0){let D=Number.parseInt(R.trim(),10);Number.isFinite(D)&&D>=0&&(r.appearDelay=D)}let b=t("data-disclaimer");if(b!==void 0){let D=b.trim(),ae=D.toLowerCase();ae==="false"||ae==="0"?r.disclaimer=!1:D&&(r.disclaimer=D)}return r}function or(e){if(!e)return{};let t={};for(let a in e)e[a]!==void 0&&(t[a]=e[a]);return t}function fs(e,t,a){let r=a??Dx(),o=Bx(t,r,e),n={...t?.composer??{},...or(r.composer),...or(e?.composer)},s=Object.keys(n).length>0,i={token:"",...Fx,...or(t),...or(r),...or(e),...o?{appearance:o}:{},...s?{composer:n}:{}};if(!i.token)throw new Error("[Waniwani] Missing required config: `token`. Set data-token on the script tag or pass it to Waniwani.chat.init().");return i}function Bx(e,t,a){let r=a?.appearance?.theme??t.appearance?.theme??e?.appearance?.theme,o={...e?.appearance?.variables??{},...t.appearance?.variables??{},...a?.appearance?.variables??{}},n=Object.keys(o).length>0,s=a?.appearance?.assistantBubble??t.appearance?.assistantBubble??e?.appearance?.assistantBubble;if(!r&&!n&&s===void 0)return;let i={};return r&&(i.theme=r),n&&(i.variables=o),s!==void 0&&(i.assistantBubble=s),i}import{useEffect as jR,useState as zR}from"react";var Ox="/api/mcp/events/v2/batch",ps=new Set;function Ux(e,t,a){return`${e}|${t}|${a??""}`}function nr(e){return kr(e,Ox)}async function ms(e){let{api:t,token:a,channelId:r,mode:o,source:n}=e;if(typeof window>"u"||!t||!a)return;let s=nr(t);if(!s){lt("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!r&&!n){lt("page.viewed skipped: no channelId or source to attribute it");return}let i=Ux(t,a,r);if(!ps.has(i)){ps.add(i);try{let l=await _a(),u=new Date().toISOString(),d=JSON.stringify({sentAt:u,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:"page.viewed",source:n,timestamp:u,correlation:{visitorId:l.visitorId},properties:{channelId:r,mode:o,url:window.location.href,referrer:l.referrer,deviceType:l.deviceType,language:l.language,timezone:l.timezone},metadata:{}}]}),c=fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:d,keepalive:!0});$t("pageViewSent"),await c}catch{ps.delete(i)}}}import{useMemo as Kx}from"react";import{useEffect as $x,useSyncExternalStore as Wx}from"react";function Nx(e){return e?.patterns??e?.rules??[]}var oc="\0\0";function qx(e){let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*\\\*/g,oc).replace(/\\\*/g,"[^/]*").split(oc).join(".*");return new RegExp(`^${a}$`)}function Hx(e,t){try{return qx(e).test(t)}catch{return!1}}function nc(e,t){if(!e)return!0;let a=!1;for(let r of Nx(e))if(Hx(r.glob,t)){if(r.action==="hide")return!1;a=!0}return a?!0:(e.default??"show")!=="hide"}var hs="waniwani:locationchange",sc=!1;function jx(){if(!(sc||typeof history>"u")){sc=!0;for(let e of["pushState","replaceState"]){let t=history[e];history[e]=function(...r){let o=t.apply(this,r);return window.dispatchEvent(new Event(hs)),o}}}}function zx(e){return jx(),window.addEventListener(hs,e),window.addEventListener("popstate",e),()=>{window.removeEventListener(hs,e),window.removeEventListener("popstate",e)}}function Vx(){return window.location.pathname}function Gx(){return"/"}function gs(){return Wx(zx,Vx,Gx)}function ic(e,t){let a=gs(),r=t&&nc(e,a);return $x(()=>{lt("visibility gate",{pathname:a,ready:t,visible:r,rules:e})},[a,t,r]),r}var Xx=3,Jx=["low","medium","high"];function ws(e){if(e.length===0)return;let t=Math.floor(Math.random()*e.length),[a]=e.splice(t,1);return a}function Qx(e){let t=new Map,a=[];for(let n of e)if(n.tier){let s=t.get(n.tier)??[];s.push(n),t.set(n.tier,s)}else a.push(n);let r=[];for(let n of Jx){let s=ws(t.get(n)??[])??ws(a);s&&r.push(s)}let o=[...t.values()].flat().concat(a);for(;r.length<Math.min(Xx,e.length);){let n=ws(o);if(!n)break;r.push(n)}return r}function lc(e){let t;try{t=new URL(e,"http://localhost").pathname}catch{t="/"}let a=t.replace(/\/+$/,"");return(a===""?"/":a).toLowerCase()}function uc(e){return Array.isArray(e)?e.flatMap(t=>{let a=t;if(typeof a?.url!="string"||a.url.length===0||!Array.isArray(a.prompts))return[];let r=a.prompts.flatMap(o=>{let n=o;return typeof n?.text!="string"||n.text.length===0?[]:[{id:typeof n.id=="string"?n.id:null,text:n.text,tier:n.tier==="low"||n.tier==="medium"||n.tier==="high"?n.tier:void 0}]});return r.length>0?[{url:a.url,prompts:r}]:[]}):[]}function dc(e){let{pageSuggestions:t,suggestions:a}=e,r=gs();return Kx(()=>{let o=lc(r),n=t?.find(i=>lc(i.url)===o),s=n?Qx(n.prompts).map(({id:i,text:l})=>({id:i,text:l})):null;return lt("configured suggestions resolve",{pathname:o,matched:!!n,count:s?.length??0}),{page:s,channel:pa(a??[])}},[r,t,a])}var Yx="waniwani:config:";function cc(e,t,a){return`${Yx}${e}|${t}|${a??""}`}function ko(e,t,a){if(typeof window>"u")return null;try{let r=window.sessionStorage.getItem(cc(e,t,a));if(!r)return null;let o=JSON.parse(r);return o&&typeof o=="object"?o:null}catch{return null}}function fc(e,t,a,r){if(!(typeof window>"u"))try{window.sessionStorage.setItem(cc(e,t,a),JSON.stringify(r))}catch{}}function Zx(e){if(typeof e!="object"||e===null||typeof e.enabled!="boolean")return null;let t=Array.isArray(e.accept)?e.accept.filter(r=>typeof r=="string"):[],a=r=>typeof r=="number"&&Number.isFinite(r)&&r>0;return e.enabled?a(e.maxBytes)&&a(e.maxPdfPages)&&a(e.maxFiles)&&t.length>0?{enabled:!0,maxBytes:e.maxBytes,maxPdfPages:e.maxPdfPages,maxFiles:e.maxFiles,accept:t}:null:{enabled:!1,maxBytes:0,maxPdfPages:0,maxFiles:0,accept:t}}async function pc(e,t,a,r){$t("configStart");let o=await ey(e,t,a,r);return $t("configEnd"),a?.aborted||Rr(o.metadata),o}async function ey(e,t,a,r){try{let o=tt(e,"/config",r?{channel:r}:void 0),n=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:a});if(!n.ok)return{};let s=await n.json(),i=s&&typeof s=="object"&&"data"in s&&s.data?s.data:s;return i?ty(i):{}}catch{return{}}}function ty(e){let t={};e.source!=null&&(t.source=e.source),e.channelId!=null&&(t.channelId=e.channelId),e.title!=null&&(t.title=e.title),e.welcomeMessage!=null&&(t.welcomeMessage=e.welcomeMessage),e.placeholder!=null&&(t.placeholder=e.placeholder),e.suggestions!=null&&e.suggestions.length>0&&(t.suggestions=e.suggestions);let a=uc(e.pageSuggestions);a.length>0&&(t.pageSuggestions=a),typeof e.enableThreadHistory=="boolean"&&(t.enableThreadHistory=e.enableThreadHistory),typeof e.sessionApi=="string"&&e.sessionApi&&(t.sessionApi=e.sessionApi),typeof e.webmcp?.enabled=="boolean"&&(t.webmcp={enabled:e.webmcp.enabled}),e.toolCallDisplay==="full"?t.showToolCalls=!0:e.toolCallDisplay==="titles-only"?t.showToolCalls="titles-only":e.toolCallDisplay==="hidden"&&(t.showToolCalls=!1),e.visibility&&(t.visibility=e.visibility);let r=Zx(e.documentUpload);return r&&(t.documentUpload=r),e.metadata&&typeof e.metadata=="object"&&(t.metadata=e.metadata),t}import{useRef as cS,useState as fS}from"react";import{readUIMessageStream as ay}from"ai";function To(){let e=new Set,t=new Map,a,r=0,o=!1,n=!1,s=d=>(a||(a=`text-${++r}`,d.enqueue({type:"text-start",id:a})),a),i=d=>{a&&(d.enqueue({type:"text-end",id:a}),a=void 0)},l=(d,c)=>{d.enqueue({type:"text-delta",id:s(d),delta:c})},u=(d,c,p)=>{e.has(c.callId)||(e.add(c.callId),d.enqueue({type:"tool-input-available",toolCallId:c.callId,toolName:c.toolName??c.kind,input:p,dynamic:!0}))};return new TransformStream({start(d){d.enqueue({type:"start",messageId:crypto.randomUUID()})},transform(d,c){switch(d.type){case"step.started":{t.set(d.data.stepIndex,d.data.modelId),c.enqueue({type:"start-step"}),o=!0;break}case"message.appended":{d.data.messageDelta&&l(c,d.data.messageDelta);break}case"message.completed":{!a&&d.data.message&&l(c,d.data.message),i(c);break}case"actions.requested":{i(c);for(let p of d.data.actions)u(c,p,p.input);break}case"action.result":{let{result:p,status:f,error:m}=d.data;if(p.kind!=="tool-result")break;if(u(c,p,{}),p.isError===!0||f!=="completed"){c.enqueue({type:"tool-output-error",toolCallId:p.callId,errorText:m?.message??"The tool call failed.",dynamic:!0});break}c.enqueue({type:"tool-output-available",toolCallId:p.callId,output:p.output,dynamic:!0});break}case"step.completed":{let{stepIndex:p,usage:f}=d.data;i(c),o&&(c.enqueue({type:"finish-step"}),o=!1),c.enqueue({type:"message-metadata",messageMetadata:{"waniwani/step":{stepIndex:p,modelId:t.get(p),usage:f}}});break}case"turn.failed":case"session.failed":{n=!0,c.enqueue({type:"error",errorText:d.data.message||"The agent could not answer."});break}}},flush(d){i(d),o&&d.enqueue({type:"finish-step"}),d.enqueue({type:"finish",finishReason:n?"error":"stop"})}})}async function ry(e){let t=new ReadableStream({start(r){for(let o of e)r.enqueue(o);r.close()}}).pipeThrough(To()),a;for await(let r of ay({stream:t}))a=r;return a?.parts.length?a:void 0}async function mc(e){let t=[];for(let r of e){let o=r.type==="message.received"&&!r.data.kind?r.data.message:void 0;o!==void 0?t.push({visitor:{id:r.meta?.id??crypto.randomUUID(),role:"user",parts:[{type:"text",text:o}]},events:[]}):t.at(-1)?.events.push(r)}let a=[];for(let r of t){a.push(r.visitor);let o=await ry(r.events);o&&a.push(o)}return a}import{z as $e}from"zod";import{z as B}from"zod";import{z as Ao}from"zod";var Kt=Symbol("invalid-json-value-candidate");function xs(e){let t=Is(e);if(t===Kt)throw TypeError("Expected a JSON-serializable value.");return t}function sr(e){let t=xs(e);if(!oy(t))throw TypeError("Expected a JSON-serializable object.");return t}function Is(e,t=new WeakSet){if(e===null||typeof e=="boolean"||typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:Kt;if(Array.isArray(e)){let r=[];for(let o of e){let n=Is(o,t);if(n===Kt)return Kt;r.push(n)}return r}if(typeof e!="object"||e===void 0||!ny(e)||t.has(e))return Kt;t.add(e);let a={};for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let n=Is(o,t);if(n===Kt)return Kt;a[r]=n}return t.delete(e),a}function oy(e){return e!==null&&!Array.isArray(e)&&typeof e=="object"}function ny(e){let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var ir=Ao.unknown().transform((e,t)=>{try{return xs(e)}catch(a){return t.addIssue({code:"custom",message:hc(a,"Expected a JSON-serializable value.")}),Ao.NEVER}}),yt=Ao.unknown().transform((e,t)=>{try{return sr(e)}catch(a){return t.addIssue({code:"custom",message:hc(a,"Expected a JSON-serializable object.")}),Ao.NEVER}});function hc(e,t){return e instanceof Error?e.message:t}var gc=B.object({callId:B.string(),input:yt,kind:B.literal("tool-call"),toolName:B.string()}).strict();B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("subagent-call"),name:B.string(),nodeId:B.string(),subagentName:B.string()}).strict(),B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("remote-agent-call"),name:B.string(),nodeId:B.string(),remoteAgentName:B.string()}).strict(),B.object({callId:B.string(),input:yt,kind:B.literal("workflow-tool-call"),toolName:B.string(),workflowId:B.string()}).strict(),B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("subagent-call"),name:B.string(),nodeId:B.string(),subagentName:B.string()}).strict();var uE=B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("remote-agent-call"),name:B.string(),nodeId:B.string(),remoteAgentName:B.string()}).strict(),dE=B.object({callId:B.string(),executeInput:ir.optional(),input:yt,kind:B.literal("workflow-task"),nodeId:B.string().optional(),toolName:B.string(),workflowId:B.string()}).strict();B.object({callId:B.string(),input:yt,kind:B.literal("load-skill")}).strict();B.object({callId:B.string(),isError:B.boolean().optional(),kind:B.literal("tool-result"),output:ir,toolName:B.string()}).strict(),B.object({callId:B.string(),isError:B.literal(!0),kind:B.literal("subagent-result"),origin:B.literal("dispatch"),output:ir,subagentName:B.string()}).strict(),B.object({callId:B.string(),isError:B.boolean().optional(),kind:B.literal("load-skill-result"),output:ir,name:B.string().optional()}).strict();var sy=$e.object({description:$e.string().describe("Optional additional context for this option.").optional(),id:$e.string().describe("Stable identifier for the option."),label:$e.string().describe("User-facing label for the option."),style:$e.enum(["primary","danger","default"]).describe("Visual treatment hint for the option.").optional()}).strict(),iy=$e.enum(["question","session-limit","tool-approval"]),mE=$e.object({action:gc,allowFreeform:$e.boolean().describe("Whether the user may answer with freeform text instead of selecting one of the provided options.").optional(),display:$e.enum(["confirmation","select","text"]).describe("Rendering hint: the channel uses this to pick a UX treatment.").optional(),kind:iy.describe("Framework-owned request source used to resolve, route, and render the response."),options:$e.array(sy).describe("Selectable answer options to present to the user.").optional(),prompt:$e.string().describe("The prompt to present to the user."),requestId:$e.string().describe("Stable identifier for this request.")}).strict(),hE=$e.object({optionId:$e.string().optional(),requestId:$e.string(),text:$e.string().optional()}).strict();var ze="/eve/v1",wE=`${ze}/cron/:token`,wc=`${ze}/health`,Ic=`${ze}/info`,We=`${ze}/session`,IE=`${We}/:sessionId`,xE=`${We}/:sessionId/cancel`,yE=`${We}/:sessionId/compact`,LE=`${We}/:sessionId/clear`,SE=`${We}/:sessionId/reset`,CE=`${We}/:sessionId/stream`,bE=`${We}/:parentSessionId/subagents/:callId/:childSessionId/stream`,vE=`${ze}/dev/schedules/:scheduleId`,ys=`${ze}/dev/runtime-artifacts`,kE=`${ys}/rebuild`,TE=`${ys}/suspend`,AE=`${ys}/resume`;var PE=`${ze}/connections/:name/callback/:attemptId/:token`,RE=`${ze}/callback/:token`,EE=`${ze}/task-input/:token`,ME=`${ze}/activity/:token`;function xc(e){return`${We}/${encodeURIComponent(e)}`}function yc(e){return`${We}/${encodeURIComponent(e)}/cancel`}function Lc(e){return`${We}/${encodeURIComponent(e)}/compact`}function Sc(e){return`${We}/${encodeURIComponent(e)}/clear`}function Cc(e){return`${We}/${encodeURIComponent(e)}/reset`}function Ls(e){return`${We}/${encodeURIComponent(e)}/stream`}function ft(e){return typeof e=="object"&&!!e&&!Array.isArray(e)}function lr(e){return e instanceof Error?e.message:typeof e=="string"?e:e==null?String(e):ft(e)?typeof e.message=="string"&&e.message.length>0?e.message:ly(e):String(e)}function Xt(e){if(e instanceof Error)return e;let t=Error(lr(e));return ft(e)&&(typeof e.name=="string"&&e.name.length>0&&(t.name=e.name),typeof e.stack=="string"&&e.stack.length>0&&(t.stack=e.stack),"cause"in e&&e.cause!==void 0&&e.cause!==e&&(t.cause=e.cause)),t}function ly(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var vc="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function uy(){let e=-1,t=new Uint8Array(10);return function(){let a=Date.now();if(!Number.isInteger(a)||a<0||a>0xffffffffffff)throw Error(`Cannot mint a ULID: timestamp must be an integer from 0 to ${0xffffffffffff}.`);if(a>e)e=a,bc(t);else if(!py(t)){if(e===0xffffffffffff)throw Error("Cannot mint a ULID: random component overflowed at the maximum timestamp.");e+=1,bc(t)}return`${cy(e)}${fy(t)}`}}var dy=uy();function bc(e){let t=globalThis.crypto;if(typeof t?.getRandomValues!="function")throw Error("Cannot mint a ULID: globalThis.crypto.getRandomValues is unavailable.");t.getRandomValues(e)}function cy(e){let t=e,a="";for(let r=0;r<10;r+=1)a=vc[t%32]+a,t=Math.floor(t/32);return a}function fy(e){let t=0,a=0,r="";for(let o of e){for(t=t<<8|o,a+=8;a>=5;)a-=5,r+=vc[t>>>a&31];t&=(1<<a)-1}return r}function py(e){for(let t=e.length-1;t>=0;--t){let a=e[t]??0;if(a<255)return e[t]=a+1,e.fill(0,t+1),!0}return!1}var kc="x-eve-session-id";var Ss="x-eve-stream-tail-index",Cs="x-eve-stream-version";var Tc="1",Ac="streamControlVersion",bs={$eve:"stream.lease-ended",version:1},lM=new TextEncoder;function Qe(e){return e.type==="session.completed"||e.type==="session.failed"||e.type==="session.waiting"}function vs(e){return e.type==="session.failed"||e.type==="step.failed"||e.type==="turn.failed"}var Po=class extends Error{issues;constructor(e=[]){let t=e.length===0?"":` (${e.join("; ")})`;super(`The server returned an unrecognized response from the eve agent info route.${t}`),this.name="AgentInfoResponseError",this.issues=e}};var Ro=class extends Error{issues;constructor(e=[]){let t=e.length===0?"":` (${e.join("; ")})`;super(`The server returned an unrecognized eve health response.${t}`),this.name="HealthResponseError",this.issues=e}};var Ve=class extends Error{code;status;body;headers;constructor(e,t,a){let r=Object.freeze(Object.fromEntries(new Headers(a).entries())),o=r["content-type"]?.toLowerCase(),n=t||`Server returned ${e}.`,s;try{let i=JSON.parse(t);ft(i)&&(typeof i.error=="string"&&(n=i.error),typeof i.code=="string"&&(s=i.code))}catch{o?.includes("text/html")&&(n=`Server returned ${e} with an HTML response. Check the eve route and development server configuration.`)}super(n),this.name="ClientError",this.code=s,this.status=e,this.body=t,this.headers=r}};function Pc(e){let t,a,r,o=[],n=new Map;for(let s of e)Qe(s)&&(t=s),vs(s)&&(a=s),my(s)&&(r=s.data.message??void 0),s.type==="input.requested"&&o.push(...s.data.requests),s.type==="authorization.required"&&n.set(s.data.name,s.data),s.type==="authorization.completed"&&n.delete(s.data.name);return{boundary:t,failure:a,inputRequests:o,message:r,pendingAuthorizations:[...n.values()],status:t?.type==="session.waiting"?"waiting":t?.type==="session.failed"?"failed":"completed"}}function my(e){return e.type==="message.completed"&&e.data.finishReason!=="tool-calls"}function Jt(e,t){t.type==="authorization.required"&&t.data.webhookUrl!==void 0?e.add(t.data.name):t.type==="authorization.completed"&&e.delete(t.data.name)}var hy=/^\/eve\/[a-z0-9][a-z0-9_-]*$/,gy=/^\/eve\/[a-z0-9][a-z0-9_-]*\/v1$/;function ks(e,t){let a=wy(e),r=t.startsWith("/")?t:`/${t}`;if(r===ze||r.startsWith(`${ze}/`)){if(hy.test(a))return`${a}${r.slice(4)}`;if(gy.test(a))return`${a}${r.slice(ze.length)}`}return`${a}${r}`}function wy(e){return e==="/"?"":e.endsWith("/")?e.slice(0,-1):e}function pt(e,t,a){let r=t.indexOf("?"),o=r===-1?t:t.slice(0,r),n=r===-1?"":t.slice(r+1),s=o.startsWith("/")?o:`/${o}`;if(Iy(e)){let u=new URL(e),d=Ec(u.pathname);return u.pathname=ks(d,s),Rc(u.searchParams,n),Mc(u.searchParams,a),u.hash="",u.toString()}let i=new URL(e,"http://eve.local"),l=Ec(i.pathname);return Rc(i.searchParams,n),Mc(i.searchParams,a),`${ks(l,s)}${xy(i.searchParams)}`}function Rc(e,t){if(t.length!==0)for(let[a,r]of new URLSearchParams(t))e.append(a,r)}function Iy(e){return/^[a-z][a-z\d+\-.]*:/i.test(e)}function Ec(e){return e==="/"?"":e.endsWith("/")?e.slice(0,-1):e}function Mc(e,t){if(t!==void 0)for(let[a,r]of Object.entries(t))e.set(a,r)}function xy(e){let t=e.toString();return t.length===0?"":`?${t}`}function Fc(e){let t;for(let a of e)yy(a)&&(t=a.data.result);return t}function yy(e){return e.type==="result.completed"}var Ts=Symbol("consumeMessageResponse"),As=Symbol("acceptedDeliveryId"),Ps=class{sessionId;[As];#t;#e;#a=!1;#r;#n=!1;#u=Promise.withResolvers();constructor(e){this.#t=e.cancelTurn,this.sessionId=e.sessionId,this[As]=e.deliveryId,this.#r=e.createStream}cancel(){if(this.#n)return Promise.resolve({status:"no_active_turn"});if(this.#e!==void 0)return this.#e;let e=this.#u.promise.then(t=>t===void 0?{status:"no_active_turn"}:this.#t(t));return this.#e=e,e.catch(()=>{!this.#n&&this.#e===e&&(this.#e=void 0)}),e}async result(){let e=[];for await(let a of this)e.push(a);let t=Pc(e);return{data:Fc(e),events:e,inputRequests:t.inputRequests,message:t.message,sessionId:this.sessionId,status:t.status}}[Symbol.asyncIterator](){return this[Ts]()}[Ts](e){if(this.#a)throw Error("MessageResponse has already been consumed.");return this.#a=!0,this.#g(e)}async*#g(e){try{for await(let t of this.#r(e))t.type==="turn.started"?this.#u.resolve(t.data.turnId):Qe(t)&&(this.#n=!0,this.#u.resolve(void 0)),yield t}finally{this.#u.resolve(void 0)}}};function Rs(e){return e[As]}function _c(e,t){return e[Ts](t)}function Bc(e,t){switch(e){case"21":case"22":case"23":case"24":return Ly(e,t);case"25":return Sy(t);default:return Cy(e)}}function Ly(e,t){if(t.type==="message.appended")return Dc(t.data.messageSoFar,t.data.messageDelta,"message",e),{data:{messageDelta:t.data.messageDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,turnId:t.data.turnId},meta:t.meta,type:"message.appended"};if(t.type==="reasoning.appended")return Dc(t.data.reasoningSoFar,t.data.reasoningDelta,"reasoning",e),{data:{reasoningDelta:t.data.reasoningDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,turnId:t.data.turnId},meta:t.meta,type:"reasoning.appended"};if(t.type==="action.input.appended"){if(e!==void 0&&e!=="24")throw TypeError(`Invalid action input append for stream version ${e}.`);return by(t.data.inputTextOffset,e),{data:{callId:t.data.callId,inputTextDelta:t.data.inputTextDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,toolName:t.data.toolName,turnId:t.data.turnId},meta:t.meta,type:"action.input.appended"}}return t}function Sy(e){return e.type==="message.appended"?(Es(e.data.messageDelta,"message"),ur(e.data,"messageOffset","message"),ur(e.data,"messageSoFar","message")):e.type==="reasoning.appended"?(Es(e.data.reasoningDelta,"reasoning"),ur(e.data,"reasoningOffset","reasoning"),ur(e.data,"reasoningSoFar","reasoning")):e.type==="action.input.appended"&&(Es(e.data.inputTextDelta,"action input"),ur(e.data,"inputTextOffset","action input")),e}function Es(e,t){if(typeof e!="string")throw TypeError(`Invalid ${t} append delta for stream version 25.`)}function ur(e,t,a){if(t in e)throw TypeError(`Invalid ${a} append shape for stream version 25.`)}function Cy(e){throw TypeError(`Unsupported message stream version: ${String(e)}.`)}function by(e,t){if(!Number.isSafeInteger(e)||e<0){let a=t===void 0?"persisted stream":`stream version ${t}`;throw TypeError(`Invalid action input append offset for ${a}.`)}}function Dc(e,t,a,r){let o=e.length-t.length;if(o<0||e.slice(o)!==t){let n=r===void 0?"persisted stream":`stream version ${r}`;throw TypeError(`Invalid cumulative ${a} append for ${n}.`)}}function Ms(e){if(e instanceof DOMException)return e.name==="AbortError";if(!(e instanceof Error))return!1;let t="code"in e&&typeof e.code=="string"?e.code:void 0;return e.name==="AbortError"||e.message==="terminated"||t==="UND_ERR_SOCKET"||e instanceof TypeError&&/^(?:failed to fetch|fetch failed)$/i.test(e.message)||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*Nc(e,t){let a=e.getReader(),r=new TextDecoder,o="",n=!1,s=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{for(;;){t.signal?.throwIfAborted();let l=await vy(a,t?.idleTimeoutMs);if(t.signal?.throwIfAborted(),l.done){n=!0,o+=r.decode();break}l.value&&(o+=r.decode(l.value,{stream:!0}));let u=o.indexOf(`
|
|
14
|
+
\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function qu(e,t,a,r){let o=r.schema,n=o.space==="svg"?!1:r.settings.omitOptionalTags,s=o.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),i=[],l;o.space==="html"&&e.tagName==="svg"&&(r.schema=Sr);let u=rw(r,e.properties),d=r.all(o.space==="html"&&e.tagName==="template"?e.content:e);return r.schema=o,d&&(s=!1),(u||!n||!Nu(e,t,a))&&(i.push("<",e.tagName,u?" "+u:""),s&&(o.space==="svg"||r.settings.closeSelfClosing)&&(l=u.charAt(u.length-1),(!r.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&i.push(" "),i.push("/")),i.push(">")),i.push(d),!s&&(!n||!Ja(e,t,a))&&i.push("</"+e.tagName+">"),i.join("")}function rw(e,t){let a=[],r=-1,o;if(t){for(o in t)if(t[o]!==null&&t[o]!==void 0){let n=ow(e,o,t[o]);n&&a.push(n)}}for(;++r<a.length;){let n=e.settings.tightAttributes?a[r].charAt(a[r].length-1):void 0;r!==a.length-1&&n!=='"'&&n!=="'"&&(a[r]+=" ")}return a.join("")}function ow(e,t,a){let r=pi(e.schema,t),o=e.settings.allowParseErrors&&e.schema.space==="html"?0:1,n=e.settings.allowDangerousCharacters?0:1,s=e.quote,i;if(r.overloadedBoolean&&(a===r.attribute||a==="")?a=!0:(r.boolean||r.overloadedBoolean)&&(typeof a!="string"||a===r.attribute||a==="")&&(a=!!a),a==null||a===!1||typeof a=="number"&&Number.isNaN(a))return"";let l=wt(r.attribute,Object.assign({},e.settings.characterReferences,{subset:Yr.name[o][n]}));return a===!0||(a=Array.isArray(a)?(r.commaSeparated?hi:gi)(a,{padLeft:!e.settings.tightCommaSeparatedLists}):String(a),e.settings.collapseEmptyAttributes&&!a)?l:(e.settings.preferUnquoted&&(i=wt(a,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:Yr.unquoted[o][n]}))),i!==a&&(e.settings.quoteSmart&&No(a,s)>No(a,e.alternative)&&(s=e.alternative),i=s+wt(a,Object.assign({},e.settings.characterReferences,{subset:(s==="'"?Yr.single:Yr.double)[o][n],attribute:!0}))+s),l+(i&&"="+i))}var nw=["<","&"];function Zr(e,t,a,r){return a&&a.type==="element"&&(a.tagName==="script"||a.tagName==="style")?e.value:wt(e.value,Object.assign({},r.settings.characterReferences,{subset:nw}))}function Hu(e,t,a,r){return r.settings.allowDangerousHtml?e.value:Zr(e,t,a,r)}function $u(e,t,a,r){return r.all(e)}var Wu=wi("type",{invalid:sw,unknown:iw,handlers:{comment:_u,doctype:Du,element:qu,raw:Hu,root:$u,text:Zr}});function sw(e){throw new Error("Expected node, not `"+e+"`")}function iw(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var lw={},uw={},dw=[];function Dn(e,t){let a=t||lw,r=a.quote||'"',o=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:cw,all:fw,settings:{omitOptionalTags:a.omitOptionalTags||!1,allowParseErrors:a.allowParseErrors||!1,allowDangerousCharacters:a.allowDangerousCharacters||!1,quoteSmart:a.quoteSmart||!1,preferUnquoted:a.preferUnquoted||!1,tightAttributes:a.tightAttributes||!1,upperDoctype:a.upperDoctype||!1,tightDoctype:a.tightDoctype||!1,bogusComments:a.bogusComments||!1,tightCommaSeparatedLists:a.tightCommaSeparatedLists||!1,tightSelfClosing:a.tightSelfClosing||!1,collapseEmptyAttributes:a.collapseEmptyAttributes||!1,allowDangerousHtml:a.allowDangerousHtml||!1,voids:a.voids||Ii,characterReferences:a.characterReferences||uw,closeSelfClosing:a.closeSelfClosing||!1,closeEmptyElements:a.closeEmptyElements||!1},schema:a.space==="svg"?Sr:mi,quote:r,alternative:o}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function cw(e,t,a){return Wu(e,t,a,this)}function fw(e){let t=[],a=e&&e.children||dw,r=-1;for(;++r<a.length;)t[r]=this.one(a[r],r,e);return t.join("")}function eo(e,t){let a=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[o,n]of Object.entries(t?.colorReplacements||{}))typeof n=="string"?a[o]=n:o===r&&Object.assign(a,n);return a}function Mt(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function pw(e){return Array.isArray(e)?e:[e]}async function Ju(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function Hn(e){return!e||["plaintext","txt","text","plain"].includes(e)}function Qu(e){return e==="ansi"||Hn(e)}function $n(e){return e==="none"}function Yu(e){return $n(e)}function Zu(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class=="string"&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let a=Array.isArray(t)?t:t.split(/\s+/g);for(let r of a)r&&!e.properties.class.includes(r)&&e.properties.class.push(r);return e}function no(e,t=!1){if(e.length===0)return[["",0]];let a=e.split(/(\r?\n)/g),r=0,o=[];for(let n=0;n<a.length;n+=2){let s=t?a[n]+(a[n+1]||""):a[n];o.push([s,r]),r+=a[n].length,r+=a[n+1]?.length||0}return o}function mw(e){let t=no(e,!0).map(([o])=>o);function a(o){if(o===e.length)return{line:t.length-1,character:t[t.length-1].length};let n=o,s=0;for(let i of t){if(n<i.length)break;n-=i.length,s++}return{line:s,character:n}}function r(o,n){let s=0;for(let i=0;i<o;i++)s+=t[i].length;return s+=n,s}return{lines:t,indexToPos:a,posToIndex:r}}function ed(e,t,a){let r=new Set;for(let n of e.matchAll(/:?lang=["']([^"']+)["']/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/\\begin\{([\w-]+)\}/g)){let s=n[1].toLowerCase().trim();s&&r.add(s)}for(let n of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let s=n[1].toLowerCase().trim(),i=s.includes("/")?s.split("/").pop():s;i&&r.add(i)}if(!a)return Array.from(r);let o=a.getBundledLanguages();return Array.from(r).filter(n=>n&&o[n])}var Wn="light-dark()",hw=["color","background-color"];function gw(e,t){let a=0,r=[];for(let o of t)o>a&&r.push({...e,content:e.content.slice(a,o),offset:e.offset+a}),a=o;return a<e.content.length&&r.push({...e,content:e.content.slice(a),offset:e.offset+a}),r}function ww(e,t){let a=Array.from(t instanceof Set?t:new Set(t)).sort((r,o)=>r-o);return a.length?e.map(r=>r.flatMap(o=>{let n=a.filter(s=>o.offset<s&&s<o.offset+o.content.length).map(s=>s-o.offset).sort((s,i)=>s-i);return n.length?gw(o,n):o})):e}function Iw(e,t,a,r,o="css-vars"){let n={content:e.content,explanation:e.explanation,offset:e.offset},s=t.map(d=>to(e.variants[d])),i=new Set(s.flatMap(d=>Object.keys(d))),l={},u=(d,c)=>{let p=c==="color"?"":c==="background-color"?"-bg":`-${c}`;return a+t[d]+(c==="color"?"":p)};return s.forEach((d,c)=>{for(let p of i){let f=d[p]||"inherit";if(c===0&&r&&hw.includes(p))if(r===Wn&&s.length>1){let m=t.findIndex(C=>C==="light"),y=t.findIndex(C=>C==="dark");if(m===-1||y===-1)throw new ve('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let S=s[m][p]||"inherit",L=s[y][p]||"inherit";l[p]=`light-dark(${S}, ${L})`,o==="css-vars"&&(l[u(c,p)]=f)}else l[p]=f;else o==="css-vars"&&(l[u(c,p)]=f)}}),n.htmlStyle=l,n}function to(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&Ue.Italic&&(t["font-style"]="italic"),e.fontStyle&Ue.Bold&&(t["font-weight"]="bold");let a=[];e.fontStyle&Ue.Underline&&a.push("underline"),e.fontStyle&Ue.Strikethrough&&a.push("line-through"),a.length&&(t["text-decoration"]=a.join(" "))}return t}function Un(e){return typeof e=="string"?e:Object.entries(e).map(([t,a])=>`${t}:${a}`).join(";")}var td=new WeakMap;function so(e,t){td.set(e,t)}function Ya(e){return td.get(e)}var da=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,a){return new e(Object.fromEntries(pw(a).map(r=>[r,Kr])),t)}constructor(...t){if(t.length===2){let[a,r]=t;this.lang=r,this._stacks=a}else{let[a,r,o]=t;this.lang=r,this._stacks={[o]:a}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return xw(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function xw(e){let t=[],a=new Set;function r(o){if(a.has(o))return;a.add(o);let n=o?.nameScopesList?.scopeName;n&&t.push(n),o.parent&&r(o.parent)}return r(e),t}function yw(e,t){if(!(e instanceof da))throw new ve("Invalid grammar state");return e.getInternalStack(t)}function Lw(){let e=new WeakMap;function t(a){if(!e.has(a.meta)){let r=function(s){if(typeof s=="number"){if(s<0||s>a.source.length)throw new ve(`Invalid decoration offset: ${s}. Code length: ${a.source.length}`);return{...o.indexToPos(s),offset:s}}else{let i=o.lines[s.line];if(i===void 0)throw new ve(`Invalid decoration position ${JSON.stringify(s)}. Lines length: ${o.lines.length}`);let l=s.character;if(l<0&&(l=i.length+l),l<0||l>i.length)throw new ve(`Invalid decoration position ${JSON.stringify(s)}. Line ${s.line} length: ${i.length}`);return{...s,character:l,offset:o.posToIndex(s.line,l)}}},o=mw(a.source),n=(a.options.decorations||[]).map(s=>({...s,start:r(s.start),end:r(s.end)}));Sw(n),e.set(a.meta,{decorations:n,converter:o,source:a.source})}return e.get(a.meta)}return{name:"shiki:decorations",tokens(a){if(!this.options.decorations?.length)return;let o=t(this).decorations.flatMap(s=>[s.start.offset,s.end.offset]);return ww(a,o)},code(a){if(!this.options.decorations?.length)return;let r=t(this),o=Array.from(a.children).filter(d=>d.type==="element"&&d.tagName==="span");if(o.length!==r.converter.lines.length)throw new ve(`Number of lines in code element (${o.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);function n(d,c,p,f){let m=o[d],y="",S=-1,L=-1;if(c===0&&(S=0),p===0&&(L=0),p===Number.POSITIVE_INFINITY&&(L=m.children.length),S===-1||L===-1)for(let I=0;I<m.children.length;I++)y+=ad(m.children[I]),S===-1&&y.length===c&&(S=I+1),L===-1&&y.length===p&&(L=I+1);if(S===-1)throw new ve(`Failed to find start index for decoration ${JSON.stringify(f.start)}`);if(L===-1)throw new ve(`Failed to find end index for decoration ${JSON.stringify(f.end)}`);let C=m.children.slice(S,L);if(!f.alwaysWrap&&C.length===m.children.length)i(m,f,"line");else if(!f.alwaysWrap&&C.length===1&&C[0].type==="element")i(C[0],f,"token");else{let I={type:"element",tagName:"span",properties:{},children:C};i(I,f,"wrapper"),m.children.splice(S,C.length,I)}}function s(d,c){o[d]=i(o[d],c,"line")}function i(d,c,p){let f=c.properties||{},m=c.transform||(y=>y);return d.tagName=c.tagName||"span",d.properties={...d.properties,...f,class:d.properties.class},c.properties?.class&&Zu(d,c.properties.class),d=m(d,p)||d,d}let l=[],u=r.decorations.sort((d,c)=>c.start.offset-d.start.offset||d.end.offset-c.end.offset);for(let d of u){let{start:c,end:p}=d;if(c.line===p.line)n(c.line,c.character,p.character,d);else if(c.line<p.line){n(c.line,c.character,Number.POSITIVE_INFINITY,d);for(let f=c.line+1;f<p.line;f++)l.unshift(()=>s(f,d));n(p.line,0,p.character,d)}}l.forEach(d=>d())}}}function Sw(e){for(let t=0;t<e.length;t++){let a=e[t];if(a.start.offset>a.end.offset)throw new ve(`Invalid decoration range: ${JSON.stringify(a.start)} - ${JSON.stringify(a.end)}`);for(let r=t+1;r<e.length;r++){let o=e[r],n=a.start.offset<=o.start.offset&&o.start.offset<a.end.offset,s=a.start.offset<o.end.offset&&o.end.offset<=a.end.offset,i=o.start.offset<=a.start.offset&&a.start.offset<o.end.offset,l=o.start.offset<a.end.offset&&a.end.offset<=o.end.offset;if(n||s||i||l){if(n&&s||i&&l||i&&a.start.offset===a.end.offset||s&&o.start.offset===o.end.offset)continue;throw new ve(`Decorations ${JSON.stringify(a.start)} and ${JSON.stringify(o.start)} intersect.`)}}}}function ad(e){return e.type==="text"?e.value:e.type==="element"?e.children.map(ad).join(""):""}var Cw=[Lw()];function ao(e){let t=bw(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...Cw]}function bw(e){let t=[],a=[],r=[];for(let o of e)switch(o.enforce){case"pre":t.push(o);break;case"post":a.push(o);break;default:r.push(o)}return{pre:t,post:a,normal:r}}var Gt=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],Bn={1:"bold",2:"dim",3:"italic",4:"underline",7:"reverse",8:"hidden",9:"strikethrough"};function vw(e,t){let a=e.indexOf("\x1B",t);if(a!==-1&&e[a+1]==="["){let r=e.indexOf("m",a);if(r!==-1)return{sequence:e.substring(a+2,r).split(";"),startPosition:a,position:r+1}}return{position:e.length}}function ju(e){let t=e.shift();if(t==="2"){let a=e.splice(0,3).map(r=>Number.parseInt(r));return a.length!==3||a.some(r=>Number.isNaN(r))?void 0:{type:"rgb",rgb:a}}else if(t==="5"){let a=e.shift();if(a)return{type:"table",index:Number(a)}}}function kw(e){let t=[];for(;e.length>0;){let a=e.shift();if(!a)continue;let r=Number.parseInt(a);if(!Number.isNaN(r))if(r===0)t.push({type:"resetAll"});else if(r<=9)Bn[r]&&t.push({type:"setDecoration",value:Bn[r]});else if(r<=29){let o=Bn[r-20];o&&(t.push({type:"resetDecoration",value:o}),o==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(r<=37)t.push({type:"setForegroundColor",value:{type:"named",name:Gt[r-30]}});else if(r===38){let o=ju(e);o&&t.push({type:"setForegroundColor",value:o})}else if(r===39)t.push({type:"resetForegroundColor"});else if(r<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:Gt[r-40]}});else if(r===48){let o=ju(e);o&&t.push({type:"setBackgroundColor",value:o})}else r===49?t.push({type:"resetBackgroundColor"}):r===53?t.push({type:"setDecoration",value:"overline"}):r===55?t.push({type:"resetDecoration",value:"overline"}):r>=90&&r<=97?t.push({type:"setForegroundColor",value:{type:"named",name:Gt[r-90+8]}}):r>=100&&r<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:Gt[r-100+8]}})}return t}function Tw(){let e=null,t=null,a=new Set;return{parse(r){let o=[],n=0;do{let s=vw(r,n),i=s.sequence?r.substring(n,s.startPosition):r.substring(n);if(i.length>0&&o.push({value:i,foreground:e,background:t,decorations:new Set(a)}),s.sequence){let l=kw(s.sequence);for(let u of l)u.type==="resetAll"?(e=null,t=null,a.clear()):u.type==="resetForegroundColor"?e=null:u.type==="resetBackgroundColor"?t=null:u.type==="resetDecoration"&&a.delete(u.value);for(let u of l)u.type==="setForegroundColor"?e=u.value:u.type==="setBackgroundColor"?t=u.value:u.type==="setDecoration"&&a.add(u.value)}n=s.position}while(n<r.length);return o}}}var Aw={black:"#000000",red:"#bb0000",green:"#00bb00",yellow:"#bbbb00",blue:"#0000bb",magenta:"#ff00ff",cyan:"#00bbbb",white:"#eeeeee",brightBlack:"#555555",brightRed:"#ff5555",brightGreen:"#00ff00",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"};function Pw(e=Aw){function t(i){return e[i]}function a(i){return`#${i.map(l=>Math.max(0,Math.min(l,255)).toString(16).padStart(2,"0")).join("")}`}let r;function o(){if(r)return r;r=[];for(let u=0;u<Gt.length;u++)r.push(t(Gt[u]));let i=[0,95,135,175,215,255];for(let u=0;u<6;u++)for(let d=0;d<6;d++)for(let c=0;c<6;c++)r.push(a([i[u],i[d],i[c]]));let l=8;for(let u=0;u<24;u++,l+=10)r.push(a([l,l,l]));return r}function n(i){return o()[i]}function s(i){switch(i.type){case"named":return t(i.name);case"rgb":return a(i.rgb);case"table":return n(i.index)}}return{value:s}}var Rw={black:"#000000",red:"#cd3131",green:"#0DBC79",yellow:"#E5E510",blue:"#2472C8",magenta:"#BC3FBC",cyan:"#11A8CD",white:"#E5E5E5",brightBlack:"#666666",brightRed:"#F14C4C",brightGreen:"#23D18B",brightYellow:"#F5F543",brightBlue:"#3B8EEA",brightMagenta:"#D670D6",brightCyan:"#29B8DB",brightWhite:"#FFFFFF"};function Ew(e,t,a){let r=eo(e,a),o=no(t),n=Object.fromEntries(Gt.map(l=>{let u=`terminal.ansi${l[0].toUpperCase()}${l.substring(1)}`,d=e.colors?.[u];return[l,d||Rw[l]]})),s=Pw(n),i=Tw();return o.map(l=>i.parse(l[0]).map(u=>{let d,c;u.decorations.has("reverse")?(d=u.background?s.value(u.background):e.bg,c=u.foreground?s.value(u.foreground):e.fg):(d=u.foreground?s.value(u.foreground):e.fg,c=u.background?s.value(u.background):void 0),d=Mt(d,r),c=Mt(c,r),u.decorations.has("dim")&&(d=Mw(d));let p=Ue.None;return u.decorations.has("bold")&&(p|=Ue.Bold),u.decorations.has("italic")&&(p|=Ue.Italic),u.decorations.has("underline")&&(p|=Ue.Underline),u.decorations.has("strikethrough")&&(p|=Ue.Strikethrough),{content:u.value,offset:l[1],color:d,bgColor:c,fontStyle:p}}))}function Mw(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let r=t[1];if(r.length===8){let o=Math.round(Number.parseInt(r.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${r.slice(0,6)}${o}`}else{if(r.length===6)return`#${r}80`;if(r.length===4){let o=r[0],n=r[1],s=r[2],i=r[3],l=Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,"0");return`#${o}${o}${n}${n}${s}${s}${l}`}else if(r.length===3){let o=r[0],n=r[1],s=r[2];return`#${o}${o}${n}${n}${s}${s}80`}}}let a=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return a?`var(${a[1]}-dim)`:e}function jn(e,t,a={}){let{theme:r=e.getLoadedThemes()[0]}=a,o=e.resolveLangAlias(a.lang||"text");if(Hn(o)||$n(r))return no(t).map(l=>[{content:l[0],offset:l[1]}]);let{theme:n,colorMap:s}=e.setTheme(r);if(o==="ansi")return Ew(n,t,a);let i=e.getLanguage(a.lang||"text");if(a.grammarState){if(a.grammarState.lang!==i.name)throw new ve(`Grammar state language "${a.grammarState.lang}" does not match highlight language "${i.name}"`);if(!a.grammarState.themes.includes(n.name))throw new ve(`Grammar state themes "${a.grammarState.themes}" do not contain highlight theme "${n.name}"`)}return _w(t,i,n,s,a)}function Fw(...e){if(e.length===2)return Ya(e[1]);let[t,a,r={}]=e,{lang:o="text",theme:n=t.getLoadedThemes()[0]}=r;if(Hn(o)||$n(n))throw new ve("Plain language does not have grammar state");if(o==="ansi")throw new ve("ANSI language does not have grammar state");let{theme:s,colorMap:i}=t.setTheme(n),l=t.getLanguage(o);return new da(zn(a,l,s,i,r).stateStack,l.name,s.name)}function _w(e,t,a,r,o){let n=zn(e,t,a,r,o),s=new da(n.stateStack,t.name,a.name);return so(n.tokens,s),n.tokens}function zn(e,t,a,r,o){let n=eo(a,o),{tokenizeMaxLineLength:s=0,tokenizeTimeLimit:i=500}=o,l=no(e),u=o.grammarState?yw(o.grammarState,a.name)??Kr:o.grammarContextCode!=null?zn(o.grammarContextCode,t,a,r,{...o,grammarState:void 0,grammarContextCode:void 0}).stateStack:Kr,d=[],c=[];for(let p=0,f=l.length;p<f;p++){let[m,y]=l[p];if(m===""){d=[],c.push([]);continue}if(s>0&&m.length>=s){d=[],c.push([{content:m,offset:y,color:"",fontStyle:0}]);continue}let S,L,C;o.includeExplanation&&(S=t.tokenizeLine(m,u,i),L=S.tokens,C=0);let I=t.tokenizeLine2(m,u,i),x=I.tokens.length/2;for(let v=0;v<x;v++){let q=I.tokens[2*v],N=v+1<x?I.tokens[2*v+2]:m.length;if(q===N)continue;let V=I.tokens[2*v+1],G=Mt(r[Vt.getForeground(V)],n),Q=Vt.getFontStyle(V),O={content:m.substring(q,N),offset:y+q,color:G,fontStyle:Q};if(o.includeExplanation){let re=[];if(o.includeExplanation!=="scopeName")for(let J of a.settings){let X;switch(typeof J.scope){case"string":X=J.scope.split(/,/).map(R=>R.trim());break;case"object":X=J.scope;break;default:continue}re.push({settings:J,selectors:X.map(R=>R.split(/ /))})}O.explanation=[];let K=0;for(;q+K<N;){let J=L[C],X=m.substring(J.startIndex,J.endIndex);K+=X.length,O.explanation.push({content:X,scopes:o.includeExplanation==="scopeName"?Dw(J.scopes):Bw(re,J.scopes)}),C+=1}}d.push(O)}c.push(d),d=[],u=I.ruleStack}return{tokens:c,stateStack:u}}function Dw(e){return e.map(t=>({scopeName:t}))}function Bw(e,t){let a=[];for(let r=0,o=t.length;r<o;r++){let n=t[r];a[r]={scopeName:n,themeMatches:Uw(e,n,t.slice(0,r))}}return a}function zu(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]==="."}function Ow(e,t,a){if(!zu(e[e.length-1],t))return!1;let r=e.length-2,o=a.length-1;for(;r>=0&&o>=0;)zu(e[r],a[o])&&(r-=1),o-=1;return r===-1}function Uw(e,t,a){let r=[];for(let{selectors:o,settings:n}of e)for(let s of o)if(Ow(s,t,a)){r.push(n);break}return r}function rd(e,t,a){let r=Object.entries(a.themes).filter(l=>l[1]).map(l=>({color:l[0],theme:l[1]})),o=r.map(l=>{let u=jn(e,t,{...a,theme:l.theme}),d=Ya(u),c=typeof l.theme=="string"?l.theme:l.theme.name;return{tokens:u,state:d,theme:c}}),n=Nw(...o.map(l=>l.tokens)),s=n[0].map((l,u)=>l.map((d,c)=>{let p={content:d.content,variants:{},offset:d.offset};return"includeExplanation"in a&&a.includeExplanation&&(p.explanation=d.explanation),n.forEach((f,m)=>{let{content:y,explanation:S,offset:L,...C}=f[u][c];p.variants[r[m].color]=C}),p})),i=o[0].state?new da(Object.fromEntries(o.map(l=>[l.theme,l.state?.getInternalStack(l.theme)])),o[0].state.lang):void 0;return i&&so(s,i),s}function Nw(...e){let t=e.map(()=>[]),a=e.length;for(let r=0;r<e[0].length;r++){let o=e.map(l=>l[r]),n=t.map(()=>[]);t.forEach((l,u)=>l.push(n[u]));let s=o.map(()=>0),i=o.map(l=>l[0]);for(;i.every(l=>l);){let l=Math.min(...i.map(u=>u.content.length));for(let u=0;u<a;u++){let d=i[u];d.content.length===l?(n[u].push(d),s[u]+=1,i[u]=o[u][s[u]]):(n[u].push({...d,content:d.content.slice(0,l)}),i[u]={...d,content:d.content.slice(l),offset:d.offset+l})}}}return t}function ro(e,t,a){let r,o,n,s,i,l;if("themes"in a){let{defaultColor:u="light",cssVariablePrefix:d="--shiki-",colorsRendering:c="css-vars"}=a,p=Object.entries(a.themes).filter(L=>L[1]).map(L=>({color:L[0],theme:L[1]})).sort((L,C)=>L.color===u?-1:C.color===u?1:0);if(p.length===0)throw new ve("`themes` option must not be empty");let f=rd(e,t,a);if(l=Ya(f),u&&Wn!==u&&!p.find(L=>L.color===u))throw new ve(`\`themes\` option must contain the defaultColor key \`${u}\``);let m=p.map(L=>e.getTheme(L.theme)),y=p.map(L=>L.color);n=f.map(L=>L.map(C=>Iw(C,y,d,u,c))),l&&so(n,l);let S=p.map(L=>eo(L.theme,a));o=Vu(p,m,S,d,u,"fg",c),r=Vu(p,m,S,d,u,"bg",c),s=`shiki-themes ${m.map(L=>L.name).join(" ")}`,i=u?void 0:[o,r].join(";")}else if("theme"in a){let u=eo(a.theme,a);n=jn(e,t,a);let d=e.getTheme(a.theme);r=Mt(d.bg,u),o=Mt(d.fg,u),s=d.name,l=Ya(n)}else throw new ve("Invalid options, either `theme` or `themes` must be provided");return{tokens:n,fg:o,bg:r,themeName:s,rootStyle:i,grammarState:l}}function Vu(e,t,a,r,o,n,s){return e.map((i,l)=>{let u=Mt(t[l][n],a[l])||"inherit",d=`${r+i.color}${n==="bg"?"-bg":""}:${u}`;if(l===0&&o){if(o===Wn&&e.length>1){let c=e.findIndex(y=>y.color==="light"),p=e.findIndex(y=>y.color==="dark");if(c===-1||p===-1)throw new ve('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let f=Mt(t[c][n],a[c])||"inherit",m=Mt(t[p][n],a[p])||"inherit";return`light-dark(${f}, ${m});${d}`}return u}return s==="css-vars"?d:null}).filter(i=>!!i).join(";")}function oo(e,t,a,r={meta:{},options:a,codeToHast:(o,n)=>oo(e,o,n),codeToTokens:(o,n)=>ro(e,o,n)}){let o=t;for(let m of ao(a))o=m.preprocess?.call(r,o,a)||o;let{tokens:n,fg:s,bg:i,themeName:l,rootStyle:u,grammarState:d}=ro(e,o,a),{mergeWhitespaces:c=!0,mergeSameStyleTokens:p=!1}=a;c===!0?n=Hw(n):c==="never"&&(n=$w(n)),p&&(n=Ww(n));let f={...r,get source(){return o}};for(let m of ao(a))n=m.tokens?.call(f,n)||n;return qw(n,{...a,fg:s,bg:i,themeName:l,rootStyle:a.rootStyle===!1?!1:a.rootStyle??u},f,d)}function qw(e,t,a,r=Ya(e)){let o=ao(t),n=[],s={type:"root",children:[]},{structure:i="classic",tabindex:l="0"}=t,u={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?u.style=t.rootStyle:u.style=`background-color:${t.bg};color:${t.fg}`),l!==!1&&l!=null&&(u.tabindex=l.toString());for(let[y,S]of Object.entries(t.meta||{}))y.startsWith("_")||(u[y]=S);let d={type:"element",tagName:"pre",properties:u,children:[],data:t.data},c={type:"element",tagName:"code",properties:{},children:n},p=[],f={...a,structure:i,addClassToHast:Zu,get source(){return a.source},get tokens(){return e},get options(){return t},get root(){return s},get pre(){return d},get code(){return c},get lines(){return p}};if(e.forEach((y,S)=>{S&&(i==="inline"?s.children.push({type:"element",tagName:"br",properties:{},children:[]}):i==="classic"&&n.push({type:"text",value:`
|
|
15
|
+
`}));let L={type:"element",tagName:"span",properties:{class:"line"},children:[]},C=0;for(let I of y){let x={type:"element",tagName:"span",properties:{...I.htmlAttrs},children:[{type:"text",value:I.content}]},v=Un(I.htmlStyle||to(I));v&&(x.properties.style=v);for(let q of o)x=q?.span?.call(f,x,S+1,C,L,I)||x;i==="inline"?s.children.push(x):i==="classic"&&L.children.push(x),C+=I.content.length}if(i==="classic"){for(let I of o)L=I?.line?.call(f,L,S+1)||L;p.push(L),n.push(L)}else i==="inline"&&p.push(L)}),i==="classic"){for(let y of o)c=y?.code?.call(f,c)||c;d.children.push(c);for(let y of o)d=y?.pre?.call(f,d)||d;s.children.push(d)}else if(i==="inline"){let y=[],S={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let I of s.children)I.type==="element"&&I.tagName==="br"?(y.push(S),S={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(I.type==="element"||I.type==="text")&&S.children.push(I);y.push(S);let C={type:"element",tagName:"code",properties:{},children:y};for(let I of o)C=I?.code?.call(f,C)||C;s.children=[];for(let I=0;I<C.children.length;I++){I>0&&s.children.push({type:"element",tagName:"br",properties:{},children:[]});let x=C.children[I];x.type==="element"&&s.children.push(...x.children)}}let m=s;for(let y of o)m=y?.root?.call(f,m)||m;return r&&so(m,r),m}function Hw(e){return e.map(t=>{let a=[],r="",o;return t.forEach((n,s)=>{let l=!(n.fontStyle&&(n.fontStyle&Ue.Underline||n.fontStyle&Ue.Strikethrough));l&&n.content.match(/^\s+$/)&&t[s+1]?(o===void 0&&(o=n.offset),r+=n.content):r?(l?a.push({...n,offset:o,content:r+n.content}):a.push({content:r,offset:o},n),o=void 0,r=""):a.push(n)}),a})}function $w(e){return e.map(t=>t.flatMap(a=>{if(a.content.match(/^\s+$/))return a;let r=a.content.match(/^(\s*)(.*?)(\s*)$/);if(!r)return a;let[,o,n,s]=r;if(!o&&!s)return a;let i=[{...a,offset:a.offset+o.length,content:n}];return o&&i.unshift({content:o,offset:a.offset}),s&&i.push({content:s,offset:a.offset+o.length+n.length}),i}))}function Ww(e){return e.map(t=>{let a=[];for(let r of t){if(a.length===0){a.push({...r});continue}let o=a[a.length-1],n=Un(o.htmlStyle||to(o)),s=Un(r.htmlStyle||to(r)),i=o.fontStyle&&(o.fontStyle&Ue.Underline||o.fontStyle&Ue.Strikethrough),l=r.fontStyle&&(r.fontStyle&Ue.Underline||r.fontStyle&Ue.Strikethrough);!i&&!l&&n===s?o.content+=r.content:a.push({...r})}return a})}var jw=Dn;function zw(e,t,a){let r={meta:{},options:a,codeToHast:(n,s)=>oo(e,n,s),codeToTokens:(n,s)=>ro(e,n,s)},o=jw(oo(e,t,a,r));for(let n of ao(a))o=n.postprocess?.call(r,o,a)||o;return o}var Gu={light:"#333333",dark:"#bbbbbb"},Ku={light:"#fffffe",dark:"#1e1e1e"},Xu="__shiki_resolved";function Vn(e){if(e?.[Xu])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||="dark",t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:a,fg:r}=t;if(!a||!r){let i=t.settings?t.settings.find(l=>!l.name&&!l.scope):void 0;i?.settings?.foreground&&(r=i.settings.foreground),i?.settings?.background&&(a=i.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!a&&t?.colors?.["editor.background"]&&(a=t.colors["editor.background"]),r||(r=t.type==="light"?Gu.light:Gu.dark),a||(a=t.type==="light"?Ku.light:Ku.dark),t.fg=r,t.bg=a}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let o=0,n=new Map;function s(i){if(n.has(i))return n.get(i);o+=1;let l=`#${o.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${l}`]?s(i):(n.set(i,l),l)}t.settings=t.settings.map(i=>{let l=i.settings?.foreground&&!i.settings.foreground.startsWith("#"),u=i.settings?.background&&!i.settings.background.startsWith("#");if(!l&&!u)return i;let d={...i,settings:{...i.settings}};if(l){let c=s(i.settings.foreground);t.colorReplacements[c]=i.settings.foreground,d.settings.foreground=c}if(u){let c=s(i.settings.background);t.colorReplacements[c]=i.settings.background,d.settings.background=c}return d});for(let i of Object.keys(t.colors||{}))if((i==="editor.foreground"||i==="editor.background"||i.startsWith("terminal.ansi"))&&!t.colors[i]?.startsWith("#")){let l=s(t.colors[i]);t.colorReplacements[l]=t.colors[i],t.colors[i]=l}return Object.defineProperty(t,Xu,{enumerable:!1,writable:!1,value:!0}),t}async function od(e){return Array.from(new Set((await Promise.all(e.filter(t=>!Qu(t)).map(async t=>await Ju(t).then(a=>Array.isArray(a)?a:[a])))).flat()))}async function nd(e){return(await Promise.all(e.map(async a=>Yu(a)?null:Vn(await Ju(a))))).filter(a=>!!a)}var On=3,Vw=!1;function Gw(e,t=3){if(On&&!(typeof On=="number"&&t>On)){if(Vw)throw new Error(`[SHIKI DEPRECATE]: ${e}`);console.trace(`[SHIKI DEPRECATE]: ${e}`)}}var Et=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function sd(e,t){if(!t)return e;if(t[e]){let a=new Set([e]);for(;t[e];){if(e=t[e],a.has(e))throw new Et(`Circular alias \`${Array.from(a).join(" -> ")} -> ${e}\``);a.add(e)}}return e}var Nn=class extends bu{constructor(t,a,r,o={}){super(t),this._resolver=t,this._themes=a,this._langs=r,this._alias=o,this._themes.map(n=>this.loadTheme(n)),this.loadLanguages(this._langs)}_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;getTheme(t){return typeof t=="string"?this._resolvedThemes.get(t):this.loadTheme(t)}loadTheme(t){let a=Vn(t);return a.name&&(this._resolvedThemes.set(a.name,a),this._loadedThemesCache=null),a}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(t){let a=this._textmateThemeCache.get(t);a||(a=za.createFromRawTheme(t),this._textmateThemeCache.set(t,a)),this._syncRegistry.setTheme(a)}getGrammar(t){return t=sd(t,this._alias),this._resolvedGrammars.get(t)}loadLanguage(t){if(this.getGrammar(t.name))return;let a=new Set([...this._langMap.values()].filter(n=>n.embeddedLangsLazy?.includes(t.name)));this._resolver.addLanguage(t);let r={balancedBracketSelectors:t.balancedBracketSelectors||["*"],unbalancedBracketSelectors:t.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(t.scopeName,t);let o=this.loadGrammarWithConfiguration(t.scopeName,1,r);if(o.name=t.name,this._resolvedGrammars.set(t.name,o),t.aliases&&t.aliases.forEach(n=>{this._alias[n]=t.name}),this._loadedLanguagesCache=null,a.size)for(let n of a)this._resolvedGrammars.delete(n.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(n.scopeName),this._syncRegistry?._grammars?.delete(n.scopeName),this.loadLanguage(this._langMap.get(n.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(t){for(let o of t)this.resolveEmbeddedLanguages(o);let a=Array.from(this._langGraph.entries()),r=a.filter(([o,n])=>!n);if(r.length){let o=a.filter(([n,s])=>s?(s.embeddedLanguages||s.embeddedLangs)?.some(l=>r.map(([u])=>u).includes(l)):!1).filter(n=>!r.includes(n));throw new Et(`Missing languages ${r.map(([n])=>`\`${n}\``).join(", ")}, required by ${o.map(([n])=>`\`${n}\``).join(", ")}`)}for(let[o,n]of a)this._resolver.addLanguage(n);for(let[o,n]of a)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(t){this._langMap.set(t.name,t),this._langGraph.set(t.name,t);let a=t.embeddedLanguages??t.embeddedLangs;if(a)for(let r of a)this._langGraph.set(r,this._langMap.get(r))}},qn=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(t,a){this._onigLib={createOnigScanner:r=>t.createScanner(r),createOnigString:r=>t.createString(r)},a.forEach(r=>this.addLanguage(r))}get onigLib(){return this._onigLib}getLangRegistration(t){return this._langs.get(t)}loadGrammar(t){return this._scopeToLang.get(t)}addLanguage(t){this._langs.set(t.name,t),t.aliases&&t.aliases.forEach(a=>{this._langs.set(a,t)}),this._scopeToLang.set(t.scopeName,t),t.injectTo&&t.injectTo.forEach(a=>{this._injections.get(a)||this._injections.set(a,[]),this._injections.get(a).push(t.scopeName)})}getInjections(t){let a=t.split("."),r=[];for(let o=1;o<=a.length;o++){let n=a.slice(0,o).join(".");r=[...r,...this._injections.get(n)||[]]}return r}},Qa=0;function Kw(e){Qa+=1,e.warnings!==!1&&Qa>=10&&Qa%10===0&&console.warn(`[Shiki] ${Qa} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new Et("`engine` option is required for synchronous mode");let a=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(Vn),o=new qn(e.engine,a),n=new Nn(o,r,a,e.langAlias),s;function i(I){return sd(I,e.langAlias)}function l(I){L();let x=n.getGrammar(typeof I=="string"?I:I.name);if(!x)throw new Et(`Language \`${I}\` not found, you may need to load it first`);return x}function u(I){if(I==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};L();let x=n.getTheme(I);if(!x)throw new Et(`Theme \`${I}\` not found, you may need to load it first`);return x}function d(I){L();let x=u(I);s!==I&&(n.setTheme(x),s=I);let v=n.getColorMap();return{theme:x,colorMap:v}}function c(){return L(),n.getLoadedThemes()}function p(){return L(),n.getLoadedLanguages()}function f(...I){L(),n.loadLanguages(I.flat(1))}async function m(...I){return f(await od(I))}function y(...I){L();for(let x of I.flat(1))n.loadTheme(x)}async function S(...I){return L(),y(await nd(I))}function L(){if(t)throw new Et("Shiki instance has been disposed")}function C(){t||(t=!0,n.dispose(),Qa-=1)}return{setTheme:d,getTheme:u,getLanguage:l,getLoadedThemes:c,getLoadedLanguages:p,resolveLangAlias:i,loadLanguage:m,loadLanguageSync:f,loadTheme:S,loadThemeSync:y,dispose:C,[Symbol.dispose]:C}}async function Xw(e){e.engine||Gw("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,a,r]=await Promise.all([nd(e.themes||[]),od(e.langs||[]),e.engine]);return Kw({...e,themes:t,langs:a,engine:r})}async function Jw(e){let t=await Xw(e);return{getLastGrammarState:(...a)=>Fw(t,...a),codeToTokensBase:(a,r)=>jn(t,a,r),codeToTokensWithThemes:(a,r)=>rd(t,a,r),codeToTokens:(a,r)=>ro(t,a,r),codeToHast:(a,r)=>oo(t,a,r),codeToHtml:(a,r)=>zw(t,a,r),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function id(e){let t=e.langs,a=e.themes,r=e.engine;async function o(n){function s(c){if(typeof c=="string"){if(c=n.langAlias?.[c]||c,Qu(c))return[];let p=t[c];if(!p)throw new ve(`Language \`${c}\` is not included in this bundle. You may want to load it from external source.`);return p}return c}function i(c){if(Yu(c))return"none";if(typeof c=="string"){let p=a[c];if(!p)throw new ve(`Theme \`${c}\` is not included in this bundle. You may want to load it from external source.`);return p}return c}let l=(n.themes??[]).map(c=>i(c)),u=(n.langs??[]).map(c=>s(c)),d=await Jw({engine:n.engine??r(),...n,themes:l,langs:u});return{...d,loadLanguage(...c){return d.loadLanguage(...c.map(s))},loadTheme(...c){return d.loadTheme(...c.map(i))},getBundledLanguages(){return t},getBundledThemes(){return a}}}return o}function Qw(e){let t;async function a(r={}){if(t){let o=await t;return await Promise.all([o.loadTheme(...r.themes||[]),o.loadLanguage(...r.langs||[])]),o}else{t=e({...r,themes:[],langs:[]});let o=await t;return await Promise.all([o.loadTheme(...r.themes||[]),o.loadLanguage(...r.langs||[])]),o}}return a}function ld(e,t){let a=Qw(e);async function r(o,n){let s=await a({langs:[n.lang],themes:"theme"in n?[n.theme]:Object.values(n.themes)}),i=await t?.guessEmbeddedLanguages?.(o,n.lang,s);return i&&await s.loadLanguage(...i),s}return{getSingletonHighlighter(o){return a(o)},async codeToHtml(o,n){return(await r(o,n)).codeToHtml(o,n)},async codeToHast(o,n){return(await r(o,n)).codeToHast(o,n)},async codeToTokens(o,n){return(await r(o,n)).codeToTokens(o,n)},async codeToTokensBase(o,n){return(await r(o,n)).codeToTokensBase(o,n)},async codeToTokensWithThemes(o,n){return(await r(o,n)).codeToTokensWithThemes(o,n)},async getLastGrammarState(o,n){return(await a({langs:[n.lang],themes:[n.theme]})).getLastGrammarState(o,n)}}}var Gn=[{id:"abap",name:"ABAP",import:(()=>import("../abap-KGVIZMDC.js"))},{id:"actionscript-3",name:"ActionScript",import:(()=>import("../actionscript-3-2UHK5QYP.js"))},{id:"ada",name:"Ada",import:(()=>import("../ada-JKTWR5BV.js"))},{id:"angular-html",name:"Angular HTML",import:(()=>import("../angular-html-PU3MXNBE.js"))},{id:"angular-ts",name:"Angular TypeScript",import:(()=>import("../angular-ts-WMZKXXGP.js"))},{id:"apache",name:"Apache Conf",import:(()=>import("../apache-MPGFGQFB.js"))},{id:"apex",name:"Apex",import:(()=>import("../apex-BOAZL66Z.js"))},{id:"apl",name:"APL",import:(()=>import("../apl-YU3KF3Y6.js"))},{id:"applescript",name:"AppleScript",import:(()=>import("../applescript-C4CJ3STL.js"))},{id:"ara",name:"Ara",import:(()=>import("../ara-FSFFBRSD.js"))},{id:"asciidoc",name:"AsciiDoc",aliases:["adoc"],import:(()=>import("../asciidoc-QQK2LANG.js"))},{id:"asm",name:"Assembly",import:(()=>import("../asm-X43A2VYW.js"))},{id:"astro",name:"Astro",import:(()=>import("../astro-BMSTTQT4.js"))},{id:"awk",name:"AWK",import:(()=>import("../awk-4Z3PRTF7.js"))},{id:"ballerina",name:"Ballerina",import:(()=>import("../ballerina-JCXSJ2QD.js"))},{id:"bat",name:"Batch File",aliases:["batch"],import:(()=>import("../bat-XFWR7RMZ.js"))},{id:"beancount",name:"Beancount",import:(()=>import("../beancount-7BBDB4BH.js"))},{id:"berry",name:"Berry",aliases:["be"],import:(()=>import("../berry-PQ2BEJIZ.js"))},{id:"bibtex",name:"BibTeX",import:(()=>import("../bibtex-J2PAB23I.js"))},{id:"bicep",name:"Bicep",import:(()=>import("../bicep-TNKT6R3W.js"))},{id:"blade",name:"Blade",import:(()=>import("../blade-YKL22AM4.js"))},{id:"bsl",name:"1C (Enterprise)",aliases:["1c"],import:(()=>import("../bsl-PQW6E45S.js"))},{id:"c",name:"C",import:(()=>import("../c-PZBJFNXE.js"))},{id:"c3",name:"C3",import:(()=>import("../c3-GP7XYHE6.js"))},{id:"cadence",name:"Cadence",aliases:["cdc"],import:(()=>import("../cadence-NABGDHKY.js"))},{id:"cairo",name:"Cairo",import:(()=>import("../cairo-WQSC2GLN.js"))},{id:"clarity",name:"Clarity",import:(()=>import("../clarity-NXNSINKX.js"))},{id:"clojure",name:"Clojure",aliases:["clj"],import:(()=>import("../clojure-Y57BKRMA.js"))},{id:"cmake",name:"CMake",import:(()=>import("../cmake-LVMEA3JZ.js"))},{id:"cobol",name:"COBOL",import:(()=>import("../cobol-YD3RINFS.js"))},{id:"codeowners",name:"CODEOWNERS",import:(()=>import("../codeowners-JYHOTXQS.js"))},{id:"codeql",name:"CodeQL",aliases:["ql"],import:(()=>import("../codeql-IWWSYR3L.js"))},{id:"coffee",name:"CoffeeScript",aliases:["coffeescript"],import:(()=>import("../coffee-NNDQ5QXC.js"))},{id:"common-lisp",name:"Common Lisp",aliases:["lisp"],import:(()=>import("../common-lisp-JKXCDYH3.js"))},{id:"coq",name:"Coq",import:(()=>import("../coq-BEHPNP64.js"))},{id:"cpp",name:"C++",aliases:["c++"],import:(()=>import("../cpp-IALOHSZA.js"))},{id:"crystal",name:"Crystal",import:(()=>import("../crystal-AUUIRTAZ.js"))},{id:"csharp",name:"C#",aliases:["c#","cs"],import:(()=>import("../csharp-ODFBXRGA.js"))},{id:"css",name:"CSS",import:(()=>import("../css-CJGL5AVH.js"))},{id:"csv",name:"CSV",import:(()=>import("../csv-LIK4TU3Z.js"))},{id:"cue",name:"CUE",import:(()=>import("../cue-UAAEAKHI.js"))},{id:"cypher",name:"Cypher",aliases:["cql"],import:(()=>import("../cypher-SZPVUQZJ.js"))},{id:"d",name:"D",import:(()=>import("../d-VSCA3XHG.js"))},{id:"dart",name:"Dart",import:(()=>import("../dart-A4PE6FIS.js"))},{id:"dax",name:"DAX",import:(()=>import("../dax-TILIKSFB.js"))},{id:"desktop",name:"Desktop",import:(()=>import("../desktop-75KK3D55.js"))},{id:"diff",name:"Diff",import:(()=>import("../diff-HOT6P45M.js"))},{id:"docker",name:"Dockerfile",aliases:["dockerfile"],import:(()=>import("../docker-FF35TY6T.js"))},{id:"dotenv",name:"dotEnv",import:(()=>import("../dotenv-FVPPHJI3.js"))},{id:"dream-maker",name:"Dream Maker",import:(()=>import("../dream-maker-SYE3ZPSJ.js"))},{id:"edge",name:"Edge",import:(()=>import("../edge-44UF6IIM.js"))},{id:"elixir",name:"Elixir",import:(()=>import("../elixir-ZJ4WTHOY.js"))},{id:"elm",name:"Elm",import:(()=>import("../elm-5QRQXDZ6.js"))},{id:"emacs-lisp",name:"Emacs Lisp",aliases:["elisp"],import:(()=>import("../emacs-lisp-NJ4S4OHV.js"))},{id:"erb",name:"ERB",import:(()=>import("../erb-ZF7YKJP7.js"))},{id:"erlang",name:"Erlang",aliases:["erl"],import:(()=>import("../erlang-APEONNZ6.js"))},{id:"fennel",name:"Fennel",import:(()=>import("../fennel-7OCMFVPS.js"))},{id:"fish",name:"Fish",import:(()=>import("../fish-BC46ME2N.js"))},{id:"fluent",name:"Fluent",aliases:["ftl"],import:(()=>import("../fluent-MXZS6EX3.js"))},{id:"fortran-fixed-form",name:"Fortran (Fixed Form)",aliases:["f","for","f77"],import:(()=>import("../fortran-fixed-form-35BC2KX6.js"))},{id:"fortran-free-form",name:"Fortran (Free Form)",aliases:["f90","f95","f03","f08","f18"],import:(()=>import("../fortran-free-form-AXRAI2HH.js"))},{id:"fsharp",name:"F#",aliases:["f#","fs"],import:(()=>import("../fsharp-JKNSQXHD.js"))},{id:"gdresource",name:"GDResource",aliases:["tscn","tres"],import:(()=>import("../gdresource-ZMKZGPZV.js"))},{id:"gdscript",name:"GDScript",aliases:["gd"],import:(()=>import("../gdscript-HNCVXEYB.js"))},{id:"gdshader",name:"GDShader",import:(()=>import("../gdshader-XAJ4QRYP.js"))},{id:"genie",name:"Genie",import:(()=>import("../genie-HEFVQZAP.js"))},{id:"gherkin",name:"Gherkin",import:(()=>import("../gherkin-OFBRDPXX.js"))},{id:"git-commit",name:"Git Commit Message",import:(()=>import("../git-commit-ZE2M3Q5H.js"))},{id:"git-rebase",name:"Git Rebase Message",import:(()=>import("../git-rebase-3N3INGLU.js"))},{id:"gleam",name:"Gleam",import:(()=>import("../gleam-NFFQFQLP.js"))},{id:"glimmer-js",name:"Glimmer JS",aliases:["gjs"],import:(()=>import("../glimmer-js-TKADNZF5.js"))},{id:"glimmer-ts",name:"Glimmer TS",aliases:["gts"],import:(()=>import("../glimmer-ts-WFYWDU2O.js"))},{id:"glsl",name:"GLSL",import:(()=>import("../glsl-VJLRYEVJ.js"))},{id:"gn",name:"GN",import:(()=>import("../gn-UH2XQWLG.js"))},{id:"gnuplot",name:"Gnuplot",import:(()=>import("../gnuplot-K6IV6NNR.js"))},{id:"go",name:"Go",import:(()=>import("../go-BDV7RR5G.js"))},{id:"graphql",name:"GraphQL",aliases:["gql"],import:(()=>import("../graphql-NLMAEKLI.js"))},{id:"groovy",name:"Groovy",import:(()=>import("../groovy-SX7K3XGL.js"))},{id:"hack",name:"Hack",import:(()=>import("../hack-HCRIHDCF.js"))},{id:"haml",name:"Ruby Haml",import:(()=>import("../haml-335RVEQR.js"))},{id:"handlebars",name:"Handlebars",aliases:["hbs"],import:(()=>import("../handlebars-7EKNR6OR.js"))},{id:"haskell",name:"Haskell",aliases:["hs"],import:(()=>import("../haskell-P5PTJARU.js"))},{id:"haxe",name:"Haxe",import:(()=>import("../haxe-RCPSSA3N.js"))},{id:"hcl",name:"HashiCorp HCL",import:(()=>import("../hcl-AKKZAVC2.js"))},{id:"hjson",name:"Hjson",import:(()=>import("../hjson-REXV6F6N.js"))},{id:"hlsl",name:"HLSL",import:(()=>import("../hlsl-AJ7VWOVL.js"))},{id:"html",name:"HTML",import:(()=>import("../html-G4Q6FSTL.js"))},{id:"html-derivative",name:"HTML (Derivative)",import:(()=>import("../html-derivative-2AGKXLI2.js"))},{id:"http",name:"HTTP",import:(()=>import("../http-7ZVVH3VM.js"))},{id:"hurl",name:"Hurl",import:(()=>import("../hurl-B6WXEN45.js"))},{id:"hxml",name:"HXML",import:(()=>import("../hxml-5BXJCAAU.js"))},{id:"hy",name:"Hy",import:(()=>import("../hy-SB4TMFE7.js"))},{id:"imba",name:"Imba",import:(()=>import("../imba-Y64MHYWP.js"))},{id:"ini",name:"INI",aliases:["properties"],import:(()=>import("../ini-J2OP4CNW.js"))},{id:"java",name:"Java",import:(()=>import("../java-MJKJ5GPP.js"))},{id:"javascript",name:"JavaScript",aliases:["js","cjs","mjs"],import:(()=>import("../javascript-IYAGHPR6.js"))},{id:"jinja",name:"Jinja",import:(()=>import("../jinja-K2EDFFOP.js"))},{id:"jison",name:"Jison",import:(()=>import("../jison-UYDZQBN5.js"))},{id:"json",name:"JSON",import:(()=>import("../json-5V4JESJO.js"))},{id:"json5",name:"JSON5",import:(()=>import("../json5-7SHUZD3R.js"))},{id:"jsonc",name:"JSON with Comments",import:(()=>import("../jsonc-X3Z34FN3.js"))},{id:"jsonl",name:"JSON Lines",import:(()=>import("../jsonl-6I3D2HM6.js"))},{id:"jsonnet",name:"Jsonnet",import:(()=>import("../jsonnet-PZEQIBYV.js"))},{id:"jssm",name:"JSSM",aliases:["fsl"],import:(()=>import("../jssm-GJJ25IKR.js"))},{id:"jsx",name:"JSX",import:(()=>import("../jsx-NI2J427C.js"))},{id:"julia",name:"Julia",aliases:["jl"],import:(()=>import("../julia-CPV3A4MM.js"))},{id:"kdl",name:"KDL",import:(()=>import("../kdl-IA7HA2TL.js"))},{id:"kotlin",name:"Kotlin",aliases:["kt","kts"],import:(()=>import("../kotlin-CCRMGYMI.js"))},{id:"kusto",name:"Kusto",aliases:["kql"],import:(()=>import("../kusto-7DW25GYH.js"))},{id:"latex",name:"LaTeX",import:(()=>import("../latex-F2CTDTFG.js"))},{id:"lean",name:"Lean 4",aliases:["lean4"],import:(()=>import("../lean-MGJJWBTR.js"))},{id:"less",name:"Less",import:(()=>import("../less-WFSIMX5G.js"))},{id:"liquid",name:"Liquid",import:(()=>import("../liquid-YEOV5OY7.js"))},{id:"llvm",name:"LLVM IR",import:(()=>import("../llvm-CFQSEDXB.js"))},{id:"log",name:"Log file",import:(()=>import("../log-YQNML6LA.js"))},{id:"logo",name:"Logo",import:(()=>import("../logo-2PPKBL2M.js"))},{id:"lua",name:"Lua",import:(()=>import("../lua-RPAMRKNG.js"))},{id:"luau",name:"Luau",import:(()=>import("../luau-GR2DOH6N.js"))},{id:"make",name:"Makefile",aliases:["makefile"],import:(()=>import("../make-DQQEEPI4.js"))},{id:"markdown",name:"Markdown",aliases:["md"],import:(()=>import("../markdown-OC5ILZSY.js"))},{id:"marko",name:"Marko",import:(()=>import("../marko-XSB3CTWQ.js"))},{id:"matlab",name:"MATLAB",import:(()=>import("../matlab-YQY6FS4U.js"))},{id:"mdc",name:"MDC",import:(()=>import("../mdc-I5IJFJ2O.js"))},{id:"mdx",name:"MDX",import:(()=>import("../mdx-ZIH2JLVR.js"))},{id:"mermaid",name:"Mermaid",aliases:["mmd"],import:(()=>import("../mermaid-WPX56SBB.js"))},{id:"mipsasm",name:"MIPS Assembly",aliases:["mips"],import:(()=>import("../mipsasm-IDXQRZ2B.js"))},{id:"mojo",name:"Mojo",import:(()=>import("../mojo-MH7EQVOK.js"))},{id:"moonbit",name:"MoonBit",aliases:["mbt","mbti"],import:(()=>import("../moonbit-5JDFTWKE.js"))},{id:"move",name:"Move",import:(()=>import("../move-RWSXKYDY.js"))},{id:"narrat",name:"Narrat Language",aliases:["nar"],import:(()=>import("../narrat-QJUEXMVV.js"))},{id:"nextflow",name:"Nextflow",aliases:["nf"],import:(()=>import("../nextflow-2EICNZA3.js"))},{id:"nginx",name:"Nginx",import:(()=>import("../nginx-RIWAEC5Z.js"))},{id:"nim",name:"Nim",import:(()=>import("../nim-JXWLGPJS.js"))},{id:"nix",name:"Nix",import:(()=>import("../nix-XCKQVWCN.js"))},{id:"nushell",name:"nushell",aliases:["nu"],import:(()=>import("../nushell-QGW7HANA.js"))},{id:"objective-c",name:"Objective-C",aliases:["objc"],import:(()=>import("../objective-c-V7KYXFHL.js"))},{id:"objective-cpp",name:"Objective-C++",import:(()=>import("../objective-cpp-NKUEWVGU.js"))},{id:"ocaml",name:"OCaml",import:(()=>import("../ocaml-QT2CZJZN.js"))},{id:"odin",name:"Odin",import:(()=>import("../odin-MVMIXBHP.js"))},{id:"openscad",name:"OpenSCAD",aliases:["scad"],import:(()=>import("../openscad-BJDUXUUZ.js"))},{id:"pascal",name:"Pascal",import:(()=>import("../pascal-HGWEFD6L.js"))},{id:"perl",name:"Perl",import:(()=>import("../perl-HORNVRGS.js"))},{id:"php",name:"PHP",import:(()=>import("../php-JGPDZKQ3.js"))},{id:"pkl",name:"Pkl",import:(()=>import("../pkl-VA5ZK5DW.js"))},{id:"plsql",name:"PL/SQL",import:(()=>import("../plsql-J7A7YWFH.js"))},{id:"po",name:"Gettext PO",aliases:["pot","potx"],import:(()=>import("../po-5RDI65JX.js"))},{id:"polar",name:"Polar",import:(()=>import("../polar-VUJL2E7F.js"))},{id:"postcss",name:"PostCSS",import:(()=>import("../postcss-ESTB5G7N.js"))},{id:"powerquery",name:"PowerQuery",import:(()=>import("../powerquery-ODTEKQCW.js"))},{id:"powershell",name:"PowerShell",aliases:["ps","ps1"],import:(()=>import("../powershell-ZOYRAWBJ.js"))},{id:"prisma",name:"Prisma",import:(()=>import("../prisma-QHG2W5GE.js"))},{id:"prolog",name:"Prolog",import:(()=>import("../prolog-CSAPG5PH.js"))},{id:"proto",name:"Protocol Buffer 3",aliases:["protobuf"],import:(()=>import("../proto-WDNJBTSW.js"))},{id:"pug",name:"Pug",aliases:["jade"],import:(()=>import("../pug-3YFWZUJ6.js"))},{id:"puppet",name:"Puppet",import:(()=>import("../puppet-LHFWHTY3.js"))},{id:"purescript",name:"PureScript",import:(()=>import("../purescript-DUFJP4FY.js"))},{id:"python",name:"Python",aliases:["py"],import:(()=>import("../python-5ZNZSNQ2.js"))},{id:"qml",name:"QML",import:(()=>import("../qml-LTAXB6W5.js"))},{id:"qmldir",name:"QML Directory",import:(()=>import("../qmldir-7Z2ODQLM.js"))},{id:"qss",name:"Qt Style Sheets",import:(()=>import("../qss-FDFD3HQD.js"))},{id:"r",name:"R",import:(()=>import("../r-6ZOS53WN.js"))},{id:"racket",name:"Racket",import:(()=>import("../racket-7AYZPEUI.js"))},{id:"raku",name:"Raku",aliases:["perl6"],import:(()=>import("../raku-A4F6VHVG.js"))},{id:"razor",name:"ASP.NET Razor",import:(()=>import("../razor-7T4OK2LD.js"))},{id:"reg",name:"Windows Registry Script",import:(()=>import("../reg-FAPHGG66.js"))},{id:"regexp",name:"RegExp",aliases:["regex"],import:(()=>import("../regexp-5BYLYA2R.js"))},{id:"rel",name:"Rel",import:(()=>import("../rel-7DJ7HHU4.js"))},{id:"riscv",name:"RISC-V",import:(()=>import("../riscv-YIYJATFG.js"))},{id:"ron",name:"RON",import:(()=>import("../ron-HYYMCHTX.js"))},{id:"rosmsg",name:"ROS Interface",import:(()=>import("../rosmsg-FDNH6QF7.js"))},{id:"rst",name:"reStructuredText",import:(()=>import("../rst-SR6APMGO.js"))},{id:"ruby",name:"Ruby",aliases:["rb"],import:(()=>import("../ruby-IYOQSPDU.js"))},{id:"rust",name:"Rust",aliases:["rs"],import:(()=>import("../rust-V3GMJA2K.js"))},{id:"sas",name:"SAS",import:(()=>import("../sas-D3G4GB3X.js"))},{id:"sass",name:"Sass",import:(()=>import("../sass-JTO65AGR.js"))},{id:"scala",name:"Scala",import:(()=>import("../scala-4XQGFSVM.js"))},{id:"scheme",name:"Scheme",import:(()=>import("../scheme-CB7AC7IL.js"))},{id:"scss",name:"SCSS",import:(()=>import("../scss-6SKV4OGI.js"))},{id:"sdbl",name:"1C (Query)",aliases:["1c-query"],import:(()=>import("../sdbl-LKGZFJ46.js"))},{id:"shaderlab",name:"ShaderLab",aliases:["shader"],import:(()=>import("../shaderlab-K536DHEB.js"))},{id:"shellscript",name:"Shell",aliases:["bash","sh","shell","zsh"],import:(()=>import("../shellscript-LRNUKUSZ.js"))},{id:"shellsession",name:"Shell Session",aliases:["console"],import:(()=>import("../shellsession-IBQK7VWQ.js"))},{id:"smalltalk",name:"Smalltalk",import:(()=>import("../smalltalk-DQOSWAW7.js"))},{id:"solidity",name:"Solidity",import:(()=>import("../solidity-V2FMZEG4.js"))},{id:"soy",name:"Closure Templates",aliases:["closure-templates"],import:(()=>import("../soy-WHPD3NJL.js"))},{id:"sparql",name:"SPARQL",import:(()=>import("../sparql-L2VKP7YP.js"))},{id:"splunk",name:"Splunk Query Language",aliases:["spl"],import:(()=>import("../splunk-KDKHP7GC.js"))},{id:"sql",name:"SQL",import:(()=>import("../sql-UF27CALT.js"))},{id:"ssh-config",name:"SSH Config",import:(()=>import("../ssh-config-JC2DQ6ED.js"))},{id:"stata",name:"Stata",import:(()=>import("../stata-7PXCUY24.js"))},{id:"stylus",name:"Stylus",aliases:["styl"],import:(()=>import("../stylus-2L7N3EZD.js"))},{id:"surrealql",name:"SurrealQL",aliases:["surql"],import:(()=>import("../surrealql-ZY3E6XEL.js"))},{id:"svelte",name:"Svelte",import:(()=>import("../svelte-Q45XIK2A.js"))},{id:"swift",name:"Swift",import:(()=>import("../swift-XBH5HZSC.js"))},{id:"system-verilog",name:"SystemVerilog",import:(()=>import("../system-verilog-VRAUSZY3.js"))},{id:"systemd",name:"Systemd Units",import:(()=>import("../systemd-JOTSGJD4.js"))},{id:"talonscript",name:"TalonScript",aliases:["talon"],import:(()=>import("../talonscript-NNZRZKOU.js"))},{id:"tasl",name:"Tasl",import:(()=>import("../tasl-MBFZ4QNC.js"))},{id:"tcl",name:"Tcl",import:(()=>import("../tcl-4GEDCBVE.js"))},{id:"templ",name:"Templ",import:(()=>import("../templ-VI6LYHRW.js"))},{id:"terraform",name:"Terraform",aliases:["tf","tfvars"],import:(()=>import("../terraform-XTHOS4UK.js"))},{id:"tex",name:"TeX",import:(()=>import("../tex-UXMN2CV7.js"))},{id:"toml",name:"TOML",import:(()=>import("../toml-J6K55ZSV.js"))},{id:"ts-tags",name:"TypeScript with Tags",aliases:["lit"],import:(()=>import("../ts-tags-MU4UAPH3.js"))},{id:"tsv",name:"TSV",import:(()=>import("../tsv-DOUJHQDQ.js"))},{id:"tsx",name:"TSX",import:(()=>import("../tsx-G5BMVRHK.js"))},{id:"turtle",name:"Turtle",import:(()=>import("../turtle-JHJ7W6U5.js"))},{id:"twig",name:"Twig",import:(()=>import("../twig-OY2C64LG.js"))},{id:"typescript",name:"TypeScript",aliases:["ts","cts","mts"],import:(()=>import("../typescript-LMKEAHFC.js"))},{id:"typespec",name:"TypeSpec",aliases:["tsp"],import:(()=>import("../typespec-5CLTIJYY.js"))},{id:"typst",name:"Typst",aliases:["typ"],import:(()=>import("../typst-4W4Z436Z.js"))},{id:"v",name:"V",import:(()=>import("../v-Y4SBDBN7.js"))},{id:"vala",name:"Vala",import:(()=>import("../vala-UMKT2MFA.js"))},{id:"vb",name:"Visual Basic",aliases:["cmd"],import:(()=>import("../vb-DQ7A5WJU.js"))},{id:"verilog",name:"Verilog",import:(()=>import("../verilog-N6ZF7GQD.js"))},{id:"vhdl",name:"VHDL",import:(()=>import("../vhdl-BNYDT37G.js"))},{id:"viml",name:"Vim Script",aliases:["vim","vimscript"],import:(()=>import("../viml-37RMDCBC.js"))},{id:"vue",name:"Vue",import:(()=>import("../vue-M6XWA362.js"))},{id:"vue-html",name:"Vue HTML",import:(()=>import("../vue-html-ZLTZN573.js"))},{id:"vue-vine",name:"Vue Vine",import:(()=>import("../vue-vine-6JKAZ54I.js"))},{id:"vyper",name:"Vyper",aliases:["vy"],import:(()=>import("../vyper-GVXF46KD.js"))},{id:"wasm",name:"WebAssembly",import:(()=>import("../wasm-NTB4O7GL.js"))},{id:"wenyan",name:"Wenyan",aliases:["\u6587\u8A00"],import:(()=>import("../wenyan-W7WB3BC7.js"))},{id:"wgsl",name:"WGSL",import:(()=>import("../wgsl-7GTDVXHG.js"))},{id:"wikitext",name:"Wikitext",aliases:["mediawiki","wiki"],import:(()=>import("../wikitext-ASAFPAIL.js"))},{id:"wit",name:"WebAssembly Interface Types",import:(()=>import("../wit-ZBCR6544.js"))},{id:"wolfram",name:"Wolfram",aliases:["wl"],import:(()=>import("../wolfram-SZRZOETJ.js"))},{id:"xml",name:"XML",import:(()=>import("../xml-EBTJCOTU.js"))},{id:"xsl",name:"XSL",import:(()=>import("../xsl-IBYEXWDX.js"))},{id:"yaml",name:"YAML",aliases:["yml"],import:(()=>import("../yaml-GMVQNECR.js"))},{id:"zenscript",name:"ZenScript",import:(()=>import("../zenscript-O2TZFP4A.js"))},{id:"zig",name:"Zig",import:(()=>import("../zig-ZLGM7IMN.js"))}],ud=Object.fromEntries(Gn.map(e=>[e.id,e.import])),dd=Object.fromEntries(Gn.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),Za={...ud,...dd};var Yw=[{id:"andromeeda",displayName:"Andromeeda",type:"dark",import:(()=>import("../andromeeda-HAPOYWX3.js"))},{id:"aurora-x",displayName:"Aurora X",type:"dark",import:(()=>import("../aurora-x-R6WAWEBC.js"))},{id:"ayu-dark",displayName:"Ayu Dark",type:"dark",import:(()=>import("../ayu-dark-KMD4YO7F.js"))},{id:"ayu-light",displayName:"Ayu Light",type:"light",import:(()=>import("../ayu-light-2ATPDILG.js"))},{id:"ayu-mirage",displayName:"Ayu Mirage",type:"dark",import:(()=>import("../ayu-mirage-LJ7PG5AM.js"))},{id:"catppuccin-frappe",displayName:"Catppuccin Frapp\xE9",type:"dark",import:(()=>import("../catppuccin-frappe-Z4Y2POK6.js"))},{id:"catppuccin-latte",displayName:"Catppuccin Latte",type:"light",import:(()=>import("../catppuccin-latte-4TQUIKX4.js"))},{id:"catppuccin-macchiato",displayName:"Catppuccin Macchiato",type:"dark",import:(()=>import("../catppuccin-macchiato-B7YYPERT.js"))},{id:"catppuccin-mocha",displayName:"Catppuccin Mocha",type:"dark",import:(()=>import("../catppuccin-mocha-KX33VXKA.js"))},{id:"dark-plus",displayName:"Dark Plus",type:"dark",import:(()=>import("../dark-plus-LNHXUR7U.js"))},{id:"dracula",displayName:"Dracula Theme",type:"dark",import:(()=>import("../dracula-T2CMBBQ5.js"))},{id:"dracula-soft",displayName:"Dracula Theme Soft",type:"dark",import:(()=>import("../dracula-soft-SMFRNKX2.js"))},{id:"everforest-dark",displayName:"Everforest Dark",type:"dark",import:(()=>import("../everforest-dark-DBZHIUAO.js"))},{id:"everforest-light",displayName:"Everforest Light",type:"light",import:(()=>import("../everforest-light-TDAGYJUK.js"))},{id:"github-dark",displayName:"GitHub Dark",type:"dark",import:(()=>import("../github-dark-3E25TTAN.js"))},{id:"github-dark-default",displayName:"GitHub Dark Default",type:"dark",import:(()=>import("../github-dark-default-KCBFVSS5.js"))},{id:"github-dark-dimmed",displayName:"GitHub Dark Dimmed",type:"dark",import:(()=>import("../github-dark-dimmed-WRCBXEVS.js"))},{id:"github-dark-high-contrast",displayName:"GitHub Dark High Contrast",type:"dark",import:(()=>import("../github-dark-high-contrast-ET7SAHAV.js"))},{id:"github-light",displayName:"GitHub Light",type:"light",import:(()=>import("../github-light-6FNTZH5H.js"))},{id:"github-light-default",displayName:"GitHub Light Default",type:"light",import:(()=>import("../github-light-default-GGTAKNM7.js"))},{id:"github-light-high-contrast",displayName:"GitHub Light High Contrast",type:"light",import:(()=>import("../github-light-high-contrast-LHYKPR5E.js"))},{id:"gruvbox-dark-hard",displayName:"Gruvbox Dark Hard",type:"dark",import:(()=>import("../gruvbox-dark-hard-IQWZCHF7.js"))},{id:"gruvbox-dark-medium",displayName:"Gruvbox Dark Medium",type:"dark",import:(()=>import("../gruvbox-dark-medium-ARPWF4FS.js"))},{id:"gruvbox-dark-soft",displayName:"Gruvbox Dark Soft",type:"dark",import:(()=>import("../gruvbox-dark-soft-ODS6FPID.js"))},{id:"gruvbox-light-hard",displayName:"Gruvbox Light Hard",type:"light",import:(()=>import("../gruvbox-light-hard-KFA5YFDW.js"))},{id:"gruvbox-light-medium",displayName:"Gruvbox Light Medium",type:"light",import:(()=>import("../gruvbox-light-medium-MMET4L3Y.js"))},{id:"gruvbox-light-soft",displayName:"Gruvbox Light Soft",type:"light",import:(()=>import("../gruvbox-light-soft-DBZDERMK.js"))},{id:"horizon",displayName:"Horizon",type:"dark",import:(()=>import("../horizon-FSOMPXNP.js"))},{id:"houston",displayName:"Houston",type:"dark",import:(()=>import("../houston-FAQBCORN.js"))},{id:"kanagawa-dragon",displayName:"Kanagawa Dragon",type:"dark",import:(()=>import("../kanagawa-dragon-JNDVF5RJ.js"))},{id:"kanagawa-lotus",displayName:"Kanagawa Lotus",type:"light",import:(()=>import("../kanagawa-lotus-S7JK6TQ6.js"))},{id:"kanagawa-wave",displayName:"Kanagawa Wave",type:"dark",import:(()=>import("../kanagawa-wave-QJJIMVEV.js"))},{id:"laserwave",displayName:"LaserWave",type:"dark",import:(()=>import("../laserwave-YFP3EJVX.js"))},{id:"light-plus",displayName:"Light Plus",type:"light",import:(()=>import("../light-plus-NGDHCPUZ.js"))},{id:"material-theme",displayName:"Material Theme",type:"dark",import:(()=>import("../material-theme-H2BHKUKX.js"))},{id:"material-theme-darker",displayName:"Material Theme Darker",type:"dark",import:(()=>import("../material-theme-darker-VENCGWTB.js"))},{id:"material-theme-lighter",displayName:"Material Theme Lighter",type:"light",import:(()=>import("../material-theme-lighter-SDMLS22W.js"))},{id:"material-theme-ocean",displayName:"Material Theme Ocean",type:"dark",import:(()=>import("../material-theme-ocean-UHDBRLVF.js"))},{id:"material-theme-palenight",displayName:"Material Theme Palenight",type:"dark",import:(()=>import("../material-theme-palenight-3TB2BEET.js"))},{id:"min-dark",displayName:"Min Dark",type:"dark",import:(()=>import("../min-dark-CQ5WKNT7.js"))},{id:"min-light",displayName:"Min Light",type:"light",import:(()=>import("../min-light-LZRD4NPR.js"))},{id:"monokai",displayName:"Monokai",type:"dark",import:(()=>import("../monokai-WHRY6275.js"))},{id:"night-owl",displayName:"Night Owl",type:"dark",import:(()=>import("../night-owl-7PNEW2JB.js"))},{id:"night-owl-light",displayName:"Night Owl Light",type:"light",import:(()=>import("../night-owl-light-GJUYOOJR.js"))},{id:"nord",displayName:"Nord",type:"dark",import:(()=>import("../nord-EVGUMUX2.js"))},{id:"one-dark-pro",displayName:"One Dark Pro",type:"dark",import:(()=>import("../one-dark-pro-PMTR3SA7.js"))},{id:"one-light",displayName:"One Light",type:"light",import:(()=>import("../one-light-O7WH4N5X.js"))},{id:"plastic",displayName:"Plastic",type:"dark",import:(()=>import("../plastic-FBVUW6NJ.js"))},{id:"poimandres",displayName:"Poimandres",type:"dark",import:(()=>import("../poimandres-WBB7GZAD.js"))},{id:"red",displayName:"Red",type:"dark",import:(()=>import("../red-7KAMONOP.js"))},{id:"rose-pine",displayName:"Ros\xE9 Pine",type:"dark",import:(()=>import("../rose-pine-F2G5IHZD.js"))},{id:"rose-pine-dawn",displayName:"Ros\xE9 Pine Dawn",type:"light",import:(()=>import("../rose-pine-dawn-ALZ7XGH2.js"))},{id:"rose-pine-moon",displayName:"Ros\xE9 Pine Moon",type:"dark",import:(()=>import("../rose-pine-moon-D3K4SWUL.js"))},{id:"slack-dark",displayName:"Slack Dark",type:"dark",import:(()=>import("../slack-dark-YFPJODWS.js"))},{id:"slack-ochin",displayName:"Slack Ochin",type:"light",import:(()=>import("../slack-ochin-H67AWZOI.js"))},{id:"snazzy-light",displayName:"Snazzy Light",type:"light",import:(()=>import("../snazzy-light-OUVS63VK.js"))},{id:"solarized-dark",displayName:"Solarized Dark",type:"dark",import:(()=>import("../solarized-dark-2RCAVEXJ.js"))},{id:"solarized-light",displayName:"Solarized Light",type:"light",import:(()=>import("../solarized-light-XFSENHTC.js"))},{id:"synthwave-84",displayName:"Synthwave '84",type:"dark",import:(()=>import("../synthwave-84-5XXB3K6S.js"))},{id:"tokyo-night",displayName:"Tokyo Night",type:"dark",import:(()=>import("../tokyo-night-CHJCCBJH.js"))},{id:"vesper",displayName:"Vesper",type:"dark",import:(()=>import("../vesper-Y5GIEAN4.js"))},{id:"vitesse-black",displayName:"Vitesse Black",type:"dark",import:(()=>import("../vitesse-black-7TI33KHX.js"))},{id:"vitesse-dark",displayName:"Vitesse Dark",type:"dark",import:(()=>import("../vitesse-dark-FOB25MRB.js"))},{id:"vitesse-light",displayName:"Vitesse Light",type:"light",import:(()=>import("../vitesse-light-4WCNCTCO.js"))}],cd=Object.fromEntries(Yw.map(e=>[e.id,e.import]));var er=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Zw(){return 2147483648}function eI(){return typeof performance<"u"?performance.now():Date.now()}var tI=(e,t)=>e+(t-e%t)%t;async function aI(e){let t,a,r={};function o(f){a=f,r.HEAPU8=new Uint8Array(f),r.HEAPU32=new Uint32Array(f)}function n(f,m,y){r.HEAPU8.copyWithin(f,m,m+y)}function s(f){try{return t.grow(f-a.byteLength+65535>>>16),o(t.buffer),1}catch{}}function i(f){let m=r.HEAPU8.length;f=f>>>0;let y=Zw();if(f>y)return!1;for(let S=1;S<=4;S*=2){let L=m*(1+.2/S);L=Math.min(L,f+100663296);let C=Math.min(y,tI(Math.max(f,L),65536));if(s(C))return!0}return!1}let l=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function u(f,m,y=1024){let S=m+y,L=m;for(;f[L]&&!(L>=S);)++L;if(L-m>16&&f.buffer&&l)return l.decode(f.subarray(m,L));let C="";for(;m<L;){let I=f[m++];if(!(I&128)){C+=String.fromCharCode(I);continue}let x=f[m++]&63;if((I&224)===192){C+=String.fromCharCode((I&31)<<6|x);continue}let v=f[m++]&63;if((I&240)===224?I=(I&15)<<12|x<<6|v:I=(I&7)<<18|x<<12|v<<6|f[m++]&63,I<65536)C+=String.fromCharCode(I);else{let q=I-65536;C+=String.fromCharCode(55296|q>>10,56320|q&1023)}}return C}function d(f,m){return f?u(r.HEAPU8,f,m):""}let c={emscripten_get_now:eI,emscripten_memcpy_big:n,emscripten_resize_heap:i,fd_write:()=>0};async function p(){let m=await e({env:c,wasi_snapshot_preview1:c});t=m.memory,o(t.buffer),Object.assign(r,m),r.UTF8ToString=d}return await p(),r}var rI=Object.defineProperty,oI=(e,t,a)=>t in e?rI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,Me=(e,t,a)=>oI(e,typeof t!="symbol"?t+"":t,a),Be=null;function nI(e){throw new er(e.UTF8ToString(e.getLastOnigError()))}var lo=class e{constructor(t){Me(this,"utf16Length"),Me(this,"utf8Length"),Me(this,"utf16Value"),Me(this,"utf8Value"),Me(this,"utf16OffsetToUtf8"),Me(this,"utf8OffsetToUtf16");let a=t.length,r=e._utf8ByteLength(t),o=r!==a,n=o?new Uint32Array(a+1):null;o&&(n[a]=r);let s=o?new Uint32Array(r+1):null;o&&(s[r]=a);let i=new Uint8Array(r),l=0;for(let u=0;u<a;u++){let d=t.charCodeAt(u),c=d,p=!1;if(d>=55296&&d<=56319&&u+1<a){let f=t.charCodeAt(u+1);f>=56320&&f<=57343&&(c=(d-55296<<10)+65536|f-56320,p=!0)}o&&(n[u]=l,p&&(n[u+1]=l),c<=127?s[l+0]=u:c<=2047?(s[l+0]=u,s[l+1]=u):c<=65535?(s[l+0]=u,s[l+1]=u,s[l+2]=u):(s[l+0]=u,s[l+1]=u,s[l+2]=u,s[l+3]=u)),c<=127?i[l++]=c:c<=2047?(i[l++]=192|(c&1984)>>>6,i[l++]=128|(c&63)>>>0):c<=65535?(i[l++]=224|(c&61440)>>>12,i[l++]=128|(c&4032)>>>6,i[l++]=128|(c&63)>>>0):(i[l++]=240|(c&1835008)>>>18,i[l++]=128|(c&258048)>>>12,i[l++]=128|(c&4032)>>>6,i[l++]=128|(c&63)>>>0),p&&u++}this.utf16Length=a,this.utf8Length=r,this.utf16Value=t,this.utf8Value=i,this.utf16OffsetToUtf8=n,this.utf8OffsetToUtf16=s}static _utf8ByteLength(t){let a=0;for(let r=0,o=t.length;r<o;r++){let n=t.charCodeAt(r),s=n,i=!1;if(n>=55296&&n<=56319&&r+1<o){let l=t.charCodeAt(r+1);l>=56320&&l<=57343&&(s=(n-55296<<10)+65536|l-56320,i=!0)}s<=127?a+=1:s<=2047?a+=2:s<=65535?a+=3:a+=4,i&&r++}return a}createString(t){let a=t.omalloc(this.utf8Length);return t.HEAPU8.set(this.utf8Value,a),a}},uo=class ct{constructor(t){if(Me(this,"id",++ct.LAST_ID),Me(this,"_onigBinding"),Me(this,"content"),Me(this,"utf16Length"),Me(this,"utf8Length"),Me(this,"utf16OffsetToUtf8"),Me(this,"utf8OffsetToUtf16"),Me(this,"ptr"),!Be)throw new er("Must invoke loadWasm first.");this._onigBinding=Be,this.content=t;let a=new lo(t);this.utf16Length=a.utf16Length,this.utf8Length=a.utf8Length,this.utf16OffsetToUtf8=a.utf16OffsetToUtf8,this.utf8OffsetToUtf16=a.utf8OffsetToUtf16,this.utf8Length<1e4&&!ct._sharedPtrInUse?(ct._sharedPtr||(ct._sharedPtr=Be.omalloc(1e4)),ct._sharedPtrInUse=!0,Be.HEAPU8.set(a.utf8Value,ct._sharedPtr),this.ptr=ct._sharedPtr):this.ptr=a.createString(Be)}convertUtf8OffsetToUtf16(t){return this.utf8OffsetToUtf16?t<0?0:t>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[t]:t}convertUtf16OffsetToUtf8(t){return this.utf16OffsetToUtf8?t<0?0:t>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[t]:t}dispose(){this.ptr===ct._sharedPtr?ct._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};Me(uo,"LAST_ID",0);Me(uo,"_sharedPtr",0);Me(uo,"_sharedPtrInUse",!1);var fd=uo,Xn=class{constructor(t){if(Me(this,"_onigBinding"),Me(this,"_ptr"),!Be)throw new er("Must invoke loadWasm first.");let a=[],r=[];for(let i=0,l=t.length;i<l;i++){let u=new lo(t[i]);a[i]=u.createString(Be),r[i]=u.utf8Length}let o=Be.omalloc(4*t.length);Be.HEAPU32.set(a,o/4);let n=Be.omalloc(4*t.length);Be.HEAPU32.set(r,n/4);let s=Be.createOnigScanner(o,n,t.length);for(let i=0,l=t.length;i<l;i++)Be.ofree(a[i]);Be.ofree(n),Be.ofree(o),s===0&&nI(Be),this._onigBinding=Be,this._ptr=s}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(t,a,r){let o=0;if(typeof r=="number"&&(o=r),typeof t=="string"){t=new fd(t);let n=this._findNextMatchSync(t,a,!1,o);return t.dispose(),n}return this._findNextMatchSync(t,a,!1,o)}_findNextMatchSync(t,a,r,o){let n=this._onigBinding,s=n.findNextOnigScannerMatch(this._ptr,t.id,t.ptr,t.utf8Length,t.convertUtf16OffsetToUtf8(a),o);if(s===0)return null;let i=n.HEAPU32,l=s/4,u=i[l++],d=i[l++],c=[];for(let p=0;p<d;p++){let f=t.convertUtf8OffsetToUtf16(i[l++]),m=t.convertUtf8OffsetToUtf16(i[l++]);c[p]={start:f,end:m,length:m-f}}return{index:u,captureIndices:c}}};function sI(e){return typeof e.instantiator=="function"}function iI(e){return typeof e.default=="function"}function lI(e){return typeof e.data<"u"}function uI(e){return typeof Response<"u"&&e instanceof Response}function dI(e){return typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<"u"&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||typeof Uint32Array<"u"&&e instanceof Uint32Array}var io;function cI(e){if(io)return io;async function t(){Be=await aI(async a=>{let r=e;return r=await r,typeof r=="function"&&(r=await r(a)),typeof r=="function"&&(r=await r(a)),sI(r)?r=await r.instantiator(a):iI(r)?r=await r.default(a):(lI(r)&&(r=r.data),uI(r)?typeof WebAssembly.instantiateStreaming=="function"?r=await fI(r)(a):r=await pI(r)(a):dI(r)?r=await Kn(r)(a):r instanceof WebAssembly.Module?r=await Kn(r)(a):"default"in r&&r.default instanceof WebAssembly.Module&&(r=await Kn(r.default)(a))),"instance"in r&&(r=r.instance),"exports"in r&&(r=r.exports),r})}return io=t(),io}function Kn(e){return t=>WebAssembly.instantiate(e,t)}function fI(e){return t=>WebAssembly.instantiateStreaming(e,t)}function pI(e){return async t=>{let a=await e.arrayBuffer();return WebAssembly.instantiate(a,t)}}async function pd(e){return e&&await cI(e),{createScanner(t){return new Xn(t.map(a=>typeof a=="string"?a:a.source))},createString(t){return new fd(t)}}}var co=id({langs:Za,themes:cd,engine:()=>pd(import("../wasm-EOPKAILK.js"))}),{codeToHtml:mI,codeToHast:hI,codeToTokens:gI,codeToTokensBase:wI,codeToTokensWithThemes:II,getSingletonHighlighter:xI,getLastGrammarState:yI}=ld(co,{guessEmbeddedLanguages:ed});var md=new Set(Object.keys(Za)),Jn=new Map,Qn=new Map,ca=new Map,LI=(e,t)=>`${e}-${t[0]}-${t[1]}`,SI=(e,t,a)=>{let r=e.slice(0,100),o=e.length>100?e.slice(-100):"";return`${t}:${a[0]}:${a[1]}:${e.length}:${r}:${o}`},CI=(e,t)=>{let a=LI(e,t);if(Jn.has(a))return Jn.get(a);let r=co({themes:t,langs:[e]});return Jn.set(a,r),r};function bI(e={}){var t;let a=(t=e.themes)!=null?t:["github-light","github-dark"];return{name:"shiki",type:"code-highlighter",supportsLanguage(r){return md.has(r)},getSupportedLanguages(){return Array.from(md)},getThemes(){return a},highlight({code:r,language:o,themes:n},s){let i=SI(r,o,n);return Qn.has(i)?Qn.get(i):(s&&(ca.has(i)||ca.set(i,new Set),ca.get(i).add(s)),CI(o,n).then(l=>{let u=l.getLoadedLanguages().includes(o)?o:"text",d=l.codeToTokens(r,{lang:u,themes:{light:n[0],dark:n[1]}});Qn.set(i,d);let c=ca.get(i);if(c){for(let p of c)p(d);ca.delete(i)}}).catch(l=>{console.error("[Streamdown Code] Failed to highlight code:",l),ca.delete(i)}),null)}}}var hd=bI();import{memo as AI}from"react";import{useEffect as vI,useRef as fo,useState as kI}from"react";var TI=5,gd=400;function wd(e,t,a={}){let{msPerChar:r=TI}=a,[o,n]=kI(t?"":e),s=fo(e),i=fo(t?0:e.length),l=fo(0),u=fo(null);return(e.length<i.current||!e.startsWith(o.slice(0,i.current)))&&(i.current=t?0:e.length),s.current=e,vI(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),i.current=e.length,n(e);return}if(s.current.length-i.current>gd&&(i.current=s.current.length-gd),u.current!==null)return;let c=p=>{let f=s.current;if(i.current>=f.length){u.current=null;return}l.current===0&&(l.current=p);let m=p-l.current;if(m>=r){let y=Math.min(Math.floor(m/r),f.length-i.current);i.current+=y,n(f.slice(0,i.current)),l.current=p}u.current=requestAnimationFrame(c)};return u.current=requestAnimationFrame(c),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,r]),o}import{jsx as po}from"react/jsx-runtime";var Yn=({className:e,from:t,children:a,...r})=>po("div",{className:P("ww-message ww:group ww:flex ww:w-full",t==="user"?"ww-message-user is-user ww:ml-auto ww:flex-col ww:items-end ww:[max-width:var(--ww-msg-max-width,80%)]":"ww-message-assistant is-assistant ww:flex-col",e),...r,children:po("div",{className:P("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Zn=({children:e,className:t,...a})=>po("div",{className:P("ww-bubble ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden","ww:[font-size:var(--ww-font-size,1rem)] ww:[line-height:var(--ww-line-height,1.5)]","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:[color:var(--ww-color-user-bubble-text)] ww:group-[.is-user]:[border-radius:var(--ww-msg-radius,8px)] ww:group-[.is-user]:[padding:var(--ww-msg-pad-y,12px)_var(--ww-msg-pad-x,16px)]","ww:group-[.is-assistant]:text-foreground",t),...a,children:e}),PI={cjk:Ln,code:hd},RI={cjk:Ln},EI={enabled:!1};function MI({className:e,linkSafety:t,isStreaming:a,children:r,...o}){let s=wd(typeof r=="string"?r:"",!!a),i=typeof r=="string"?s:r;return po(ya,{className:P("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??EI,plugins:a?RI:PI,...o,children:i})}var mo=AI(MI,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);mo.displayName="MessageResponse";import{jsx as Id,jsxs as FI}from"react/jsx-runtime";function xd(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function yd(e){return e.parts.some(xd)}function Ld(e,t,a){if(t!=="submitted"&&t!=="streaming")return!1;let r=e[e.length-1];return!r||r.role!=="assistant"?!0:!r.parts.some(n=>!(!xd(n)||a?.ignoreToolParts&&"toolCallId"in n||a?.ignoreReasoningParts&&n.type==="reasoning"))}function Sd({className:e,...t}){let{t:a}=te();return FI("div",{"aria-live":"polite",className:P("ww:mb-4 ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...t,children:[Id(Ea,{className:"ww:size-4 ww:shrink-0"}),Id(et,{duration:1.6,children:a.workingIndicator.default})]})}import{jsx as tr,jsxs as _I}from"react/jsx-runtime";function Cd({icon:e,title:t,description:a,suggestions:r,onSuggestionSelect:o}){return _I("div",{className:"ww:flex ww:flex-col ww:items-center ww:justify-center ww:py-12 ww:px-6 ww:text-center ww:min-h-full",children:[e&&tr("div",{className:"ww:mb-4 ww:flex ww:items-center ww:justify-center ww:size-12 ww:rounded-xl ww:bg-foreground ww:text-background",children:e}),tr("h2",{className:"ww:text-lg ww:font-semibold ww:text-foreground",children:t}),a&&tr("p",{className:"ww:mt-1 ww:text-sm ww:text-muted-foreground ww:max-w-sm",children:a}),r&&r.length>0&&tr("div",{className:"ww:mt-6 ww:w-full ww:max-w-md ww:flex ww:flex-col ww:gap-2",children:r.map((n,s)=>tr("button",{type:"button",onClick:()=>o?.(n),className:P("ww:w-full ww:text-left ww:rounded-xl ww:border ww:border-border ww:bg-background ww:px-4 ww:py-3 ww:text-sm","ww:text-foreground ww:hover:bg-accent ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${s*50}ms`},children:n},n))})]})}import{Component as DI}from"react";import{jsx as es,jsxs as OI}from"react/jsx-runtime";function BI({onRetry:e}){let{t}=te();return OI("div",{className:"ww:flex ww:items-center ww:justify-between ww:rounded-md ww:border ww:border-border ww:bg-muted/50 ww:px-4 ww:py-3 ww:text-sm ww:text-muted-foreground",children:[es("span",{children:t.widgetErrorBoundary.failedToLoad}),es("button",{type:"button",onClick:e,className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:t.widgetErrorBoundary.retry})]})}var ho=class extends DI{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.warn("[Waniwani] Widget failed to render:",t.message)}render(){return this.state.hasError?es(BI,{onRetry:()=>this.setState({hasError:!1})}):this.props.children}};import{Fragment as UI,jsx as we,jsxs as Ft}from"react/jsx-runtime";function ts(e){return e?e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase()):"Tool"}function bd(e){return e&&/search|find|lookup|query|web|browse|google/i.test(e)?Ta:qt}function vd({messages:e,status:t,welcomeMessage:a,welcome:r,onSuggestionSelect:o,resourceEndpoint:n,chatSessionId:s,isDark:i,onFollowUp:l,onCallTool:u,onWidgetDisplayModeChange:d,fullscreenToolCallId:c,debug:p,showToolCalls:f=!0,toolDefinitions:m,messageClassNames:y}){let{t:S}=te(),L=e[e.length-1],C=e.length>0,I=c!=null,x=!I&&Ld(e,t,{ignoreToolParts:f===!1,ignoreReasoningParts:f===!1});return Ft(UI,{children:[!I&&(!C&&r?we(Cd,{...r,onSuggestionSelect:o}):a&&we(Yn,{from:"assistant",children:we(Zn,{children:we(mo,{children:a})})})),e.map(v=>{let q=v.parts.filter(R=>R.type==="text"),N=v.parts.filter(R=>R.type==="reasoning"),V=v.parts.filter(R=>R.type==="file"),G=ul(v.metadata),Q=v.parts.filter(R=>"toolCallId"in R),O=v.parts.filter(R=>R.type==="reasoning"||"toolCallId"in R),re=v===L&&v.role==="assistant",K=q.length>0,J=I?Q.some(R=>R.toolCallId===c):!1,X=f!==!1&&!J&&O.length>=2;return I&&!J?we("div",{style:{display:"none"}},v.id):v.role==="assistant"&&!yd(v)?we("div",{style:{display:"none"}},v.id):f===!1&&v.role==="assistant"&&!K&&V.length===0&&Q.every(R=>{let b="output"in R?R.output:void 0;return b===void 0||!n||!Fa(R.toolName,b,m)})?we("div",{style:{display:"none"}},v.id):Ft(Yn,{from:v.role,className:y?.message,children:[f!==!1&&!J&&!X&&N.map((R,b)=>Ft(Na,{isStreaming:R.state==="streaming",children:[we(qa,{}),we(Ha,{children:R.text})]},`reasoning-${v.id}-${b}`)),X&&(()=>{let R=O[O.length-1],b=R.type==="reasoning"?{icon:ht,label:S.reasoning.thinking}:{icon:bd(R.toolName),label:R.title??ts(R.toolName)};return Ft(Dl,{isWorking:re&&(t==="streaming"||t==="submitted"),activeStep:b,children:[we(Bl,{workingLabel:S.chainOfThought.working,label:S.chainOfThought.done}),we(Ol,{children:O.map((D,ae)=>{let oe=ae===O.length-1;if(D.type==="reasoning")return we(Nl,{isStreaming:D.state==="streaming",isLast:oe,children:D.text},`reasoning-${v.id}-${ae}`);let Re=D.title??ts(D.toolName),Ne=bd(D.toolName);if(f==="titles-only")return we(In,{icon:Ne,title:Re,state:D.state,isLast:oe},D.toolCallId);let k="output"in D?D.output:void 0;return Ft(In,{icon:Ne,title:Re,state:D.state,isLast:oe,children:[we(Qo,{input:D.input,debug:p}),k!==void 0&&we(Yo,{output:k,errorText:"errorText"in D?D.errorText:void 0,debug:p})]},D.toolCallId)})})]})})(),f!==!1&&!J&&!X&&Q.length===1&&(()=>{let R=Q[0],b=R.title??ts(R.toolName);if(f==="titles-only")return we(Ui,{title:b,state:R.state});let D="output"in R?R.output:void 0;return Ft(Bi,{children:[we(Oi,{title:b,state:R.state}),Ft(Ni,{children:[we(Qo,{input:R.input,debug:p}),D!==void 0&&we(Yo,{output:D,errorText:"errorText"in R?R.errorText:void 0,debug:p})]})]})})(),Q.map(R=>{let b="output"in R?R.output:void 0,D=Fa(R.toolName,b,m),ae=qi(R.toolName,b,m),oe=R.toolCallId===c;return D&&n&&b!==void 0?we("div",{style:oe?{position:"absolute",inset:0,zIndex:10,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--ww-color-background)"}:void 0,children:D&&n&&b!==void 0&&we(ho,{children:we(Ba,{isFullscreen:oe,resourceUri:D,toolInput:R.input??{},toolResult:{content:b.content,structuredContent:b.structuredContent,_meta:b._meta},resourceEndpoint:n,chatSessionId:s,isDark:i,autoHeight:ae,toolDefinitions:m,onFollowUp:l,onCallTool:u,onDisplayModeChange:d?Re=>d(Re,{toolCallId:R.toolCallId,resourceUri:D,toolInput:R.input??{},toolResult:{content:b.content,structuredContent:b.structuredContent,_meta:b._meta},autoHeight:ae}):void 0})})},R.toolCallId):null}),!J&&G.length>0&&we(dl,{documents:G}),!J&&we("div",{children:Ft(Zn,{className:P(v.role==="user"?y?.userBubble:y?.assistantBubble),children:[V.length>0&&we(il,{files:V}),K?q.map((R,b)=>{let D=re&&t==="streaming"&&b===q.length-1;return we(mo,{isStreaming:D,children:R.type==="text"?R.text:""},`${v.id}-${b}`)}):null]})})]},v.id)}),x&&we(Sd,{})]})}import{jsx as ar,jsxs as qI}from"react/jsx-runtime";function NI({label:e}){return qI("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[ar("title",{children:e}),ar("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),ar("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function go({onClick:e}){let{t}=te();return ar("button",{type:"button",onClick:e,title:t.threadMenu.newChat,"aria-label":t.threadMenu.newChat,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:ar(NI,{label:t.threadMenu.newChat})})}import{jsx as kd,jsxs as WI}from"react/jsx-runtime";var HI="https://app.waniwani.ai/assets/waniwani-logo.svg",$I="https://waniwani.ai";function Td(){let{t:e}=te();return WI("a",{href:$I,target:"_blank",rel:"noopener noreferrer",className:"ww:flex ww:items-center ww:gap-1.5 ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70 hover:ww:opacity-100 ww:transition-opacity",children:[kd("span",{children:e.poweredBy.label}),kd("img",{src:HI,alt:"Waniwani",width:72,height:10,"data-waniwani-logo":"",className:"ww:h-2.5 ww:w-auto"})]})}import{jsx as wo}from"react/jsx-runtime";function Ad({suggestions:e,isLoading:t,onSelect:a,align:r="start",className:o,...n}){return e.length===0&&!t?null:wo("div",{className:P("ww:px-4 ww:py-2",o),...n,children:wo("div",{className:P("ww:mx-auto ww:w-full ww:max-w-3xl ww:flex ww:flex-wrap ww:gap-2",r==="center"&&"ww:justify-center"),children:t?[0,1,2].map(s=>wo("div",{className:"ww:h-8 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+s*20}px`}},s)):e.map((s,i)=>wo("button",{type:"button",onClick:()=>a(s),className:P("ww:rounded-full ww:border ww:border-border ww:bg-accent ww:px-3.5 ww:py-1.5 ww:text-sm","ww:text-foreground ww:hover:bg-border ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${i*50}ms`},children:s},s))})})}import{useEffect as jI,useRef as zI,useState as VI}from"react";import{jsx as Fe,jsxs as fa}from"react/jsx-runtime";var Pd=20;function GI({label:e}){return fa("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[Fe("title",{children:e}),Fe("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),Fe("polyline",{points:"3 4 3 9 8 9"}),Fe("line",{x1:"12",y1:"7",x2:"12",y2:"12"}),Fe("line",{x1:"12",y1:"12",x2:"15",y2:"14"})]})}function KI({label:e}){return fa("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[Fe("title",{children:e}),Fe("polyline",{points:"3 6 5 6 21 6"}),Fe("path",{d:"M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"}),Fe("path",{d:"M10 11v6"}),Fe("path",{d:"M14 11v6"})]})}function Rd({threads:e,activeThreadId:t,onNewThread:a,onSelectThread:r,onDeleteThread:o}){let{locale:n,t:s}=te(),[i,l]=VI(!1),u=zI(null);jI(()=>{if(!i)return;let p=f=>{let m=u.current;m&&(f.composedPath().includes(m)||l(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[i]);let d=e.slice(0,Pd),c=Math.max(0,e.length-Pd);return fa("div",{ref:u,className:"ww:relative ww:flex ww:items-center ww:gap-1",children:[Fe(go,{onClick:a}),Fe("button",{type:"button",onClick:()=>l(p=>!p),title:s.threadMenu.threadHistory,"aria-label":s.threadMenu.threadHistory,"aria-expanded":i,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:Fe(GI,{label:s.threadMenu.threadHistory})}),i&&fa("div",{role:"menu",className:"ww:absolute ww:right-0 ww:top-full ww:mt-1 ww:w-72 ww:max-h-80 ww:overflow-y-auto ww:rounded-lg ww:border ww:border-border ww:bg-background ww:shadow-lg ww:z-50",children:[d.length===0&&Fe("div",{className:"ww:px-3 ww:py-3 ww:text-xs ww:text-muted-foreground",children:s.threadMenu.noPreviousChats}),d.map(p=>{let f=p.threadId===t,m=Date.parse(p.updatedAt);return fa("div",{className:`ww:flex ww:items-center ww:gap-2 ww:px-3 ww:py-2 ww:text-xs hover:ww:bg-foreground/5 ${f?"ww:bg-foreground/5":""}`,children:[fa("button",{type:"button",onClick:()=>{r(p.threadId),l(!1)},className:"ww:flex-1 ww:min-w-0 ww:text-left ww:cursor-pointer",children:[Fe("div",{className:"ww:truncate ww:text-foreground ww:font-medium",children:p.title}),Fe("div",{className:"ww:text-[10px] ww:text-muted-foreground",children:Number.isNaN(m)?"":Go(m,n)})]}),Fe("button",{type:"button",onClick:y=>{y.stopPropagation(),o(p.threadId)},title:s.threadMenu.deleteThread,"aria-label":s.threadMenu.deleteThread,className:"ww:p-1 ww:rounded ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/10 ww:transition-colors ww:cursor-pointer",children:Fe(KI,{label:s.threadMenu.deleteThread})})]},p.threadId)}),c>0&&Fe("div",{className:"ww:px-3 ww:py-2 ww:text-[10px] ww:text-muted-foreground ww:border-t ww:border-border",children:s.threadMenu.hiddenThreads(c)})]})]})}import{createContext as XI,useContext as JI}from"react";function Ed(e){let t=new Set;return{subscribe(a){return t.add(a),()=>{t.delete(a)}},emit(a){let{sessionId:r,...o}=a,n=a.name==="session.started"?a.properties.sessionId:void 0,s={...o,mode:e.mode,sessionId:Object.hasOwn(a,"sessionId")?r:n??e.getSessionId?.(),timestamp:Date.now()};for(let i of[...t])try{i(s)}catch(l){console.warn("[Waniwani] onEvent subscriber threw:",l)}}}}function Md(){return{subscribe(){return()=>{}},emit(){}}}var Fd=XI(Md());function Io(){return JI(Fd)}var _d=Fd.Provider;import{useCallback as QI,useRef as YI}from"react";function Dd(e){let t=YI(e);return t.current=e,QI(async a=>{let{api:r,headers:o,onCallTool:n,sessionId:s}=t.current;if(n)return n(a);let i=tt(r??"/api/waniwani","/tool"),l=typeof s=="string"&&s.trim().length>0?s.trim():void 0,u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",...l?{"X-Session-Id":l}:{},...o},body:JSON.stringify(a)});if(!u.ok)throw new Error(`Tool call failed: ${u.status} ${u.statusText}`);return u.json()},[])}import{useChat as ux}from"@ai-sdk/react";import{useCallback as Se,useEffect as He,useRef as Ce,useState as _t}from"react";var ZI="/api/mcp/modules/documents",ex=2e4,tx=3e5,Ze=class extends Error{code;constructor(t,a){super(a),this.name="DocumentUploadError",this.code=t}};function Bd(e,t){return kr(e,`${ZI}${t}`)}function ax(e){return Bd(e,"/upload-url")}function Od(e,t){let a=new Headers(e);return new Headers(t).forEach((r,o)=>{a.set(o,r)}),a}function rx(e){let t=e?.data;if(typeof t?.documentId!="string"||typeof t.uploadUrl!="string"||!(t.documentId&&t.uploadUrl))return null;let a={};for(let[r,o]of Object.entries(t.headers??{}))typeof o=="string"&&(a[r]=o);return{documentId:t.documentId,uploadUrl:t.uploadUrl,headers:a}}function ox(e){return e===403?new Ze("upload_disabled","This agent does not accept document uploads."):e===413?new Ze("max_file_size","That file is too large."):e===422||e===400?new Ze("accept","That file type is not accepted."):new Ze("upload_failed",`The upload could not be started (${e}).`)}function nx(e){return new Promise((t,a)=>{let r=new XMLHttpRequest;r.open("PUT",e.url,!0);for(let[s,i]of Object.entries(e.headers))r.setRequestHeader(s,i);r.timeout=tx;let o=()=>r.abort();e.signal.addEventListener("abort",o,{once:!0});let n=()=>e.signal.removeEventListener("abort",o);r.upload.onprogress=s=>{s.lengthComputable&&s.total>0&&e.onProgress?.(s.loaded/s.total)},r.onload=()=>{if(n(),r.status>=200&&r.status<300||r.status===412){e.onProgress?.(1),t();return}a(new Ze("upload_failed",`The upload was rejected (${r.status}).`))},r.onerror=()=>{n(),a(new Ze("upload_failed","The upload could not be completed."))},r.ontimeout=()=>{n(),a(new Ze("upload_failed","The upload timed out."))},r.onabort=()=>{n(),a(e.signal.reason instanceof Error?e.signal.reason:new Error("aborted"))},r.send(e.file)})}async function xo(e){let t=Bd(e.api,`/${e.documentId}`);if(t)try{await fetch(t,{method:"DELETE",headers:Od(e.headers,e.uploadHeaders)})}catch{}}async function Ud(e){e.signal.throwIfAborted();let t=ax(e.api);if(!t)throw new Ze("upload_disabled","This agent does not accept document uploads.");let a=new AbortController,r=setTimeout(()=>a.abort(),ex),o=()=>a.abort(e.signal.reason);e.signal.addEventListener("abort",o,{once:!0});let n;try{let i=Od(e.headers,e.uploadHeaders);i.set("Content-Type","application/json"),n=await fetch(t,{method:"POST",headers:i,signal:a.signal,body:JSON.stringify({filename:e.file.name,contentType:e.file.type,byteSize:e.file.size,...e.sessionId?{sessionId:e.sessionId}:{}})})}catch(i){throw e.signal.aborted?i:new Ze("upload_failed","The upload could not be started.")}finally{clearTimeout(r),e.signal.removeEventListener("abort",o)}if(!n.ok)throw ox(n.status);let s=rx(await n.json().catch(()=>null));if(e.signal.throwIfAborted(),!s)throw new Ze("upload_failed","The upload could not be started.");return await nx({url:s.uploadUrl,headers:s.headers,file:e.file,signal:e.signal,onProgress:e.onProgress}),{documentId:s.documentId,filename:e.file.name,mediaType:e.file.type}}import{DefaultChatTransport as sx,uiMessageChunkSchema as ix}from"ai";function lx(e){let t=e?.cause,a=t?.issues??t?.errors;if(!Array.isArray(a))return null;let r=a.find(o=>o.code==="invalid_union");if(!r?.errors)return null;for(let o of r.errors){if(!Array.isArray(o)||o.some(i=>(i.code==="invalid_value"||i.code==="invalid_literal")&&i.path?.[0]==="type"))continue;let s=o.filter(i=>i.code==="unrecognized_keys").flatMap(i=>i.keys??[]);if(s.length>0)return s}return null}var yo=class extends sx{processResponseStream(t){let a="",r=ix(),o=r.validate?.bind(r);return t.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({async transform(n,s){a+=n;let i=a.split(`
|
|
16
|
+
`);a=i.pop()??"";for(let l of i){let u=l.trim();if(!u.startsWith("data:"))continue;let d=u.slice(5).trim();if(d!=="[DONE]")try{let c=JSON.parse(d);if(!o){s.enqueue(c);continue}let p=await o(c);if(p.success){s.enqueue(p.value);continue}let f=lx(p.error);if(f?.length){let m={...c};for(let S of f)delete m[S];let y=await o(m);y.success&&s.enqueue(y.value)}}catch{}}}}))}};var Nd=50,qd=1e3;function Lo(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.threadId=="string"&&typeof t.memoryUserId=="string"&&typeof t.title=="string"&&Array.isArray(t.messages)&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"}async function So(e){if(typeof indexedDB>"u")return null;let t=null;try{return t=await on(),await e(t)}catch{return null}finally{try{t?.close()}catch{}}}function as(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error)})}async function rs(e){return await So(async a=>{let n=a.transaction(Ke,"readonly").objectStore(Ke).index(Tr),i=(await as(n.getAll(e))??[]).filter(Lo);return i.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),i})??[]}async function Co(e){return await So(async a=>{let o=a.transaction(Ke,"readonly").objectStore(Ke),n=await as(o.get(e));return Lo(n)?n:null})??null}async function os(e){if(!Lo(e))return;let t=e.messages.length>qd?{...e,messages:e.messages.slice(e.messages.length-qd)}:e;await So(async a=>{await new Promise((l,u)=>{let d=a.transaction(Ke,"readwrite");d.oncomplete=()=>l(),d.onerror=()=>u(d.error),d.onabort=()=>u(d.error),d.objectStore(Ke).put(t)});let r=a.transaction(Ke,"readwrite"),o=r.objectStore(Ke),n=o.index(Tr),i=(await as(n.getAll(t.memoryUserId))??[]).filter(Lo);if(i.length>Nd){i.sort((u,d)=>u.updatedAt<d.updatedAt?-1:1);let l=i.slice(0,i.length-Nd);for(let u of l)o.delete(u.threadId)}return await new Promise((l,u)=>{r.oncomplete=()=>l(),r.onerror=()=>u(r.error),r.onabort=()=>u(r.error)}),null})}async function Hd(e){await So(async t=>(await new Promise((a,r)=>{let o=t.transaction(Ke,"readwrite");o.oncomplete=()=>a(),o.onerror=()=>r(o.error),o.onabort=()=>r(o.error),o.objectStore(Ke).delete(e)}),null))}async function ns(e){return(await rs(e))[0]?.threadId??null}function $d(e){let t=e.trim();if(!t)return`Conversation on ${new Date().toISOString().slice(0,10)}`;let a=t.split(/\r?\n/,1)[0]??t;return a.length<=60?a:`${a.slice(0,60).trimEnd()}\u2026`}var dx="x-session-id",cx=250,fx=200;function Wd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Oa()}function bo(){return new Date().toISOString()}function jd(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}async function px(e,t){let a=tt(e,"/tools"),r=await fetch(a,{method:"GET",headers:t?{...t}:void 0});if(!r.ok)throw new Error(`[Waniwani] Failed to fetch /tools: ${r.status} ${r.statusText}`);let o=await r.json();if(!o||!Array.isArray(o.tools))return{};let n={};for(let s of o.tools)s&&typeof s.name=="string"&&(n[s.name]=s);return n}function zd(e){let{api:t="/api/waniwani",headers:a,uploadHeaders:r,body:o,onMessageSent:n,onResponseReceived:s,enableThreadHistory:i=!1,activeThreadId:l,onThreadChange:u}=e,d=e.visitorId;He(()=>tn(d),[d]);let c=Io(),p=Ce(a),f=Ce(r),m=Ce(o),y=Ce(i);He(()=>{y.current=i},[i]);let S=Ce(void 0),L=Ce(void 0),C=Ce(null),[I,x]=_t(void 0),v=Ce(I),[q,N]=_t(l),V=Ce(q),[G,Q]=_t([]),[O,re]=_t(!i),K=Ce(void 0),J=Ce(void 0),X=Ce(void 0),R=Ce(void 0),b=Ce(0),D=Ce(u);He(()=>{D.current=u},[u]);let ae=Se(g=>{V.current=g,N(g),g&&(D.current?.(g),c.emit({name:"thread.changed",sessionId:v.current,properties:{threadId:g}}))},[c]),oe=Se(async()=>{if(!i)return;let g=C.current?.memoryUserId;if(!g)return;let U=await rs(g);Q(U)},[i]),Re=Se(()=>v.current,[]),Ne=Se(g=>{let U=jd(g);if(!U||v.current===U)return;let j=v.current===void 0;v.current=U,x(U),j&&c.emit({name:"session.started",properties:{sessionId:U}})},[c]),k=Se(()=>{v.current=void 0,x(void 0)},[]);He(()=>{p.current=a,f.current=r},[a,r]),He(()=>{m.current=o},[o]),He(()=>{let g=!1,U=b.current;return(async()=>{try{let de=await _a();if(g)return;C.current=de}catch{}if(!i)return;let j=C.current?.memoryUserId;if(!j){re(!0);return}try{let de=l??await ns(j);if(g||U!==b.current)return;if(de){let be=await Co(de);if(g||U!==b.current)return;be&&be.memoryUserId===j&&(V.current=be.threadId,N(be.threadId),K.current=be.createdAt,J.current=be.title,be.sessionId&&(v.current=be.sessionId,x(be.sessionId)),ye(be.messages))}await oe()}finally{g||re(!0)}})(),()=>{g=!0}},[]);let H=Ce(null),$=Se(g=>{let U=m.current?.[g];return typeof U=="string"?U:void 0},[]),ne=Se(()=>({api:t,token:Pr(p.current),channelId:$("channelId"),sessionId:v.current}),[t,$]),me=Se(g=>{let U=H.current;H.current=null,U?.report(ne(),{mode:$("mode"),outcome:g})},[ne,$]),Ie=Se(g=>{let U=typeof g=="object"&&g!==null&&!Array.isArray(g)?g:void 0,j=C.current?.memoryUserId,de=C.current?.language,be={};return j&&(be.memoryUserId=j),de&&(be.locale=de),Object.keys(be).length>0||U?{...be,...U??{}}:void 0},[]),fe=Se(()=>{let g=V.current;return g||(g=Wd(),K.current=bo(),J.current=void 0,ae(g)),g},[ae]),Z=Ce(new yo({api:t,headers:()=>({...p.current}),body:()=>{let g={...m.current??{}},U=Object.hasOwn(g,"sessionId"),j=jd(g.sessionId);if(j)Ne(j),g.sessionId=j;else if(U)k(),delete g.sessionId;else{let Uo=Re();Uo&&(g.sessionId=Uo)}ra(S.current)&&(g.modelContext=S.current),L.current?.length&&(g.documents=L.current);let de=C.current,be=Ge();de&&(g.visitorContext={timezone:de.timezone,language:de.language,languages:de.languages,deviceType:de.deviceType,referrer:de.referrer,visitorId:be});let Ae=typeof g.visitor=="object"&&g.visitor!==null?g.visitor:{},lp=typeof Ae.client=="object"&&Ae.client!==null?Ae.client:{};g.visitor={...Ae,id:be,client:{...lp,...de&&{memoryUserId:de.memoryUserId}}};let ui=Ie(g.extra);return ui&&(g.extra=ui),y.current&&(Object.hasOwn(g,"threadId")?typeof g.threadId=="string"&&(V.current=g.threadId):g.threadId=fe()),g},fetch:(async(g,U)=>{let j=H.current;j?.mark("requestStart");try{let de=await fetch(g,U);return S.current=void 0,Ne(de.headers.get(dx)),j?j.instrument(de):de}finally{L.current=void 0}})})),W=Ce(e.transport?.({fallback:Z.current,headers:()=>p.current,body:()=>{let g=Ie(m.current?.extra);return{channelId:$("channelId"),visitor:{id:Ge()},...g?{extra:g}:{}}},threadHistory:()=>y.current,threadId:()=>y.current?fe():void 0,hasMessages:()=>z.current.length>0,takeTurnInput:()=>{let g=L.current;return L.current=void 0,S.current=void 0,g?.length?{documents:g}:{}},onSession:Ne})??Z.current),se=Ce(null),xe=Ce(null),ie=Ce({}),[le,ee]=_t(0),ue=e.skipRemoteConfig===!0,Y=Se(async()=>{if(!ue)try{let g=await px(t,p.current);ie.current=g,ee(U=>U+1)}catch(g){console.warn("[Waniwani] Failed to fetch tool definitions:",g instanceof Error?g.message:g)}},[t,ue]);He(()=>{Y()},[Y]);let{messages:he,sendMessage:T,setMessages:ye,status:_,stop:M}=ux({messages:e.initialMessages,transport:W.current,onFinish({message:g,isAbort:U,isDisconnect:j,isError:de}){H.current?.mark("streamEnd"),me(U||j||de?"error":"ok"),s?.(),!U&&!j&&!de&&c.emit({name:"message.received"}),se.current&&(xe.current=g)},onError(g){me("error"),console.warn("[Waniwani] Chat error:",g.message),c.emit({name:"chat.error",properties:{message:g.message.slice(0,fx)}}),se.current&&(se.current.reject(g),se.current=null)}}),z=Ce(he);He(()=>{z.current=he},[he]);let E=W.current.keepsSession?.()??!1,w=Ce(!1);He(()=>{!E||w.current||z.current.length>0||(w.current=!0,W.current.restore?.().then(g=>{g.length>0&&z.current.length===0&&ye(g)}).catch(()=>{}))},[E]),He(()=>{let g=W.current;return()=>g.dispose?.()},[]);let A=Se(()=>{H.current=Xi(z.current.filter(g=>g.role==="user").length+1)},[]),[F,pe]=_t(!1),nt=Se(async()=>{pe(!0);try{await M();let g=v.current;if(!g)return;await fetch(tt(t,"/cancel"),{method:"POST",headers:{"Content-Type":"application/json",...p.current},body:JSON.stringify({sessionId:g})})}catch{}finally{pe(!1)}},[t,M]),st=Ce(i);He(()=>{if(!i||st.current||(st.current=!0,z.current.length>0))return;let g=!1,U=b.current;return re(!1),(async()=>{try{let j=C.current;if(!j)try{j=await _a(),C.current=j}catch{}let de=j?.memoryUserId;if(!de||g||U!==b.current){g||re(!0);return}let be=l??await ns(de);if(g||U!==b.current)return;if(be){let Ae=await Co(be);if(g||U!==b.current)return;Ae&&Ae.memoryUserId===de&&(V.current=Ae.threadId,N(Ae.threadId),K.current=Ae.createdAt,J.current=Ae.title,Ae.sessionId&&(v.current=Ae.sessionId,x(Ae.sessionId)),ye(Ae.messages))}await oe()}finally{g||re(!0)}})(),()=>{g=!0}},[i]),He(()=>{if(_==="ready"&&se.current&&xe.current){let g=se.current,U=xe.current;se.current=null,xe.current=null,g.resolve(U)}},[_]);let[wr,St]=_t(""),oi=typeof d!="function",ni=wr.length>0;He(()=>{oi&&ni&&W.current.prepare?.()},[oi,ni]);let[Ct,Ir]=_t([]),Bo=Ce([]);Bo.current=Ct;let xa=_==="submitted"||_==="streaming",xr=Se(g=>{for(let U of g)for(let j of U.documents??[])xo({documentId:j.documentId,api:t,headers:p.current,uploadHeaders:f.current})},[t]),bt=Se(()=>{xr(Bo.current),Ir([])},[xr]),Yf=Se(g=>{let U=Bo.current.find(j=>j.id===g);U&&xr([U]),Ir(j=>j.filter(de=>de.id!==g))},[xr]),Zf=xa&&Ct.length>0,ep=Se(g=>{let U=!!g.text?.trim(),j=!!(g.files?.length||g.documents?.length);if(U||j){if(xa){if(Ct.length>0)return;Ir(de=>[...de,{id:Oa(),text:g.text||"",files:g.files??[],documents:g.documents??[],modelContext:g.modelContext}]),St("");return}A(),S.current=g.modelContext,L.current=g.documents,T({text:g.text||"",files:g.files,...g.documents?.length&&{metadata:{documents:g.documents}}}),n?.(g.text||""),c.emit({name:"message.sent"}),St("")}},[T,n,xa,Ct.length,c,A]),tp=Se(g=>new Promise((U,j)=>{se.current={resolve:U,reject:j},A(),T({text:g}),n?.(g),c.emit({name:"message.sent"})}),[T,n,c,A]);He(()=>{if(_!=="ready"||F||Ct.length===0)return;let[g,...U]=Ct;Ir(U),A(),S.current=g.modelContext,L.current=g.documents,T({text:g.text,files:g.files.length>0?g.files:void 0,...g.documents.length>0&&{metadata:{documents:g.documents}}}),n?.(g.text),c.emit({name:"message.sent"})},[_,F,T,n,Ct,c,A]);let ap=Se(()=>{W.current.reset?.(),ye([]),bt(),k(),St(""),ie.current={},ee(g=>g+1),Y()},[ye,k,Y,bt]),yr=Se(()=>{if(!y.current)return;let g=C.current?.memoryUserId,U=V.current,j=z.current;if(!(!g||!U||j.length===0)){if(K.current||(K.current=bo()),!J.current){let de=j.find(Ae=>Ae.role==="user"),be=de?de.parts.map(Ae=>"text"in Ae&&typeof Ae.text=="string"?Ae.text:"").join(" "):"";J.current=$d(be)}return{threadId:U,memoryUserId:g,title:J.current,messages:j,sessionId:v.current,createdAt:K.current,updatedAt:bo()}}},[]),si=Se(async()=>{let g=yr();g&&(await os(g),await oe())},[yr,oe]);He(()=>{if(i&&O&&!(_==="submitted"||_==="streaming")&&he.length!==0)return X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{X.current=void 0;let g=si().finally(()=>{R.current===g&&(R.current=void 0)});R.current=g},cx),()=>{X.current&&clearTimeout(X.current)}},[i,O,he,_,si]);let Lr=Se(()=>{let g=R.current,U=X.current,j=U?yr():void 0;return U&&(clearTimeout(U),X.current=void 0),(async()=>{g&&await g,j&&(await os(j),await oe())})()},[yr,oe]),rp=Se(()=>{b.current+=1,Lr(),W.current.dispose?.(),ye([]),bt(),k(),St("");let g=Wd();return K.current=bo(),J.current=void 0,ae(g),oe(),g},[ye,k,ae,oe,Lr,bt]),Oo=Se(async g=>{b.current+=1;let U=b.current;if(await Lr(),U!==b.current)return;let j=await Co(g);U===b.current&&j&&(W.current.dispose?.(),j.sessionId?(v.current=j.sessionId,x(j.sessionId)):k(),ae(j.threadId),K.current=j.createdAt,J.current=j.title,ye(j.messages),bt(),St(""))},[ye,k,ae,Lr,bt]),op=Se(async g=>{if(V.current===g){b.current+=1,X.current&&(clearTimeout(X.current),X.current=void 0);let U=R.current;U&&await U}await Hd(g),W.current.forget?.(g),await oe(),V.current===g&&(W.current.dispose?.(),ye([]),bt(),k(),St(""),V.current=void 0,N(void 0),K.current=void 0,J.current=void 0)},[ye,k,oe,bt]);He(()=>{i&&O&&l!==void 0&&l!==V.current&&Oo(l)},[l,i,O,Oo]);let np=Se(g=>{St(g.target.value)},[]),ii=he[he.length-1],li=he.length>0,sp=xa&&(!li||ii.role==="user"),ip=ie.current;return{messages:he,status:_,text:wr,setText:St,handleSubmit:ep,handleTextChange:np,isLoading:xa,showLoaderBubble:sp,lastMessage:ii,hasMessages:li,sendMessage:T,sendMessageAndWait:tp,stop:nt,reset:ap,queuedMessages:Ct,queueFull:Zf,removeQueuedMessage:Yf,sessionId:I,toolDefinitions:ip,refreshToolDefinitions:Y,threads:G,activeThreadId:q,isThreadHistoryReady:O,startNewThread:rp,switchThread:Oo,deleteThread:op,keepsSession:E}}import{useCallback as Vd,useEffect as mx,useState as hx}from"react";var gx=6e3;function Gd(e){let{api:t,headers:a,uploadHeaders:r,sessionId:o,documentUpload:n,allowAttachments:s}=e,[i,l]=hx(null),u=Vd((p,f,m)=>Ud({file:p,api:t,headers:a,uploadHeaders:r,sessionId:o,signal:f,onProgress:m}),[t,a,r,o]),d=Vd(p=>{xo({documentId:p.documentId,api:t,headers:a,uploadHeaders:r})},[t,a,r]);mx(()=>{if(!i)return;let p=setTimeout(()=>l(null),gx);return()=>clearTimeout(p)},[i]);let c=n?.enabled??!1;return{enabled:n?n.enabled:!!s,accept:n?.accept.join(","),maxFileSize:n?.maxBytes,maxPdfPages:n?.maxPdfPages,maxFiles:n?.maxFiles,upload:c?u:void 0,onDiscard:c?d:void 0,error:i,reportError:l}}import{useCallback as Ix,useEffect as ls,useMemo as us,useRef as xx,useState as Qd}from"react";function pa(e){return e.map(t=>({id:null,text:t}))}function ss(e){let{flow:t,followup:a,page:r,channel:o}=e;return t!==null?{origin:"flow",suggestions:t}:a?.length?{origin:"followup",suggestions:a}:r?.length?{origin:"page",suggestions:r}:o?.length?{origin:"channel",suggestions:o}:null}var is="waniwani/suggestions";function ma(e){return typeof e=="object"&&e!==null}function Kd(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function wx(e){if(!ma(e)||!("toolCallId"in e)||!("output"in e))return null;let t=e.output;if(!ma(t)||!ma(t._meta))return null;let a=t._meta[is];return!ma(a)||!Kd(a.suggestions)?null:a.suggestions}function Xd(e){let t=null;for(let a of e.parts){let r=wx(a);r!==null&&(t=r)}return t}function Jd(e){for(let t of e.parts){if(!ma(t)||t.type!=="data-suggestions")continue;let a=t.data;if(ma(a)&&Kd(a.suggestions)&&a.suggestions.length>0)return a.suggestions}return null}function yx(e){return"page"in e||"channel"in e}function Lx(e){return typeof e!="object"||e===null?{}:yx(e)?{rungs:e}:{initial:e.initial}}function Yd(e){let{messages:t,status:a,suggestions:r}=e,o=r!==!1,{rungs:n,initial:s}=Lx(r),i=us(()=>({page:null,channel:pa(s??[])}),[s]),l=n??i,u=us(()=>o?ss({flow:null,followup:null,...l}):null,[o,l]),d=us(()=>u?.suggestions.map(I=>I.text)??[],[u]),[c,p]=Qd(d),[f,m]=Qd(u?.origin??"channel"),y=xx(a),S=Ix(()=>{p([])},[]),L=t.length>0;ls(()=>{L||(p(d),m(u?.origin??"channel"))},[d,u,L]);let C=t[t.length-1];return ls(()=>{C?.role==="user"&&S()},[C,S]),ls(()=>{let I=y.current;if(y.current=a,I!=="streaming"||a!=="ready"||!o)return;let x=[...t].reverse().find(V=>V.role==="assistant");if(!x)return;let v=Xd(x),q=Jd(x),N=ss({flow:v===null?null:pa(v),followup:q===null?null:pa(q),page:null,channel:null});p(N?N.suggestions.map(V=>V.text):[]),m(N?.origin??"channel")},[a,o,t]),{suggestions:c,source:f,isLoading:!1,clear:S}}import{useEffect as Sx,useRef as Cx,useState as bx}from"react";var vx=80,kx=50,Tx=15e3,Zd=500;function ec(e,t=!0){let[a,r]=bx(""),o=Cx(void 0);return Sx(()=>{if(!t){r("");return}let n=0,s=!1,i=!1,l=()=>{i||(s?(n--,r(e.slice(0,n)),n<=0?(s=!1,o.current=setTimeout(l,Zd)):o.current=setTimeout(l,kx)):(n++,r(e.slice(0,n)),n>=e.length?(s=!0,o.current=setTimeout(l,Tx)):o.current=setTimeout(l,vx)))};return o.current=setTimeout(l,Zd),()=>{i=!0,clearTimeout(o.current)}},[e,t]),a}function tc(e,t){let a=t?.Authorization,r=typeof a=="string"&&a.startsWith("Bearer ")?a.slice(7):null;return tt(e,"/resource",r?{token:r}:void 0)}var ac={primaryColor:"#6366f1",primaryForeground:"#1f2937",backgroundColor:"#ffffff",textColor:"#1f2937",mutedColor:"#6b7280",borderColor:"#e5e7eb",borderWidth:0,boxShadow:"none",assistantBubbleColor:"#f3f4f6",userBubbleColor:"#f4f4f4",inputBackgroundColor:"#f9fafb",borderRadius:16,messageBorderRadius:8,fontFamily:"system-ui, -apple-system, 'Segoe UI', sans-serif",headerBackgroundColor:"#ffffff",headerTextColor:"#1f2937",statusColor:"#22c55e",toolCardColor:"#f4f4f5",userBubbleTextColor:"#1f2937",assistantBubbleTextColor:"#1f2937",messagePaddingX:16,messagePaddingY:12,messageMaxWidth:"80%",fontSize:16,lineHeight:"1.5",glassTint:"transparent",glassTintStrength:"0"},Ax={backgroundColor:"#212121",headerBackgroundColor:"#1e1e1e",headerTextColor:"#ececec",textColor:"#ececec",primaryForeground:"#ffffff",mutedColor:"#8e8ea0",borderColor:"#444444",assistantBubbleColor:"#2f2f2f",userBubbleColor:"#303030",inputBackgroundColor:"#2f2f2f",primaryColor:"#6366f1",statusColor:"#22c55e",toolCardColor:"#262626",userBubbleTextColor:"#ffffff",assistantBubbleTextColor:"#ececec"},Px={primaryColor:["--ww-primary","--ww-color-primary"],primaryForeground:["--ww-primary-fg","--ww-color-primary-foreground"],backgroundColor:["--ww-bg","--ww-color-background"],textColor:["--ww-text","--ww-color-foreground","--ww-color-accent-foreground"],mutedColor:["--ww-muted","--ww-color-muted-foreground"],borderColor:["--ww-border","--ww-color-border"],borderWidth:["--ww-border-width"],boxShadow:["--ww-shadow"],assistantBubbleColor:["--ww-assistant-bubble","--ww-color-accent"],userBubbleColor:["--ww-user-bubble"],inputBackgroundColor:["--ww-input-bg","--ww-color-input"],borderRadius:["--ww-radius"],messageBorderRadius:["--ww-msg-radius"],fontFamily:["--ww-font"],headerBackgroundColor:["--ww-header-bg"],headerTextColor:["--ww-header-text"],statusColor:["--ww-status"],toolCardColor:["--ww-tool-card","--ww-color-tool-card"],userBubbleTextColor:["--ww-user-bubble-text"],assistantBubbleTextColor:["--ww-assistant-bubble-text"],messagePaddingX:["--ww-msg-pad-x"],messagePaddingY:["--ww-msg-pad-y"],messageMaxWidth:["--ww-msg-max-width"],fontSize:["--ww-font-size"],lineHeight:["--ww-line-height"],glassTint:["--ww-glass-tint"],glassTintStrength:["--ww-glass-tint-opacity"]};function Rx(e){return{...ac,...e}}function ds(e){let t={};for(let[a,r]of Object.entries(Px)){let o=e[a];if(o===void 0)continue;let n=typeof o=="number"?`${o}px`:String(o);for(let s of r)t[s]=n}return t}import{jsx as ke,jsxs as xt}from"react/jsx-runtime";var cs=rc(function(t,a){let{locale:r,messages:o}=t;return ke(Vo,{locale:r,messages:o,children:ke(Mx,{...t,ref:a})})}),Mx=rc(function(t,a){let{t:r,ready:o}=te(),{appearance:n,className:s,classNames:i,allowAttachments:l=!1,documentUpload:u,welcomeMessage:d,welcome:c,placeholder:p=r.promptInput.placeholder,triggerEvent:f="triggerDemoRequest",api:m,mcp:y,debug:S=!1,readOnly:L=!1,title:C,headerActions:I,hideHeader:x=!1,enableThreadHistory:v=!1,showToolCalls:q=!0,initializing:N=!1,onScreen:V=!0,disclaimer:G}=t,Q=n?.theme,O=n?.variables,re=n?.assistantBubble??!1,K=O?ds(O):{},[J,X]=vo(!1);It(()=>{if(Q!=="auto"||typeof window>"u")return;let w=window.matchMedia("(prefers-color-scheme: dark)");X(w.matches);let A=()=>X(w.matches);return w.addEventListener("change",A),()=>w.removeEventListener("change",A)},[Q]);let R=Q==="dark"||Q==="auto"&&J,b=zd({...t,api:m}),D=Io(),ae=Dd({...t,api:m,sessionId:b.sessionId,onCallTool:y?.onCallTool}),oe=y?.resourceEndpoint??tc(m,t.headers),Re=Dt({});Re.current={api:m,token:Pr(t.headers),channelId:typeof t.body?.channelId=="string"?t.body.channelId:void 0,sessionId:b.sessionId};let Ne=rr(w=>{Er("widget",Re.current,{widget:w.widget,outcome:w.outcome},w.metrics)},[]),k=ec(p,!b.text),H=Gd({api:m,headers:t.headers,uploadHeaders:t.uploadHeaders,sessionId:b.sessionId,documentUpload:u,allowAttachments:l}),[$,ne]=vo(null),[me,Ie]=vo(null),fe=Dt(null),Z=Dt(null),W=Dt(null),se=Dt(null),[xe,ie]=vo(!0),le=Dt(xe);le.current=xe;let ee=rr(()=>{let w=fe.current;if(!w)return;let A=w.querySelector("textarea");A&&A.focus()},[]),ue=rr((w="smooth")=>{let A=Z.current;A&&A.scrollTo({top:A.scrollHeight,behavior:w})},[]);It(()=>{let w=se.current,A=Z.current;if(!w||!A)return;let F=new IntersectionObserver(([pe])=>ie(pe.isIntersecting),{root:A,rootMargin:"0px 0px 200px 0px",threshold:0});return F.observe(w),()=>F.disconnect()},[]),It(()=>{let w=Z.current;if(!w)return;let A=F=>{let nt=(F.target instanceof Element?F.target:null)?.closest("a");nt?.href&&D.emit({name:"link.clicked",properties:{url:nt.href}})};return w.addEventListener("click",A),()=>w.removeEventListener("click",A)},[D]),It(()=>{(b.messages[b.messages.length-1]?.role==="user"||le.current)&&ue("smooth")},[b.messages.length,b.messages[b.messages.length-1]]),It(()=>{ue("auto")},[ue]),It(()=>{if(typeof ResizeObserver>"u")return;let w=Z.current,A=W.current;if(!w&&!A)return;let F=w?.scrollHeight??0,pe=w?.clientHeight??0,nt=new ResizeObserver(()=>{let st=Z.current;if(!st)return;let wr=st.scrollTop+pe>=F-5;F=st.scrollHeight,pe=st.clientHeight,wr&&ue("auto")});return w&&nt.observe(w),A&&nt.observe(A),()=>nt.disconnect()},[ue]);let Y=Yd({messages:b.messages,status:b.status,suggestions:t.suggestions}),he=Dt(null);It(()=>{let w=Y.suggestions;!V||w.length===0||he.current===w||(he.current=w,D.emit({name:"suggestions.shown",properties:{texts:w,origin:Y.source}}))},[Y.suggestions,Y.source,D,V]);let T=c?.suggestions,ye=Dt(null);It(()=>{!V||b.messages.length>0||!T?.length||ye.current===T||(ye.current=T,D.emit({name:"suggestions.shown",properties:{texts:T,origin:"channel"}}))},[T,b.messages.length,D,V]);let _=rr(w=>{let A=w.content.map(F=>F.text??"").join("").trim();A&&b.handleSubmit({text:A,files:[],modelContext:w.modelContext})},[b.handleSubmit]),M=rr(w=>{let A=Y.suggestions.indexOf(w),F=A>=0?A:c?.suggestions?.indexOf(w)??-1,pe=A>=0?Y.source:"channel";D.emit({name:"suggestion.clicked",properties:{text:w,index:F,origin:pe}}),Y.clear(),b.handleSubmit({text:w,files:[]})},[Y.suggestions,Y.source,Y.clear,b.handleSubmit,c,D]);Ex(a,()=>({sendMessage:w=>{b.handleSubmit({text:w,files:[]}),ee()},sendMessageAndWait:w=>b.sendMessageAndWait(w),reset:b.reset,focus:ee,get messages(){return b.messages},get sessionId(){return b.sessionId}}),[b.handleSubmit,b.sendMessageAndWait,b.reset,b.messages,b.sessionId,ee]),It(()=>{if(!f)return;let w=A=>{let F=A.detail,pe=typeof F?.message=="string"?F.message:void 0;pe&&b.handleSubmit({text:pe,files:[]}),ee()};return window.addEventListener(f,w),()=>window.removeEventListener(f,w)},[f,b.handleSubmit,ee]);let z=!x&&!!(C||v||b.keepsSession||I),E=N||!o;return xt("div",{ref:fe,style:{...K,maxHeight:"inherit",...$&&me?{height:me}:{},opacity:E?0:1,transition:"opacity 220ms ease-out"},"data-waniwani-chat":"","data-waniwani-layout":"embed","data-assistant-bubble":re?"true":void 0,"data-color-scheme":Q==="auto"?"auto":void 0,...E?{"data-waniwani-initializing":""}:{},...R?{"data-waniwani-dark":""}:{},className:P("ww:relative ww:w-full ww:h-full ww:flex ww:flex-col ww:bg-background ww:text-foreground ww:font-[family-name:var(--ww-font)] ww:overflow-hidden",Q==="dark"&&"dark",s,i?.root),children:[z&&xt("div",{className:P("ww-header ww:shrink-0 ww:flex ww:items-center ww:gap-2 ww:pl-4 ww:pr-3 ww:py-3 ww:border-b ww:border-border",i?.header),style:{backgroundColor:"var(--ww-color-card-header)",color:"var(--ww-color-card-header-foreground)"},children:[C&&ke("div",{className:"ww:text-sm ww:font-semibold ww:truncate ww:flex-1 ww:min-w-0",children:C}),!C&&ke("div",{className:"ww:flex-1"}),!v&&b.keepsSession&&ke(go,{onClick:b.reset}),v&&ke(Rd,{threads:b.threads,activeThreadId:b.activeThreadId,onNewThread:b.startNewThread,onSelectThread:w=>{b.switchThread(w)},onDeleteThread:w=>{b.deleteThread(w)}}),I]}),xt("div",{ref:Z,className:P("ww:relative ww:flex-1 ww:min-h-0",$?"ww:overflow-hidden":"ww:overflow-y-auto"),children:[xt("div",{ref:W,className:P("ww:mx-auto ww:w-full ww:max-w-3xl ww:px-4 ww:py-6 ww:flex ww:flex-col ww:gap-6",$&&"ww:!py-0"),children:[ke(el,{value:Ne,children:ke(vd,{messages:b.messages,status:b.status,welcomeMessage:d,welcome:c,onSuggestionSelect:M,resourceEndpoint:oe,chatSessionId:b.sessionId,isDark:R,onFollowUp:_,onCallTool:ae,fullscreenToolCallId:$,debug:S,showToolCalls:q,toolDefinitions:b.toolDefinitions,messageClassNames:{message:i?.message,userBubble:i?.userBubble,assistantBubble:i?.assistantBubble},onWidgetDisplayModeChange:(w,A)=>{if(w==="fullscreen"){let F=fe.current?.getBoundingClientRect().height??0;Ie(F>0?F:null),ne(A.toolCallId)}else Ie(null),ne(null)}})}),ke("div",{ref:se,"aria-hidden":!0,style:{height:1}})]}),!xe&&!$&&ke("div",{className:"ww:sticky ww:bottom-2 ww:flex ww:justify-center ww:pointer-events-none",children:ke(it,{type:"button",onClick:()=>ue("smooth"),size:"icon",variant:"outline",className:"ww:rounded-full ww:shadow ww:pointer-events-auto","aria-label":"Scroll to latest",children:ke(La,{className:"ww:size-4"})})})]}),!L&&xt("div",{className:"ww:shrink-0 ww:bg-background",style:$?{display:"none"}:void 0,children:[ke(Ad,{suggestions:Y.suggestions,isLoading:Y.isLoading,onSelect:M}),ke(Al,{queuedMessages:b.queuedMessages,onRemove:b.removeQueuedMessage}),ke("div",{className:"ww:px-4 ww:pb-2 ww:pt-2",children:xt("div",{className:"ww:mx-auto ww:w-full ww:max-w-3xl",children:[xt(pl,{onSubmit:b.handleSubmit,attachmentsEnabled:H.enabled,globalDrop:H.enabled,multiple:H.enabled,accept:H.accept,maxFileSize:H.maxFileSize,maxPdfPages:H.maxPdfPages,maxFiles:H.maxFiles,upload:H.upload,onDiscard:H.onDiscard,onError:H.reportError,className:P("ww-input ww:rounded-2xl ww:border-border ww:bg-input",i?.input),children:[ke(xl,{enabled:H.enabled}),H.enabled&&ke(Il,{className:"ww:px-4 ww:pt-3"}),xt("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-4 ww:pr-3 ww:py-2.5",children:[H.enabled&&ke(wl,{}),ke(hl,{onChange:b.handleTextChange,value:b.text,placeholder:k,className:"ww:min-h-0 ww:py-1 ww:px-0"}),ke(gl,{status:b.status,disabled:b.queueFull,onStop:b.stop})]})]}),H.error&&ke("output",{className:"ww:block ww:pt-1.5 ww:text-center ww:text-destructive ww:text-xs",children:H.error.message}),xt("div",{className:"ww:pt-2 ww:pb-1 ww:flex ww:flex-nowrap ww:justify-center ww:items-center ww:gap-1.5",children:[ke(Td,{}),ke(yl,{text:G})]})]})})]})]})});import{forwardRef as qS,useEffect as Do,useImperativeHandle as HS,useMemo as ai,useRef as ri,useState as Xf}from"react";var Fx="https://app.waniwani.ai/api/mcp/chat",_x={api:Fx};function Dx(){if(typeof document>"u")return null;if(document.currentScript instanceof HTMLScriptElement)return document.currentScript;let e=document.querySelector("script[src][data-token]");if(e instanceof HTMLScriptElement)return e;let t=document.querySelectorAll("script[src]");for(let a of t)if(a instanceof HTMLScriptElement&&/embed/i.test(a.src))return a;return null}function Bx(){let e=Dx();if(!e)return{};let t=D=>e.getAttribute(D)??void 0,a=D=>{let ae=e.getAttribute(D);if(ae==null)return;let oe=ae.trim().toLowerCase();if(oe==="true"||oe==="1"||oe==="")return!0;if(oe==="false"||oe==="0")return!1},r={},o=t("data-api");o&&(r.api=o);let n=t("data-token");n&&(r.token=n);let s=t("data-visitor-id");s&&(r.visitorId=s);let i=t("data-title");i&&(r.title=i);let l=t("data-welcome-message");l&&(r.welcomeMessage=l);let u=t("data-placeholder");u&&(r.placeholder=u);let d=t("data-mcp-server-url");d&&(r.mcpServerUrl=d);let c=t("data-webmcp");c&&(r.webmcp={enabled:c!=="false"&&c!=="off"});let p=t("data-channel-id");if(p&&(r.channelId=p),t("data-show-tool-calls")?.trim().toLowerCase()==="titles-only")r.showToolCalls="titles-only";else{let D=a("data-show-tool-calls");D!==void 0&&(r.showToolCalls=D)}let m=t("data-css");m&&(r.css=m);let y=t("data-suggestions");y&&(r.suggestions=y.split(",").map(D=>D.trim()).filter(Boolean));let S=a("data-enable-thread-history");S!==void 0&&(r.enableThreadHistory=S);let L=a("data-disable-page-view");L!==void 0&&(r.disablePageView=L);let C=a("data-hide-header");C!==void 0&&(r.hideHeader=C);let I=t("data-theme");(I==="light"||I==="dark"||I==="auto")&&(r.appearance={...r.appearance,theme:I});let x=a("data-assistant-bubble");x!==void 0&&(r.appearance={...r.appearance,assistantBubble:x});let v=t("data-locale");(v==="en"||v==="fr"||v==="es")&&(r.locale=v);let q=t("data-mode");(q==="inline"||q==="floating"||q==="composer"||q==="off")&&(r.mode=q);let N={},V=t("data-composer-variant")?.trim().toLowerCase();(V==="glow"||V==="outline")&&(N.variant=V);let G=t("data-composer-size")?.trim().toLowerCase();(G==="sm"||G==="md"||G==="lg")&&(N.size=G);let Q=a("data-composer-suggestions");Q!==void 0&&(N.showSuggestions=Q);let O=t("data-composer-align")?.trim().toLowerCase();(O==="start"||O==="center")&&(N.align=O);let re=a("data-composer-trigger");re!==void 0&&(N.trigger=re);let K=a("data-composer-mobile-trigger");K!==void 0&&(N.mobileTrigger=K),Object.keys(N).length>0&&(r.composer=N);let J=t("data-height");J&&(r.height=J);let X=t("data-launcher-text");X&&(r.launcherText=X);let R=t("data-appear-delay");if(R!==void 0){let D=Number.parseInt(R.trim(),10);Number.isFinite(D)&&D>=0&&(r.appearDelay=D)}let b=t("data-disclaimer");if(b!==void 0){let D=b.trim(),ae=D.toLowerCase();ae==="false"||ae==="0"?r.disclaimer=!1:D&&(r.disclaimer=D)}return r}function or(e){if(!e)return{};let t={};for(let a in e)e[a]!==void 0&&(t[a]=e[a]);return t}function fs(e,t,a){let r=a??Bx(),o=Ox(t,r,e),n={...t?.composer??{},...or(r.composer),...or(e?.composer)},s=Object.keys(n).length>0,i={token:"",..._x,...or(t),...or(r),...or(e),...o?{appearance:o}:{},...s?{composer:n}:{}};if(!i.token)throw new Error("[Waniwani] Missing required config: `token`. Set data-token on the script tag or pass it to Waniwani.chat.init().");return i}function Ox(e,t,a){let r=a?.appearance?.theme??t.appearance?.theme??e?.appearance?.theme,o={...e?.appearance?.variables??{},...t.appearance?.variables??{},...a?.appearance?.variables??{}},n=Object.keys(o).length>0,s=a?.appearance?.assistantBubble??t.appearance?.assistantBubble??e?.appearance?.assistantBubble;if(!r&&!n&&s===void 0)return;let i={};return r&&(i.theme=r),n&&(i.variables=o),s!==void 0&&(i.assistantBubble=s),i}import{useEffect as zR,useState as VR}from"react";var Ux="/api/mcp/events/v2/batch",ps=new Set;function Nx(e,t,a){return`${e}|${t}|${a??""}`}function nr(e){return kr(e,Ux)}async function ms(e){let{api:t,token:a,channelId:r,mode:o,source:n}=e;if(typeof window>"u"||!t||!a)return;let s=nr(t);if(!s){lt("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!r&&!n){lt("page.viewed skipped: no channelId or source to attribute it");return}let i=Nx(t,a,r);if(!ps.has(i)){ps.add(i);try{let l=await _a(),u=new Date().toISOString(),d=JSON.stringify({sentAt:u,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:"page.viewed",source:n,timestamp:u,correlation:{visitorId:l.visitorId},properties:{channelId:r,mode:o,url:window.location.href,referrer:l.referrer,deviceType:l.deviceType,language:l.language,timezone:l.timezone},metadata:{}}]}),c=fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:d,keepalive:!0});$t("pageViewSent"),await c}catch{ps.delete(i)}}}import{useMemo as Xx}from"react";import{useEffect as Wx,useSyncExternalStore as jx}from"react";function qx(e){return e?.patterns??e?.rules??[]}var oc="\0\0";function Hx(e){let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*\\\*/g,oc).replace(/\\\*/g,"[^/]*").split(oc).join(".*");return new RegExp(`^${a}$`)}function $x(e,t){try{return Hx(e).test(t)}catch{return!1}}function nc(e,t){if(!e)return!0;let a=!1;for(let r of qx(e))if($x(r.glob,t)){if(r.action==="hide")return!1;a=!0}return a?!0:(e.default??"show")!=="hide"}var hs="waniwani:locationchange",sc=!1;function zx(){if(!(sc||typeof history>"u")){sc=!0;for(let e of["pushState","replaceState"]){let t=history[e];history[e]=function(...r){let o=t.apply(this,r);return window.dispatchEvent(new Event(hs)),o}}}}function Vx(e){return zx(),window.addEventListener(hs,e),window.addEventListener("popstate",e),()=>{window.removeEventListener(hs,e),window.removeEventListener("popstate",e)}}function Gx(){return window.location.pathname}function Kx(){return"/"}function gs(){return jx(Vx,Gx,Kx)}function ic(e,t){let a=gs(),r=t&&nc(e,a);return Wx(()=>{lt("visibility gate",{pathname:a,ready:t,visible:r,rules:e})},[a,t,r]),r}var Jx=3,Qx=["low","medium","high"];function ws(e){if(e.length===0)return;let t=Math.floor(Math.random()*e.length),[a]=e.splice(t,1);return a}function Yx(e){let t=new Map,a=[];for(let n of e)if(n.tier){let s=t.get(n.tier)??[];s.push(n),t.set(n.tier,s)}else a.push(n);let r=[];for(let n of Qx){let s=ws(t.get(n)??[])??ws(a);s&&r.push(s)}let o=[...t.values()].flat().concat(a);for(;r.length<Math.min(Jx,e.length);){let n=ws(o);if(!n)break;r.push(n)}return r}function lc(e){let t;try{t=new URL(e,"http://localhost").pathname}catch{t="/"}let a=t.replace(/\/+$/,"");return(a===""?"/":a).toLowerCase()}function uc(e){return Array.isArray(e)?e.flatMap(t=>{let a=t;if(typeof a?.url!="string"||a.url.length===0||!Array.isArray(a.prompts))return[];let r=a.prompts.flatMap(o=>{let n=o;return typeof n?.text!="string"||n.text.length===0?[]:[{id:typeof n.id=="string"?n.id:null,text:n.text,tier:n.tier==="low"||n.tier==="medium"||n.tier==="high"?n.tier:void 0}]});return r.length>0?[{url:a.url,prompts:r}]:[]}):[]}function dc(e){let{pageSuggestions:t,suggestions:a}=e,r=gs();return Xx(()=>{let o=lc(r),n=t?.find(i=>lc(i.url)===o),s=n?Yx(n.prompts).map(({id:i,text:l})=>({id:i,text:l})):null;return lt("configured suggestions resolve",{pathname:o,matched:!!n,count:s?.length??0}),{page:s,channel:pa(a??[])}},[r,t,a])}var Zx="waniwani:config:";function cc(e,t,a){return`${Zx}${e}|${t}|${a??""}`}function ko(e,t,a){if(typeof window>"u")return null;try{let r=window.sessionStorage.getItem(cc(e,t,a));if(!r)return null;let o=JSON.parse(r);return o&&typeof o=="object"?o:null}catch{return null}}function fc(e,t,a,r){if(!(typeof window>"u"))try{window.sessionStorage.setItem(cc(e,t,a),JSON.stringify(r))}catch{}}function ey(e){if(typeof e!="object"||e===null||typeof e.enabled!="boolean")return null;let t=Array.isArray(e.accept)?e.accept.filter(r=>typeof r=="string"):[],a=r=>typeof r=="number"&&Number.isFinite(r)&&r>0;return e.enabled?a(e.maxBytes)&&a(e.maxPdfPages)&&a(e.maxFiles)&&t.length>0?{enabled:!0,maxBytes:e.maxBytes,maxPdfPages:e.maxPdfPages,maxFiles:e.maxFiles,accept:t}:null:{enabled:!1,maxBytes:0,maxPdfPages:0,maxFiles:0,accept:t}}async function pc(e,t,a,r){$t("configStart");let o=await ty(e,t,a,r);return $t("configEnd"),a?.aborted||Rr(o.metadata),o}async function ty(e,t,a,r){try{let o=tt(e,"/config",r?{channel:r}:void 0),n=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:a});if(!n.ok)return{};let s=await n.json(),i=s&&typeof s=="object"&&"data"in s&&s.data?s.data:s;return i?ay(i):{}}catch{return{}}}function ay(e){let t={};e.source!=null&&(t.source=e.source),e.channelId!=null&&(t.channelId=e.channelId),e.title!=null&&(t.title=e.title),e.welcomeMessage!=null&&(t.welcomeMessage=e.welcomeMessage),e.placeholder!=null&&(t.placeholder=e.placeholder),e.suggestions!=null&&e.suggestions.length>0&&(t.suggestions=e.suggestions);let a=uc(e.pageSuggestions);a.length>0&&(t.pageSuggestions=a),typeof e.enableThreadHistory=="boolean"&&(t.enableThreadHistory=e.enableThreadHistory),typeof e.sessionApi=="string"&&e.sessionApi&&(t.sessionApi=e.sessionApi),typeof e.webmcp?.enabled=="boolean"&&(t.webmcp={enabled:e.webmcp.enabled}),e.toolCallDisplay==="full"?t.showToolCalls=!0:e.toolCallDisplay==="titles-only"?t.showToolCalls="titles-only":e.toolCallDisplay==="hidden"&&(t.showToolCalls=!1),e.visibility&&(t.visibility=e.visibility);let r=ey(e.documentUpload);return r&&(t.documentUpload=r),e.metadata&&typeof e.metadata=="object"&&(t.metadata=e.metadata),t}import{useRef as fS,useState as pS}from"react";import{readUIMessageStream as ry}from"ai";function To(){let e=new Set,t=new Map,a,r=0,o=!1,n=!1,s=d=>(a||(a=`text-${++r}`,d.enqueue({type:"text-start",id:a})),a),i=d=>{a&&(d.enqueue({type:"text-end",id:a}),a=void 0)},l=(d,c)=>{d.enqueue({type:"text-delta",id:s(d),delta:c})},u=(d,c,p)=>{e.has(c.callId)||(e.add(c.callId),d.enqueue({type:"tool-input-available",toolCallId:c.callId,toolName:c.toolName??c.kind,input:p,dynamic:!0}))};return new TransformStream({start(d){d.enqueue({type:"start",messageId:crypto.randomUUID()})},transform(d,c){switch(d.type){case"step.started":{t.set(d.data.stepIndex,d.data.modelId),c.enqueue({type:"start-step"}),o=!0;break}case"message.appended":{d.data.messageDelta&&l(c,d.data.messageDelta);break}case"message.completed":{!a&&d.data.message&&l(c,d.data.message),i(c);break}case"actions.requested":{i(c);for(let p of d.data.actions)u(c,p,p.input);break}case"action.result":{let{result:p,status:f,error:m}=d.data;if(p.kind!=="tool-result")break;if(u(c,p,{}),p.isError===!0||f!=="completed"){c.enqueue({type:"tool-output-error",toolCallId:p.callId,errorText:m?.message??"The tool call failed.",dynamic:!0});break}c.enqueue({type:"tool-output-available",toolCallId:p.callId,output:p.output,dynamic:!0});break}case"step.completed":{let{stepIndex:p,usage:f}=d.data;i(c),o&&(c.enqueue({type:"finish-step"}),o=!1),c.enqueue({type:"message-metadata",messageMetadata:{"waniwani/step":{stepIndex:p,modelId:t.get(p),usage:f}}});break}case"turn.failed":case"session.failed":{n=!0,c.enqueue({type:"error",errorText:d.data.message||"The agent could not answer."});break}}},flush(d){i(d),o&&d.enqueue({type:"finish-step"}),d.enqueue({type:"finish",finishReason:n?"error":"stop"})}})}async function oy(e){let t=new ReadableStream({start(r){for(let o of e)r.enqueue(o);r.close()}}).pipeThrough(To()),a;for await(let r of ry({stream:t}))a=r;return a?.parts.length?a:void 0}async function mc(e){let t=[];for(let r of e){let o=r.type==="message.received"&&!r.data.kind?r.data.message:void 0;o!==void 0?t.push({visitor:{id:r.meta?.id??crypto.randomUUID(),role:"user",parts:[{type:"text",text:o}]},events:[]}):t.at(-1)?.events.push(r)}let a=[];for(let r of t){a.push(r.visitor);let o=await oy(r.events);o&&a.push(o)}return a}import{z as $e}from"zod";import{z as B}from"zod";import{z as Ao}from"zod";var Kt=Symbol("invalid-json-value-candidate");function xs(e){let t=Is(e);if(t===Kt)throw TypeError("Expected a JSON-serializable value.");return t}function sr(e){let t=xs(e);if(!ny(t))throw TypeError("Expected a JSON-serializable object.");return t}function Is(e,t=new WeakSet){if(e===null||typeof e=="boolean"||typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:Kt;if(Array.isArray(e)){let r=[];for(let o of e){let n=Is(o,t);if(n===Kt)return Kt;r.push(n)}return r}if(typeof e!="object"||e===void 0||!sy(e)||t.has(e))return Kt;t.add(e);let a={};for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let n=Is(o,t);if(n===Kt)return Kt;a[r]=n}return t.delete(e),a}function ny(e){return e!==null&&!Array.isArray(e)&&typeof e=="object"}function sy(e){let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var ir=Ao.unknown().transform((e,t)=>{try{return xs(e)}catch(a){return t.addIssue({code:"custom",message:hc(a,"Expected a JSON-serializable value.")}),Ao.NEVER}}),yt=Ao.unknown().transform((e,t)=>{try{return sr(e)}catch(a){return t.addIssue({code:"custom",message:hc(a,"Expected a JSON-serializable object.")}),Ao.NEVER}});function hc(e,t){return e instanceof Error?e.message:t}var gc=B.object({callId:B.string(),input:yt,kind:B.literal("tool-call"),toolName:B.string()}).strict();B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("subagent-call"),name:B.string(),nodeId:B.string(),subagentName:B.string()}).strict(),B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("remote-agent-call"),name:B.string(),nodeId:B.string(),remoteAgentName:B.string()}).strict(),B.object({callId:B.string(),input:yt,kind:B.literal("workflow-tool-call"),toolName:B.string(),workflowId:B.string()}).strict(),B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("subagent-call"),name:B.string(),nodeId:B.string(),subagentName:B.string()}).strict();var dE=B.object({callId:B.string(),description:B.string(),input:yt,kind:B.literal("remote-agent-call"),name:B.string(),nodeId:B.string(),remoteAgentName:B.string()}).strict(),cE=B.object({callId:B.string(),executeInput:ir.optional(),input:yt,kind:B.literal("workflow-task"),nodeId:B.string().optional(),toolName:B.string(),workflowId:B.string()}).strict();B.object({callId:B.string(),input:yt,kind:B.literal("load-skill")}).strict();B.object({callId:B.string(),isError:B.boolean().optional(),kind:B.literal("tool-result"),output:ir,toolName:B.string()}).strict(),B.object({callId:B.string(),isError:B.literal(!0),kind:B.literal("subagent-result"),origin:B.literal("dispatch"),output:ir,subagentName:B.string()}).strict(),B.object({callId:B.string(),isError:B.boolean().optional(),kind:B.literal("load-skill-result"),output:ir,name:B.string().optional()}).strict();var iy=$e.object({description:$e.string().describe("Optional additional context for this option.").optional(),id:$e.string().describe("Stable identifier for the option."),label:$e.string().describe("User-facing label for the option."),style:$e.enum(["primary","danger","default"]).describe("Visual treatment hint for the option.").optional()}).strict(),ly=$e.enum(["question","session-limit","tool-approval"]),hE=$e.object({action:gc,allowFreeform:$e.boolean().describe("Whether the user may answer with freeform text instead of selecting one of the provided options.").optional(),display:$e.enum(["confirmation","select","text"]).describe("Rendering hint: the channel uses this to pick a UX treatment.").optional(),kind:ly.describe("Framework-owned request source used to resolve, route, and render the response."),options:$e.array(iy).describe("Selectable answer options to present to the user.").optional(),prompt:$e.string().describe("The prompt to present to the user."),requestId:$e.string().describe("Stable identifier for this request.")}).strict(),gE=$e.object({optionId:$e.string().optional(),requestId:$e.string(),text:$e.string().optional()}).strict();var ze="/eve/v1",IE=`${ze}/cron/:token`,wc=`${ze}/health`,Ic=`${ze}/info`,We=`${ze}/session`,xE=`${We}/:sessionId`,yE=`${We}/:sessionId/cancel`,LE=`${We}/:sessionId/compact`,SE=`${We}/:sessionId/clear`,CE=`${We}/:sessionId/reset`,bE=`${We}/:sessionId/stream`,vE=`${We}/:parentSessionId/subagents/:callId/:childSessionId/stream`,kE=`${ze}/dev/schedules/:scheduleId`,ys=`${ze}/dev/runtime-artifacts`,TE=`${ys}/rebuild`,AE=`${ys}/suspend`,PE=`${ys}/resume`;var RE=`${ze}/connections/:name/callback/:attemptId/:token`,EE=`${ze}/callback/:token`,ME=`${ze}/task-input/:token`,FE=`${ze}/activity/:token`;function xc(e){return`${We}/${encodeURIComponent(e)}`}function yc(e){return`${We}/${encodeURIComponent(e)}/cancel`}function Lc(e){return`${We}/${encodeURIComponent(e)}/compact`}function Sc(e){return`${We}/${encodeURIComponent(e)}/clear`}function Cc(e){return`${We}/${encodeURIComponent(e)}/reset`}function Ls(e){return`${We}/${encodeURIComponent(e)}/stream`}function ft(e){return typeof e=="object"&&!!e&&!Array.isArray(e)}function lr(e){return e instanceof Error?e.message:typeof e=="string"?e:e==null?String(e):ft(e)?typeof e.message=="string"&&e.message.length>0?e.message:uy(e):String(e)}function Xt(e){if(e instanceof Error)return e;let t=Error(lr(e));return ft(e)&&(typeof e.name=="string"&&e.name.length>0&&(t.name=e.name),typeof e.stack=="string"&&e.stack.length>0&&(t.stack=e.stack),"cause"in e&&e.cause!==void 0&&e.cause!==e&&(t.cause=e.cause)),t}function uy(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var vc="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function dy(){let e=-1,t=new Uint8Array(10);return function(){let a=Date.now();if(!Number.isInteger(a)||a<0||a>0xffffffffffff)throw Error(`Cannot mint a ULID: timestamp must be an integer from 0 to ${0xffffffffffff}.`);if(a>e)e=a,bc(t);else if(!my(t)){if(e===0xffffffffffff)throw Error("Cannot mint a ULID: random component overflowed at the maximum timestamp.");e+=1,bc(t)}return`${fy(e)}${py(t)}`}}var cy=dy();function bc(e){let t=globalThis.crypto;if(typeof t?.getRandomValues!="function")throw Error("Cannot mint a ULID: globalThis.crypto.getRandomValues is unavailable.");t.getRandomValues(e)}function fy(e){let t=e,a="";for(let r=0;r<10;r+=1)a=vc[t%32]+a,t=Math.floor(t/32);return a}function py(e){let t=0,a=0,r="";for(let o of e){for(t=t<<8|o,a+=8;a>=5;)a-=5,r+=vc[t>>>a&31];t&=(1<<a)-1}return r}function my(e){for(let t=e.length-1;t>=0;--t){let a=e[t]??0;if(a<255)return e[t]=a+1,e.fill(0,t+1),!0}return!1}var kc="x-eve-session-id";var Ss="x-eve-stream-tail-index",Cs="x-eve-stream-version";var Tc="1",Ac="streamControlVersion",bs={$eve:"stream.lease-ended",version:1},uM=new TextEncoder;function Qe(e){return e.type==="session.completed"||e.type==="session.failed"||e.type==="session.waiting"}function vs(e){return e.type==="session.failed"||e.type==="step.failed"||e.type==="turn.failed"}var Po=class extends Error{issues;constructor(e=[]){let t=e.length===0?"":` (${e.join("; ")})`;super(`The server returned an unrecognized response from the eve agent info route.${t}`),this.name="AgentInfoResponseError",this.issues=e}};var Ro=class extends Error{issues;constructor(e=[]){let t=e.length===0?"":` (${e.join("; ")})`;super(`The server returned an unrecognized eve health response.${t}`),this.name="HealthResponseError",this.issues=e}};var Ve=class extends Error{code;status;body;headers;constructor(e,t,a){let r=Object.freeze(Object.fromEntries(new Headers(a).entries())),o=r["content-type"]?.toLowerCase(),n=t||`Server returned ${e}.`,s;try{let i=JSON.parse(t);ft(i)&&(typeof i.error=="string"&&(n=i.error),typeof i.code=="string"&&(s=i.code))}catch{o?.includes("text/html")&&(n=`Server returned ${e} with an HTML response. Check the eve route and development server configuration.`)}super(n),this.name="ClientError",this.code=s,this.status=e,this.body=t,this.headers=r}};function Pc(e){let t,a,r,o=[],n=new Map;for(let s of e)Qe(s)&&(t=s),vs(s)&&(a=s),hy(s)&&(r=s.data.message??void 0),s.type==="input.requested"&&o.push(...s.data.requests),s.type==="authorization.required"&&n.set(s.data.name,s.data),s.type==="authorization.completed"&&n.delete(s.data.name);return{boundary:t,failure:a,inputRequests:o,message:r,pendingAuthorizations:[...n.values()],status:t?.type==="session.waiting"?"waiting":t?.type==="session.failed"?"failed":"completed"}}function hy(e){return e.type==="message.completed"&&e.data.finishReason!=="tool-calls"}function Jt(e,t){t.type==="authorization.required"&&t.data.webhookUrl!==void 0?e.add(t.data.name):t.type==="authorization.completed"&&e.delete(t.data.name)}var gy=/^\/eve\/[a-z0-9][a-z0-9_-]*$/,wy=/^\/eve\/[a-z0-9][a-z0-9_-]*\/v1$/;function ks(e,t){let a=Iy(e),r=t.startsWith("/")?t:`/${t}`;if(r===ze||r.startsWith(`${ze}/`)){if(gy.test(a))return`${a}${r.slice(4)}`;if(wy.test(a))return`${a}${r.slice(ze.length)}`}return`${a}${r}`}function Iy(e){return e==="/"?"":e.endsWith("/")?e.slice(0,-1):e}function pt(e,t,a){let r=t.indexOf("?"),o=r===-1?t:t.slice(0,r),n=r===-1?"":t.slice(r+1),s=o.startsWith("/")?o:`/${o}`;if(xy(e)){let u=new URL(e),d=Ec(u.pathname);return u.pathname=ks(d,s),Rc(u.searchParams,n),Mc(u.searchParams,a),u.hash="",u.toString()}let i=new URL(e,"http://eve.local"),l=Ec(i.pathname);return Rc(i.searchParams,n),Mc(i.searchParams,a),`${ks(l,s)}${yy(i.searchParams)}`}function Rc(e,t){if(t.length!==0)for(let[a,r]of new URLSearchParams(t))e.append(a,r)}function xy(e){return/^[a-z][a-z\d+\-.]*:/i.test(e)}function Ec(e){return e==="/"?"":e.endsWith("/")?e.slice(0,-1):e}function Mc(e,t){if(t!==void 0)for(let[a,r]of Object.entries(t))e.set(a,r)}function yy(e){let t=e.toString();return t.length===0?"":`?${t}`}function Fc(e){let t;for(let a of e)Ly(a)&&(t=a.data.result);return t}function Ly(e){return e.type==="result.completed"}var Ts=Symbol("consumeMessageResponse"),As=Symbol("acceptedDeliveryId"),Ps=class{sessionId;[As];#t;#e;#a=!1;#r;#n=!1;#u=Promise.withResolvers();constructor(e){this.#t=e.cancelTurn,this.sessionId=e.sessionId,this[As]=e.deliveryId,this.#r=e.createStream}cancel(){if(this.#n)return Promise.resolve({status:"no_active_turn"});if(this.#e!==void 0)return this.#e;let e=this.#u.promise.then(t=>t===void 0?{status:"no_active_turn"}:this.#t(t));return this.#e=e,e.catch(()=>{!this.#n&&this.#e===e&&(this.#e=void 0)}),e}async result(){let e=[];for await(let a of this)e.push(a);let t=Pc(e);return{data:Fc(e),events:e,inputRequests:t.inputRequests,message:t.message,sessionId:this.sessionId,status:t.status}}[Symbol.asyncIterator](){return this[Ts]()}[Ts](e){if(this.#a)throw Error("MessageResponse has already been consumed.");return this.#a=!0,this.#g(e)}async*#g(e){try{for await(let t of this.#r(e))t.type==="turn.started"?this.#u.resolve(t.data.turnId):Qe(t)&&(this.#n=!0,this.#u.resolve(void 0)),yield t}finally{this.#u.resolve(void 0)}}};function Rs(e){return e[As]}function _c(e,t){return e[Ts](t)}function Bc(e,t){switch(e){case"21":case"22":case"23":case"24":return Sy(e,t);case"25":return Cy(t);default:return by(e)}}function Sy(e,t){if(t.type==="message.appended")return Dc(t.data.messageSoFar,t.data.messageDelta,"message",e),{data:{messageDelta:t.data.messageDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,turnId:t.data.turnId},meta:t.meta,type:"message.appended"};if(t.type==="reasoning.appended")return Dc(t.data.reasoningSoFar,t.data.reasoningDelta,"reasoning",e),{data:{reasoningDelta:t.data.reasoningDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,turnId:t.data.turnId},meta:t.meta,type:"reasoning.appended"};if(t.type==="action.input.appended"){if(e!==void 0&&e!=="24")throw TypeError(`Invalid action input append for stream version ${e}.`);return vy(t.data.inputTextOffset,e),{data:{callId:t.data.callId,inputTextDelta:t.data.inputTextDelta,sequence:t.data.sequence,stepIndex:t.data.stepIndex,toolName:t.data.toolName,turnId:t.data.turnId},meta:t.meta,type:"action.input.appended"}}return t}function Cy(e){return e.type==="message.appended"?(Es(e.data.messageDelta,"message"),ur(e.data,"messageOffset","message"),ur(e.data,"messageSoFar","message")):e.type==="reasoning.appended"?(Es(e.data.reasoningDelta,"reasoning"),ur(e.data,"reasoningOffset","reasoning"),ur(e.data,"reasoningSoFar","reasoning")):e.type==="action.input.appended"&&(Es(e.data.inputTextDelta,"action input"),ur(e.data,"inputTextOffset","action input")),e}function Es(e,t){if(typeof e!="string")throw TypeError(`Invalid ${t} append delta for stream version 25.`)}function ur(e,t,a){if(t in e)throw TypeError(`Invalid ${a} append shape for stream version 25.`)}function by(e){throw TypeError(`Unsupported message stream version: ${String(e)}.`)}function vy(e,t){if(!Number.isSafeInteger(e)||e<0){let a=t===void 0?"persisted stream":`stream version ${t}`;throw TypeError(`Invalid action input append offset for ${a}.`)}}function Dc(e,t,a,r){let o=e.length-t.length;if(o<0||e.slice(o)!==t){let n=r===void 0?"persisted stream":`stream version ${r}`;throw TypeError(`Invalid cumulative ${a} append for ${n}.`)}}function Ms(e){if(e instanceof DOMException)return e.name==="AbortError";if(!(e instanceof Error))return!1;let t="code"in e&&typeof e.code=="string"?e.code:void 0;return e.name==="AbortError"||e.message==="terminated"||t==="UND_ERR_SOCKET"||e instanceof TypeError&&/^(?:failed to fetch|fetch failed)$/i.test(e.message)||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*Nc(e,t){let a=e.getReader(),r=new TextDecoder,o="",n=!1,s=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{for(;;){t.signal?.throwIfAborted();let l=await ky(a,t?.idleTimeoutMs);if(t.signal?.throwIfAborted(),l.done){n=!0,o+=r.decode();break}l.value&&(o+=r.decode(l.value,{stream:!0}));let u=o.indexOf(`
|
|
17
17
|
`);for(;u!==-1;){let d=o.slice(0,u).trim();if(o=o.slice(u+1),d.length>0){let c=JSON.parse(d);t.controlVersion==="1"&&Oc(c)?t.onLeaseEnded?.():yield Uc(c,t.streamVersion)}u=o.indexOf(`
|
|
18
|
-
`)}}let i=o.trim();if(i.length>0){let l=JSON.parse(i);t.controlVersion==="1"&&Oc(l)?t.onLeaseEnded?.():yield Uc(l,t.streamVersion)}}finally{t.signal?.removeEventListener("abort",s),n||a.cancel().catch(()=>{}),a.releaseLock()}}function Oc(e){if(typeof e!="object"||!e)return!1;let t=e;return t.$eve===bs.$eve&&t.version===bs.version}function Uc(e,t){return Bc(t,e)}async function vy(e,t){let a;try{return t===void 0?await e.read():await Promise.race([e.read(),new Promise((r,o)=>{a=setTimeout(()=>o(new DOMException("Session stream was idle.","AbortError")),t)})])}catch(r){throw r instanceof TypeError?Error("Session stream disconnected.",{cause:r}):r}finally{a!==void 0&&clearTimeout(a)}}var ky={21:!0,22:!0,23:!0,24:!0,25:!0};function qc(e){let t=e.get(Cs);if(t!==null&&Object.hasOwn(ky,t))return t;throw TypeError(t===null?`Missing ${Cs} response header.`:`Unsupported message stream version: ${t}.`)}var Qt={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},Ty={...Qt,streamIdleReconnectPolicy:{...Qt.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...Qt.streamOpenReconnectPolicy,maxAttempts:1}};function Hc(e,t){return{...t,...e}}function $c(e,t=!1){if(e&&"reconnect"in e&&e.reconnect===!1)return Ty;let a=e;return{retryableErrorStatuses:a?.retryableErrorStatuses?new Set(a.retryableErrorStatuses):Qt.retryableErrorStatuses,streamIdleReconnectPolicy:Hc(a?.streamIdleReconnectPolicy,{...Qt.streamIdleReconnectPolicy,maxAttempts:t?1/0:Qt.streamIdleReconnectPolicy.maxAttempts}),streamOpenReconnectPolicy:Hc(a?.streamOpenReconnectPolicy,Qt.streamOpenReconnectPolicy)}}async function*Fs(e){if(e.follow===!1&&e.startIndex<0)throw Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");let t=()=>$c(e.resolveReconnectPolicy===void 0?e.streamReconnectPolicy:e.resolveReconnectPolicy(),e.keepAlive),a=t(),r=a.streamIdleReconnectPolicy,o=e.startIndex,n=r.baseDelayMs,s=0,i=!0,l,u=!1;for(;;){a=t(),r=a.streamIdleReconnectPolicy;let d;try{d=await Ay({...e,retryPolicy:a,startIndex:o,requestTailIndex:(e.follow===!1||e.onCaughtUp!==void 0)&&l===void 0})}catch(f){if(e.signal?.aborted)return;throw f}if((e.follow===!1||e.onCaughtUp!==void 0)&&l===void 0&&(l=d.tailIndex,l===void 0))throw d.close(),Error(`stream({ follow: false }) requires the server to report the ${Ss} header. The agent may be running an older eve version.`);if(!u&&l!==void 0&&o>l&&(u=!0,e.onCaughtUp?.()),e.follow===!1&&l!==void 0&&o>l){d.close();return}let c=!1,p=!1;try{for await(let f of Nc(d.body,{signal:e.signal,controlVersion:d.controlVersion,idleTimeoutMs:e.streamReadIdleTimeoutMs??15e3,onLeaseEnded:()=>{p=!0},streamVersion:d.streamVersion}))if(o+=1,c=!0,n=r.baseDelayMs,s=0,yield f,!u&&l!==void 0&&o>l&&(u=!0,e.onCaughtUp?.()),e.follow===!1&&l!==void 0&&o>l)return}catch(f){if(!Ms(f))throw f}finally{d.close()}if(r=t().streamIdleReconnectPolicy,e.signal?.aborted||e.startIndex<0||r.maxAttempts===0)return;if(!p){if(!c&&!i&&(s+=1)>=r.maxAttempts||(i=!1,await dr(n,e.signal),e.signal?.aborted))return;n=Math.min(n*2,r.maxDelayMs)}}}async function Ay(e){let t=e.retryPolicy??$c(e.streamReconnectPolicy,e.keepAlive),a=t.streamOpenReconnectPolicy,r,o,n,s=a.baseDelayMs,i=e.startIndex>=0&&t.streamIdleReconnectPolicy.maxAttempts>0?Tc:void 0,l={};i!==void 0&&(l[Ac]=i),e.startIndex!==0&&(l.startIndex=String(e.startIndex)),e.requestTailIndex===!0&&(l.includeTailIndex="1");for(let u=0;u<a.maxAttempts;u+=1){e.signal?.throwIfAborted();let d=pt(e.host,e.path,Object.keys(l).length>0?l:void 0),c=await e.resolveHeaders();e.signal?.throwIfAborted();let p=new AbortController,f=e.signal?AbortSignal.any([e.signal,p.signal]):p.signal,m;try{m=await fetch(d,{cache:"no-store",headers:c,redirect:e.redirect,signal:f})}catch(y){if(e.signal?.aborted||!Ms(y)||u===a.maxAttempts-1)throw y;await dr(s,e.signal),s=Math.min(s*2,a.maxDelayMs);continue}if(m.ok){if(!m.body)throw new Ve(m.status,"Response body is null.",m.headers);let y=!1;return{body:m.body,close:()=>{y||(y=!0,m.body?.cancel().catch(()=>{}),p.abort())},controlVersion:i,streamVersion:qc(m.headers),tailIndex:Py(m.headers)}}if(r=m.status,o=await m.text(),n=m.headers,!t.retryableErrorStatuses.has(m.status))throw new Ve(m.status,o,m.headers);u<a.maxAttempts-1&&(await dr(s,e.signal),s=Math.min(s*2,a.maxDelayMs))}throw new Ve(r??0,o??"Failed to open message stream.",n)}function Py(e){let t=e.get(Ss);if(t===null||!/^-?\d+$/.test(t))return;let a=Number(t);return Number.isSafeInteger(a)?a:void 0}async function dr(e,t){t?.aborted||await new Promise(a=>{let r=()=>{clearTimeout(o),a()},o=setTimeout(()=>{t?.removeEventListener("abort",r),a()},e);t?.addEventListener("abort",r,{once:!0})})}import{z as Bt}from"zod";var Wc=Bt.discriminatedUnion("status",[Bt.strictObject({ok:Bt.literal(!0),sessionId:Bt.string().min(1),status:Bt.literal("accepted")}),Bt.strictObject({ok:Bt.literal(!0),status:Bt.literal("no_active_turn")})]);import{z as Ot}from"zod";var jc=Ot.discriminatedUnion("status",[Ot.object({ok:Ot.literal(!0),sessionId:Ot.string().min(1),status:Ot.literal("accepted")}),Ot.object({ok:Ot.literal(!0),status:Ot.literal("no_active_session")})]);import{z as Ut}from"zod";var zc=Ut.discriminatedUnion("status",[Ut.object({ok:Ut.literal(!0),sessionId:Ut.string().min(1),status:Ut.literal("accepted")}),Ut.object({ok:Ut.literal(!0),status:Ut.literal("no_active_session")})]);import{z as Nt}from"zod";var Vc=Nt.discriminatedUnion("status",[Nt.object({ok:Nt.literal(!0),previousSessionId:Nt.string().min(1),status:Nt.literal("reset")}),Nt.object({ok:Nt.literal(!0),status:Nt.literal("no_active_session")})]);async function Gc(e){let{signal:t,...a}=e.options??{},{payload:r,response:o}=await Eo({body:a,context:e.context,operation:"Cancel",path:yc(e.sessionId),signal:t}),n=Wc.safeParse(r);if(!n.success||n.data.status==="accepted"&&n.data.sessionId!==e.sessionId)throw Error(`Cancel route returned an invalid response (${o.status}).`);return n.data.status==="accepted"?{sessionId:n.data.sessionId,status:"accepted"}:{status:"no_active_turn"}}async function Kc(e){let{payload:t}=await Eo({context:e.context,operation:"Clear",path:Sc(e.sessionId)}),a=jc.safeParse(t);if(!a.success||a.data.status==="accepted"&&a.data.sessionId!==e.sessionId)throw Error("Clear route returned an invalid response.");return a.data.status==="accepted"?{sessionId:a.data.sessionId,status:"accepted"}:{status:"no_active_session"}}async function Xc(e){let{payload:t}=await Eo({context:e.context,operation:"Compact",path:Lc(e.sessionId)}),a=zc.safeParse(t);if(!a.success||a.data.status==="accepted"&&a.data.sessionId!==e.sessionId)throw Error("Compact route returned an invalid response.");return a.data.status==="accepted"?{sessionId:a.data.sessionId,status:"accepted"}:{status:"no_active_session"}}async function Jc(e){let{signal:t,...a}=e.options??{},{payload:r}=await Eo({body:a,context:e.context,operation:"Reset",path:Cc(e.sessionId),signal:t}),o=Vc.safeParse(r);if(!o.success||o.data.status==="reset"&&o.data.previousSessionId!==e.sessionId)throw Error("Reset route returned an invalid response.");return o.data.status==="reset"?{previousSessionId:o.data.previousSessionId,status:"reset"}:{status:"no_active_session"}}async function Eo(e){let t=await e.context.resolveHeaders();t.set("content-type","application/json");let a=await fetch(pt(e.context.host,e.path),Ry({body:e.body===void 0?void 0:JSON.stringify(e.body),headers:t,method:"POST",signal:e.signal},e.context.redirect)),r=await a.text();if(!a.ok)throw new Ve(a.status,r,a.headers);try{return{payload:JSON.parse(r),response:a}}catch{throw Error(`${e.operation} route returned invalid JSON (${a.status}).`)}}function Ry(e,t){return t===void 0?e:{...e,redirect:t}}import{TypeValidationError as l1,asSchema as iL,jsonSchema as u1}from"ai";function cr(e,t){let a=typeof e;if(a!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=e.length;if(r!==t.length)return!1;for(let o=0;o<r;o++)if(!cr(e[o],t[o]))return!1;return!0}if(a==="object"){if(!e||!t)return e===t;let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let n of r)if(!cr(e[n],t[n]))return!1;return!0}return e===t}function rt(e){return encodeURI(Ey(e))}function Ey(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var My={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Fy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},_y={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Dy=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Yt(e,t=Object.create(null),a=Dy,r=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e.$id||e.id;if(n){let s=new URL(n,a.href);s.hash.length>1?t[s.href]=e:(s.hash="",r===""?a=s:Yt(e,t,a))}}else if(e!==!0&&e!==!1)return t;let o=a.href+(r?"#"+r:"");if(t[o]!==void 0)throw Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){let n=new URL(e.$ref,a.href);n.hash=n.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:n.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let n=new URL(e.$recursiveRef,a.href);n.hash=n.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:n.href})}if(e.$anchor){let n=new URL("#"+e.$anchor,a.href);t[n.href]=e}for(let n in e){if(_y[n])continue;let s=`${r}/${rt(n)}`,i=e[n];if(Array.isArray(i)){if(My[n]){let l=i.length;for(let u=0;u<l;u++)Yt(i[u],t,a,`${s}/${u}`)}}else if(Fy[n])for(let l in i)Yt(i[l],t,a,`${s}/${rt(l)}`);else Yt(i,t,a,s)}return t}var By=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Oy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Uy=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Ny=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,qy=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Hy=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,$y=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Wy=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,jy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,zy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Vy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Gy=e=>{if(e[0]==='"')return!1;let[t,a,...r]=e.split("@");return!t||!a||r.length!==0||t.length>64||a.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(a)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:a.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},Ky=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xy=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Jy=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function mt(e){return e.test.bind(e)}var Qc={date:Yc,time:Zc.bind(void 0,!1),"date-time":Zy,duration:Jy,uri:aL,"uri-reference":mt(qy),"uri-template":mt(Hy),url:mt($y),email:Gy,hostname:mt(Ny),ipv4:mt(Ky),ipv6:mt(Xy),regex:oL,uuid:mt(Wy),"json-pointer":mt(jy),"json-pointer-uri-fragment":mt(zy),"relative-json-pointer":mt(Vy)};function Qy(e){return e%4==0&&(e%100!=0||e%400==0)}function Yc(e){let t=e.match(By);if(!t)return!1;let a=+t[1],r=+t[2],o=+t[3];return r>=1&&r<=12&&o>=1&&o<=(r==2&&Qy(a)?29:Oy[r])}function Zc(e,t){let a=t.match(Uy);if(!a)return!1;let r=+a[1],o=+a[2],n=+a[3],s=!!a[5];return(r<=23&&o<=59&&n<=59||r==23&&o==59&&n==60)&&(!e||s)}var Yy=/t|\s/i;function Zy(e){let t=e.split(Yy);return t.length==2&&Yc(t[0])&&Zc(!0,t[1])}var eL=/\/|:/,tL=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function aL(e){return eL.test(e)&&tL.test(e)}var rL=/[^\\]\\Z/;function oL(e){if(rL.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var nL;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(nL||={});function sL(e){let t=0,a=e.length,r=0,o;for(;r<a;)t++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<a&&(o=e.charCodeAt(r),(o&64512)==56320&&r++);return t}function Te(e,t,a="2019-09",r=Yt(t),o=!0,n=null,s="#",i="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":d=e===null?"null":Array.isArray(e)?"array":"object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:c,$recursiveRef:p,$recursiveAnchor:f,type:m,const:y,enum:S,required:L,not:C,anyOf:I,allOf:x,oneOf:v,if:q,then:N,else:V,format:G,properties:Q,patternProperties:O,additionalProperties:re,unevaluatedProperties:K,minProperties:J,maxProperties:X,propertyNames:R,dependentRequired:b,dependentSchemas:D,dependencies:ae,prefixItems:oe,items:Re,additionalItems:Ne,unevaluatedItems:k,contains:H,minContains:$,maxContains:ne,minItems:me,maxItems:Ie,uniqueItems:fe,minimum:Z,maximum:W,exclusiveMinimum:se,exclusiveMaximum:xe,multipleOf:ie,minLength:le,maxLength:ee,pattern:ue,__absolute_ref__:Y,__absolute_recursive_ref__:he}=t,T=[];if(f===!0&&n===null&&(n=t),p==="#"){let _=n===null?r[he]:n,M=`${i}/$recursiveRef`,z=Te(e,n===null?t:n,a,r,o,_,s,M,l);z.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...z.errors)}if(c!==void 0){let _=r[Y||c];if(_===void 0){let E=`Unresolved $ref "${c}".`;throw Y&&Y!==c&&(E+=` Absolute URI "${Y}".`),E+=`
|
|
18
|
+
`)}}let i=o.trim();if(i.length>0){let l=JSON.parse(i);t.controlVersion==="1"&&Oc(l)?t.onLeaseEnded?.():yield Uc(l,t.streamVersion)}}finally{t.signal?.removeEventListener("abort",s),n||a.cancel().catch(()=>{}),a.releaseLock()}}function Oc(e){if(typeof e!="object"||!e)return!1;let t=e;return t.$eve===bs.$eve&&t.version===bs.version}function Uc(e,t){return Bc(t,e)}async function ky(e,t){let a;try{return t===void 0?await e.read():await Promise.race([e.read(),new Promise((r,o)=>{a=setTimeout(()=>o(new DOMException("Session stream was idle.","AbortError")),t)})])}catch(r){throw r instanceof TypeError?Error("Session stream disconnected.",{cause:r}):r}finally{a!==void 0&&clearTimeout(a)}}var Ty={21:!0,22:!0,23:!0,24:!0,25:!0};function qc(e){let t=e.get(Cs);if(t!==null&&Object.hasOwn(Ty,t))return t;throw TypeError(t===null?`Missing ${Cs} response header.`:`Unsupported message stream version: ${t}.`)}var Qt={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},Ay={...Qt,streamIdleReconnectPolicy:{...Qt.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...Qt.streamOpenReconnectPolicy,maxAttempts:1}};function Hc(e,t){return{...t,...e}}function $c(e,t=!1){if(e&&"reconnect"in e&&e.reconnect===!1)return Ay;let a=e;return{retryableErrorStatuses:a?.retryableErrorStatuses?new Set(a.retryableErrorStatuses):Qt.retryableErrorStatuses,streamIdleReconnectPolicy:Hc(a?.streamIdleReconnectPolicy,{...Qt.streamIdleReconnectPolicy,maxAttempts:t?1/0:Qt.streamIdleReconnectPolicy.maxAttempts}),streamOpenReconnectPolicy:Hc(a?.streamOpenReconnectPolicy,Qt.streamOpenReconnectPolicy)}}async function*Fs(e){if(e.follow===!1&&e.startIndex<0)throw Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");let t=()=>$c(e.resolveReconnectPolicy===void 0?e.streamReconnectPolicy:e.resolveReconnectPolicy(),e.keepAlive),a=t(),r=a.streamIdleReconnectPolicy,o=e.startIndex,n=r.baseDelayMs,s=0,i=!0,l,u=!1;for(;;){a=t(),r=a.streamIdleReconnectPolicy;let d;try{d=await Py({...e,retryPolicy:a,startIndex:o,requestTailIndex:(e.follow===!1||e.onCaughtUp!==void 0)&&l===void 0})}catch(f){if(e.signal?.aborted)return;throw f}if((e.follow===!1||e.onCaughtUp!==void 0)&&l===void 0&&(l=d.tailIndex,l===void 0))throw d.close(),Error(`stream({ follow: false }) requires the server to report the ${Ss} header. The agent may be running an older eve version.`);if(!u&&l!==void 0&&o>l&&(u=!0,e.onCaughtUp?.()),e.follow===!1&&l!==void 0&&o>l){d.close();return}let c=!1,p=!1;try{for await(let f of Nc(d.body,{signal:e.signal,controlVersion:d.controlVersion,idleTimeoutMs:e.streamReadIdleTimeoutMs??15e3,onLeaseEnded:()=>{p=!0},streamVersion:d.streamVersion}))if(o+=1,c=!0,n=r.baseDelayMs,s=0,yield f,!u&&l!==void 0&&o>l&&(u=!0,e.onCaughtUp?.()),e.follow===!1&&l!==void 0&&o>l)return}catch(f){if(!Ms(f))throw f}finally{d.close()}if(r=t().streamIdleReconnectPolicy,e.signal?.aborted||e.startIndex<0||r.maxAttempts===0)return;if(!p){if(!c&&!i&&(s+=1)>=r.maxAttempts||(i=!1,await dr(n,e.signal),e.signal?.aborted))return;n=Math.min(n*2,r.maxDelayMs)}}}async function Py(e){let t=e.retryPolicy??$c(e.streamReconnectPolicy,e.keepAlive),a=t.streamOpenReconnectPolicy,r,o,n,s=a.baseDelayMs,i=e.startIndex>=0&&t.streamIdleReconnectPolicy.maxAttempts>0?Tc:void 0,l={};i!==void 0&&(l[Ac]=i),e.startIndex!==0&&(l.startIndex=String(e.startIndex)),e.requestTailIndex===!0&&(l.includeTailIndex="1");for(let u=0;u<a.maxAttempts;u+=1){e.signal?.throwIfAborted();let d=pt(e.host,e.path,Object.keys(l).length>0?l:void 0),c=await e.resolveHeaders();e.signal?.throwIfAborted();let p=new AbortController,f=e.signal?AbortSignal.any([e.signal,p.signal]):p.signal,m;try{m=await fetch(d,{cache:"no-store",headers:c,redirect:e.redirect,signal:f})}catch(y){if(e.signal?.aborted||!Ms(y)||u===a.maxAttempts-1)throw y;await dr(s,e.signal),s=Math.min(s*2,a.maxDelayMs);continue}if(m.ok){if(!m.body)throw new Ve(m.status,"Response body is null.",m.headers);let y=!1;return{body:m.body,close:()=>{y||(y=!0,m.body?.cancel().catch(()=>{}),p.abort())},controlVersion:i,streamVersion:qc(m.headers),tailIndex:Ry(m.headers)}}if(r=m.status,o=await m.text(),n=m.headers,!t.retryableErrorStatuses.has(m.status))throw new Ve(m.status,o,m.headers);u<a.maxAttempts-1&&(await dr(s,e.signal),s=Math.min(s*2,a.maxDelayMs))}throw new Ve(r??0,o??"Failed to open message stream.",n)}function Ry(e){let t=e.get(Ss);if(t===null||!/^-?\d+$/.test(t))return;let a=Number(t);return Number.isSafeInteger(a)?a:void 0}async function dr(e,t){t?.aborted||await new Promise(a=>{let r=()=>{clearTimeout(o),a()},o=setTimeout(()=>{t?.removeEventListener("abort",r),a()},e);t?.addEventListener("abort",r,{once:!0})})}import{z as Bt}from"zod";var Wc=Bt.discriminatedUnion("status",[Bt.strictObject({ok:Bt.literal(!0),sessionId:Bt.string().min(1),status:Bt.literal("accepted")}),Bt.strictObject({ok:Bt.literal(!0),status:Bt.literal("no_active_turn")})]);import{z as Ot}from"zod";var jc=Ot.discriminatedUnion("status",[Ot.object({ok:Ot.literal(!0),sessionId:Ot.string().min(1),status:Ot.literal("accepted")}),Ot.object({ok:Ot.literal(!0),status:Ot.literal("no_active_session")})]);import{z as Ut}from"zod";var zc=Ut.discriminatedUnion("status",[Ut.object({ok:Ut.literal(!0),sessionId:Ut.string().min(1),status:Ut.literal("accepted")}),Ut.object({ok:Ut.literal(!0),status:Ut.literal("no_active_session")})]);import{z as Nt}from"zod";var Vc=Nt.discriminatedUnion("status",[Nt.object({ok:Nt.literal(!0),previousSessionId:Nt.string().min(1),status:Nt.literal("reset")}),Nt.object({ok:Nt.literal(!0),status:Nt.literal("no_active_session")})]);async function Gc(e){let{signal:t,...a}=e.options??{},{payload:r,response:o}=await Eo({body:a,context:e.context,operation:"Cancel",path:yc(e.sessionId),signal:t}),n=Wc.safeParse(r);if(!n.success||n.data.status==="accepted"&&n.data.sessionId!==e.sessionId)throw Error(`Cancel route returned an invalid response (${o.status}).`);return n.data.status==="accepted"?{sessionId:n.data.sessionId,status:"accepted"}:{status:"no_active_turn"}}async function Kc(e){let{payload:t}=await Eo({context:e.context,operation:"Clear",path:Sc(e.sessionId)}),a=jc.safeParse(t);if(!a.success||a.data.status==="accepted"&&a.data.sessionId!==e.sessionId)throw Error("Clear route returned an invalid response.");return a.data.status==="accepted"?{sessionId:a.data.sessionId,status:"accepted"}:{status:"no_active_session"}}async function Xc(e){let{payload:t}=await Eo({context:e.context,operation:"Compact",path:Lc(e.sessionId)}),a=zc.safeParse(t);if(!a.success||a.data.status==="accepted"&&a.data.sessionId!==e.sessionId)throw Error("Compact route returned an invalid response.");return a.data.status==="accepted"?{sessionId:a.data.sessionId,status:"accepted"}:{status:"no_active_session"}}async function Jc(e){let{signal:t,...a}=e.options??{},{payload:r}=await Eo({body:a,context:e.context,operation:"Reset",path:Cc(e.sessionId),signal:t}),o=Vc.safeParse(r);if(!o.success||o.data.status==="reset"&&o.data.previousSessionId!==e.sessionId)throw Error("Reset route returned an invalid response.");return o.data.status==="reset"?{previousSessionId:o.data.previousSessionId,status:"reset"}:{status:"no_active_session"}}async function Eo(e){let t=await e.context.resolveHeaders();t.set("content-type","application/json");let a=await fetch(pt(e.context.host,e.path),Ey({body:e.body===void 0?void 0:JSON.stringify(e.body),headers:t,method:"POST",signal:e.signal},e.context.redirect)),r=await a.text();if(!a.ok)throw new Ve(a.status,r,a.headers);try{return{payload:JSON.parse(r),response:a}}catch{throw Error(`${e.operation} route returned invalid JSON (${a.status}).`)}}function Ey(e,t){return t===void 0?e:{...e,redirect:t}}import{TypeValidationError as u1,asSchema as lL,jsonSchema as d1}from"ai";function cr(e,t){let a=typeof e;if(a!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=e.length;if(r!==t.length)return!1;for(let o=0;o<r;o++)if(!cr(e[o],t[o]))return!1;return!0}if(a==="object"){if(!e||!t)return e===t;let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let n of r)if(!cr(e[n],t[n]))return!1;return!0}return e===t}function rt(e){return encodeURI(My(e))}function My(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Fy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},_y={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Dy={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},By=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Yt(e,t=Object.create(null),a=By,r=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e.$id||e.id;if(n){let s=new URL(n,a.href);s.hash.length>1?t[s.href]=e:(s.hash="",r===""?a=s:Yt(e,t,a))}}else if(e!==!0&&e!==!1)return t;let o=a.href+(r?"#"+r:"");if(t[o]!==void 0)throw Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){let n=new URL(e.$ref,a.href);n.hash=n.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:n.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let n=new URL(e.$recursiveRef,a.href);n.hash=n.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:n.href})}if(e.$anchor){let n=new URL("#"+e.$anchor,a.href);t[n.href]=e}for(let n in e){if(Dy[n])continue;let s=`${r}/${rt(n)}`,i=e[n];if(Array.isArray(i)){if(Fy[n]){let l=i.length;for(let u=0;u<l;u++)Yt(i[u],t,a,`${s}/${u}`)}}else if(_y[n])for(let l in i)Yt(i[l],t,a,`${s}/${rt(l)}`);else Yt(i,t,a,s)}return t}var Oy=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Uy=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ny=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,qy=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Hy=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,$y=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Wy=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,jy=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,zy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Vy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Gy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Ky=e=>{if(e[0]==='"')return!1;let[t,a,...r]=e.split("@");return!t||!a||r.length!==0||t.length>64||a.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(a)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:a.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},Xy=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Jy=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Qy=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function mt(e){return e.test.bind(e)}var Qc={date:Yc,time:Zc.bind(void 0,!1),"date-time":eL,duration:Qy,uri:rL,"uri-reference":mt(Hy),"uri-template":mt($y),url:mt(Wy),email:Ky,hostname:mt(qy),ipv4:mt(Xy),ipv6:mt(Jy),regex:nL,uuid:mt(jy),"json-pointer":mt(zy),"json-pointer-uri-fragment":mt(Vy),"relative-json-pointer":mt(Gy)};function Yy(e){return e%4==0&&(e%100!=0||e%400==0)}function Yc(e){let t=e.match(Oy);if(!t)return!1;let a=+t[1],r=+t[2],o=+t[3];return r>=1&&r<=12&&o>=1&&o<=(r==2&&Yy(a)?29:Uy[r])}function Zc(e,t){let a=t.match(Ny);if(!a)return!1;let r=+a[1],o=+a[2],n=+a[3],s=!!a[5];return(r<=23&&o<=59&&n<=59||r==23&&o==59&&n==60)&&(!e||s)}var Zy=/t|\s/i;function eL(e){let t=e.split(Zy);return t.length==2&&Yc(t[0])&&Zc(!0,t[1])}var tL=/\/|:/,aL=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function rL(e){return tL.test(e)&&aL.test(e)}var oL=/[^\\]\\Z/;function nL(e){if(oL.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var sL;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(sL||={});function iL(e){let t=0,a=e.length,r=0,o;for(;r<a;)t++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<a&&(o=e.charCodeAt(r),(o&64512)==56320&&r++);return t}function Te(e,t,a="2019-09",r=Yt(t),o=!0,n=null,s="#",i="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":d=e===null?"null":Array.isArray(e)?"array":"object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:c,$recursiveRef:p,$recursiveAnchor:f,type:m,const:y,enum:S,required:L,not:C,anyOf:I,allOf:x,oneOf:v,if:q,then:N,else:V,format:G,properties:Q,patternProperties:O,additionalProperties:re,unevaluatedProperties:K,minProperties:J,maxProperties:X,propertyNames:R,dependentRequired:b,dependentSchemas:D,dependencies:ae,prefixItems:oe,items:Re,additionalItems:Ne,unevaluatedItems:k,contains:H,minContains:$,maxContains:ne,minItems:me,maxItems:Ie,uniqueItems:fe,minimum:Z,maximum:W,exclusiveMinimum:se,exclusiveMaximum:xe,multipleOf:ie,minLength:le,maxLength:ee,pattern:ue,__absolute_ref__:Y,__absolute_recursive_ref__:he}=t,T=[];if(f===!0&&n===null&&(n=t),p==="#"){let _=n===null?r[he]:n,M=`${i}/$recursiveRef`,z=Te(e,n===null?t:n,a,r,o,_,s,M,l);z.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...z.errors)}if(c!==void 0){let _=r[Y||c];if(_===void 0){let E=`Unresolved $ref "${c}".`;throw Y&&Y!==c&&(E+=` Absolute URI "${Y}".`),E+=`
|
|
19
19
|
Known schemas:
|
|
20
20
|
- ${Object.keys(r).join(`
|
|
21
|
-
- `)}`,Error(E)}let M=`${i}/$ref`,z=Te(e,_,a,r,o,n,s,M,l);if(z.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...z.errors),a==="4"||a==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(m)){let _=m.length,M=!1;for(let z=0;z<_;z++)if(d===m[z]||m[z]==="integer"&&d==="number"&&e%1==0&&e===e){M=!0;break}M||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(d!=="number"||e%1||e!==e)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`}):m!==void 0&&d!==m&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`});if(y!==void 0&&(d==="object"||d==="array"?cr(e,y)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),S!==void 0&&(d==="object"||d==="array"?S.some(_=>cr(e,_))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(_=>e===_)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),C!==void 0){let _=`${i}/not`;Te(e,C,a,r,o,n,s,_).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:_,error:'Instance matched "not" schema.'})}let ye=[];if(I!==void 0){let _=`${i}/anyOf`,M=T.length,z=!1;for(let E=0;E<I.length;E++){let w=I[E],A=Object.create(l),F=Te(e,w,a,r,o,f===!0?n:null,s,`${_}/${E}`,A);T.push(...F.errors),z||=F.valid,F.valid&&ye.push(A)}z?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:_,error:"Instance does not match any subschemas."})}if(x!==void 0){let _=`${i}/allOf`,M=T.length,z=!0;for(let E=0;E<x.length;E++){let w=x[E],A=Object.create(l),F=Te(e,w,a,r,o,f===!0?n:null,s,`${_}/${E}`,A);T.push(...F.errors),z&&=F.valid,F.valid&&ye.push(A)}z?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"allOf",keywordLocation:_,error:"Instance does not match every subschema."})}if(v!==void 0){let _=`${i}/oneOf`,M=T.length,z=v.filter((E,w)=>{let A=Object.create(l),F=Te(e,E,a,r,o,f===!0?n:null,s,`${_}/${w}`,A);return T.push(...F.errors),F.valid&&ye.push(A),F.valid}).length;z===1?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:_,error:`Instance does not match exactly one subschema (${z} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...ye),q!==void 0){let _=`${i}/if`;if(Te(e,q,a,r,o,n,s,_,l).valid){if(N!==void 0){let M=Te(e,N,a,r,o,n,s,`${i}/then`,l);M.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:_,error:'Instance does not match "then" schema.'},...M.errors)}}else if(V!==void 0){let M=Te(e,V,a,r,o,n,s,`${i}/else`,l);M.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:_,error:'Instance does not match "else" schema.'},...M.errors)}}if(d==="object"){if(L!==void 0)for(let E of L)E in e||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${E}".`});let _=Object.keys(e);if(J!==void 0&&_.length<J&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${J} properties.`}),X!==void 0&&_.length>X&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${X} properties.`}),R!==void 0){let E=`${i}/propertyNames`;for(let w in e){let A=`${s}/${rt(w)}`,F=Te(w,R,a,r,o,n,A,E);F.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:E,error:`Property name "${w}" does not match schema.`},...F.errors)}}if(b!==void 0){let E=`${i}/dependantRequired`;for(let w in b)if(w in e){let A=b[w];for(let F of A)F in e||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:E,error:`Instance has "${w}" but does not have "${F}".`})}}if(D!==void 0)for(let E in D){let w=`${i}/dependentSchemas`;if(E in e){let A=Te(e,D[E],a,r,o,n,s,`${w}/${rt(E)}`,l);A.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:w,error:`Instance has "${E}" but does not match dependant schema.`},...A.errors)}}if(ae!==void 0){let E=`${i}/dependencies`;for(let w in ae)if(w in e){let A=ae[w];if(Array.isArray(A))for(let F of A)F in e||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${w}" but does not have "${F}".`});else{let F=Te(e,A,a,r,o,n,s,`${E}/${rt(w)}`);F.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${w}" but does not match dependant schema.`},...F.errors)}}}let M=Object.create(null),z=!1;if(Q!==void 0){let E=`${i}/properties`;for(let w in Q){if(!(w in e))continue;let A=`${s}/${rt(w)}`,F=Te(e[w],Q[w],a,r,o,n,A,`${E}/${rt(w)}`);if(F.valid)l[w]=M[w]=!0;else if(z=o,T.push({instanceLocation:s,keyword:"properties",keywordLocation:E,error:`Property "${w}" does not match schema.`},...F.errors),z)break}}if(!z&&O!==void 0){let E=`${i}/patternProperties`;for(let w in O){let A=new RegExp(w,"u"),F=O[w];for(let pe in e){if(!A.test(pe))continue;let nt=`${s}/${rt(pe)}`,st=Te(e[pe],F,a,r,o,n,nt,`${E}/${rt(w)}`);st.valid?l[pe]=M[pe]=!0:(z=o,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:E,error:`Property "${pe}" matches pattern "${w}" but does not match associated schema.`},...st.errors))}}}if(!z&&re!==void 0){let E=`${i}/additionalProperties`;for(let w in e){if(M[w])continue;let A=`${s}/${rt(w)}`,F=Te(e[w],re,a,r,o,n,A,E);F.valid?l[w]=!0:(z=o,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:E,error:`Property "${w}" does not match additional properties schema.`},...F.errors))}}else if(!z&&K!==void 0){let E=`${i}/unevaluatedProperties`;for(let w in e)if(!l[w]){let A=`${s}/${rt(w)}`,F=Te(e[w],K,a,r,o,n,A,E);F.valid?l[w]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:E,error:`Property "${w}" does not match unevaluated properties schema.`},...F.errors)}}}else if(d==="array"){Ie!==void 0&&e.length>Ie&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${Ie}).`}),me!==void 0&&e.length<me&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${me}).`});let _=e.length,M=0,z=!1;if(oe!==void 0){let E=`${i}/prefixItems`,w=Math.min(oe.length,_);for(;M<w;M++){let A=Te(e[M],oe[M],a,r,o,n,`${s}/${M}`,`${E}/${M}`);if(l[M]=!0,!A.valid&&(z=o,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:E,error:"Items did not match schema."},...A.errors),z))break}}if(Re!==void 0){let E=`${i}/items`;if(Array.isArray(Re)){let w=Math.min(Re.length,_);for(;M<w;M++){let A=Te(e[M],Re[M],a,r,o,n,`${s}/${M}`,`${E}/${M}`);if(l[M]=!0,!A.valid&&(z=o,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...A.errors),z))break}}else for(;M<_;M++){let w=Te(e[M],Re,a,r,o,n,`${s}/${M}`,E);if(l[M]=!0,!w.valid&&(z=o,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...w.errors),z))break}if(!z&&Ne!==void 0){let w=`${i}/additionalItems`;for(;M<_;M++){let A=Te(e[M],Ne,a,r,o,n,`${s}/${M}`,w);l[M]=!0,A.valid||(z=o,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:w,error:"Items did not match additional items schema."},...A.errors))}}}if(H!==void 0)if(_===0&&$===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if($!==void 0&&_<$)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${_}) than minContains (${$}).`});else{let E=`${i}/contains`,w=T.length,A=0;for(let F=0;F<_;F++){let pe=Te(e[F],H,a,r,o,n,`${s}/${F}`,E);pe.valid?(l[F]=!0,A++):T.push(...pe.errors)}A>=($||0)&&(T.length=w),$===void 0&&ne===void 0&&A===0?T.splice(w,0,{instanceLocation:s,keyword:"contains",keywordLocation:E,error:"Array does not contain item matching schema."}):$!==void 0&&A<$?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${$} items matching schema. Only ${A} items were found.`}):ne!==void 0&&A>ne&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${ne} items matching schema. ${A} items were found.`})}if(!z&&k!==void 0){let E=`${i}/unevaluatedItems`;for(;M<_;M++){if(l[M])continue;let w=Te(e[M],k,a,r,o,n,`${s}/${M}`,E);l[M]=!0,w.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:E,error:"Items did not match unevaluated items schema."},...w.errors)}}if(fe)for(let E=0;E<_;E++){let w=e[E],A=typeof w=="object"&&!!w;for(let F=0;F<_;F++){if(E===F)continue;let pe=e[F];(w===pe||A&&typeof pe=="object"&&pe&&cr(w,pe))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${E} and ${F}.`}),E=2**53-1,F=2**53-1)}}}else if(d==="number"){if(a==="4"?(Z!==void 0&&(se===!0&&e<=Z||e<Z)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${se?"or equal to ":""} ${Z}.`}),W!==void 0&&(xe===!0&&e>=W||e>W)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${xe?"or equal to ":""} ${W}.`})):(Z!==void 0&&e<Z&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${Z}.`}),W!==void 0&&e>W&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${W}.`}),se!==void 0&&e<=se&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${se}.`}),xe!==void 0&&e>=xe&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${xe}.`})),ie!==void 0){let _=e%ie;Math.abs(0-_)>=11920929e-14&&Math.abs(ie-_)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${ie}.`})}}else if(d==="string"){let _=le===void 0&&ee===void 0?0:sL(e);le!==void 0&&_<le&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${_} < ${le}).`}),ee!==void 0&&_>ee&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${_} > ${ee}).`}),ue!==void 0&&!new RegExp(ue,"u").test(e)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),G!==void 0&&Qc[G]&&!Qc[G](e)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${G}".`})}return{valid:T.length===0,errors:T}}var ef=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",a=!0){this.schema=e,this.draft=t,this.shortCircuit=a,this.lookup=Yt(e)}validate(e){return Te(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Yt(e,this.lookup)}};function rf(e){return dL(e,"output")}function lL(e,t){let a=()=>structuredClone(e),r={"~standard":{version:1,vendor:"eve",validate:pL(e,t),jsonSchema:{input:a,output:a}}};return uL.add(r),r}var uL=new WeakSet,m1=lL({});function dL(e,t){return e==null?e:cL(e,t)}function cL(e,t){let a=fL(e),r=a?.jsonSchema,o=typeof r=="object"&&r?r[t]:void 0,n=typeof a?.vendor=="string"?a.vendor:"unknown";if(a!==void 0&&typeof o!="function"&&n==="zod"){if(t==="input"){let l=iL(e),{$schema:u,...d}=sr(l.jsonSchema);return d}throw Error("Zod 3 cannot emit an output JSON Schema. Upgrade to Zod 4 or provide a plain JSON Schema object.")}if(a!==void 0&&typeof o!="function")throw Error(`Standard Schema vendor "${n}" does not support JSON Schema conversion. Provide a Standard Schema implementation with JSON Schema conversion or a plain JSON Schema object.`);let{$schema:s,...i}=sr(a===void 0?e:o({target:"draft-07"}));return i}function fL(e){if(typeof e!="object"||!e||!("~standard"in e))return;let t=e["~standard"];return typeof t=="object"&&t?t:void 0}function pL(e,t){let a,r=!1,o=(n,s)=>(r||(r=!0,console.warn(`[eve] Tool schema cannot validate values locally; passing them through unvalidated: ${s}`)),{value:n});return n=>{if(a===void 0){let u=wL(e);if(typeof u=="string")return a=null,o(n,u);a=u}if(a===null)return{value:n};let s;try{s=a.validate(n)}catch(u){return n===void 0?{issues:[{message:"Expected a JSON value."}]}:o(n,lr(u))}if(!s.valid)return{issues:bL(s.errors)};let i=Ds(e,e,n),l=t?.(i);return l===void 0?{value:i}:{issues:[{message:l}]}}}function Ds(e,t,a){let r=a;for(let o of of(e,t)){let{items:n,properties:s}=o;if(ft(r)&&ft(s))r=mL(e,s,r);else if(Array.isArray(r)&&ft(n)){let i=r,l=i.map(u=>Ds(e,n,u));l.some((u,d)=>u!==i[d])&&(r=l)}}return r}function mL(e,t,a){let r=a;for(let[o,n]of Object.entries(t)){let s=Object.hasOwn(a,o)?a[o]:void 0,i=s===void 0?hL(e,n):Ds(e,n,s);i!==s&&(r===a&&(r={...a}),r[o]=i)}return r}function hL(e,t){for(let a of of(e,t))if("default"in a)return structuredClone(a.default)}function*of(e,t){let a=new Set,r=t;for(;ft(r)&&!a.has(r);)a.add(r),yield r,r=gL(e,r.$ref)}function gL(e,t){if(typeof t!="string"||t!=="#"&&!t.startsWith("#/"))return;let a=e;for(let r of _s(t)){if(typeof a!="object"||!a||!Object.hasOwn(a,r))return;a=a[r]}return a}function wL(e){try{let t=structuredClone(e);return fr(t)??new ef(t,"2020-12",!1)}catch(t){return lr(t)}}var IL=new Set(["array","boolean","integer","null","number","object","string"]),xL=[["exclusiveMinimum","minimum"],["exclusiveMaximum","maximum"]],yL=["additionalItems","additionalProperties","contains","else","if","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"],LL=["allOf","anyOf","oneOf","prefixItems"],SL=["$defs","definitions","dependencies","dependentSchemas","patternProperties","properties"];function fr(e){if(typeof e=="boolean")return;if(typeof e!="object"||!e||Array.isArray(e))return"a subschema is neither an object nor a boolean";let t=e;delete t.format;for(let[i,l]of xL)typeof t[i]=="boolean"&&(t[i]&&typeof t[l]=="number"?(t[i]=t[l],delete t[l]):delete t[i]);let{enum:a,pattern:r,required:o,type:n}=t;if(n!==void 0&&!(Array.isArray(n)?n.every(tf):tf(n)))return`unsupported type ${JSON.stringify(n)}`;if(a!==void 0&&!Array.isArray(a))return"`enum` is not an array";if(o!==void 0&&!(Array.isArray(o)&&o.every(i=>typeof i=="string")))return"`required` is not an array of strings";if(r!==void 0&&!af(r))return`invalid pattern ${JSON.stringify(r)}`;for(let i of yL)if(i in t){let l=fr(t[i]);if(l!==void 0)return l}let s=t.items;for(let i of Array.isArray(s)?s:s===void 0?[]:[s]){let l=fr(i);if(l!==void 0)return l}for(let i of LL){let l=t[i];if(l!==void 0){if(!Array.isArray(l))return`\`${i}\` is not an array`;for(let u of l){let d=fr(u);if(d!==void 0)return d}}}for(let i of SL){let l=t[i];if(l!==void 0){if(typeof l!="object"||!l||Array.isArray(l))return`\`${i}\` is not an object`;for(let[u,d]of Object.entries(l)){if(i==="patternProperties"&&!af(u))return`invalid pattern ${JSON.stringify(u)}`;if(i==="dependencies"&&Array.isArray(d))continue;let c=fr(d);if(c!==void 0)return c}}}}function tf(e){return typeof e=="string"&&IL.has(e)}function af(e){if(typeof e!="string")return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var CL=/\/(?:additional|unevaluated)Properties$/;function bL(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r],n=e[r+1];if(CL.test(o.keywordLocation)&&n?.keyword==="false"){let s=_s(n.instanceLocation).at(-1);t.push({keyword:"false",location:n.instanceLocation,message:`Unrecognized key: ${JSON.stringify(s)}`,object:o.instanceLocation}),r++}else t.push({keyword:o.keyword,location:o.instanceLocation,message:o.error})}let a=t.filter(r=>r.object===void 0||!t.some(o=>o.object===void 0&&(o.location===r.location||o.location.startsWith(`${r.location}/`))));return a.filter((r,o)=>{let n=a[o+1];return n===void 0?!0:n.location.startsWith(`${r.location}/`)?!1:r.keyword!=="$ref"||n.location!==r.location}).map(({location:r,message:o,object:n})=>{let s=_s(n??r);return s.length===0?{message:o}:{message:o,path:s}})}function _s(e){return e.split("/").slice(1).map(t=>{let a=t;try{a=decodeURIComponent(t)}catch{}return a.replaceAll("~1","/").replaceAll("~0","~")})}var nf=Symbol("followClientSession"),pr=class Os{#t;#e;constructor(t,a){this.#t=t,this.#e=a}static async create(t,a){let r=await Us(t,We,a,!0),{sessionId:o}=await Bs(r),n=new Os(t,{sessionId:o,streamIndex:0});return{response:n.#r(r,a,0),session:n}}static async prewarm(t,a={}){let{sessionId:r}=await Bs(await kL(t,a));return new Os(t,{sessionId:r,streamIndex:0})}get state(){return this.#e}async snapshot(t){t?.signal?.throwIfAborted();let a=[];for await(let r of this.#p({follow:!1,signal:t?.signal,startIndex:0}))a.push(r);return t?.signal?.throwIfAborted(),{events:a,session:{sessionId:this.#e.sessionId,streamIndex:a.length}}}async send(t,a={}){return await this.#a({...a,message:t},!0)}async respond(t,a={}){if(t.length===0)throw Error("ClientSession.respond() requires at least one input response.");return await this.#a({...a,inputResponses:t},!1)}async#a(t,a){let r=this.#e.streamIndex,o=xc(this.#e.sessionId),n=a?await vL(this.#t,o,t):await Us(this.#t,o,t,!1),{sessionId:s,deliveryId:i}=await Bs(n,this.#e.sessionId);if(s!==this.#e.sessionId)throw Error("Message route returned a different session id.");if(t.message!==void 0&&i===void 0)throw Error("Message route did not return a delivery id. Update the server before sending with this client.");return this.#r(n,t,r,t.message===void 0?void 0:i)}async cancel(t){return await Gc({context:this.#t,options:t,sessionId:this.#e.sessionId})}async clear(){return await Kc({context:this.#t,sessionId:this.#e.sessionId})}async compact(){return await Xc({context:this.#t,sessionId:this.#e.sessionId})}async reset(t){return await Jc({context:this.#t,options:t,sessionId:this.#e.sessionId})}stream(t){if(t?.follow===!1&&(t.startIndex??this.#e.streamIndex)<0)throw Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return this.#u(t)}streamSubagent(t,a){if(t.data.sessionId!==this.#e.sessionId)throw Error(`streamSubagent() requires a subagent.called event from session ${this.#e.sessionId}, but it came from session ${t.data.sessionId}.`);if(typeof t.data.childStreamPath!="string")throw Error(`streamSubagent() requires a subagent.called event with childStreamPath, but call ${t.data.callId} has none. The event was recorded by an older eve version.`);let r=a?.startIndex??0;if(a?.follow===!1&&r<0)throw Error("streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return Fs({follow:a?.follow,host:this.#t.host,path:t.data.childStreamPath,redirect:this.#t.redirect,resolveHeaders:()=>this.#t.resolveHeaders(),signal:a?.signal,startIndex:r,streamReconnectPolicy:a?.streamReconnectPolicy})}[nf](t){return this.#u({...t,keepAlive:!0})}#r(t,a,r,o){return t.body?.cancel().catch(()=>{}),new Ps({cancelTurn:async n=>await this.cancel({turnId:n}),createStream:n=>this.#n(r,a,o,n),deliveryId:o,sessionId:this.#e.sessionId})}async*#n(t,a,r,o){let n=0,s=r===void 0,i=!1,l=new Set;try{for await(let u of o??this.#p({headers:a.headers,keepAlive:!0,signal:a.signal,startIndex:t,streamReconnectPolicy:a.streamReconnectPolicy})){if(n+=1,r!==void 0){let d=u.meta?.deliveryIds?.includes(r)===!0,c=u.type==="session.failed"||u.type==="session.completed";if(!d&&c&&(!s||u.type==="session.completed"))throw Error("The session ended before the accepted message reached its turn boundary.");if(!s&&!d||!c&&u.meta?.deliveryIds!==void 0&&!d)continue;s=!0}if(Jt(l,u),i=Qe(u)&&(u.type!=="session.waiting"||l.size===0),yield u,i)break}if(r!==void 0&&!i&&!a.signal?.aborted)throw Error("The response stream ended before the accepted message reached its turn boundary.")}finally{this.#g(t+n)}}async*#u(t){let a=t?.startIndex??this.#e.streamIndex,r=0;for await(let o of this.#p({follow:t?.follow,headers:t?.headers,keepAlive:t?.keepAlive,onCaughtUp:t?.onCaughtUp,resolveHeaders:t?.resolveHeaders,resolveReconnectPolicy:t?.resolveReconnectPolicy,signal:t?.signal,startIndex:a,streamReconnectPolicy:t?.streamReconnectPolicy}))r+=1,a>=0&&this.#g(a+r),yield o}#g(t){this.#e={sessionId:this.#e.sessionId,streamIndex:Math.max(this.#e.streamIndex,t)}}#p(t){return Fs({onCaughtUp:t.onCaughtUp,follow:t.follow,host:this.#t.host,keepAlive:t.keepAlive,resolveHeaders:()=>this.#t.resolveHeaders(t.resolveHeaders?.()??t.headers),path:Ls(this.#e.sessionId),redirect:this.#t.redirect,signal:t.signal,startIndex:t.startIndex,streamReconnectPolicy:t.streamReconnectPolicy,resolveReconnectPolicy:t.resolveReconnectPolicy})}};function sf(e,t){return e[nf](t)}async function vL(e,t,a){let r=Date.now()+2e4,o=250;for(;;){try{return await Us(e,t,a,!1)}catch(n){if(!TL(n))throw n;let s=r-Date.now();if(s<=0)throw n;await dr(Math.min(o,s),a.signal)}a.signal?.throwIfAborted(),o=Math.min(o*2,2e3)}}async function kL(e,t){let a=await e.resolveHeaders(t.headers),r=await fetch(pt(e.host,We),{headers:a,method:"POST",redirect:e.redirect,signal:t.signal??null});if(!r.ok){let o=await r.text();throw new Ve(r.status,o,r.headers)}return r}function TL(e){return e instanceof Ve&&e.status===409&&e.code==="session_not_ready"}async function Us(e,t,a,r){let o=AL(a,r);if(o===null)throw Error(r?"Creating a session requires a non-empty message.":"A session turn requires a non-empty message or inputResponses.");let n=await e.resolveHeaders(a.headers);n.set("content-type","application/json");let s=await fetch(pt(e.host,t),{body:JSON.stringify(o),headers:n,method:"POST",redirect:e.redirect,signal:a.signal??null});if(!s.ok){let i=await s.text();throw new Ve(s.status,i,s.headers)}return s}async function Bs(e,t){let a=await e.json(),r=(typeof a.sessionId=="string"?a.sessionId:void 0)??e.headers.get(kc)?.trim()??t;if(!r)throw Error("Message route did not return a session id.");return{sessionId:r,deliveryId:typeof a.deliveryId=="string"&&a.deliveryId.length>0?a.deliveryId:void 0}}function AL(e,t){let a={};e.message!==void 0&&(a.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(a.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(a.turnPolicy=e.turnPolicy),e.message!==void 0&&e.taskDeliveryPolicy!==void 0&&(a.taskDeliveryPolicy=e.taskDeliveryPolicy),e.clientContext!==void 0&&(a.clientContext=e.clientContext);let r=rf(e.outputSchema);return r!==void 0&&(a.outputSchema=r),t&&a.message===void 0||a.message===void 0&&a.inputResponses===void 0?null:a}var Ns=class{#t;constructor(e){this.#t=e}async create(e={}){return"message"in e?await pr.create(this.#t,e):{session:await pr.prewarm(this.#t,e)}}attach(e,t){if(e.length===0)throw Error("sessionId must be a non-empty string.");return new pr(this.#t,{sessionId:e,streamIndex:t?.streamIndex??0})}};function lf(e,t){let a=new TextEncoder().encode(`${e}:${t}`),r=Array.from(a,o=>String.fromCodePoint(o)).join("");return btoa(r)}import{z as Mo}from"zod";var uf=Mo.object({ok:Mo.literal(!0),status:Mo.literal("ready"),workflowId:Mo.string().min(1)}).strict();import{z as h}from"zod";var Fo=h.discriminatedUnion("kind",[h.object({kind:h.literal("application")}).strict(),h.object({feature:h.string(),kind:h.literal("framework")}).strict(),h.object({kind:h.literal("extension"),namespace:h.string(),packageName:h.string()}).strict()]),ff=h.discriminatedUnion("kind",[h.object({externalDependencies:h.array(h.string()),extensionScope:h.object({namespace:h.string(),sourceRoot:h.string()}).strict().optional(),kind:h.literal("filesystem"),sourcePath:h.string()}).strict(),h.object({dependencies:h.record(h.string(),h.string()).optional(),kind:h.literal("programmatic"),moduleId:h.string(),parameters:h.record(h.string(),h.unknown()).optional(),registryId:h.string(),revision:h.string(),semanticRevision:h.string().optional()}).strict()]),pf=h.object({backing:ff,logicalPath:h.string(),owner:Fo}).strict(),Lt=h.object({binding:pf.optional(),exportName:h.string().optional(),logicalPath:h.string(),owner:Fo,sourceId:h.string(),sourceKind:h.enum(["markdown","module","skill-package"])}).strict(),Zt=Lt.extend({name:h.string()}).strict(),mr=Lt.extend({eventNames:h.array(h.string()),slug:h.string()}).strict(),PL=h.discriminatedUnion("kind",[h.object({kind:h.literal("gateway"),target:h.string(),byok:h.string().optional()}).strict(),h.object({kind:h.literal("external"),provider:h.string()}).strict()]),RL=h.union([h.object({kind:h.literal("external"),provider:h.string()}).strict(),h.object({kind:h.literal("chatgpt"),state:h.enum(["checking","ready","signed-out","reauth-required","unavailable"]),accountLabel:h.string().optional()}).strict(),h.object({kind:h.literal("gateway"),connected:h.literal(!0),credential:h.enum(["api-key","oidc","oauth"]),team:h.optional(h.string())}).strict(),h.object({kind:h.literal("gateway"),connected:h.literal(!1)}).strict()]),df={contextWindowTokens:h.number().optional(),providerOptions:h.unknown().optional(),reasoning:h.enum(["provider-default","none","minimal","low","medium","high","xhigh"]).optional().catch(void 0),source:Lt.optional()},EL=h.union([h.object({...df,endpoint:RL.optional(),id:h.string(),routing:PL}).strict(),h.object({...df,endpoint:h.never().optional(),id:h.never().optional(),routing:h.object({kind:h.literal("dynamic"),resolver:mr}).strict()}).strict()]),ML=Zt.extend({description:h.string(),hasAuth:h.boolean(),hasExecute:h.boolean(),hasModelOutputProjection:h.boolean(),hasOutputSchema:h.boolean(),inputSchema:h.unknown(),outputSchema:h.unknown().optional(),requiresApproval:h.boolean()}).strict(),FL=Zt.extend({description:h.string(),license:h.string().optional(),markdown:h.string(),metadata:h.record(h.string(),h.string()).optional()}).strict(),_L=Zt.extend({content:h.string(),role:h.enum(["system","user"])}).strict(),DL=Zt.extend({cron:h.string(),hasRun:h.boolean(),markdown:h.string().optional()}).strict(),mf=h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS","WEBSOCKET"]),BL=Zt.extend({adapterKind:h.string().optional(),method:mf,urlPath:h.string()}).strict(),OL=h.object({backing:h.union([ff,h.object({kind:h.literal("resource"),sourcePath:h.string()}).strict()]),form:h.enum(["derived","direct"]),layer:h.enum(["framework-default","extension-package","extension-override","application"]),logicalPath:h.string(),owner:Fo,sourceId:h.string()}).strict(),UL=h.object({method:mf,source:OL,urlPath:h.string(),winnerSourceId:h.string()}).strict(),NL=Lt.extend({connectionName:h.string(),description:h.string(),hasApproval:h.boolean(),hasAuthorization:h.boolean(),hasHeaders:h.boolean(),protocol:h.string(),toolFilter:h.unknown().optional(),url:h.string()}).strict(),qL=Lt.extend({eventNames:h.array(h.string()),slug:h.string()}).strict(),HL=Lt.extend({description:h.string().optional(),slot:h.string(),visibility:h.enum(["scope","session"])}).strict(),$L=Lt.extend({provider:h.string().optional(),environmentExportName:h.string().optional(),revisionHash:h.string()}).strict(),WL=Zt.extend({configResolver:mr.optional(),description:h.string().optional(),entryPath:h.string(),nodeId:h.string(),parentNodeId:h.string(),rootPath:h.string(),summary:h.object({channels:h.number(),connections:h.number(),hooks:h.number(),instructions:h.number(),memories:h.number(),schedules:h.number(),skills:h.number(),tools:h.number()}).strict()}).strict(),jL=Zt.extend({description:h.string(),nodeId:h.string(),parentNodeId:h.string(),url:h.string().optional()}).strict(),zL=h.object({action:h.enum(["subagent-call","task-cancel","workflow-tool-call"]).optional(),audience:h.array(h.enum(["root-session","delegated-task-child"])),kind:h.enum(["dispatch","provider-tool"]),sourceId:h.string()}).strict(),cf=h.object({kind:h.enum(["disabled","shadowed"]),logicalPath:h.string(),owner:Fo,sourceId:h.string(),winnerSourceId:h.string().optional()}).strict(),hf=h.object({agent:h.object({agentRoot:h.string(),appRoot:h.string(),config:Lt.extend({binding:pf}).strict(),description:h.string().optional(),model:EL,name:h.string(),nodeId:h.string(),outputSchema:h.unknown().optional()}).strict(),capabilities:h.object({devRoutes:h.boolean()}).strict(),channels:h.object({routes:h.array(BL),shadowed:h.array(UL)}).strict(),composition:h.object({disabled:h.array(cf),shadowed:h.array(cf)}).strict(),connections:h.array(NL),diagnostics:h.object({discoveryErrors:h.number(),discoveryWarnings:h.number()}).strict(),hooks:h.array(qL),instructions:h.object({dynamic:h.array(mr),static:h.array(_L)}).strict(),instrumentation:Lt.optional(),kernelEffects:h.array(zL),kind:h.literal("eve-agent-info"),memories:h.array(HL),mode:h.enum(["development","production"]),remoteAgents:h.object({entries:h.array(jL),total:h.number()}).strict(),sandbox:$L,schedules:h.array(DL),skills:h.object({dynamic:h.array(mr),static:h.array(FL)}).strict(),subagents:h.object({local:h.array(WL),total:h.number()}).strict(),tools:h.object({dynamic:h.array(mr),static:h.array(ML)}).strict(),version:h.literal(5),workspace:h.object({resourceRoot:h.unknown(),rootEntries:h.array(h.string())}).strict()}).strict().superRefine((e,t)=>{let a=(n,s,i)=>{let l=new Set;n.forEach((u,d)=>{let c=s(u);l.has(c)&&t.addIssue({code:"custom",message:`Duplicate public identity "${c}".`,path:[...i,d]}),l.add(c)})},r=(n,s,i)=>{(!Number.isSafeInteger(n)||n<0||n!==s.length)&&t.addIssue({code:"custom",message:`Expected total ${s.length}, received ${n}.`,path:[...i]})};a(e.tools.static,n=>n.name,["tools","static"]),a(e.tools.dynamic,n=>n.slug,["tools","dynamic"]),a(e.skills.static,n=>n.name,["skills","static"]),a(e.skills.dynamic,n=>n.slug,["skills","dynamic"]),a(e.instructions.static,n=>n.name,["instructions","static"]),a(e.instructions.dynamic,n=>n.slug,["instructions","dynamic"]),a(e.schedules,n=>n.name,["schedules"]),a(e.connections,n=>n.connectionName,["connections"]),a(e.hooks,n=>n.slug,["hooks"]),a(e.memories,n=>n.slot,["memories"]),a(e.channels.routes,n=>`${n.method} ${VL(n.urlPath)}`,["channels","routes"]),a(e.subagents.local,n=>n.nodeId,["subagents","local"]),a(e.remoteAgents.entries,n=>n.nodeId,["remoteAgents","entries"]),r(e.subagents.total,e.subagents.local,["subagents","total"]),r(e.remoteAgents.total,e.remoteAgents.entries,["remoteAgents","total"]);let o=[[e.agent.config,["agent","config"]],...e.agent.model.source===void 0?[]:[[e.agent.model.source,["agent","model","source"]]],...e.agent.model.routing.kind==="dynamic"?[[e.agent.model.routing.resolver,["agent","model","routing","resolver"]]]:[],...e.channels.routes.map((n,s)=>[n,["channels","routes",s]]),...e.connections.map((n,s)=>[n,["connections",s]]),...e.hooks.map((n,s)=>[n,["hooks",s]]),...e.instructions.dynamic.map((n,s)=>[n,["instructions","dynamic",s]]),...e.instructions.static.map((n,s)=>[n,["instructions","static",s]]),...e.memories.map((n,s)=>[n,["memories",s]]),...e.instrumentation===void 0?[]:[[e.instrumentation,["instrumentation"]]],...e.remoteAgents.entries.map((n,s)=>[n,["remoteAgents","entries",s]]),...e.schedules.map((n,s)=>[n,["schedules",s]]),...e.skills.dynamic.map((n,s)=>[n,["skills","dynamic",s]]),...e.skills.static.map((n,s)=>[n,["skills","static",s]]),...e.subagents.local.flatMap((n,s)=>n.configResolver===void 0?[]:[[n.configResolver,["subagents","local",s,"configResolver"]]]),...e.tools.dynamic.map((n,s)=>[n,["tools","dynamic",s]]),...e.tools.static.map((n,s)=>[n,["tools","static",s]]),[e.sandbox,["sandbox"]]];for(let[n,s]of o){if(n.sourceKind==="module"&&n.binding===void 0){t.addIssue({code:"custom",message:"Module source is missing its compiled binding.",path:[...s,"binding"]});continue}if(n.sourceKind!=="module"&&n.binding!==void 0){t.addIssue({code:"custom",message:`${n.sourceKind} source cannot carry a module binding.`,path:[...s,"binding"]});continue}n.binding!==void 0&&(n.binding.logicalPath!==n.logicalPath&&t.addIssue({code:"custom",message:"Source and binding logical paths do not match.",path:[...s,"binding","logicalPath"]}),JSON.stringify(n.binding.owner)!==JSON.stringify(n.owner)&&t.addIssue({code:"custom",message:"Source and binding owners do not match.",path:[...s,"binding","owner"]}))}});function VL(e){return e.replace(/^\/+|\/+$/g,"").split("/").map(t=>t.startsWith(":")||/^\[[^\]]+\]$/.test(t)?":":t).join("/")}var gf="x-vercel-trusted-oidc-idp-token";var Hs=class{#t;#e;#a;#r;sessions;constructor(e){this.#a=e.host,this.#t=e.auth,this.#e=e.headers,this.#r=e.redirect,this.sessions=new Ns({host:this.#a,redirect:this.#r,resolveHeaders:t=>this.#n(t)})}async health(){let e=pt(this.#a,wc),t=await this.#n(),a=await fetch(e,wf({headers:t},this.#r));if(!a.ok){let n=await a.text();throw new Ve(a.status,n,a.headers)}let r;try{r=await a.json()}catch{throw new Ro}let o=uf.safeParse(r);if(!o.success)throw new Ro(o.error.issues.slice(0,5).map(n=>{let s=n.path.join(".");return s.length===0?n.message:`${s}: ${n.message}`}));return o.data}async info(e={}){let t=await this.fetch(Ic,e);if(!t.ok){let o=await t.text();throw new Ve(t.status,o,t.headers)}let a;try{a=await t.json()}catch{throw new Po}let r=hf.safeParse(a);if(!r.success)throw new Po(r.error.issues.slice(0,5).map(o=>{let n=o.path.join(".");return n.length===0?o.message:`${n}: ${o.message}`}));return r.data}async fetch(e,t={}){let a=pt(this.#a,e),r=await this.#n(KL(t.headers));return await fetch(a,wf({...t,headers:r},this.#r))}async#n(e){let t=new Headers,[a,r]=await Promise.all([GL(this.#e),this.#u()]);for(let[o,n]of Object.entries(a))t.set(o,n);for(let[o,n]of Object.entries(r))t.set(o,n);if(e)for(let[o,n]of Object.entries(e))t.set(o,n);return t}async#u(){let e=this.#t;if(!e)return{};if("vercelOidc"in e){let t=(await qs(e.vercelOidc.token)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`,[gf]:t}}if("bearer"in e){let t=(await qs(e.bearer)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`}}if("basic"in e){let t=await qs(e.basic.password);return{authorization:`Basic ${lf(e.basic.username,t)}`}}return{}}};async function qs(e){return typeof e=="function"?e():e}async function GL(e){return e===void 0?{}:typeof e=="function"?await e():e}function KL(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function wf(e,t){return t===void 0?e:{...e,redirect:t}}function $s(){let e=new Set;return{admit(t){let a=t.meta?.id;return a===void 0||!e.has(a)&&(e.add(a),!0)},get size(){return e.size}}}var If=class{#t=new AbortController;#e=new Set;#a=Promise.withResolvers();caughtUp=this.#a.promise;#r=!1;#n;#u;#g;constructor(e,t){this.setOptions(t),this.caughtUp.catch(()=>{}),t.catchUp||this.#a.resolve(),(async()=>{try{for await(let a of sf(e,{signal:this.#t.signal,resolveHeaders:()=>this.#u,resolveReconnectPolicy:()=>this.#g,startIndex:t.startIndex,onCaughtUp:t.catchUp?()=>this.#a.resolve():void 0})){if(this.#t.signal.aborted)return;t.onEvent(a);for(let r of this.#e)r.push(a);if(a.type==="session.completed"||a.type==="session.failed")break}this.#a.resolve(),this.#p()}catch(a){this.#a.reject(a),this.#p(a),this.#t.signal.aborted||t.onError(a)}})()}subscribe(e){let t=new XL(()=>this.#e.delete(t),e);return this.#r?t.end(this.#n):this.#e.add(t),t}get ended(){return this.#r}setOptions(e){"headers"in e&&(this.#u=e.headers),"streamReconnectPolicy"in e&&(this.#g=e.streamReconnectPolicy)}close(){let e=new DOMException("Session stream was detached.","AbortError");this.#t.abort(e),this.#a.reject(e),this.#p(e)}#p(e){if(!this.#r){this.#r=!0,this.#n=e;for(let t of this.#e)t.end(e)}}},XL=class{#t=[];#e=Promise.withResolvers();#a=!1;#r;#n;constructor(e,t){let a=()=>this.end(t?.reason);t?.addEventListener("abort",a,{once:!0}),this.#n=()=>{t?.removeEventListener("abort",a),e()},t?.aborted&&a()}push(e){this.#a||(this.#t.push(e),this.#e.resolve())}end(e){this.#a||(this.#a=!0,this.#r=e,this.#e.resolve())}[Symbol.dispose](){this.end(),this.#t=[],this.#n()}discard(){this.#t=[]}async*[Symbol.asyncIterator](){for(;;){for(;this.#t.length>0;)yield this.#t.shift();if(this.#a){if(this.#r!==void 0)throw this.#r;return}this.#e=Promise.withResolvers(),await this.#e.promise}}};var xf=class{#t;#e;#a;constructor(e,t){this.#t=e,this.#e=t,this.#a=this.#r()}get data(){return this.#a}reset(){this.#e=[],this.#a=this.#t.initial()}append(e){this.#e=[...this.#e,e],this.#a=this.#t.reduce(this.#a,e)}remove(e){this.#e=this.#e.filter(t=>!e(t)),this.#a=this.#r()}replace(e,t){let a=this.#e.findIndex(e);this.#e=a===-1?[...this.#e,t]:this.#e.map((r,o)=>o===a?t:r),this.#a=this.#r()}#r(){let e=this.#t.initial();for(let t of this.#e)e=this.#t.reduce(e,t);return e}};function Lf(e){let t=e.at(-1);return t!==void 0&&Qe(t)&&(t.type!=="session.waiting"||JL(e).size===0)}function JL(e){let t=new Set;for(let a of e)Jt(t,a);return t}function Ws(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error("A turn requires exactly one of message or inputResponses.")}var yf=0;function Sf(){let e=globalThis.crypto?.randomUUID;return e===void 0?(yf+=1,`submission_${yf.toString()}`):e.call(globalThis.crypto)}function hr(e,t){return e?AbortSignal.any([e,t]):t}function Cf(e){if(typeof e=="string")return e;let t=[];for(let a of e)a.type==="text"?t.push(a.text):a.type==="file"&&t.push(a.filename?`[file: ${a.filename}]`:"[file]");return t.join(`
|
|
22
|
-
`)}function js(e){return e instanceof Error&&e.name==="AbortError"}function bf(e){if(e.type!=="session.failed")return;let t=Error(e.data.message);return t.name=e.data.code,t}function zs(e){let t=Promise.withResolvers(),a=Promise.withResolvers(),r={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>e(r),completion:a.promise,followUpDispatches:new Set,receivedFollowUps:0,receivedFollowUpEvents:new Map,followUpSubmissionIds:new Set,resolveCompletion:a.resolve,response:t.promise,resolveResponse:t.resolve};return r}async function Vs(e,t,a){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps))for await(let r of t){if(!a())return;if(e.receivedFollowUps+=e.receivedFollowUpEvents.get(r)??0,e.receivedFollowUpEvents.delete(r),Qe(r)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async function gr(e,t){if(t===void 0)return await e;let a=Promise.withResolvers(),r=()=>a.reject(t.reason);t.addEventListener("abort",r,{once:!0}),t.aborted&&r();try{return await Promise.race([a.promise,e])}finally{t.removeEventListener("abort",r)}}var vf=class{#t;#e;#a=[];constructor(e,t){this.#e=e,this.#t=t}reset(){this.#a=[]}submit(e,t){if(e.message===void 0)return;let a={createdAt:Date.now(),eventStartIndex:t,id:Sf(),message:Cf(e.message),requiresDeliveryId:!0};return this.#a=[...this.#a,a],this.#t&&this.#e.append({data:{createdAt:a.createdAt,message:a.message,submissionId:a.id},type:"client.message.submitted"}),a.id}apply(e){if(e.type!=="message.received"){this.#e.append(e);return}if(e.data.kind==="execution.background_task"){this.#e.append(e);return}let t=this.#r(e);if(t.length===0){this.#e.append(e);return}return this.#n(t,e,!1)}correlate(e,t,a){if(e===void 0)return;this.#a=this.#a.map(o=>o.id===e?{...o,deliveryId:t,requiresDeliveryId:t!==void 0}:o);let r=this.#a.find(o=>o.id===e);if(r!==void 0)for(let o of a.slice(r.eventStartIndex)){if(o.type!=="message.received"||o.data.kind==="execution.background_task")continue;let n=this.#r(o);if(n.some(s=>s.id===e))return this.#n(n,o,!0)}}fail(e,t){let a=t===void 0?this.#a[0]:this.#a.find(r=>r.id===t);a!==void 0&&(this.#a=this.#a.filter(r=>r.id!==a.id),this.#e.replace(r=>r.type==="client.message.submitted"&&r.data.submissionId===a.id,{data:{createdAt:a.createdAt,error:{message:e.message},message:a.message,submissionId:a.id},type:"client.message.failed"}))}failAll(e){for(let t of this.#a)this.fail(e,t.id)}#r(e){return this.#a.filter(t=>t.deliveryId===void 0?!t.requiresDeliveryId:e.meta.deliveryIds?.includes(t.deliveryId)===!0)}#n(e,t,a){let r=e.map(n=>n.id),o=new Set(r);return this.#a=this.#a.filter(n=>!o.has(n.id)),a||this.#e.replace(n=>n.type==="client.message.submitted"&&n.data.submissionId===r[0],t),this.#e.remove(n=>n.type==="client.message.submitted"&&o.has(n.data.submissionId)),{alreadyProjected:a,event:t,ids:r}}};var QL=Symbol("detachEveAgentStore"),YL=Symbol("attachEveAgentStore"),Gs=class{#t;#e;#a=!1;#r;#n=new Set;#u;#g;#p;#C=new Set;#b=$s();#l;#c={};#i;#m;#h;#w=0;#I;#S;#x;#s;#y;#o="ready";constructor(e){this.#e=e.prewarm??!1,this.#u=e.session!==void 0,this.#t=this.#u?void 0:new Hs({auth:e.auth,headers:e.headers,host:e.host??""});let t=[];for(let a of e.initialEvents??[])this.#b.admit(a)&&t.push(a),Jt(this.#n,a);this.#m=t,this.#p=new xf(e.reducer,this.#m),this.#g=e.optimistic??!0,this.#h=new vf(this.#p,this.#g),this.#s=e.session??(e.initialSession===void 0?void 0:this.#t?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#y=this.#R()}get snapshot(){return this.#y}setCallbacks(e){this.#c=e}subscribe(e){return this.#C.add(e),()=>{this.#C.delete(e)}}prewarm(){if(this.#I!==void 0)return this.#I;if(this.#s!==void 0||this.#u)return Promise.resolve();if(this.#l!==void 0)return this.#l.response.then(n=>{if(n===void 0)throw this.#i??new DOMException("Session creation was aborted.","AbortError")});let e=this.#t;if(e===void 0)return Promise.reject(Error("This eve agent store does not own a session client."));let t=this.#w,a=new AbortController;this.#S=a;let r=(async()=>{try{let n=await e.sessions.create({signal:a.signal});if(t!==this.#w)return;this.#s=n.session,this.#i=void 0,this.#o==="error"&&(this.#o="ready"),this.#c.onSessionChange?.(n.session.state),this.#f(),this.#L()}catch(n){throw t===this.#w&&this.#l===void 0&&this.#i===void 0&&(this.#i=Xt(n),this.#o="error",this.#c.onError?.(this.#i),this.#f()),n}})();this.#I=r;let o=()=>{this.#I===r&&(this.#I=void 0,this.#S=void 0)};return r.then(o,o),r}async send(e){return await this.#k(e,this.#c.prepareSend)}async#k(e,t){if(this.#l!==void 0){if(this.#o==="resuming")throw Error("eve session is resuming.");return await this.#M(this.#l,e,t)}let a=zs(o=>o.acceptedFollowUps>0&&this.#s!==void 0?this.#s.cancel():o.response.then(n=>n===void 0?{status:"no_active_turn"}:n.cancel()));this.#l=a,this.#i=void 0,this.#o="submitted",this.#f();let r;try{let o=await(t===void 0?e:gr(Promise.resolve(t(e)),hr(e.signal,a.abortController.signal)));if(Ws(o),!this.#d(a))return;let n=this.#h.submit(o,this.#m.length);this.#_(o),this.#f();let s={...o,signal:hr(o.signal,a.abortController.signal)},i=await this.#F(s),l=i.response;if(r=i.reader,!this.#d(a))return;a.resolveResponse(l),this.#v(this.#h.correlate(n,Rs(l),this.#m))&&this.#f();for await(let u of _c(l,r)){if(!this.#d(a))return;a.receivedFollowUps+=a.receivedFollowUpEvents.get(u)??0,a.receivedFollowUpEvents.delete(u)}if(!this.#d(a)||(await Vs(a,r,()=>this.#d(a)),!this.#d(a)))return;this.#o=this.#i===void 0?"ready":"error"}catch(o){if(!this.#d(a))return;if(js(o))this.#o="ready",this.#h.fail(Xt(o));else{let n=this.#i!==void 0;this.#i??=Xt(o),this.#o="error",this.#h.fail(this.#i),n||this.#c.onError?.(this.#i)}}finally{r?.[Symbol.dispose](),this.#A(a)}}resume(){if(this.#x!==void 0)return this.#x;let e=this.#E();this.#x=e;let t=()=>{this.#x===e&&(this.#x=void 0)};return e.then(t,t),e}async#E(){if(this.#o==="resuming"||this.#o==="streaming"||this.#o==="submitted")throw Error("eve session is already processing a turn.");if(this.#s===void 0)throw Error("An eve session is required before resuming.");let e=this.#s,t=zs(()=>e.cancel());this.#l=t,t.resolveResponse(void 0),this.#i=void 0,this.#o="resuming",this.#f();let a;try{let r=this.#L({catchUp:!0,startIndex:this.#m.length===e.state.streamIndex?e.state.streamIndex:0});if(a=r.subscribe(t.abortController.signal),await r.caughtUp,!this.#d(t))return;a.discard();let o=this.#m.at(-1);if(o!==void 0&&this.#P(o),o!==void 0&&this.#i===void 0&&!Lf(this.#m)){this.#o="streaming",this.#f();for await(let n of a){if(!this.#d(t))return;if(t.receivedFollowUps+=t.receivedFollowUpEvents.get(n)??0,t.receivedFollowUpEvents.delete(n),Qe(n)&&this.#n.size===0)break}}await Vs(t,a,()=>this.#d(t)),this.#d(t)&&(this.#o=this.#i===void 0?"ready":"error")}catch(r){if(!this.#d(t))return;js(r)?this.#o="ready":(this.#i=Xt(r),this.#o="error",this.#c.onError?.(this.#i))}finally{a?.[Symbol.dispose](),this.#A(t)}}cancel(){let e=this.#l;return e===void 0?this.#o==="streaming"&&this.#s!==void 0?this.#s.cancel():Promise.resolve({status:"no_active_turn"}):e.cancel()}[YL](){this.#a=!0,this.#e&&this.#s===void 0&&this.prewarm().catch(()=>{})}[QL](){this.#a=!1,this.#r?.close(),this.#r=void 0,this.#l?.abortController.abort(),this.#T(),this.#x=void 0}reset(){this.#r?.close(),this.#r=void 0,this.#n.clear();let e=this.#l;this.#l=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#T(),this.#x=void 0,this.#u||(this.#s=void 0),this.#m=[],this.#b=$s(),this.#h.reset(),this.#p.reset(),this.#i=void 0,this.#o="ready",this.#c.onSessionChange?.(this.#s?.state),this.#f(),this.#e&&this.#a&&this.prewarm().catch(()=>{})}async#M(e,t,a){if(t.message===void 0||t.turnPolicy!=="steer")throw Error('eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.');let r=this.#w,o=hr(t.signal,e.abortController.signal),n=await gr(Promise.resolve(a?.(t)),o)??t;if(r!==this.#w)return;if(Ws(n),n.message===void 0||n.turnPolicy!=="steer")throw Error('An in-flight follow-up requires a message with turnPolicy: "steer".');if(!this.#d(e))return await this.#k(n);let s=this.#h.submit(n,this.#m.length);s!==void 0&&e.followUpSubmissionIds.add(s),this.#f(),this.#L({headers:n.headers,streamReconnectPolicy:n.streamReconnectPolicy});let i;i=(async()=>{try{let l=hr(n.signal,e.abortController.signal);if(await gr(e.response,l),!this.#d(e)||this.#s===void 0)throw Error("The active eve turn ended before the follow-up could be sent.");let{message:u,...d}=n,c=await this.#s.send(u,{...d,signal:l});e.acceptedFollowUps+=1,this.#v(this.#h.correlate(s,Rs(c),this.#m))&&this.#f()}catch(l){throw this.#d(e)&&(this.#h.fail(Xt(l),s),this.#f()),l}finally{e.followUpDispatches.delete(i)}})(),e.followUpDispatches.add(i),await i,await e.completion}async#F(e){let t={headers:e.headers,streamReconnectPolicy:e.streamReconnectPolicy};if(this.#I!==void 0&&(await gr(this.#I.catch(r=>{if(this.#s!==void 0)throw r}),e.signal),e.signal?.throwIfAborted()),this.#s===void 0){if(this.#t===void 0)throw Error("An external eve session is required before sending.");if(e.message===void 0)throw Error("Cannot answer an input request before the session starts.");let r=await this.#t.sessions.create({...e,message:e.message});return e.signal?.throwIfAborted(),this.#s=r.session,this.#c.onSessionChange?.(r.session.state),this.#f(),{response:r.response,reader:this.#L(t).subscribe(e.signal)}}let a=this.#L(t).subscribe(e.signal);try{if(e.inputResponses===void 0){let{message:n,...s}=e;return{response:await this.#s.send(n,s),reader:a}}let{inputResponses:r,...o}=e;return{response:await this.#s.respond(r,o),reader:a}}catch(r){throw a[Symbol.dispose](),r}}#L(e={}){if(this.#r!==void 0&&!this.#r.ended)return this.#r.setOptions(e),this.#r;if(this.#s===void 0)throw Error("A session is required before opening its stream.");let t=this.#s,a=this.#w;return this.#r=new If(t,{...e,onEvent:r=>{a===this.#w&&this.#D(r)},onError:r=>{a===this.#w&&(this.#r=void 0,this.#l===void 0&&(this.#i=Xt(r),this.#o="error",this.#c.onError?.(this.#i),this.#f()))}}),this.#r}#T(){this.#w+=1,this.#S?.abort(),this.#S=void 0,this.#I=void 0}#A(e){if(this.#d(e)){e.resolveResponse(void 0),this.#l=void 0;try{this.#c.onSessionChange?.(this.#s?.state),this.#f(),this.#c.onFinish?.(this.#y)}finally{e.resolveCompletion()}}}#d(e){return this.#l===e}#_(e){e.inputResponses!==void 0&&e.inputResponses.length!==0&&this.#p.append({data:{createdAt:Date.now(),responses:e.inputResponses},type:"client.input.responded"})}#D(e){if(!this.#b.admit(e))return;let t=this.#o==="streaming";Jt(this.#n,e),this.#m=[...this.#m,e],this.#v(this.#h.apply(e)),this.#c.onEvent?.(e),this.#P(e);let a=Qe(e)&&this.#n.size===0;this.#o!=="resuming"&&this.#i===void 0&&("data"in e&&"turnId"in e.data&&(this.#o="streaming"),this.#l===void 0&&a&&(this.#o="ready")),this.#c.onSessionChange?.(this.#s?.state),this.#o!=="resuming"&&this.#f(),this.#l===void 0&&t&&a&&this.#c.onFinish?.(this.#y)}#v(e){if(e===void 0)return!1;let t=0;for(let a of e.ids)this.#l?.followUpSubmissionIds.delete(a)&&(t+=1);if(t>0&&this.#l!==void 0)if(e.alreadyProjected)this.#l.receivedFollowUps+=t;else{let a=this.#l.receivedFollowUpEvents.get(e.event)??0;this.#l.receivedFollowUpEvents.set(e.event,a+t)}return!0}#P(e){let t=bf(e);t!==void 0&&(this.#o="error",this.#h.failAll(t),this.#i===void 0&&(this.#i=t,this.#c.onError?.(t)))}#R(){return{data:this.#p.data,error:this.#i,events:this.#m,session:this.#s?.state,status:this.#o}}#f(){this.#y=this.#R();for(let e of this.#C)e()}};function ZL(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function eS(e){let t=new AbortController;for(let a of e){if(a.aborted)return t.abort(a.reason),t.signal;a.addEventListener("abort",()=>t.abort(a.reason),{once:!0,signal:t.signal})}return t.signal}function kf(){"withResolvers"in Promise||Object.defineProperty(Promise,"withResolvers",{value:ZL,configurable:!0,writable:!0}),"any"in AbortSignal||Object.defineProperty(AbortSignal,"any",{value:eS,configurable:!0,writable:!0})}var tS=3e4;function aS(){let e=crypto.getRandomValues(new Uint8Array(32));return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Xs(e){let t=e.channelId??"";return e.threadId===void 0?t:`${t}:${e.threadId}`}function Ks(e){return`waniwani:eve-conversation:${e}`}function Js(e){try{let t=JSON.parse(localStorage.getItem(Ks(e))??"null");return typeof t=="object"&&t!==null&&"conversationId"in t&&typeof t.conversationId=="string"&&"ownerSecret"in t&&typeof t.ownerSecret=="string"?{conversationId:t.conversationId,ownerSecret:t.ownerSecret}:null}catch{return null}}function ga(e,t){try{t?localStorage.setItem(Ks(e),JSON.stringify(t)):localStorage.removeItem(Ks(e))}catch{}}function Tf(e){return JSON.stringify(e).replace(/[\u007f-\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function rS(e){return{...e.documents?.length?{"x-waniwani-documents":Tf(e.documents)}:{},...e.extra&&Object.keys(e.extra).length>0?{"x-waniwani-extra":Tf(e.extra)}:{}}}var oS={initial:()=>{},reduce:()=>{}},ha=class e{constructor(t,a,r){this.open=t;this.secret=a;this.grant=r,kf(),this.store=new Gs({host:r.eveHost,auth:{bearer:()=>this.bearer()},initialSession:{sessionId:r.sessionId,streamIndex:0},optimistic:!1,reducer:oS}),this.store.setCallbacks({onEvent:o=>this.forward?.(o)}),this.caughtUp=this.store.resume().catch(()=>{})}grant;refreshing=null;store;forward;caughtUp;used=!1;static async create(t){let a=aS(),r=await t.open({operation:"create",requestId:crypto.randomUUID(),ownerSecret:a,channelId:t.channelId,visitorId:t.visitorId});return r?await new e(t.open,a,r).reachable():null}static async resume(t){let a=await t.open({operation:"resume",...t.saved});return a?await new e(t.open,t.saved.ownerSecret,a).reachable():null}async reachable(){return await this.caughtUp,this.store.snapshot.error===void 0?this:(this.close(),null)}get sessionId(){return this.grant.sessionId}get saved(){return{conversationId:this.grant.conversationId,ownerSecret:this.secret}}get followups(){return this.grant.followups}async history(){await this.caughtUp;let{events:t}=this.store.snapshot;return this.used||=t.some(a=>a.type==="message.received"),t}async bearer(){return this.grant.expiresAt-tS>Date.now()?this.grant.accessToken:(this.refreshing??=this.open({operation:"refresh",conversationId:this.grant.conversationId,ownerSecret:this.secret}).then(t=>{if(!t)throw new Error("The conversation left the direct runtime");return this.grant=t,t.accessToken}).finally(()=>{this.refreshing=null}),await this.refreshing)}turn(t,a,r){this.used=!0;let o=()=>{this.store.cancel()};return r?.addEventListener("abort",o,{once:!0}),new ReadableStream({start:async s=>{let i=!1;this.forward=u=>{i||=u.type==="turn.failed"||u.type==="session.failed",s.enqueue(u)},await this.caughtUp;let l=await this.store.send({message:t,signal:r,headers:rS(a)}).then(()=>this.store.snapshot.error,u=>u instanceof Error?u:new Error(String(u)));this.forward=void 0,r?.removeEventListener("abort",o),l&&!i&&!r?.aborted&&s.enqueue({type:"session.failed",data:{code:"transport_failed",message:l.message,sessionId:this.sessionId}}),s.close()}}).pipeThrough(To())}close(){this.forward=void 0,this.store.reset()}};function wa(e,t){let a=e[t];return typeof a=="string"&&a?a:void 0}function nS(e){let t=e.visitor;return typeof t=="object"&&t!==null&&"id"in t&&typeof t.id=="string"?t.id:void 0}function sS(e){return e.filter(t=>t.role==="user").map(t=>t.parts.flatMap(a=>a.type==="text"?[a.text]:[]).join(`
|
|
23
|
-
`))}function Af(e){return fetch(new URL(e.path,new URL(e.sessionApi,location.href)),{method:"POST",headers:{...e.headers(),"content-type":"application/json"},body:JSON.stringify(e.body),cache:"no-store",signal:e.signal})}function iS(e){return async t=>{let a=await Af({...e,path:"followups",body:t,signal:AbortSignal.timeout(8e3)}),r=a.ok?await a.json():null,o=typeof r=="object"&&r!==null&&"data"in r?r.data:null,n=typeof o=="object"&&o!==null&&"suggestions"in o?o.suggestions:null;return Array.isArray(n)?n.filter(s=>typeof s=="string"):[]}}function lS(e){let t="",a=!1,r=new Set;return new TransformStream({async transform(o,n){if(o.type==="text-delta"&&(t+=o.delta),o.type==="tool-input-available"&&r.add(o.toolName),o.type==="error"&&(a=!0),o.type==="finish"&&!a&&!e.signal?.aborted&&t.trim()){let s=await e.suggest(t,[...r]).catch(()=>[]);s.length>0&&n.enqueue({type:"data-suggestions",data:{suggestions:s}})}n.enqueue(o)}})}function uS(e){return async t=>{let a=await Af({...e,path:e.sessionApi,body:t});if(!a.ok)throw new Error(`Opening the chat failed (${a.status})`);let r=await a.json(),o=typeof r=="object"&&r!==null&&"data"in r?r.data:null;if(typeof o!="object"||o===null||!("transport"in o))throw new Error("The session route answered no transport");if(o.transport!=="eve-native")return null;let n={...o},s=n.session,i=typeof s=="object"&&s!==null&&"sessionId"in s?s.sessionId:void 0,l=wa(n,"conversationId"),u=wa(n,"eveHost"),d=wa(n,"accessToken"),c=Date.parse(wa(n,"expiresAt")??"");if(!l||!u||!d||typeof i!="string"||Number.isNaN(c))throw new Error("The session route answered an incomplete session");return{conversationId:l,eveHost:u,sessionId:i,accessToken:d,expiresAt:c,followups:n.followups===!0}}}function dS(e){let t=e.extra;return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t)):void 0}var Qs=class{constructor(t){this.options=t}pending;threadOnFallback=!1;generation=0;get channelId(){return wa(this.options.body(),"channelId")}key(){return Xs({channelId:this.channelId,threadId:this.options.threadId()})}keepsSession(){return this.options.open!==void 0}prepare(){this.open(this.options.hasMessages())}open(t){this.options.open&&(this.pending??=this.start(this.options.open,t))}async restore(){let{open:t}=this.options;if(!t||this.options.threadHistory())return[];let a=this.key(),r=Js(a);if(!r)return[];let o=this.generation,n=ha.resume({open:t,saved:r}).catch(()=>null).then(i=>this.kept(i,o));this.pending=n;let s=await n;return s?await mc(await s.history()):(ga(a,null),this.pending===n&&(this.pending=void 0),[])}reset(){ga(this.key(),null),this.dispose()}forget(t){ga(Xs({channelId:this.channelId,threadId:t}),null)}dispose(){this.generation+=1,this.threadOnFallback=!1,this.pending?.then(t=>t?.close()).catch(()=>{}),this.pending=void 0}async start(t,a){let r=this.generation,o=this.key(),n=Js(o);if(n){let u=await ha.resume({open:t,saved:n}).catch(()=>null);return!u&&r===this.generation&&ga(o,null),this.kept(u,r)}if(a)return null;let s=this.options.body(),i=await ha.create({open:t,channelId:wa(s,"channelId"),visitorId:nS(s)}),l=this.kept(i,r);return r===this.generation&&ga(o,l?.saved??null),l}kept(t,a){return t&&a!==this.generation?(t.close(),null):t}async sendMessages(t){let a=t.messages.filter(f=>f.role==="user").length<=1;a&&(this.threadOnFallback=!1);let o=[...t.messages].reverse().find(f=>f.role==="user")?.parts.some(f=>f.type==="file")??!1;if(this.threadOnFallback||o||!this.options.open)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.open(!a);let n=await this.pending?.catch(()=>null);if(n?.used&&a&&(this.reset(),this.open(!1),n=await this.pending?.catch(()=>null)),!n)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.options.onSession(n.sessionId);let{documents:s}=this.options.takeTurnInput(),i=sS(t.messages),l=i.at(-1)??"",u=l.trim()?l:s?.map(f=>f.filename).join(", ")??l,d=n.turn(u,{documents:s,extra:dS(this.options.body())},t.abortSignal),{suggest:c}=this.options;if(!n.followups||!c)return d;let{saved:p}=n;return d.pipeThrough(lS({suggest:(f,m)=>c({...p,answerText:f.slice(-8e3),recentUserMessages:i.slice(-3).map(y=>y.slice(-2e3)),toolNames:m.slice(0,20)}),signal:t.abortSignal}))}async reconnectToStream(t){return await this.pending?.catch(()=>null)?null:await this.options.fallback.reconnectToStream(t)}};function Pf(e){let t=typeof e=="string"?()=>e:e;return a=>{let r=o=>{let n=t();return n?o(n):void 0};return new Qs({...a,get open(){return r(o=>uS({sessionApi:o,headers:a.headers}))},get suggest(){return r(o=>iS({sessionApi:o,headers:a.headers}))}})}}function Rf(e){let t=cS(e);t.current=e;let[a]=fS(()=>Pf(()=>t.current));return a}import{useEffect as pS,useRef as mS}from"react";function Ys(e,t){return e.find(a=>a.text===t)?.id??null}async function Ef(e){let{api:t,token:a,name:r,source:o,sessionId:n,properties:s}=e;if(typeof window>"u"||!t||!a)return;let i=nr(t);if(i)try{let l=new Date().toISOString(),u=JSON.stringify({sentAt:l,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:r,source:o,timestamp:l,correlation:{visitorId:Ge(),sessionId:n},properties:{...s,url:window.location.href},metadata:{}}]});await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function Mf(e){let{api:t,token:a,channelId:r,mode:o,source:n,sessionId:s,promptId:i,origin:l,text:u,index:d}=e;await Ef({api:t,token:a,name:"suggestion.clicked",source:n,sessionId:s,properties:{promptId:i,origin:l,text:u,index:d,channelId:r,mode:o}})}function Ff(e,t){return t.map(a=>({id:Ys(e,a),text:a}))}async function _f(e){let{api:t,token:a,channelId:r,mode:o,source:n,sessionId:s,prompts:i,origin:l}=e;i.length!==0&&await Ef({api:t,token:a,name:"suggestion.shown",source:n,sessionId:s,properties:{prompts:i,count:i.length,origin:l,channelId:r,mode:o}})}function Df(e){let{widgetEvents:t,api:a,token:r,channelId:o,source:n,mode:s,pagePrompts:i}=e,l=mS(e.getSessionId);l.current=e.getSessionId,pS(()=>{if(!(!a||!r))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:d,origin:c,index:p}=u.properties;Mf({api:a,token:r,channelId:o,mode:s,source:n,sessionId:l.current(),promptId:Ys(i??[],d),origin:c,text:d,index:p});return}if(u.name==="suggestions.shown"){let{texts:d,origin:c}=u.properties;_f({api:a,token:r,channelId:o,mode:s,source:n,sessionId:l.current(),prompts:Ff(i??[],d),origin:c})}})},[t,a,r,o,n,s,i])}function Ia(e,t){for(let a of t){let r=e[a];if(typeof r=="string"&&r.length>0)return r}}var hS=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],gS=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],wS=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],IS=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],xS=["waniwani/visitorId","visitorId"],yS=["correlationId","openai/requestId"];function Bf(e){return e?Ia(e,hS):void 0}function Of(e){return e?Ia(e,gS):void 0}function Uf(e){return e?Ia(e,wS):void 0}function Nf(e){return e?Ia(e,IS):void 0}function qf(e){return e?Ia(e,xS):void 0}function Hf(e){return e?Ia(e,yS):void 0}var LS=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],SS=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function $f(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:n}of LS){let s=e[o];if(typeof s=="string"&&s.length>0)return n}}let a=t?.name;if(typeof a=="string"&&a.length>0){let r=a.toLowerCase();for(let{needle:o,source:n}of SS)if(r.includes(o))return n}}var CS="@waniwani/sdk";function Wf(e,t={}){let a=t.now??(()=>new Date),r=t.generateId??bS,o=TS(e),n=_o(e.meta),s=_o(e.metadata),i=AS(e,n),l=ot(e.eventId)??r(),u=PS(e.timestamp,a),d=ot(e.source)??$f(n)??t.source??CS,c=Zs(e)?{...e}:void 0,p={...s};return Object.keys(n).length>0&&(p.meta=n),c&&(p.rawLegacy=c),{id:l,type:"mcp.event",name:o,source:d,timestamp:u,correlation:i,properties:vS(e,o),metadata:p,rawLegacy:c}}function bS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function vS(e,t){if(!Zs(e))return _o(e.properties);let a=kS(e,t),r=_o(e.properties);return{...a,...r}}function kS(e,t){switch(t){case"tool.called":{let a={};return ot(e.toolName)&&(a.name=e.toolName),ot(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return ot(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function TS(e){return Zs(e)?e.eventType:e.event}function AS(e,t){let a=ot(e.requestId)??Of(t),r=ot(e.sessionId)??Bf(t),o=ot(e.traceId)??Uf(t),n=ot(e.externalUserId)??Nf(t),s=ot(e.visitorId)??qf(t),i=ot(e.correlationId)??Hf(t)??a,l={};return r&&(l.sessionId=r),o&&(l.traceId=o),a&&(l.requestId=a),i&&(l.correlationId=i),n&&(l.externalUserId=n),s&&(l.visitorId=s),l}function PS(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let a=new Date(e);if(!Number.isNaN(a.getTime()))return a.toISOString()}return t().toISOString()}function _o(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function ot(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Zs(e){return"eventType"in e}function jf(e){return{priceShown:({amount:t,currency:a,itemId:r,label:o,...n})=>e({event:"price_shown",properties:{amount:t,currency:a,itemId:r,label:o},...n}),pricesCompared:({options:t,...a})=>e({event:"prices_compared",properties:{options:t},...a}),optionSelected:({id:t,amount:a,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:a,currency:r},...o}),leadQualified:t=>{let{externalId:a,email:r,name:o,...n}=t??{};return e({event:"lead_qualified",properties:{externalId:a,email:r,name:o},...n})},converted:({amount:t,currency:a,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:a,occurredAt:r},...o})}}var RS="/api/mcp/events/v2/batch";var zf="@waniwani/sdk";var ES=new Set([401,403]),MS=new Set([408,425,429,500,502,503,504]),FS=(e,t)=>globalThis.fetch(e,t);function Vf(e){return new ei(e)}var ei=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=BS(t.apiUrl,t.endpointPath??RS),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??FS,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(a=>new Promise(r=>setTimeout(r,a))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let a=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,a),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",a)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let a=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(a)||a<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(a).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let a=JSON.stringify(this.makeBatchRequest(t));if(a.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:a,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":zf};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let a=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(a)),a+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(a)),a+=1;continue}}}async sendBatchOnce(t){let a;try{a=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(n){return{kind:"retryable",reason:OS(n)}}if(ES.has(a.status))return{kind:"auth",status:a.status};if(MS.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let r=await DS(a);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:zf,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,a){let r=new Map(t.map(s=>[s.id,s])),o=[],n=[];for(let s of a){let i=r.get(s.eventId);if(i){if(_S(s)){o.push(i);continue}n.push(i)}}return{retryable:o,permanent:n}}backoffDelayMs(t){let a=this.retryBaseDelayMs*2**t;return Math.min(a,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,a){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,a+r)}};function _S(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function DS(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function BS(e,t){let a=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${a}${r}`}function OS(e){return e instanceof Error?e.message:String(e)}function Gf(e){let{apiUrl:t,endpointPath:a}=US(e.endpoint),r=Vf({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),o,n=i=>typeof i=="function"?i():i,s=async i=>{let l=e.identity?.()??{},u=n(e.channelId),d=u===void 0?i.properties:{channelId:u,...i.properties},c=Wf({sessionId:l.sessionId,visitorId:l.visitorId,externalUserId:l.externalUserId??o,traceId:l.traceId,...i,properties:d,metadata:{...e.metadata,...i.metadata}},{source:n(e.source)});return r.enqueue(c),{eventId:c.id}};return{track:Object.assign(s,jf(s)),identify(i,l){return o=i,s({event:"user.identified",externalUserId:i,properties:l})},flush:()=>r.flush(),shutdown:i=>r.shutdown(i)}}function US(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function Kf(e){let t=nr(e.api);return t?Gf({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Ge()})}):ti("the chat api does not point at a Waniwani event ingest")}function ti(e){let t=!1,a=async()=>(t||(t=!0,console.warn(`[Waniwani] track() is disabled: ${e}`)),{eventId:""});return{track:Object.assign(a,{priceShown:a,pricesCompared:a,optionSelected:a,leadQualified:a,converted:a}),identify:a,flush:async()=>{},shutdown:async()=>({timedOut:!1,pendingEvents:0})}}import{jsx as Qf}from"react/jsx-runtime";var HS=600,Jf="https://app.waniwani.ai/api/mcp/chat",$S=NS(function(t,a){let{token:r,channelId:o,className:n,visitorId:s,overrides:i,onEvent:l}=t,u=ri(null),d=ri(null),c=ai(()=>Ed({mode:"inline",getSessionId:()=>u.current?.sessionId}),[]);Do(()=>{if(l)return c.subscribe(l)},[l,c]);let p=ai(()=>({token:r,channelId:o,api:i?.api,mcpServerUrl:i?.mcpServerUrl,title:i?.title,hideHeader:i?.hideHeader,welcomeMessage:i?.welcomeMessage,placeholder:i?.placeholder,suggestions:i?.suggestions,enableThreadHistory:i?.enableThreadHistory,showToolCalls:i?.showToolCalls,appearance:i?.appearance,disclaimer:i?.disclaimer,locale:i?.locale}),[r,o,i?.api,i?.mcpServerUrl,i?.title,i?.hideHeader,i?.welcomeMessage,i?.placeholder,i?.suggestions,i?.enableThreadHistory,i?.showToolCalls,i?.appearance,i?.disclaimer,i?.locale]),f=i?.api??Jf,[m,y]=Xf({}),[S,L]=Xf(!1),C=ri(!1);Do(()=>{S&&!C.current&&(C.current=!0,c.emit({name:"chat.ready"}))},[S,c]);let I=i?.disablePageView;Do(()=>{if(!r){L(!0);return}let G=K=>{I||ms({api:f,token:r,channelId:o??K.channelId,mode:"inline",source:K.source})},Q=ko(f,r,o);Q&&(y(Q),Da("cache"),Rr(Q.metadata),L(!0),G(Q));let O=new AbortController,re=setTimeout(()=>{Da("timeout"),L(!0)},HS);return pc(f,r,O.signal,o).then(K=>{O.signal.aborted||(Object.keys(K).length>0&&(fc(f,r,o,K),y(K)),Da("remote"),L(!0),G(K))}).catch(K=>{console.error("[Waniwani] Remote config fetch failed:",K),L(!0)}).finally(()=>clearTimeout(re)),()=>{O.abort(),clearTimeout(re)}},[f,r,o,I]);let x=ai(()=>fs(p,m,void 0),[p,m]),v=dc(x);Df({widgetEvents:c,api:x.api??f,token:x.token??r,channelId:x.channelId??o,source:x.source,mode:"inline",pagePrompts:v.page,getSessionId:()=>u.current?.sessionId}),Do(()=>{if(!r)return;let G=Kf({api:f,token:r,channelId:()=>o??ko(f,r,o)?.channelId,getSource:()=>ko(f,r,o)?.source??void 0,getSessionId:()=>u.current?.sessionId});return d.current=G,()=>{d.current=null,G.shutdown()}},[f,r,o]),qS(a,()=>{let G=()=>d.current??ti("no public token configured"),Q=Object.assign(O=>G().track(O),{priceShown:O=>G().track.priceShown(O),pricesCompared:O=>G().track.pricesCompared(O),optionSelected:O=>G().track.optionSelected(O),leadQualified:O=>G().track.leadQualified(O),converted:O=>G().track.converted(O)});return{sendMessage:O=>u.current?.sendMessage(O),sendMessageAndWait:O=>u.current?u.current.sendMessageAndWait(O):Promise.resolve(void 0),reset:()=>u.current?.reset(),focus:()=>u.current?.focus(),get messages(){return u.current?.messages??[]},get sessionId(){return u.current?.sessionId},track:Q,identify:(O,re)=>G().identify(O,re)}},[]);let q=ic(x.visibility,S);tl({api:x.api??f,token:x.token??r,channelId:x.channelId??o,mode:"inline",paintMark:"chatVisible",painted:S&&q});let N={mode:"inline"};x.mcpServerUrl&&(N.mcpServerUrl=x.mcpServerUrl),x.channelId&&(N.channelId=x.channelId);let V=Rf(i?.sessionApi??x.sessionApi);return q?Qf(_d,{value:c,children:Qf(cs,{ref:u,api:x.api??Jf,transport:V,headers:{Authorization:`Bearer ${x.token}`},visitorId:s,skipRemoteConfig:!0,body:N,appearance:x.appearance,classNames:i?.classNames,title:x.title,hideHeader:x.hideHeader,welcomeMessage:x.welcomeMessage,welcome:i?.welcome,placeholder:x.placeholder,suggestions:v,enableThreadHistory:x.enableThreadHistory,showToolCalls:x.showToolCalls,disclaimer:x.disclaimer,documentUpload:x.documentUpload,allowAttachments:i?.allowAttachments,locale:x.locale,messages:i?.messages,className:n,initializing:!S})}):null});export{cs as ChatEmbed,Tx as DARK_THEME,ac as DEFAULT_THEME,Ba as McpAppFrame,$S as WaniwaniChat,$m as WebMcpOverlay,Px as mergeTheme,ds as themeToCSSProperties};
|
|
21
|
+
- `)}`,Error(E)}let M=`${i}/$ref`,z=Te(e,_,a,r,o,n,s,M,l);if(z.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...z.errors),a==="4"||a==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(m)){let _=m.length,M=!1;for(let z=0;z<_;z++)if(d===m[z]||m[z]==="integer"&&d==="number"&&e%1==0&&e===e){M=!0;break}M||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(d!=="number"||e%1||e!==e)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`}):m!==void 0&&d!==m&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`});if(y!==void 0&&(d==="object"||d==="array"?cr(e,y)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),S!==void 0&&(d==="object"||d==="array"?S.some(_=>cr(e,_))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(_=>e===_)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),C!==void 0){let _=`${i}/not`;Te(e,C,a,r,o,n,s,_).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:_,error:'Instance matched "not" schema.'})}let ye=[];if(I!==void 0){let _=`${i}/anyOf`,M=T.length,z=!1;for(let E=0;E<I.length;E++){let w=I[E],A=Object.create(l),F=Te(e,w,a,r,o,f===!0?n:null,s,`${_}/${E}`,A);T.push(...F.errors),z||=F.valid,F.valid&&ye.push(A)}z?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:_,error:"Instance does not match any subschemas."})}if(x!==void 0){let _=`${i}/allOf`,M=T.length,z=!0;for(let E=0;E<x.length;E++){let w=x[E],A=Object.create(l),F=Te(e,w,a,r,o,f===!0?n:null,s,`${_}/${E}`,A);T.push(...F.errors),z&&=F.valid,F.valid&&ye.push(A)}z?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"allOf",keywordLocation:_,error:"Instance does not match every subschema."})}if(v!==void 0){let _=`${i}/oneOf`,M=T.length,z=v.filter((E,w)=>{let A=Object.create(l),F=Te(e,E,a,r,o,f===!0?n:null,s,`${_}/${w}`,A);return T.push(...F.errors),F.valid&&ye.push(A),F.valid}).length;z===1?T.length=M:T.splice(M,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:_,error:`Instance does not match exactly one subschema (${z} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...ye),q!==void 0){let _=`${i}/if`;if(Te(e,q,a,r,o,n,s,_,l).valid){if(N!==void 0){let M=Te(e,N,a,r,o,n,s,`${i}/then`,l);M.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:_,error:'Instance does not match "then" schema.'},...M.errors)}}else if(V!==void 0){let M=Te(e,V,a,r,o,n,s,`${i}/else`,l);M.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:_,error:'Instance does not match "else" schema.'},...M.errors)}}if(d==="object"){if(L!==void 0)for(let E of L)E in e||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${E}".`});let _=Object.keys(e);if(J!==void 0&&_.length<J&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${J} properties.`}),X!==void 0&&_.length>X&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${X} properties.`}),R!==void 0){let E=`${i}/propertyNames`;for(let w in e){let A=`${s}/${rt(w)}`,F=Te(w,R,a,r,o,n,A,E);F.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:E,error:`Property name "${w}" does not match schema.`},...F.errors)}}if(b!==void 0){let E=`${i}/dependantRequired`;for(let w in b)if(w in e){let A=b[w];for(let F of A)F in e||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:E,error:`Instance has "${w}" but does not have "${F}".`})}}if(D!==void 0)for(let E in D){let w=`${i}/dependentSchemas`;if(E in e){let A=Te(e,D[E],a,r,o,n,s,`${w}/${rt(E)}`,l);A.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:w,error:`Instance has "${E}" but does not match dependant schema.`},...A.errors)}}if(ae!==void 0){let E=`${i}/dependencies`;for(let w in ae)if(w in e){let A=ae[w];if(Array.isArray(A))for(let F of A)F in e||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${w}" but does not have "${F}".`});else{let F=Te(e,A,a,r,o,n,s,`${E}/${rt(w)}`);F.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${w}" but does not match dependant schema.`},...F.errors)}}}let M=Object.create(null),z=!1;if(Q!==void 0){let E=`${i}/properties`;for(let w in Q){if(!(w in e))continue;let A=`${s}/${rt(w)}`,F=Te(e[w],Q[w],a,r,o,n,A,`${E}/${rt(w)}`);if(F.valid)l[w]=M[w]=!0;else if(z=o,T.push({instanceLocation:s,keyword:"properties",keywordLocation:E,error:`Property "${w}" does not match schema.`},...F.errors),z)break}}if(!z&&O!==void 0){let E=`${i}/patternProperties`;for(let w in O){let A=new RegExp(w,"u"),F=O[w];for(let pe in e){if(!A.test(pe))continue;let nt=`${s}/${rt(pe)}`,st=Te(e[pe],F,a,r,o,n,nt,`${E}/${rt(w)}`);st.valid?l[pe]=M[pe]=!0:(z=o,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:E,error:`Property "${pe}" matches pattern "${w}" but does not match associated schema.`},...st.errors))}}}if(!z&&re!==void 0){let E=`${i}/additionalProperties`;for(let w in e){if(M[w])continue;let A=`${s}/${rt(w)}`,F=Te(e[w],re,a,r,o,n,A,E);F.valid?l[w]=!0:(z=o,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:E,error:`Property "${w}" does not match additional properties schema.`},...F.errors))}}else if(!z&&K!==void 0){let E=`${i}/unevaluatedProperties`;for(let w in e)if(!l[w]){let A=`${s}/${rt(w)}`,F=Te(e[w],K,a,r,o,n,A,E);F.valid?l[w]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:E,error:`Property "${w}" does not match unevaluated properties schema.`},...F.errors)}}}else if(d==="array"){Ie!==void 0&&e.length>Ie&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${Ie}).`}),me!==void 0&&e.length<me&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${me}).`});let _=e.length,M=0,z=!1;if(oe!==void 0){let E=`${i}/prefixItems`,w=Math.min(oe.length,_);for(;M<w;M++){let A=Te(e[M],oe[M],a,r,o,n,`${s}/${M}`,`${E}/${M}`);if(l[M]=!0,!A.valid&&(z=o,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:E,error:"Items did not match schema."},...A.errors),z))break}}if(Re!==void 0){let E=`${i}/items`;if(Array.isArray(Re)){let w=Math.min(Re.length,_);for(;M<w;M++){let A=Te(e[M],Re[M],a,r,o,n,`${s}/${M}`,`${E}/${M}`);if(l[M]=!0,!A.valid&&(z=o,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...A.errors),z))break}}else for(;M<_;M++){let w=Te(e[M],Re,a,r,o,n,`${s}/${M}`,E);if(l[M]=!0,!w.valid&&(z=o,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...w.errors),z))break}if(!z&&Ne!==void 0){let w=`${i}/additionalItems`;for(;M<_;M++){let A=Te(e[M],Ne,a,r,o,n,`${s}/${M}`,w);l[M]=!0,A.valid||(z=o,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:w,error:"Items did not match additional items schema."},...A.errors))}}}if(H!==void 0)if(_===0&&$===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if($!==void 0&&_<$)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${_}) than minContains (${$}).`});else{let E=`${i}/contains`,w=T.length,A=0;for(let F=0;F<_;F++){let pe=Te(e[F],H,a,r,o,n,`${s}/${F}`,E);pe.valid?(l[F]=!0,A++):T.push(...pe.errors)}A>=($||0)&&(T.length=w),$===void 0&&ne===void 0&&A===0?T.splice(w,0,{instanceLocation:s,keyword:"contains",keywordLocation:E,error:"Array does not contain item matching schema."}):$!==void 0&&A<$?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${$} items matching schema. Only ${A} items were found.`}):ne!==void 0&&A>ne&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${ne} items matching schema. ${A} items were found.`})}if(!z&&k!==void 0){let E=`${i}/unevaluatedItems`;for(;M<_;M++){if(l[M])continue;let w=Te(e[M],k,a,r,o,n,`${s}/${M}`,E);l[M]=!0,w.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:E,error:"Items did not match unevaluated items schema."},...w.errors)}}if(fe)for(let E=0;E<_;E++){let w=e[E],A=typeof w=="object"&&!!w;for(let F=0;F<_;F++){if(E===F)continue;let pe=e[F];(w===pe||A&&typeof pe=="object"&&pe&&cr(w,pe))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${E} and ${F}.`}),E=2**53-1,F=2**53-1)}}}else if(d==="number"){if(a==="4"?(Z!==void 0&&(se===!0&&e<=Z||e<Z)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${se?"or equal to ":""} ${Z}.`}),W!==void 0&&(xe===!0&&e>=W||e>W)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${xe?"or equal to ":""} ${W}.`})):(Z!==void 0&&e<Z&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${Z}.`}),W!==void 0&&e>W&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${W}.`}),se!==void 0&&e<=se&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${se}.`}),xe!==void 0&&e>=xe&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${xe}.`})),ie!==void 0){let _=e%ie;Math.abs(0-_)>=11920929e-14&&Math.abs(ie-_)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${ie}.`})}}else if(d==="string"){let _=le===void 0&&ee===void 0?0:iL(e);le!==void 0&&_<le&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${_} < ${le}).`}),ee!==void 0&&_>ee&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${_} > ${ee}).`}),ue!==void 0&&!new RegExp(ue,"u").test(e)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),G!==void 0&&Qc[G]&&!Qc[G](e)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${G}".`})}return{valid:T.length===0,errors:T}}var ef=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",a=!0){this.schema=e,this.draft=t,this.shortCircuit=a,this.lookup=Yt(e)}validate(e){return Te(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Yt(e,this.lookup)}};function rf(e){return cL(e,"output")}function uL(e,t){let a=()=>structuredClone(e),r={"~standard":{version:1,vendor:"eve",validate:mL(e,t),jsonSchema:{input:a,output:a}}};return dL.add(r),r}var dL=new WeakSet,h1=uL({});function cL(e,t){return e==null?e:fL(e,t)}function fL(e,t){let a=pL(e),r=a?.jsonSchema,o=typeof r=="object"&&r?r[t]:void 0,n=typeof a?.vendor=="string"?a.vendor:"unknown";if(a!==void 0&&typeof o!="function"&&n==="zod"){if(t==="input"){let l=lL(e),{$schema:u,...d}=sr(l.jsonSchema);return d}throw Error("Zod 3 cannot emit an output JSON Schema. Upgrade to Zod 4 or provide a plain JSON Schema object.")}if(a!==void 0&&typeof o!="function")throw Error(`Standard Schema vendor "${n}" does not support JSON Schema conversion. Provide a Standard Schema implementation with JSON Schema conversion or a plain JSON Schema object.`);let{$schema:s,...i}=sr(a===void 0?e:o({target:"draft-07"}));return i}function pL(e){if(typeof e!="object"||!e||!("~standard"in e))return;let t=e["~standard"];return typeof t=="object"&&t?t:void 0}function mL(e,t){let a,r=!1,o=(n,s)=>(r||(r=!0,console.warn(`[eve] Tool schema cannot validate values locally; passing them through unvalidated: ${s}`)),{value:n});return n=>{if(a===void 0){let u=IL(e);if(typeof u=="string")return a=null,o(n,u);a=u}if(a===null)return{value:n};let s;try{s=a.validate(n)}catch(u){return n===void 0?{issues:[{message:"Expected a JSON value."}]}:o(n,lr(u))}if(!s.valid)return{issues:vL(s.errors)};let i=Ds(e,e,n),l=t?.(i);return l===void 0?{value:i}:{issues:[{message:l}]}}}function Ds(e,t,a){let r=a;for(let o of of(e,t)){let{items:n,properties:s}=o;if(ft(r)&&ft(s))r=hL(e,s,r);else if(Array.isArray(r)&&ft(n)){let i=r,l=i.map(u=>Ds(e,n,u));l.some((u,d)=>u!==i[d])&&(r=l)}}return r}function hL(e,t,a){let r=a;for(let[o,n]of Object.entries(t)){let s=Object.hasOwn(a,o)?a[o]:void 0,i=s===void 0?gL(e,n):Ds(e,n,s);i!==s&&(r===a&&(r={...a}),r[o]=i)}return r}function gL(e,t){for(let a of of(e,t))if("default"in a)return structuredClone(a.default)}function*of(e,t){let a=new Set,r=t;for(;ft(r)&&!a.has(r);)a.add(r),yield r,r=wL(e,r.$ref)}function wL(e,t){if(typeof t!="string"||t!=="#"&&!t.startsWith("#/"))return;let a=e;for(let r of _s(t)){if(typeof a!="object"||!a||!Object.hasOwn(a,r))return;a=a[r]}return a}function IL(e){try{let t=structuredClone(e);return fr(t)??new ef(t,"2020-12",!1)}catch(t){return lr(t)}}var xL=new Set(["array","boolean","integer","null","number","object","string"]),yL=[["exclusiveMinimum","minimum"],["exclusiveMaximum","maximum"]],LL=["additionalItems","additionalProperties","contains","else","if","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"],SL=["allOf","anyOf","oneOf","prefixItems"],CL=["$defs","definitions","dependencies","dependentSchemas","patternProperties","properties"];function fr(e){if(typeof e=="boolean")return;if(typeof e!="object"||!e||Array.isArray(e))return"a subschema is neither an object nor a boolean";let t=e;delete t.format;for(let[i,l]of yL)typeof t[i]=="boolean"&&(t[i]&&typeof t[l]=="number"?(t[i]=t[l],delete t[l]):delete t[i]);let{enum:a,pattern:r,required:o,type:n}=t;if(n!==void 0&&!(Array.isArray(n)?n.every(tf):tf(n)))return`unsupported type ${JSON.stringify(n)}`;if(a!==void 0&&!Array.isArray(a))return"`enum` is not an array";if(o!==void 0&&!(Array.isArray(o)&&o.every(i=>typeof i=="string")))return"`required` is not an array of strings";if(r!==void 0&&!af(r))return`invalid pattern ${JSON.stringify(r)}`;for(let i of LL)if(i in t){let l=fr(t[i]);if(l!==void 0)return l}let s=t.items;for(let i of Array.isArray(s)?s:s===void 0?[]:[s]){let l=fr(i);if(l!==void 0)return l}for(let i of SL){let l=t[i];if(l!==void 0){if(!Array.isArray(l))return`\`${i}\` is not an array`;for(let u of l){let d=fr(u);if(d!==void 0)return d}}}for(let i of CL){let l=t[i];if(l!==void 0){if(typeof l!="object"||!l||Array.isArray(l))return`\`${i}\` is not an object`;for(let[u,d]of Object.entries(l)){if(i==="patternProperties"&&!af(u))return`invalid pattern ${JSON.stringify(u)}`;if(i==="dependencies"&&Array.isArray(d))continue;let c=fr(d);if(c!==void 0)return c}}}}function tf(e){return typeof e=="string"&&xL.has(e)}function af(e){if(typeof e!="string")return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var bL=/\/(?:additional|unevaluated)Properties$/;function vL(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r],n=e[r+1];if(bL.test(o.keywordLocation)&&n?.keyword==="false"){let s=_s(n.instanceLocation).at(-1);t.push({keyword:"false",location:n.instanceLocation,message:`Unrecognized key: ${JSON.stringify(s)}`,object:o.instanceLocation}),r++}else t.push({keyword:o.keyword,location:o.instanceLocation,message:o.error})}let a=t.filter(r=>r.object===void 0||!t.some(o=>o.object===void 0&&(o.location===r.location||o.location.startsWith(`${r.location}/`))));return a.filter((r,o)=>{let n=a[o+1];return n===void 0?!0:n.location.startsWith(`${r.location}/`)?!1:r.keyword!=="$ref"||n.location!==r.location}).map(({location:r,message:o,object:n})=>{let s=_s(n??r);return s.length===0?{message:o}:{message:o,path:s}})}function _s(e){return e.split("/").slice(1).map(t=>{let a=t;try{a=decodeURIComponent(t)}catch{}return a.replaceAll("~1","/").replaceAll("~0","~")})}var nf=Symbol("followClientSession"),pr=class Os{#t;#e;constructor(t,a){this.#t=t,this.#e=a}static async create(t,a){let r=await Us(t,We,a,!0),{sessionId:o}=await Bs(r),n=new Os(t,{sessionId:o,streamIndex:0});return{response:n.#r(r,a,0),session:n}}static async prewarm(t,a={}){let{sessionId:r}=await Bs(await TL(t,a));return new Os(t,{sessionId:r,streamIndex:0})}get state(){return this.#e}async snapshot(t){t?.signal?.throwIfAborted();let a=[];for await(let r of this.#p({follow:!1,signal:t?.signal,startIndex:0}))a.push(r);return t?.signal?.throwIfAborted(),{events:a,session:{sessionId:this.#e.sessionId,streamIndex:a.length}}}async send(t,a={}){return await this.#a({...a,message:t},!0)}async respond(t,a={}){if(t.length===0)throw Error("ClientSession.respond() requires at least one input response.");return await this.#a({...a,inputResponses:t},!1)}async#a(t,a){let r=this.#e.streamIndex,o=xc(this.#e.sessionId),n=a?await kL(this.#t,o,t):await Us(this.#t,o,t,!1),{sessionId:s,deliveryId:i}=await Bs(n,this.#e.sessionId);if(s!==this.#e.sessionId)throw Error("Message route returned a different session id.");if(t.message!==void 0&&i===void 0)throw Error("Message route did not return a delivery id. Update the server before sending with this client.");return this.#r(n,t,r,t.message===void 0?void 0:i)}async cancel(t){return await Gc({context:this.#t,options:t,sessionId:this.#e.sessionId})}async clear(){return await Kc({context:this.#t,sessionId:this.#e.sessionId})}async compact(){return await Xc({context:this.#t,sessionId:this.#e.sessionId})}async reset(t){return await Jc({context:this.#t,options:t,sessionId:this.#e.sessionId})}stream(t){if(t?.follow===!1&&(t.startIndex??this.#e.streamIndex)<0)throw Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return this.#u(t)}streamSubagent(t,a){if(t.data.sessionId!==this.#e.sessionId)throw Error(`streamSubagent() requires a subagent.called event from session ${this.#e.sessionId}, but it came from session ${t.data.sessionId}.`);if(typeof t.data.childStreamPath!="string")throw Error(`streamSubagent() requires a subagent.called event with childStreamPath, but call ${t.data.callId} has none. The event was recorded by an older eve version.`);let r=a?.startIndex??0;if(a?.follow===!1&&r<0)throw Error("streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return Fs({follow:a?.follow,host:this.#t.host,path:t.data.childStreamPath,redirect:this.#t.redirect,resolveHeaders:()=>this.#t.resolveHeaders(),signal:a?.signal,startIndex:r,streamReconnectPolicy:a?.streamReconnectPolicy})}[nf](t){return this.#u({...t,keepAlive:!0})}#r(t,a,r,o){return t.body?.cancel().catch(()=>{}),new Ps({cancelTurn:async n=>await this.cancel({turnId:n}),createStream:n=>this.#n(r,a,o,n),deliveryId:o,sessionId:this.#e.sessionId})}async*#n(t,a,r,o){let n=0,s=r===void 0,i=!1,l=new Set;try{for await(let u of o??this.#p({headers:a.headers,keepAlive:!0,signal:a.signal,startIndex:t,streamReconnectPolicy:a.streamReconnectPolicy})){if(n+=1,r!==void 0){let d=u.meta?.deliveryIds?.includes(r)===!0,c=u.type==="session.failed"||u.type==="session.completed";if(!d&&c&&(!s||u.type==="session.completed"))throw Error("The session ended before the accepted message reached its turn boundary.");if(!s&&!d||!c&&u.meta?.deliveryIds!==void 0&&!d)continue;s=!0}if(Jt(l,u),i=Qe(u)&&(u.type!=="session.waiting"||l.size===0),yield u,i)break}if(r!==void 0&&!i&&!a.signal?.aborted)throw Error("The response stream ended before the accepted message reached its turn boundary.")}finally{this.#g(t+n)}}async*#u(t){let a=t?.startIndex??this.#e.streamIndex,r=0;for await(let o of this.#p({follow:t?.follow,headers:t?.headers,keepAlive:t?.keepAlive,onCaughtUp:t?.onCaughtUp,resolveHeaders:t?.resolveHeaders,resolveReconnectPolicy:t?.resolveReconnectPolicy,signal:t?.signal,startIndex:a,streamReconnectPolicy:t?.streamReconnectPolicy}))r+=1,a>=0&&this.#g(a+r),yield o}#g(t){this.#e={sessionId:this.#e.sessionId,streamIndex:Math.max(this.#e.streamIndex,t)}}#p(t){return Fs({onCaughtUp:t.onCaughtUp,follow:t.follow,host:this.#t.host,keepAlive:t.keepAlive,resolveHeaders:()=>this.#t.resolveHeaders(t.resolveHeaders?.()??t.headers),path:Ls(this.#e.sessionId),redirect:this.#t.redirect,signal:t.signal,startIndex:t.startIndex,streamReconnectPolicy:t.streamReconnectPolicy,resolveReconnectPolicy:t.resolveReconnectPolicy})}};function sf(e,t){return e[nf](t)}async function kL(e,t,a){let r=Date.now()+2e4,o=250;for(;;){try{return await Us(e,t,a,!1)}catch(n){if(!AL(n))throw n;let s=r-Date.now();if(s<=0)throw n;await dr(Math.min(o,s),a.signal)}a.signal?.throwIfAborted(),o=Math.min(o*2,2e3)}}async function TL(e,t){let a=await e.resolveHeaders(t.headers),r=await fetch(pt(e.host,We),{headers:a,method:"POST",redirect:e.redirect,signal:t.signal??null});if(!r.ok){let o=await r.text();throw new Ve(r.status,o,r.headers)}return r}function AL(e){return e instanceof Ve&&e.status===409&&e.code==="session_not_ready"}async function Us(e,t,a,r){let o=PL(a,r);if(o===null)throw Error(r?"Creating a session requires a non-empty message.":"A session turn requires a non-empty message or inputResponses.");let n=await e.resolveHeaders(a.headers);n.set("content-type","application/json");let s=await fetch(pt(e.host,t),{body:JSON.stringify(o),headers:n,method:"POST",redirect:e.redirect,signal:a.signal??null});if(!s.ok){let i=await s.text();throw new Ve(s.status,i,s.headers)}return s}async function Bs(e,t){let a=await e.json(),r=(typeof a.sessionId=="string"?a.sessionId:void 0)??e.headers.get(kc)?.trim()??t;if(!r)throw Error("Message route did not return a session id.");return{sessionId:r,deliveryId:typeof a.deliveryId=="string"&&a.deliveryId.length>0?a.deliveryId:void 0}}function PL(e,t){let a={};e.message!==void 0&&(a.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(a.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(a.turnPolicy=e.turnPolicy),e.message!==void 0&&e.taskDeliveryPolicy!==void 0&&(a.taskDeliveryPolicy=e.taskDeliveryPolicy),e.clientContext!==void 0&&(a.clientContext=e.clientContext);let r=rf(e.outputSchema);return r!==void 0&&(a.outputSchema=r),t&&a.message===void 0||a.message===void 0&&a.inputResponses===void 0?null:a}var Ns=class{#t;constructor(e){this.#t=e}async create(e={}){return"message"in e?await pr.create(this.#t,e):{session:await pr.prewarm(this.#t,e)}}attach(e,t){if(e.length===0)throw Error("sessionId must be a non-empty string.");return new pr(this.#t,{sessionId:e,streamIndex:t?.streamIndex??0})}};function lf(e,t){let a=new TextEncoder().encode(`${e}:${t}`),r=Array.from(a,o=>String.fromCodePoint(o)).join("");return btoa(r)}import{z as Mo}from"zod";var uf=Mo.object({ok:Mo.literal(!0),status:Mo.literal("ready"),workflowId:Mo.string().min(1)}).strict();import{z as h}from"zod";var Fo=h.discriminatedUnion("kind",[h.object({kind:h.literal("application")}).strict(),h.object({feature:h.string(),kind:h.literal("framework")}).strict(),h.object({kind:h.literal("extension"),namespace:h.string(),packageName:h.string()}).strict()]),ff=h.discriminatedUnion("kind",[h.object({externalDependencies:h.array(h.string()),extensionScope:h.object({namespace:h.string(),sourceRoot:h.string()}).strict().optional(),kind:h.literal("filesystem"),sourcePath:h.string()}).strict(),h.object({dependencies:h.record(h.string(),h.string()).optional(),kind:h.literal("programmatic"),moduleId:h.string(),parameters:h.record(h.string(),h.unknown()).optional(),registryId:h.string(),revision:h.string(),semanticRevision:h.string().optional()}).strict()]),pf=h.object({backing:ff,logicalPath:h.string(),owner:Fo}).strict(),Lt=h.object({binding:pf.optional(),exportName:h.string().optional(),logicalPath:h.string(),owner:Fo,sourceId:h.string(),sourceKind:h.enum(["markdown","module","skill-package"])}).strict(),Zt=Lt.extend({name:h.string()}).strict(),mr=Lt.extend({eventNames:h.array(h.string()),slug:h.string()}).strict(),RL=h.discriminatedUnion("kind",[h.object({kind:h.literal("gateway"),target:h.string(),byok:h.string().optional()}).strict(),h.object({kind:h.literal("external"),provider:h.string()}).strict()]),EL=h.union([h.object({kind:h.literal("external"),provider:h.string()}).strict(),h.object({kind:h.literal("chatgpt"),state:h.enum(["checking","ready","signed-out","reauth-required","unavailable"]),accountLabel:h.string().optional()}).strict(),h.object({kind:h.literal("gateway"),connected:h.literal(!0),credential:h.enum(["api-key","oidc","oauth"]),team:h.optional(h.string())}).strict(),h.object({kind:h.literal("gateway"),connected:h.literal(!1)}).strict()]),df={contextWindowTokens:h.number().optional(),providerOptions:h.unknown().optional(),reasoning:h.enum(["provider-default","none","minimal","low","medium","high","xhigh"]).optional().catch(void 0),source:Lt.optional()},ML=h.union([h.object({...df,endpoint:EL.optional(),id:h.string(),routing:RL}).strict(),h.object({...df,endpoint:h.never().optional(),id:h.never().optional(),routing:h.object({kind:h.literal("dynamic"),resolver:mr}).strict()}).strict()]),FL=Zt.extend({description:h.string(),hasAuth:h.boolean(),hasExecute:h.boolean(),hasModelOutputProjection:h.boolean(),hasOutputSchema:h.boolean(),inputSchema:h.unknown(),outputSchema:h.unknown().optional(),requiresApproval:h.boolean()}).strict(),_L=Zt.extend({description:h.string(),license:h.string().optional(),markdown:h.string(),metadata:h.record(h.string(),h.string()).optional()}).strict(),DL=Zt.extend({content:h.string(),role:h.enum(["system","user"])}).strict(),BL=Zt.extend({cron:h.string(),hasRun:h.boolean(),markdown:h.string().optional()}).strict(),mf=h.enum(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS","WEBSOCKET"]),OL=Zt.extend({adapterKind:h.string().optional(),method:mf,urlPath:h.string()}).strict(),UL=h.object({backing:h.union([ff,h.object({kind:h.literal("resource"),sourcePath:h.string()}).strict()]),form:h.enum(["derived","direct"]),layer:h.enum(["framework-default","extension-package","extension-override","application"]),logicalPath:h.string(),owner:Fo,sourceId:h.string()}).strict(),NL=h.object({method:mf,source:UL,urlPath:h.string(),winnerSourceId:h.string()}).strict(),qL=Lt.extend({connectionName:h.string(),description:h.string(),hasApproval:h.boolean(),hasAuthorization:h.boolean(),hasHeaders:h.boolean(),protocol:h.string(),toolFilter:h.unknown().optional(),url:h.string()}).strict(),HL=Lt.extend({eventNames:h.array(h.string()),slug:h.string()}).strict(),$L=Lt.extend({description:h.string().optional(),slot:h.string(),visibility:h.enum(["scope","session"])}).strict(),WL=Lt.extend({provider:h.string().optional(),environmentExportName:h.string().optional(),revisionHash:h.string()}).strict(),jL=Zt.extend({configResolver:mr.optional(),description:h.string().optional(),entryPath:h.string(),nodeId:h.string(),parentNodeId:h.string(),rootPath:h.string(),summary:h.object({channels:h.number(),connections:h.number(),hooks:h.number(),instructions:h.number(),memories:h.number(),schedules:h.number(),skills:h.number(),tools:h.number()}).strict()}).strict(),zL=Zt.extend({description:h.string(),nodeId:h.string(),parentNodeId:h.string(),url:h.string().optional()}).strict(),VL=h.object({action:h.enum(["subagent-call","task-cancel","workflow-tool-call"]).optional(),audience:h.array(h.enum(["root-session","delegated-task-child"])),kind:h.enum(["dispatch","provider-tool"]),sourceId:h.string()}).strict(),cf=h.object({kind:h.enum(["disabled","shadowed"]),logicalPath:h.string(),owner:Fo,sourceId:h.string(),winnerSourceId:h.string().optional()}).strict(),hf=h.object({agent:h.object({agentRoot:h.string(),appRoot:h.string(),config:Lt.extend({binding:pf}).strict(),description:h.string().optional(),model:ML,name:h.string(),nodeId:h.string(),outputSchema:h.unknown().optional()}).strict(),capabilities:h.object({devRoutes:h.boolean()}).strict(),channels:h.object({routes:h.array(OL),shadowed:h.array(NL)}).strict(),composition:h.object({disabled:h.array(cf),shadowed:h.array(cf)}).strict(),connections:h.array(qL),diagnostics:h.object({discoveryErrors:h.number(),discoveryWarnings:h.number()}).strict(),hooks:h.array(HL),instructions:h.object({dynamic:h.array(mr),static:h.array(DL)}).strict(),instrumentation:Lt.optional(),kernelEffects:h.array(VL),kind:h.literal("eve-agent-info"),memories:h.array($L),mode:h.enum(["development","production"]),remoteAgents:h.object({entries:h.array(zL),total:h.number()}).strict(),sandbox:WL,schedules:h.array(BL),skills:h.object({dynamic:h.array(mr),static:h.array(_L)}).strict(),subagents:h.object({local:h.array(jL),total:h.number()}).strict(),tools:h.object({dynamic:h.array(mr),static:h.array(FL)}).strict(),version:h.literal(5),workspace:h.object({resourceRoot:h.unknown(),rootEntries:h.array(h.string())}).strict()}).strict().superRefine((e,t)=>{let a=(n,s,i)=>{let l=new Set;n.forEach((u,d)=>{let c=s(u);l.has(c)&&t.addIssue({code:"custom",message:`Duplicate public identity "${c}".`,path:[...i,d]}),l.add(c)})},r=(n,s,i)=>{(!Number.isSafeInteger(n)||n<0||n!==s.length)&&t.addIssue({code:"custom",message:`Expected total ${s.length}, received ${n}.`,path:[...i]})};a(e.tools.static,n=>n.name,["tools","static"]),a(e.tools.dynamic,n=>n.slug,["tools","dynamic"]),a(e.skills.static,n=>n.name,["skills","static"]),a(e.skills.dynamic,n=>n.slug,["skills","dynamic"]),a(e.instructions.static,n=>n.name,["instructions","static"]),a(e.instructions.dynamic,n=>n.slug,["instructions","dynamic"]),a(e.schedules,n=>n.name,["schedules"]),a(e.connections,n=>n.connectionName,["connections"]),a(e.hooks,n=>n.slug,["hooks"]),a(e.memories,n=>n.slot,["memories"]),a(e.channels.routes,n=>`${n.method} ${GL(n.urlPath)}`,["channels","routes"]),a(e.subagents.local,n=>n.nodeId,["subagents","local"]),a(e.remoteAgents.entries,n=>n.nodeId,["remoteAgents","entries"]),r(e.subagents.total,e.subagents.local,["subagents","total"]),r(e.remoteAgents.total,e.remoteAgents.entries,["remoteAgents","total"]);let o=[[e.agent.config,["agent","config"]],...e.agent.model.source===void 0?[]:[[e.agent.model.source,["agent","model","source"]]],...e.agent.model.routing.kind==="dynamic"?[[e.agent.model.routing.resolver,["agent","model","routing","resolver"]]]:[],...e.channels.routes.map((n,s)=>[n,["channels","routes",s]]),...e.connections.map((n,s)=>[n,["connections",s]]),...e.hooks.map((n,s)=>[n,["hooks",s]]),...e.instructions.dynamic.map((n,s)=>[n,["instructions","dynamic",s]]),...e.instructions.static.map((n,s)=>[n,["instructions","static",s]]),...e.memories.map((n,s)=>[n,["memories",s]]),...e.instrumentation===void 0?[]:[[e.instrumentation,["instrumentation"]]],...e.remoteAgents.entries.map((n,s)=>[n,["remoteAgents","entries",s]]),...e.schedules.map((n,s)=>[n,["schedules",s]]),...e.skills.dynamic.map((n,s)=>[n,["skills","dynamic",s]]),...e.skills.static.map((n,s)=>[n,["skills","static",s]]),...e.subagents.local.flatMap((n,s)=>n.configResolver===void 0?[]:[[n.configResolver,["subagents","local",s,"configResolver"]]]),...e.tools.dynamic.map((n,s)=>[n,["tools","dynamic",s]]),...e.tools.static.map((n,s)=>[n,["tools","static",s]]),[e.sandbox,["sandbox"]]];for(let[n,s]of o){if(n.sourceKind==="module"&&n.binding===void 0){t.addIssue({code:"custom",message:"Module source is missing its compiled binding.",path:[...s,"binding"]});continue}if(n.sourceKind!=="module"&&n.binding!==void 0){t.addIssue({code:"custom",message:`${n.sourceKind} source cannot carry a module binding.`,path:[...s,"binding"]});continue}n.binding!==void 0&&(n.binding.logicalPath!==n.logicalPath&&t.addIssue({code:"custom",message:"Source and binding logical paths do not match.",path:[...s,"binding","logicalPath"]}),JSON.stringify(n.binding.owner)!==JSON.stringify(n.owner)&&t.addIssue({code:"custom",message:"Source and binding owners do not match.",path:[...s,"binding","owner"]}))}});function GL(e){return e.replace(/^\/+|\/+$/g,"").split("/").map(t=>t.startsWith(":")||/^\[[^\]]+\]$/.test(t)?":":t).join("/")}var gf="x-vercel-trusted-oidc-idp-token";var Hs=class{#t;#e;#a;#r;sessions;constructor(e){this.#a=e.host,this.#t=e.auth,this.#e=e.headers,this.#r=e.redirect,this.sessions=new Ns({host:this.#a,redirect:this.#r,resolveHeaders:t=>this.#n(t)})}async health(){let e=pt(this.#a,wc),t=await this.#n(),a=await fetch(e,wf({headers:t},this.#r));if(!a.ok){let n=await a.text();throw new Ve(a.status,n,a.headers)}let r;try{r=await a.json()}catch{throw new Ro}let o=uf.safeParse(r);if(!o.success)throw new Ro(o.error.issues.slice(0,5).map(n=>{let s=n.path.join(".");return s.length===0?n.message:`${s}: ${n.message}`}));return o.data}async info(e={}){let t=await this.fetch(Ic,e);if(!t.ok){let o=await t.text();throw new Ve(t.status,o,t.headers)}let a;try{a=await t.json()}catch{throw new Po}let r=hf.safeParse(a);if(!r.success)throw new Po(r.error.issues.slice(0,5).map(o=>{let n=o.path.join(".");return n.length===0?o.message:`${n}: ${o.message}`}));return r.data}async fetch(e,t={}){let a=pt(this.#a,e),r=await this.#n(XL(t.headers));return await fetch(a,wf({...t,headers:r},this.#r))}async#n(e){let t=new Headers,[a,r]=await Promise.all([KL(this.#e),this.#u()]);for(let[o,n]of Object.entries(a))t.set(o,n);for(let[o,n]of Object.entries(r))t.set(o,n);if(e)for(let[o,n]of Object.entries(e))t.set(o,n);return t}async#u(){let e=this.#t;if(!e)return{};if("vercelOidc"in e){let t=(await qs(e.vercelOidc.token)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`,[gf]:t}}if("bearer"in e){let t=(await qs(e.bearer)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`}}if("basic"in e){let t=await qs(e.basic.password);return{authorization:`Basic ${lf(e.basic.username,t)}`}}return{}}};async function qs(e){return typeof e=="function"?e():e}async function KL(e){return e===void 0?{}:typeof e=="function"?await e():e}function XL(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function wf(e,t){return t===void 0?e:{...e,redirect:t}}function $s(){let e=new Set;return{admit(t){let a=t.meta?.id;return a===void 0||!e.has(a)&&(e.add(a),!0)},get size(){return e.size}}}var If=class{#t=new AbortController;#e=new Set;#a=Promise.withResolvers();caughtUp=this.#a.promise;#r=!1;#n;#u;#g;constructor(e,t){this.setOptions(t),this.caughtUp.catch(()=>{}),t.catchUp||this.#a.resolve(),(async()=>{try{for await(let a of sf(e,{signal:this.#t.signal,resolveHeaders:()=>this.#u,resolveReconnectPolicy:()=>this.#g,startIndex:t.startIndex,onCaughtUp:t.catchUp?()=>this.#a.resolve():void 0})){if(this.#t.signal.aborted)return;t.onEvent(a);for(let r of this.#e)r.push(a);if(a.type==="session.completed"||a.type==="session.failed")break}this.#a.resolve(),this.#p()}catch(a){this.#a.reject(a),this.#p(a),this.#t.signal.aborted||t.onError(a)}})()}subscribe(e){let t=new JL(()=>this.#e.delete(t),e);return this.#r?t.end(this.#n):this.#e.add(t),t}get ended(){return this.#r}setOptions(e){"headers"in e&&(this.#u=e.headers),"streamReconnectPolicy"in e&&(this.#g=e.streamReconnectPolicy)}close(){let e=new DOMException("Session stream was detached.","AbortError");this.#t.abort(e),this.#a.reject(e),this.#p(e)}#p(e){if(!this.#r){this.#r=!0,this.#n=e;for(let t of this.#e)t.end(e)}}},JL=class{#t=[];#e=Promise.withResolvers();#a=!1;#r;#n;constructor(e,t){let a=()=>this.end(t?.reason);t?.addEventListener("abort",a,{once:!0}),this.#n=()=>{t?.removeEventListener("abort",a),e()},t?.aborted&&a()}push(e){this.#a||(this.#t.push(e),this.#e.resolve())}end(e){this.#a||(this.#a=!0,this.#r=e,this.#e.resolve())}[Symbol.dispose](){this.end(),this.#t=[],this.#n()}discard(){this.#t=[]}async*[Symbol.asyncIterator](){for(;;){for(;this.#t.length>0;)yield this.#t.shift();if(this.#a){if(this.#r!==void 0)throw this.#r;return}this.#e=Promise.withResolvers(),await this.#e.promise}}};var xf=class{#t;#e;#a;constructor(e,t){this.#t=e,this.#e=t,this.#a=this.#r()}get data(){return this.#a}reset(){this.#e=[],this.#a=this.#t.initial()}append(e){this.#e=[...this.#e,e],this.#a=this.#t.reduce(this.#a,e)}remove(e){this.#e=this.#e.filter(t=>!e(t)),this.#a=this.#r()}replace(e,t){let a=this.#e.findIndex(e);this.#e=a===-1?[...this.#e,t]:this.#e.map((r,o)=>o===a?t:r),this.#a=this.#r()}#r(){let e=this.#t.initial();for(let t of this.#e)e=this.#t.reduce(e,t);return e}};function Lf(e){let t=e.at(-1);return t!==void 0&&Qe(t)&&(t.type!=="session.waiting"||QL(e).size===0)}function QL(e){let t=new Set;for(let a of e)Jt(t,a);return t}function Ws(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error("A turn requires exactly one of message or inputResponses.")}var yf=0;function Sf(){let e=globalThis.crypto?.randomUUID;return e===void 0?(yf+=1,`submission_${yf.toString()}`):e.call(globalThis.crypto)}function hr(e,t){return e?AbortSignal.any([e,t]):t}function Cf(e){if(typeof e=="string")return e;let t=[];for(let a of e)a.type==="text"?t.push(a.text):a.type==="file"&&t.push(a.filename?`[file: ${a.filename}]`:"[file]");return t.join(`
|
|
22
|
+
`)}function js(e){return e instanceof Error&&e.name==="AbortError"}function bf(e){if(e.type!=="session.failed")return;let t=Error(e.data.message);return t.name=e.data.code,t}function zs(e){let t=Promise.withResolvers(),a=Promise.withResolvers(),r={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>e(r),completion:a.promise,followUpDispatches:new Set,receivedFollowUps:0,receivedFollowUpEvents:new Map,followUpSubmissionIds:new Set,resolveCompletion:a.resolve,response:t.promise,resolveResponse:t.resolve};return r}async function Vs(e,t,a){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps))for await(let r of t){if(!a())return;if(e.receivedFollowUps+=e.receivedFollowUpEvents.get(r)??0,e.receivedFollowUpEvents.delete(r),Qe(r)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async function gr(e,t){if(t===void 0)return await e;let a=Promise.withResolvers(),r=()=>a.reject(t.reason);t.addEventListener("abort",r,{once:!0}),t.aborted&&r();try{return await Promise.race([a.promise,e])}finally{t.removeEventListener("abort",r)}}var vf=class{#t;#e;#a=[];constructor(e,t){this.#e=e,this.#t=t}reset(){this.#a=[]}submit(e,t){if(e.message===void 0)return;let a={createdAt:Date.now(),eventStartIndex:t,id:Sf(),message:Cf(e.message),requiresDeliveryId:!0};return this.#a=[...this.#a,a],this.#t&&this.#e.append({data:{createdAt:a.createdAt,message:a.message,submissionId:a.id},type:"client.message.submitted"}),a.id}apply(e){if(e.type!=="message.received"){this.#e.append(e);return}if(e.data.kind==="execution.background_task"){this.#e.append(e);return}let t=this.#r(e);if(t.length===0){this.#e.append(e);return}return this.#n(t,e,!1)}correlate(e,t,a){if(e===void 0)return;this.#a=this.#a.map(o=>o.id===e?{...o,deliveryId:t,requiresDeliveryId:t!==void 0}:o);let r=this.#a.find(o=>o.id===e);if(r!==void 0)for(let o of a.slice(r.eventStartIndex)){if(o.type!=="message.received"||o.data.kind==="execution.background_task")continue;let n=this.#r(o);if(n.some(s=>s.id===e))return this.#n(n,o,!0)}}fail(e,t){let a=t===void 0?this.#a[0]:this.#a.find(r=>r.id===t);a!==void 0&&(this.#a=this.#a.filter(r=>r.id!==a.id),this.#e.replace(r=>r.type==="client.message.submitted"&&r.data.submissionId===a.id,{data:{createdAt:a.createdAt,error:{message:e.message},message:a.message,submissionId:a.id},type:"client.message.failed"}))}failAll(e){for(let t of this.#a)this.fail(e,t.id)}#r(e){return this.#a.filter(t=>t.deliveryId===void 0?!t.requiresDeliveryId:e.meta.deliveryIds?.includes(t.deliveryId)===!0)}#n(e,t,a){let r=e.map(n=>n.id),o=new Set(r);return this.#a=this.#a.filter(n=>!o.has(n.id)),a||this.#e.replace(n=>n.type==="client.message.submitted"&&n.data.submissionId===r[0],t),this.#e.remove(n=>n.type==="client.message.submitted"&&o.has(n.data.submissionId)),{alreadyProjected:a,event:t,ids:r}}};var YL=Symbol("detachEveAgentStore"),ZL=Symbol("attachEveAgentStore"),Gs=class{#t;#e;#a=!1;#r;#n=new Set;#u;#g;#p;#C=new Set;#b=$s();#l;#c={};#i;#m;#h;#w=0;#I;#S;#x;#s;#y;#o="ready";constructor(e){this.#e=e.prewarm??!1,this.#u=e.session!==void 0,this.#t=this.#u?void 0:new Hs({auth:e.auth,headers:e.headers,host:e.host??""});let t=[];for(let a of e.initialEvents??[])this.#b.admit(a)&&t.push(a),Jt(this.#n,a);this.#m=t,this.#p=new xf(e.reducer,this.#m),this.#g=e.optimistic??!0,this.#h=new vf(this.#p,this.#g),this.#s=e.session??(e.initialSession===void 0?void 0:this.#t?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#y=this.#R()}get snapshot(){return this.#y}setCallbacks(e){this.#c=e}subscribe(e){return this.#C.add(e),()=>{this.#C.delete(e)}}prewarm(){if(this.#I!==void 0)return this.#I;if(this.#s!==void 0||this.#u)return Promise.resolve();if(this.#l!==void 0)return this.#l.response.then(n=>{if(n===void 0)throw this.#i??new DOMException("Session creation was aborted.","AbortError")});let e=this.#t;if(e===void 0)return Promise.reject(Error("This eve agent store does not own a session client."));let t=this.#w,a=new AbortController;this.#S=a;let r=(async()=>{try{let n=await e.sessions.create({signal:a.signal});if(t!==this.#w)return;this.#s=n.session,this.#i=void 0,this.#o==="error"&&(this.#o="ready"),this.#c.onSessionChange?.(n.session.state),this.#f(),this.#L()}catch(n){throw t===this.#w&&this.#l===void 0&&this.#i===void 0&&(this.#i=Xt(n),this.#o="error",this.#c.onError?.(this.#i),this.#f()),n}})();this.#I=r;let o=()=>{this.#I===r&&(this.#I=void 0,this.#S=void 0)};return r.then(o,o),r}async send(e){return await this.#k(e,this.#c.prepareSend)}async#k(e,t){if(this.#l!==void 0){if(this.#o==="resuming")throw Error("eve session is resuming.");return await this.#M(this.#l,e,t)}let a=zs(o=>o.acceptedFollowUps>0&&this.#s!==void 0?this.#s.cancel():o.response.then(n=>n===void 0?{status:"no_active_turn"}:n.cancel()));this.#l=a,this.#i=void 0,this.#o="submitted",this.#f();let r;try{let o=await(t===void 0?e:gr(Promise.resolve(t(e)),hr(e.signal,a.abortController.signal)));if(Ws(o),!this.#d(a))return;let n=this.#h.submit(o,this.#m.length);this.#_(o),this.#f();let s={...o,signal:hr(o.signal,a.abortController.signal)},i=await this.#F(s),l=i.response;if(r=i.reader,!this.#d(a))return;a.resolveResponse(l),this.#v(this.#h.correlate(n,Rs(l),this.#m))&&this.#f();for await(let u of _c(l,r)){if(!this.#d(a))return;a.receivedFollowUps+=a.receivedFollowUpEvents.get(u)??0,a.receivedFollowUpEvents.delete(u)}if(!this.#d(a)||(await Vs(a,r,()=>this.#d(a)),!this.#d(a)))return;this.#o=this.#i===void 0?"ready":"error"}catch(o){if(!this.#d(a))return;if(js(o))this.#o="ready",this.#h.fail(Xt(o));else{let n=this.#i!==void 0;this.#i??=Xt(o),this.#o="error",this.#h.fail(this.#i),n||this.#c.onError?.(this.#i)}}finally{r?.[Symbol.dispose](),this.#A(a)}}resume(){if(this.#x!==void 0)return this.#x;let e=this.#E();this.#x=e;let t=()=>{this.#x===e&&(this.#x=void 0)};return e.then(t,t),e}async#E(){if(this.#o==="resuming"||this.#o==="streaming"||this.#o==="submitted")throw Error("eve session is already processing a turn.");if(this.#s===void 0)throw Error("An eve session is required before resuming.");let e=this.#s,t=zs(()=>e.cancel());this.#l=t,t.resolveResponse(void 0),this.#i=void 0,this.#o="resuming",this.#f();let a;try{let r=this.#L({catchUp:!0,startIndex:this.#m.length===e.state.streamIndex?e.state.streamIndex:0});if(a=r.subscribe(t.abortController.signal),await r.caughtUp,!this.#d(t))return;a.discard();let o=this.#m.at(-1);if(o!==void 0&&this.#P(o),o!==void 0&&this.#i===void 0&&!Lf(this.#m)){this.#o="streaming",this.#f();for await(let n of a){if(!this.#d(t))return;if(t.receivedFollowUps+=t.receivedFollowUpEvents.get(n)??0,t.receivedFollowUpEvents.delete(n),Qe(n)&&this.#n.size===0)break}}await Vs(t,a,()=>this.#d(t)),this.#d(t)&&(this.#o=this.#i===void 0?"ready":"error")}catch(r){if(!this.#d(t))return;js(r)?this.#o="ready":(this.#i=Xt(r),this.#o="error",this.#c.onError?.(this.#i))}finally{a?.[Symbol.dispose](),this.#A(t)}}cancel(){let e=this.#l;return e===void 0?this.#o==="streaming"&&this.#s!==void 0?this.#s.cancel():Promise.resolve({status:"no_active_turn"}):e.cancel()}[ZL](){this.#a=!0,this.#e&&this.#s===void 0&&this.prewarm().catch(()=>{})}[YL](){this.#a=!1,this.#r?.close(),this.#r=void 0,this.#l?.abortController.abort(),this.#T(),this.#x=void 0}reset(){this.#r?.close(),this.#r=void 0,this.#n.clear();let e=this.#l;this.#l=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#T(),this.#x=void 0,this.#u||(this.#s=void 0),this.#m=[],this.#b=$s(),this.#h.reset(),this.#p.reset(),this.#i=void 0,this.#o="ready",this.#c.onSessionChange?.(this.#s?.state),this.#f(),this.#e&&this.#a&&this.prewarm().catch(()=>{})}async#M(e,t,a){if(t.message===void 0||t.turnPolicy!=="steer")throw Error('eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.');let r=this.#w,o=hr(t.signal,e.abortController.signal),n=await gr(Promise.resolve(a?.(t)),o)??t;if(r!==this.#w)return;if(Ws(n),n.message===void 0||n.turnPolicy!=="steer")throw Error('An in-flight follow-up requires a message with turnPolicy: "steer".');if(!this.#d(e))return await this.#k(n);let s=this.#h.submit(n,this.#m.length);s!==void 0&&e.followUpSubmissionIds.add(s),this.#f(),this.#L({headers:n.headers,streamReconnectPolicy:n.streamReconnectPolicy});let i;i=(async()=>{try{let l=hr(n.signal,e.abortController.signal);if(await gr(e.response,l),!this.#d(e)||this.#s===void 0)throw Error("The active eve turn ended before the follow-up could be sent.");let{message:u,...d}=n,c=await this.#s.send(u,{...d,signal:l});e.acceptedFollowUps+=1,this.#v(this.#h.correlate(s,Rs(c),this.#m))&&this.#f()}catch(l){throw this.#d(e)&&(this.#h.fail(Xt(l),s),this.#f()),l}finally{e.followUpDispatches.delete(i)}})(),e.followUpDispatches.add(i),await i,await e.completion}async#F(e){let t={headers:e.headers,streamReconnectPolicy:e.streamReconnectPolicy};if(this.#I!==void 0&&(await gr(this.#I.catch(r=>{if(this.#s!==void 0)throw r}),e.signal),e.signal?.throwIfAborted()),this.#s===void 0){if(this.#t===void 0)throw Error("An external eve session is required before sending.");if(e.message===void 0)throw Error("Cannot answer an input request before the session starts.");let r=await this.#t.sessions.create({...e,message:e.message});return e.signal?.throwIfAborted(),this.#s=r.session,this.#c.onSessionChange?.(r.session.state),this.#f(),{response:r.response,reader:this.#L(t).subscribe(e.signal)}}let a=this.#L(t).subscribe(e.signal);try{if(e.inputResponses===void 0){let{message:n,...s}=e;return{response:await this.#s.send(n,s),reader:a}}let{inputResponses:r,...o}=e;return{response:await this.#s.respond(r,o),reader:a}}catch(r){throw a[Symbol.dispose](),r}}#L(e={}){if(this.#r!==void 0&&!this.#r.ended)return this.#r.setOptions(e),this.#r;if(this.#s===void 0)throw Error("A session is required before opening its stream.");let t=this.#s,a=this.#w;return this.#r=new If(t,{...e,onEvent:r=>{a===this.#w&&this.#D(r)},onError:r=>{a===this.#w&&(this.#r=void 0,this.#l===void 0&&(this.#i=Xt(r),this.#o="error",this.#c.onError?.(this.#i),this.#f()))}}),this.#r}#T(){this.#w+=1,this.#S?.abort(),this.#S=void 0,this.#I=void 0}#A(e){if(this.#d(e)){e.resolveResponse(void 0),this.#l=void 0;try{this.#c.onSessionChange?.(this.#s?.state),this.#f(),this.#c.onFinish?.(this.#y)}finally{e.resolveCompletion()}}}#d(e){return this.#l===e}#_(e){e.inputResponses!==void 0&&e.inputResponses.length!==0&&this.#p.append({data:{createdAt:Date.now(),responses:e.inputResponses},type:"client.input.responded"})}#D(e){if(!this.#b.admit(e))return;let t=this.#o==="streaming";Jt(this.#n,e),this.#m=[...this.#m,e],this.#v(this.#h.apply(e)),this.#c.onEvent?.(e),this.#P(e);let a=Qe(e)&&this.#n.size===0;this.#o!=="resuming"&&this.#i===void 0&&("data"in e&&"turnId"in e.data&&(this.#o="streaming"),this.#l===void 0&&a&&(this.#o="ready")),this.#c.onSessionChange?.(this.#s?.state),this.#o!=="resuming"&&this.#f(),this.#l===void 0&&t&&a&&this.#c.onFinish?.(this.#y)}#v(e){if(e===void 0)return!1;let t=0;for(let a of e.ids)this.#l?.followUpSubmissionIds.delete(a)&&(t+=1);if(t>0&&this.#l!==void 0)if(e.alreadyProjected)this.#l.receivedFollowUps+=t;else{let a=this.#l.receivedFollowUpEvents.get(e.event)??0;this.#l.receivedFollowUpEvents.set(e.event,a+t)}return!0}#P(e){let t=bf(e);t!==void 0&&(this.#o="error",this.#h.failAll(t),this.#i===void 0&&(this.#i=t,this.#c.onError?.(t)))}#R(){return{data:this.#p.data,error:this.#i,events:this.#m,session:this.#s?.state,status:this.#o}}#f(){this.#y=this.#R();for(let e of this.#C)e()}};function eS(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function tS(e){let t=new AbortController;for(let a of e){if(a.aborted)return t.abort(a.reason),t.signal;a.addEventListener("abort",()=>t.abort(a.reason),{once:!0,signal:t.signal})}return t.signal}function kf(){"withResolvers"in Promise||Object.defineProperty(Promise,"withResolvers",{value:eS,configurable:!0,writable:!0}),"any"in AbortSignal||Object.defineProperty(AbortSignal,"any",{value:tS,configurable:!0,writable:!0})}var aS=3e4;function rS(){let e=crypto.getRandomValues(new Uint8Array(32));return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Xs(e){let t=e.channelId??"";return e.threadId===void 0?t:`${t}:${e.threadId}`}function Ks(e){return`waniwani:eve-conversation:${e}`}function Js(e){try{let t=JSON.parse(localStorage.getItem(Ks(e))??"null");return typeof t=="object"&&t!==null&&"conversationId"in t&&typeof t.conversationId=="string"&&"ownerSecret"in t&&typeof t.ownerSecret=="string"?{conversationId:t.conversationId,ownerSecret:t.ownerSecret}:null}catch{return null}}function ga(e,t){try{t?localStorage.setItem(Ks(e),JSON.stringify(t)):localStorage.removeItem(Ks(e))}catch{}}function Tf(e){return JSON.stringify(e).replace(/[\u007f-\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function oS(e){return{...e.documents?.length?{"x-waniwani-documents":Tf(e.documents)}:{},...e.extra&&Object.keys(e.extra).length>0?{"x-waniwani-extra":Tf(e.extra)}:{}}}var nS={initial:()=>{},reduce:()=>{}},ha=class e{constructor(t,a,r){this.open=t;this.secret=a;this.grant=r,kf(),this.store=new Gs({host:r.eveHost,auth:{bearer:()=>this.bearer()},initialSession:{sessionId:r.sessionId,streamIndex:0},optimistic:!1,reducer:nS}),this.store.setCallbacks({onEvent:o=>this.forward?.(o)}),this.caughtUp=this.store.resume().catch(()=>{})}grant;refreshing=null;store;forward;caughtUp;used=!1;static async create(t){let a=rS(),r=await t.open({operation:"create",requestId:crypto.randomUUID(),ownerSecret:a,channelId:t.channelId,visitorId:t.visitorId});return r?await new e(t.open,a,r).reachable():null}static async resume(t){let a=await t.open({operation:"resume",...t.saved});return a?await new e(t.open,t.saved.ownerSecret,a).reachable():null}async reachable(){return await this.caughtUp,this.store.snapshot.error===void 0?this:(this.close(),null)}get sessionId(){return this.grant.sessionId}get saved(){return{conversationId:this.grant.conversationId,ownerSecret:this.secret}}get followups(){return this.grant.followups}async history(){await this.caughtUp;let{events:t}=this.store.snapshot;return this.used||=t.some(a=>a.type==="message.received"),t}async bearer(){return this.grant.expiresAt-aS>Date.now()?this.grant.accessToken:(this.refreshing??=this.open({operation:"refresh",conversationId:this.grant.conversationId,ownerSecret:this.secret}).then(t=>{if(!t)throw new Error("The conversation left the direct runtime");return this.grant=t,t.accessToken}).finally(()=>{this.refreshing=null}),await this.refreshing)}turn(t,a,r){this.used=!0;let o=()=>{this.store.cancel()};return r?.addEventListener("abort",o,{once:!0}),new ReadableStream({start:async s=>{let i=!1;this.forward=u=>{i||=u.type==="turn.failed"||u.type==="session.failed",s.enqueue(u)},await this.caughtUp;let l=await this.store.send({message:t,signal:r,headers:oS(a)}).then(()=>this.store.snapshot.error,u=>u instanceof Error?u:new Error(String(u)));this.forward=void 0,r?.removeEventListener("abort",o),l&&!i&&!r?.aborted&&s.enqueue({type:"session.failed",data:{code:"transport_failed",message:l.message,sessionId:this.sessionId}}),s.close()}}).pipeThrough(To())}close(){this.forward=void 0,this.store.reset()}};function wa(e,t){let a=e[t];return typeof a=="string"&&a?a:void 0}function sS(e){let t=e.visitor;return typeof t=="object"&&t!==null&&"id"in t&&typeof t.id=="string"?t.id:void 0}function iS(e){return e.filter(t=>t.role==="user").map(t=>t.parts.flatMap(a=>a.type==="text"?[a.text]:[]).join(`
|
|
23
|
+
`))}function Af(e){return fetch(new URL(e.path,new URL(e.sessionApi,location.href)),{method:"POST",headers:{...e.headers(),"content-type":"application/json"},body:JSON.stringify(e.body),cache:"no-store",signal:e.signal})}function lS(e){return async t=>{let a=await Af({...e,path:"followups",body:t,signal:AbortSignal.timeout(8e3)}),r=a.ok?await a.json():null,o=typeof r=="object"&&r!==null&&"data"in r?r.data:null,n=typeof o=="object"&&o!==null&&"suggestions"in o?o.suggestions:null;return Array.isArray(n)?n.filter(s=>typeof s=="string"):[]}}function uS(e){let t="",a=!1,r=new Set;return new TransformStream({async transform(o,n){if(o.type==="text-delta"&&(t+=o.delta),o.type==="tool-input-available"&&r.add(o.toolName),o.type==="error"&&(a=!0),o.type==="finish"&&!a&&!e.signal?.aborted&&t.trim()){let s=await e.suggest(t,[...r]).catch(()=>[]);s.length>0&&n.enqueue({type:"data-suggestions",data:{suggestions:s}})}n.enqueue(o)}})}function dS(e){return async t=>{let a=await Af({...e,path:e.sessionApi,body:t});if(!a.ok)throw new Error(`Opening the chat failed (${a.status})`);let r=await a.json(),o=typeof r=="object"&&r!==null&&"data"in r?r.data:null;if(typeof o!="object"||o===null||!("transport"in o))throw new Error("The session route answered no transport");if(o.transport!=="eve-native")return null;let n={...o},s=n.session,i=typeof s=="object"&&s!==null&&"sessionId"in s?s.sessionId:void 0,l=wa(n,"conversationId"),u=wa(n,"eveHost"),d=wa(n,"accessToken"),c=Date.parse(wa(n,"expiresAt")??"");if(!l||!u||!d||typeof i!="string"||Number.isNaN(c))throw new Error("The session route answered an incomplete session");return{conversationId:l,eveHost:u,sessionId:i,accessToken:d,expiresAt:c,followups:n.followups===!0}}}function cS(e){let t=e.extra;return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t)):void 0}var Qs=class{constructor(t){this.options=t}pending;threadOnFallback=!1;generation=0;get channelId(){return wa(this.options.body(),"channelId")}key(){return Xs({channelId:this.channelId,threadId:this.options.threadId()})}keepsSession(){return this.options.open!==void 0}prepare(){this.open(this.options.hasMessages())}open(t){this.options.open&&(this.pending??=this.start(this.options.open,t))}async restore(){let{open:t}=this.options;if(!t||this.options.threadHistory())return[];let a=this.key(),r=Js(a);if(!r)return[];let o=this.generation,n=ha.resume({open:t,saved:r}).catch(()=>null).then(i=>this.kept(i,o));this.pending=n;let s=await n;return s?await mc(await s.history()):(ga(a,null),this.pending===n&&(this.pending=void 0),[])}reset(){ga(this.key(),null),this.dispose()}forget(t){ga(Xs({channelId:this.channelId,threadId:t}),null)}dispose(){this.generation+=1,this.threadOnFallback=!1,this.pending?.then(t=>t?.close()).catch(()=>{}),this.pending=void 0}async start(t,a){let r=this.generation,o=this.key(),n=Js(o);if(n){let u=await ha.resume({open:t,saved:n}).catch(()=>null);return!u&&r===this.generation&&ga(o,null),this.kept(u,r)}if(a)return null;let s=this.options.body(),i=await ha.create({open:t,channelId:wa(s,"channelId"),visitorId:sS(s)}),l=this.kept(i,r);return r===this.generation&&ga(o,l?.saved??null),l}kept(t,a){return t&&a!==this.generation?(t.close(),null):t}async sendMessages(t){let a=t.messages.filter(f=>f.role==="user").length<=1;a&&(this.threadOnFallback=!1);let o=[...t.messages].reverse().find(f=>f.role==="user")?.parts.some(f=>f.type==="file")??!1;if(this.threadOnFallback||o||!this.options.open)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.open(!a);let n=await this.pending?.catch(()=>null);if(n?.used&&a&&(this.reset(),this.open(!1),n=await this.pending?.catch(()=>null)),!n)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.options.onSession(n.sessionId);let{documents:s}=this.options.takeTurnInput(),i=iS(t.messages),l=i.at(-1)??"",u=l.trim()?l:s?.map(f=>f.filename).join(", ")??l,d=n.turn(u,{documents:s,extra:cS(this.options.body())},t.abortSignal),{suggest:c}=this.options;if(!n.followups||!c)return d;let{saved:p}=n;return d.pipeThrough(uS({suggest:(f,m)=>c({...p,answerText:f.slice(-8e3),recentUserMessages:i.slice(-3).map(y=>y.slice(-2e3)),toolNames:m.slice(0,20)}),signal:t.abortSignal}))}async reconnectToStream(t){return await this.pending?.catch(()=>null)?null:await this.options.fallback.reconnectToStream(t)}};function Pf(e){let t=typeof e=="string"?()=>e:e;return a=>{let r=o=>{let n=t();return n?o(n):void 0};return new Qs({...a,get open(){return r(o=>dS({sessionApi:o,headers:a.headers}))},get suggest(){return r(o=>lS({sessionApi:o,headers:a.headers}))}})}}function Rf(e){let t=fS(e);t.current=e;let[a]=pS(()=>Pf(()=>t.current));return a}import{useEffect as mS,useRef as hS}from"react";function Ys(e,t){return e.find(a=>a.text===t)?.id??null}async function Ef(e){let{api:t,token:a,name:r,source:o,sessionId:n,properties:s}=e;if(typeof window>"u"||!t||!a)return;let i=nr(t);if(i)try{let l=new Date().toISOString(),u=JSON.stringify({sentAt:l,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:r,source:o,timestamp:l,correlation:{visitorId:Ge(),sessionId:n},properties:{...s,url:window.location.href},metadata:{}}]});await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function Mf(e){let{api:t,token:a,channelId:r,mode:o,source:n,sessionId:s,promptId:i,origin:l,text:u,index:d}=e;await Ef({api:t,token:a,name:"suggestion.clicked",source:n,sessionId:s,properties:{promptId:i,origin:l,text:u,index:d,channelId:r,mode:o}})}function Ff(e,t){return t.map(a=>({id:Ys(e,a),text:a}))}async function _f(e){let{api:t,token:a,channelId:r,mode:o,source:n,sessionId:s,prompts:i,origin:l}=e;i.length!==0&&await Ef({api:t,token:a,name:"suggestion.shown",source:n,sessionId:s,properties:{prompts:i,count:i.length,origin:l,channelId:r,mode:o}})}function Df(e){let{widgetEvents:t,api:a,token:r,channelId:o,source:n,mode:s,pagePrompts:i}=e,l=hS(e.getSessionId);l.current=e.getSessionId,mS(()=>{if(!(!a||!r))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:d,origin:c,index:p}=u.properties;Mf({api:a,token:r,channelId:o,mode:s,source:n,sessionId:l.current(),promptId:Ys(i??[],d),origin:c,text:d,index:p});return}if(u.name==="suggestions.shown"){let{texts:d,origin:c}=u.properties;_f({api:a,token:r,channelId:o,mode:s,source:n,sessionId:l.current(),prompts:Ff(i??[],d),origin:c})}})},[t,a,r,o,n,s,i])}function Ia(e,t){for(let a of t){let r=e[a];if(typeof r=="string"&&r.length>0)return r}}var gS=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],wS=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],IS=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],xS=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],yS=["waniwani/visitorId","visitorId"],LS=["correlationId","openai/requestId"];function Bf(e){return e?Ia(e,gS):void 0}function Of(e){return e?Ia(e,wS):void 0}function Uf(e){return e?Ia(e,IS):void 0}function Nf(e){return e?Ia(e,xS):void 0}function qf(e){return e?Ia(e,yS):void 0}function Hf(e){return e?Ia(e,LS):void 0}var SS=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],CS=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function $f(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:n}of SS){let s=e[o];if(typeof s=="string"&&s.length>0)return n}}let a=t?.name;if(typeof a=="string"&&a.length>0){let r=a.toLowerCase();for(let{needle:o,source:n}of CS)if(r.includes(o))return n}}var bS="@waniwani/sdk";function Wf(e,t={}){let a=t.now??(()=>new Date),r=t.generateId??vS,o=AS(e),n=_o(e.meta),s=_o(e.metadata),i=PS(e,n),l=ot(e.eventId)??r(),u=RS(e.timestamp,a),d=ot(e.source)??$f(n)??t.source??bS,c=Zs(e)?{...e}:void 0,p={...s};return Object.keys(n).length>0&&(p.meta=n),c&&(p.rawLegacy=c),{id:l,type:"mcp.event",name:o,source:d,timestamp:u,correlation:i,properties:kS(e,o),metadata:p,rawLegacy:c}}function vS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function kS(e,t){if(!Zs(e))return _o(e.properties);let a=TS(e,t),r=_o(e.properties);return{...a,...r}}function TS(e,t){switch(t){case"tool.called":{let a={};return ot(e.toolName)&&(a.name=e.toolName),ot(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return ot(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function AS(e){return Zs(e)?e.eventType:e.event}function PS(e,t){let a=ot(e.requestId)??Of(t),r=ot(e.sessionId)??Bf(t),o=ot(e.traceId)??Uf(t),n=ot(e.externalUserId)??Nf(t),s=ot(e.visitorId)??qf(t),i=ot(e.correlationId)??Hf(t)??a,l={};return r&&(l.sessionId=r),o&&(l.traceId=o),a&&(l.requestId=a),i&&(l.correlationId=i),n&&(l.externalUserId=n),s&&(l.visitorId=s),l}function RS(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let a=new Date(e);if(!Number.isNaN(a.getTime()))return a.toISOString()}return t().toISOString()}function _o(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function ot(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Zs(e){return"eventType"in e}function jf(e){return{priceShown:({amount:t,currency:a,itemId:r,label:o,...n})=>e({event:"price_shown",properties:{amount:t,currency:a,itemId:r,label:o},...n}),pricesCompared:({options:t,...a})=>e({event:"prices_compared",properties:{options:t},...a}),optionSelected:({id:t,amount:a,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:a,currency:r},...o}),leadQualified:t=>{let{externalId:a,email:r,name:o,...n}=t??{};return e({event:"lead_qualified",properties:{externalId:a,email:r,name:o},...n})},converted:({amount:t,currency:a,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:a,occurredAt:r},...o})}}var ES="/api/mcp/events/v2/batch";var zf="@waniwani/sdk";var MS=new Set([401,403]),FS=new Set([408,425,429,500,502,503,504]),_S=(e,t)=>globalThis.fetch(e,t);function Vf(e){return new ei(e)}var ei=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=OS(t.apiUrl,t.endpointPath??ES),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??_S,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(a=>new Promise(r=>setTimeout(r,a))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let a=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,a),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",a)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let a=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(a)||a<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(a).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let a=JSON.stringify(this.makeBatchRequest(t));if(a.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:a,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":zf};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let a=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(a)),a+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(a)),a+=1;continue}}}async sendBatchOnce(t){let a;try{a=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(n){return{kind:"retryable",reason:US(n)}}if(MS.has(a.status))return{kind:"auth",status:a.status};if(FS.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let r=await BS(a);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:zf,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,a){let r=new Map(t.map(s=>[s.id,s])),o=[],n=[];for(let s of a){let i=r.get(s.eventId);if(i){if(DS(s)){o.push(i);continue}n.push(i)}}return{retryable:o,permanent:n}}backoffDelayMs(t){let a=this.retryBaseDelayMs*2**t;return Math.min(a,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,a){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,a+r)}};function DS(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function BS(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function OS(e,t){let a=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${a}${r}`}function US(e){return e instanceof Error?e.message:String(e)}function Gf(e){let{apiUrl:t,endpointPath:a}=NS(e.endpoint),r=Vf({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),o,n=i=>typeof i=="function"?i():i,s=async i=>{let l=e.identity?.()??{},u=n(e.channelId),d=u===void 0?i.properties:{channelId:u,...i.properties},c=Wf({sessionId:l.sessionId,visitorId:l.visitorId,externalUserId:l.externalUserId??o,traceId:l.traceId,...i,properties:d,metadata:{...e.metadata,...i.metadata}},{source:n(e.source)});return r.enqueue(c),{eventId:c.id}};return{track:Object.assign(s,jf(s)),identify(i,l){return o=i,s({event:"user.identified",externalUserId:i,properties:l})},flush:()=>r.flush(),shutdown:i=>r.shutdown(i)}}function NS(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function Kf(e){let t=nr(e.api);return t?Gf({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Ge()})}):ti("the chat api does not point at a Waniwani event ingest")}function ti(e){let t=!1,a=async()=>(t||(t=!0,console.warn(`[Waniwani] track() is disabled: ${e}`)),{eventId:""});return{track:Object.assign(a,{priceShown:a,pricesCompared:a,optionSelected:a,leadQualified:a,converted:a}),identify:a,flush:async()=>{},shutdown:async()=>({timedOut:!1,pendingEvents:0})}}import{jsx as Qf}from"react/jsx-runtime";var $S=600,Jf="https://app.waniwani.ai/api/mcp/chat",WS=qS(function(t,a){let{token:r,channelId:o,className:n,visitorId:s,overrides:i,onEvent:l}=t,u=ri(null),d=ri(null),c=ai(()=>Ed({mode:"inline",getSessionId:()=>u.current?.sessionId}),[]);Do(()=>{if(l)return c.subscribe(l)},[l,c]);let p=ai(()=>({token:r,channelId:o,api:i?.api,mcpServerUrl:i?.mcpServerUrl,title:i?.title,hideHeader:i?.hideHeader,welcomeMessage:i?.welcomeMessage,placeholder:i?.placeholder,suggestions:i?.suggestions,enableThreadHistory:i?.enableThreadHistory,showToolCalls:i?.showToolCalls,appearance:i?.appearance,disclaimer:i?.disclaimer,locale:i?.locale}),[r,o,i?.api,i?.mcpServerUrl,i?.title,i?.hideHeader,i?.welcomeMessage,i?.placeholder,i?.suggestions,i?.enableThreadHistory,i?.showToolCalls,i?.appearance,i?.disclaimer,i?.locale]),f=i?.api??Jf,[m,y]=Xf({}),[S,L]=Xf(!1),C=ri(!1);Do(()=>{S&&!C.current&&(C.current=!0,c.emit({name:"chat.ready"}))},[S,c]);let I=i?.disablePageView;Do(()=>{if(!r){L(!0);return}let G=K=>{I||ms({api:f,token:r,channelId:o??K.channelId,mode:"inline",source:K.source})},Q=ko(f,r,o);Q&&(y(Q),Da("cache"),Rr(Q.metadata),L(!0),G(Q));let O=new AbortController,re=setTimeout(()=>{Da("timeout"),L(!0)},$S);return pc(f,r,O.signal,o).then(K=>{O.signal.aborted||(Object.keys(K).length>0&&(fc(f,r,o,K),y(K)),Da("remote"),L(!0),G(K))}).catch(K=>{console.error("[Waniwani] Remote config fetch failed:",K),L(!0)}).finally(()=>clearTimeout(re)),()=>{O.abort(),clearTimeout(re)}},[f,r,o,I]);let x=ai(()=>fs(p,m,void 0),[p,m]),v=dc(x);Df({widgetEvents:c,api:x.api??f,token:x.token??r,channelId:x.channelId??o,source:x.source,mode:"inline",pagePrompts:v.page,getSessionId:()=>u.current?.sessionId}),Do(()=>{if(!r)return;let G=Kf({api:f,token:r,channelId:()=>o??ko(f,r,o)?.channelId,getSource:()=>ko(f,r,o)?.source??void 0,getSessionId:()=>u.current?.sessionId});return d.current=G,()=>{d.current=null,G.shutdown()}},[f,r,o]),HS(a,()=>{let G=()=>d.current??ti("no public token configured"),Q=Object.assign(O=>G().track(O),{priceShown:O=>G().track.priceShown(O),pricesCompared:O=>G().track.pricesCompared(O),optionSelected:O=>G().track.optionSelected(O),leadQualified:O=>G().track.leadQualified(O),converted:O=>G().track.converted(O)});return{sendMessage:O=>u.current?.sendMessage(O),sendMessageAndWait:O=>u.current?u.current.sendMessageAndWait(O):Promise.resolve(void 0),reset:()=>u.current?.reset(),focus:()=>u.current?.focus(),get messages(){return u.current?.messages??[]},get sessionId(){return u.current?.sessionId},track:Q,identify:(O,re)=>G().identify(O,re)}},[]);let q=ic(x.visibility,S);tl({api:x.api??f,token:x.token??r,channelId:x.channelId??o,mode:"inline",paintMark:"chatVisible",painted:S&&q});let N={mode:"inline"};x.mcpServerUrl&&(N.mcpServerUrl=x.mcpServerUrl),x.channelId&&(N.channelId=x.channelId);let V=Rf(i?.sessionApi??x.sessionApi);return q?Qf(_d,{value:c,children:Qf(cs,{ref:u,api:x.api??Jf,transport:V,headers:{Authorization:`Bearer ${x.token}`},visitorId:s,skipRemoteConfig:!0,body:N,appearance:x.appearance,classNames:i?.classNames,title:x.title,hideHeader:x.hideHeader,welcomeMessage:x.welcomeMessage,welcome:i?.welcome,placeholder:x.placeholder,suggestions:v,enableThreadHistory:x.enableThreadHistory,showToolCalls:x.showToolCalls,disclaimer:x.disclaimer,documentUpload:x.documentUpload,allowAttachments:i?.allowAttachments,locale:x.locale,messages:i?.messages,className:n,initializing:!S})}):null});export{cs as ChatEmbed,Ax as DARK_THEME,ac as DEFAULT_THEME,Ba as McpAppFrame,WS as WaniwaniChat,Wm as WebMcpOverlay,Rx as mergeTheme,ds as themeToCSSProperties};
|
|
24
24
|
/*! Bundled license information:
|
|
25
25
|
|
|
26
26
|
lucide-react/dist/esm/shared/src/utils/mergeClasses.js:
|