chain-insights 0.57.1 → 0.57.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- <!-- Chain Insights UI 413eef6c69ce271dbe460e6f657d049339a6c393 (npm run build:claude-view); refresh with scripts/refresh-claude-view.mjs, never edit by hand -->
1
+ <!-- Chain Insights UI da4ebdef03dd8fa40817af5f7931011589385531 (npm run build:claude-view); refresh with scripts/refresh-claude-view.mjs, never edit by hand -->
2
2
  <!doctype html>
3
3
  <html lang="en">
4
4
  <head>
@@ -6,50 +6,50 @@
6
6
  <meta name="viewport" content="width=device-width,initial-scale=1">
7
7
  <meta name="color-scheme" content="light dark">
8
8
  <title>Chain Insights view</title>
9
- <script type="module">const ck=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),lk=function(e,t){return new URL(e,t).href},fh={},dk=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const s=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),u=a?.nonce||a?.getAttribute("nonce");i=c(n.map(l=>{if(l=lk(l,r),l in fh)return;fh[l]=!0;const d=l.endsWith(".css"),f=d?'[rel="stylesheet"]':"";if(r)for(let p=s.length-1;p>=0;p--){const m=s[p];if(m.href===l&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${f}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":ck,d||(h.as="script"),h.crossOrigin="",h.href=l,u&&h.setAttribute("nonce",u),document.head.appendChild(h),d)return new Promise((p,m)=>{h.addEventListener("load",p),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return i.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function fk(e){return e}function hk(e){return e}function $s(){return e=>e}function pk(e){}function mk(e){throw new Error("Unexpected value in exhaustive check")}function gk(e){}function os(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Ou(e,t="|"){return e.map(n=>xc(n)).join(t)}function ss(e,t){return typeof t=="bigint"?t.toString():t}class yk{constructor(t){this._getter=t,this._value=void 0}get value(){const t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}}function ki(e){return new yk(e)}function _c(e){return e==null}function Cn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function kc(e,t){const n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const hh=Symbol("evaluating");function bm(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==hh)return r===void 0&&(r=hh,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function vk(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function It(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ts(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function cn(e){return Ts(e._zod.def)??e._zod.def.shape}function wm(e,t,n){Object.defineProperty(e,t,{get(){const r=n();return It(this,t,r),r},enumerable:!0,configurable:!0})}function _m(e,t,n){t in e?It(e,t,n):e[t]=n}function Hn(e,t,n,r){const i=cn(t);for(const o of n){const s=Object.getOwnPropertyDescriptor(i,o);s.enumerable&&(s.get?wm(e,o,()=>{const a=t._zod.def.shape[o];return r?r(a,o):a}):_m(e,o,r?r(s.value,o):s.value))}}function bk(e,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?wm(e,n,()=>t[n]):_m(e,n,r.value))}}function dt(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function wk(e){return dt(e._zod.def)}function _k(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function kk(e){const t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{const i={};for(let o=0;o<t.length;o++)i[t[o]]=r[o];return i})}function Sk(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function $t(e){return JSON.stringify(e)}function km(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Sc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ur(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Sm=ki(()=>{if(bt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ln(e){if(ur(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ur(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Si(e){return ln(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function xk(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const Ek=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},as=new Set(["string","number","symbol"]),xm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Be(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function R(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function $k(e){let t;return new Proxy({},{get(n,r,i){return t??(t=e()),Reflect.get(t,r,i)},set(n,r,i,o){return t??(t=e()),Reflect.set(t,r,i,o)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??(t=e()),Reflect.defineProperty(t,r,i)}})}function xc(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Em(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}const Ec={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$c={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $m(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const o={};return Hn(o,e,Cs(e,t)),Be(e,dt(n,{shape:o,checks:[]}))}function Cs(e,t){const n=cn(e),r=[];for(const i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw new Error(`Unrecognized key: "${String(i)}"`);t[i]&&r.push(i)}return r}function Tm(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=new Set(Cs(e,t)),s={};return Hn(s,e,Reflect.ownKeys(cn(e)).filter(a=>!o.has(a))),Be(e,dt(n,{shape:s,checks:[]}))}function Cm(e,t){if(!ln(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=cn(e);for(const o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(i,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Be(e,dt(e._zod.def,{shape:Am(e,t)}))}function Am(e,t){const n={};return Hn(n,e,Reflect.ownKeys(cn(e))),bk(n,t),n}function Im(e,t){if(!ln(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Be(e,dt(e._zod.def,{shape:Am(e,t)}))}function Nm(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};Hn(n,e,Reflect.ownKeys(cn(e))),Hn(n,t,Reflect.ownKeys(cn(t)));const r=dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Be(e,r)}function Mu(e,t,n,r="partial"){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);const a=n?new Set(Cs(t,n)):void 0,u={};return Hn(u,t,Reflect.ownKeys(cn(t)),e&&((c,l)=>a&&!a.has(l)?c:new e({type:"optional",innerType:c}))),Be(t,dt(t._zod.def,{shape:u,checks:[]}))}function Rm(e,t,n){const r=n?new Set(Cs(t,n)):void 0,i={};return Hn(i,t,Reflect.ownKeys(cn(t)),(o,s)=>r&&!r.has(s)?o:new e({type:"nonoptional",innerType:o})),Be(t,dt(t._zod.def,{shape:i}))}function kt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Lm(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Dt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function nr(e){return typeof e=="string"?e:e?.message}function Fu(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Mt(e,t,n){var r;const i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);const o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:nr(e.inst?._zod.def?.error?.(e))??nr(o?.(e))??nr(t?.error?.(e))??nr(n.customError?.(e))??nr(n.localeError?.(e))??"Invalid input",a={};for(const u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=e[u]);return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=e.input),a}function As(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}const Tk=/[\uD800-\uDBFF]/;function xi(e){const t=e.length;if(!Tk.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320&&(n--,r++);return n}function Is(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function zm(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function cr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function Ck(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Pm(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Dm(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Ak(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return Pm(t+n)}function Ik(e){return Dm(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Nk(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function Rk(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class Lk{constructor(...t){}}function Om(e,t){for(const n in t){const r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):zk(e,n,r.value)}}function fn(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ns(e,t,n){return fn(e,t,n,!1)}function Ei(e,t){for(const n in e){const r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return fn(this,n,r(this))},set(i){fn(this,n,i)}})}return t}function zk(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:fn(this,t,n.bind(this))},set(r){fn(this,t,r)}})}function Pk(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let ou,_n=!1;const Dk={configurable:!0,get(){_n=!0}};function Te(e,t,n){const r=Object.getPrototypeOf(e._zod);if(t in r&&ou!==e._zod){ou=void 0;return}ou=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Dk);const i=_n;_n=!1;try{const o=n(this);return _n?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o}),_n=_n||i,o}catch(o){throw delete this[t],_n=_n||i,o}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function Mm(e,t,n,r){const i=Pk(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){const o={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,o),o.value=n(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:o})}})}const Tc="~constantCatch";function Cc(e){const t=()=>e;return t[Tc]=!0,t}const Ac=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:$c,CONSTANT_CATCH:Tc,Class:Lk,NUMBER_FORMAT_RANGES:Ec,aborted:kt,allowsEval:Sm,assert:gk,assertEqual:fk,assertIs:pk,assertNever:mk,assertNotEqual:hk,assignProp:It,attachSchema:Fu,base64ToUint8Array:Pm,base64urlToUint8Array:Ak,cached:ki,captureStackTrace:Sc,cleanEnum:Ck,cleanRegex:Cn,clone:Be,cloneDef:wk,codePointLength:xi,constantCatch:Cc,createTransparentProxy:$k,defineLazy:bm,defineLazyInternal:Te,derived:Ei,esc:$t,escapeRegex:dn,explicitlyAborted:Lm,extend:Cm,finalizeIssue:Mt,floatSafeRemainder:kc,getElementAtPath:_k,getEnumValues:os,getLengthableOrigin:Is,getParsedType:Ek,getSizableOrigin:As,hexToUint8Array:Nk,hide:Ns,installLazyProp:Mm,isObject:ur,isPlainObject:ln,issue:cr,joinValues:Ou,jsonStringifyReplacer:ss,members:Om,merge:Nm,mergeDefs:dt,normalizeParams:R,nullish:_c,numKeys:xk,objectClone:vk,omit:Tm,optionalKeys:Em,own:fn,parsedType:zm,partial:Mu,pick:$m,prefixIssues:Dt,primitiveTypes:xm,promiseAllObject:kk,propertyKeyTypes:as,randomString:Sk,rawShape:Ts,required:Rm,safeExtend:Im,shallowClone:Si,slugify:km,stringifyPrimitive:xc,toZod:$s,uint8ArrayToBase64:Dm,uint8ArrayToBase64url:Ik,uint8ArrayToHex:Rk,unwrapMessage:nr},Symbol.toStringTag,{value:"Module"}));var ph;const Ic=Object.freeze({status:"aborted"}),su={value:void 0,enumerable:!1};let mh="captureStackTrace"in Error?Error:null;function Ok(e){const t=mh;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return mh=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function x(e,t,n,r){const i={};function o(f){this.def=f,this.constr=d,this.traits=new Set}o.prototype=i;const s=n,a=s&&new WeakSet;function u(f,h){if(f._zod){if(f._zod.traits.has(e))return}else{su.value=new o(h);try{Object.defineProperty(f,"_zod",su)}finally{su.value=void 0}}if(f._zod.traits.add(e),t(f,h),a){const m=Object.getPrototypeOf(f),y=f._zod.constr.prototype;let w=m;for(;w&&w!==y;)w=Object.getPrototypeOf(w);const g=w??m;a.has(g)||(a.add(g),Om(g,s))}const p=d.prototype;for(const m in p)Object.prototype.hasOwnProperty.call(p,m)&&(m in f||(f[m]=p[m].bind(f)))}const c=r?.Parent??Object;class l extends c{}Object.defineProperty(l,"name",{value:e});function d(f){const h=r?.Parent?Ok(l):this;u(h,f);const p=h._zod.deferred;if(p){for(const y of p)y();h._zod.deferred=void 0}const m=globalThis.__zod_globalConfig?.postProcessor;return m&&m(h),h}return Object.defineProperty(d,"init",{value:u}),Object.defineProperty(d,Symbol.hasInstance,{value:f=>r?.Parent&&f instanceof r.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}const Nc=Symbol("zod_brand");class an extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Rs extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(ph=globalThis).__zod_globalConfig??(ph.__zod_globalConfig={});const bt=globalThis.__zod_globalConfig;function Qe(e){return e&&Object.assign(bt,e),bt}function Mk(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,ss,2)),e.message}function Fk(e){this._zod.message=e}const Uk={get:Mk,set:Fk,enumerable:!0,configurable:!0},au={value:void 0,enumerable:!1},gh=new WeakSet([Object.prototype,Error.prototype]),Fm=(e,t)=>{e.name="$ZodError",au.value=t,Object.defineProperty(e,"issues",au),au.value=void 0,Object.defineProperty(e,"message",Uk);const n=Object.getPrototypeOf(e);gh.has(n)||(gh.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},Um=x("$ZodError",Fm),Nt=x("$ZodError",Fm,void 0,{Parent:Error});function Gk(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ls(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?Gk(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function zs(e,t=n=>n.message){const n={_errors:[]},r=(i,o=[])=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>r({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{const a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;for(;c<a.length;){const l=a[c],d=c===a.length-1;if(l==="_errors"){d&&u._errors.push(t(s)),c++;continue}Object.prototype.hasOwnProperty.call(u,l)||Object.defineProperty(u,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const f=u[l];d&&f._errors.push(t(s)),u=f,c++}}}};return r(e),n}function Rc(e,t=n=>n.message){const n={errors:[]},r=(i,o=[])=>{var s;for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>r({issues:u},[...o,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...o,...a.path]);else{const u=[...o,...a.path];if(u.length===0){n.errors.push(t(a));continue}let c=n,l=0;for(;l<u.length;){const d=u[l],f=l===u.length-1;typeof d=="string"?(c.properties??(c.properties={}),Object.prototype.hasOwnProperty.call(c.properties,d)||Object.defineProperty(c.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),c=c.properties[d]):(c.items??(c.items=[]),(s=c.items)[d]??(s[d]={errors:[]}),c=c.items[d]),f&&c.errors.push(t(a)),l++}}};return r(e),n}function Gm(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Lc(e){const t=[],n=[...e.issues].sort((r,i)=>(r.path??[]).length-(i.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${Gm(r.path)}`);return t.join(`
10
- `)}function Ps(e,t){return{callee:t?.callee??e,Err:t?.Err}}const $i=e=>{const t=(n,r,i,o)=>{const s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new an;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(c=>Mt(c,s,Qe())));throw Sc(u,o?.callee??t),u}return a.value};return t},Uu=$i(Nt),Ti=e=>{const t=async(n,r,i,o)=>{const s=i?{...i,async:!0}:{async:!0};let a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(c=>Mt(c,s,Qe())));throw Sc(u,o?.callee??t),u}return a.value};return t},Gu=Ti(Nt),Ci=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new an;return o.issues.length?Zm(e,o.issues,i):{success:!0,data:o.value}},jm=Ci(Nt);function Zm(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(i=>Mt(i,n,Qe()))),t=void 0,n=void 0),r},set error(i){r=i,t=void 0,n=void 0}}}const Ai=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?Zm(e,o.issues,i):{success:!0,data:o.value}},jk=Ai(Nt),Zk=Symbol.for("zod.compile.invalid"),Bk=Symbol.for("zod.compile.fallback"),Ds=((e,t,n)=>{const r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Zk)return!0;if(r.definite===!0&&n===void 0)return!1}return Hk(e,t,n)});function Hk(e,t,n){const r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun;let o;if(i?(r[Bk]=!0,o=i({value:t,issues:[]},r)):o=e._zod.run({value:t,issues:[]},r),o instanceof Promise)throw new an;return o.issues.length===0}const Os=async(e,t,n)=>{const r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},zc=e=>{const t=$i(e),n=(r,i,o,s)=>{const a=o?{...o,direction:"backward"}:{direction:"backward"};return t(r,i,a,Ps(n,s))};return n},Vk=zc(Nt),Pc=e=>{const t=$i(e),n=(r,i,o,s)=>t(r,i,o,Ps(n,s));return n},qk=Pc(Nt),Dc=e=>{const t=Ti(e),n=async(r,i,o,s)=>{const a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(r,i,a,Ps(n,s))};return n},Wk=Dc(Nt),Oc=e=>{const t=Ti(e),n=async(r,i,o,s)=>await t(r,i,o,Ps(n,s));return n},Kk=Oc(Nt),Mc=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Ci(e)(t,n,i)},Jk=Mc(Nt),Fc=e=>(t,n,r)=>Ci(e)(t,n,r),Yk=Fc(Nt),Uc=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Ai(e)(t,n,i)},Xk=Uc(Nt),Gc=e=>async(t,n,r)=>Ai(e)(t,n,r),Qk=Gc(Nt),Bm=/^[cC][0-9a-z]{6,}$/,Hm=/^[0-9a-z]+$/,Vm=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,qm=/^[0-9a-vA-V]{20}$/,Wm=/^[A-Za-z0-9]{27}$/,Km=/^[a-zA-Z0-9_-]{21}$/;function Jm(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Ym=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,eS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Xm=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,lr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tS=lr(4),nS=lr(6),rS=lr(7),Qm=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iS=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,oS=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,eg=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,sS=eg,aS=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,uS="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function tg(){return new RegExp(uS,"u")}const ng=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ig=e=>{const t=dn(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},og=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,sg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ag=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ug=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,cg=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,lg=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,jc=/^https?$/,dg=/^\+[1-9]\d{6,14}$/,Zc=/^\d(?:[ -]?\d){11,18}$/,fg=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,Bc=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,hg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function cS(e){return new RegExp(`^${e}$`)}const pg=cS(hg);function ju(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function mg(e){return new RegExp(`^${ju(e)}$`)}function gg(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${ju({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${ju({precision:e.precision})}`:n;return new RegExp(`^${hg}T(?:${r})$`)}const yg=/^[\s\S]{0,}$/,vg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},bg=/^-?\d+n?$/,Hc=/^-?\d+$/,kr=/^-?\d+(?:\.\d+)?$/,wg=/^(?:true|false)$/i,_g=/^null$/i,kg=/^undefined$/i,Sg=/^[^A-Z]*$/,xg=/^[^a-z]*$/,Eg=/^[0-9a-fA-F]*$/;function Ii(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ni(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const lS=/^[0-9a-fA-F]{32}$/,dS=Ii(22,"=="),fS=Ni(22),hS=/^[0-9a-fA-F]{40}$/,pS=Ii(27,"="),mS=Ni(27),gS=/^[0-9a-fA-F]{64}$/,yS=Ii(43,"="),vS=Ni(43),bS=/^[0-9a-fA-F]{96}$/,wS=Ii(64,""),_S=Ni(64),kS=/^[0-9a-fA-F]{128}$/,SS=Ii(86,"=="),xS=Ni(86),Ms=Object.freeze(Object.defineProperty({__proto__:null,anyString:yg,base64:ag,base64url:ug,bigint:bg,boolean:wg,browserEmail:aS,cidrv4:og,cidrv6:sg,creditCard:Zc,cuid:Bm,cuid2:Hm,currencyCode:fg,date:pg,datetime:gg,domain:lg,duration:Ym,e164:dg,email:Qm,emoji:tg,extendedDuration:eS,guid:Xm,hex:Eg,hostname:cg,html5Email:iS,httpProtocol:jc,iban:Bc,idnEmail:sS,integer:Hc,ipv4:ng,ipv6:rg,ksuid:Wm,lowercase:Sg,mac:ig,md5_base64:dS,md5_base64url:fS,md5_hex:lS,nanoid:Km,nanoidOfLength:Jm,null:_g,number:kr,rfc5322Email:oS,sha1_base64:pS,sha1_base64url:mS,sha1_hex:hS,sha256_base64:yS,sha256_base64url:vS,sha256_hex:gS,sha384_base64:wS,sha384_base64url:_S,sha384_hex:bS,sha512_base64:SS,sha512_base64url:xS,sha512_hex:kS,string:vg,time:mg,ulid:Vm,undefined:kg,unicodeEmail:eg,uppercase:xg,uuid:lr,uuid4:tS,uuid6:nS,uuid7:rS,xid:qm},Symbol.toStringTag,{value:"Module"})),He=x("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Vc=e=>{const t=e.value;return!_c(t)&&t.size!==void 0},qc=e=>{const t=e.value;return!_c(t)&&t.length!==void 0},us={number:"number",bigint:"bigint",object:"date"},Wc=x("$ZodCheckLessThan",(e,t)=>{He.init(e,t);const n=us[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:us[typeof r.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Kc=x("$ZodCheckGreaterThan",(e,t)=>{He.init(e,t);const n=us[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:us[typeof r.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$g=x("$ZodCheckMultipleOf",(e,t)=>{He.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):kc(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Tg=x("$ZodCheckNumberFormat",(e,t)=>{He.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=Ec[t.format];e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Cg=x("$ZodCheckBigIntFormat",(e,t)=>{He.init(e,t);const[n,r]=$c[t.format];e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Ag=x("$ZodCheckMaxSize",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=Vc),e._zod.check=r=>{const i=r.value;i.size<=t.maximum||r.issues.push({origin:As(i),code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ig=x("$ZodCheckMinSize",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=Vc),e._zod.check=r=>{const i=r.value;i.size>=t.minimum||r.issues.push({origin:As(i),code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ng=x("$ZodCheckSizeEquals",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=Vc),e._zod.check=r=>{const i=r.value,o=i.size;if(o===t.size)return;const s=o>t.size;r.issues.push({origin:As(i),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Rg=x("$ZodCheckMaxLength",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value,o=i.length;if((typeof i=="string"&&o>t.maximum?xi(i):o)<=t.maximum)return;const a=Is(i);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Lg=x("$ZodCheckMinLength",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value,o=i.length;if((typeof i=="string"&&o>=t.minimum&&o<t.minimum*2?xi(i):o)>=t.minimum)return;const a=Is(i);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),zg=x("$ZodCheckLengthEquals",(e,t)=>{var n;He.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value,o=i.length,s=typeof i=="string"&&o>=t.length&&o<=t.length*2?xi(i):o;if(s===t.length)return;const a=Is(i),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Ri=x("$ZodCheckStringFormat",(e,t)=>{var n,r;He.init(e,t),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Pg=x("$ZodCheckRegex",(e,t)=>{Ri.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dg=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Sg),Ri.init(e,t)}),Og=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xg),Ri.init(e,t)}),Mg=x("$ZodCheckIncludes",(e,t)=>{He.init(e,t);const n=dn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Fg=x("$ZodCheckStartsWith",(e,t)=>{He.init(e,t);const n=new RegExp(`^${dn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Ug=x("$ZodCheckEndsWith",(e,t)=>{He.init(e,t);const n=new RegExp(`.*${dn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function cs(e,t,n){e.issues.length&&t.issues.push(...Dt(n,e.issues))}const Gg=x("$ZodCheckProperty",(e,t)=>{He.init(e,t),e._zod.check=n=>{const r=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(i=>cs(i,n,t.property));cs(r,n,t.property)}}),jg=x("$ZodCheckProperties",(e,t)=>{He.init(e,t),Ns(e,Symbol.iterator,function*(){yield e});let n;e._zod.check=r=>{if(r.value==null){r.issues.push({expected:"object",code:"invalid_type",input:r.value,inst:e});return}n??(n=Reflect.ownKeys(t.shape).map(s=>[s,t.shape[s]]));const i=r.value;let o;for(const[s,a]of n){const u=a._zod.run({value:i[s],issues:[]},{});u instanceof Promise?(o??(o=[]),o.push(u.then(c=>cs(c,r,s)))):cs(u,r,s)}if(o)return Promise.all(o).then(()=>{})}}),Zg=x("$ZodCheckMimeType",(e,t)=>{He.init(e,t);const n=new Set(t.mime);e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),Bg=x("$ZodCheckOverwrite",(e,t)=>{He.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Jc{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
9
+ <script type="module">const fk=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),hk=function(e,t){return new URL(e,t).href},ph={},pk=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const s=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),u=a?.nonce||a?.getAttribute("nonce");i=c(n.map(l=>{if(l=hk(l,r),l in ph)return;ph[l]=!0;const d=l.endsWith(".css"),f=d?'[rel="stylesheet"]':"";if(r)for(let p=s.length-1;p>=0;p--){const m=s[p];if(m.href===l&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${f}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":fk,d||(h.as="script"),h.crossOrigin="",h.href=l,u&&h.setAttribute("nonce",u),document.head.appendChild(h),d)return new Promise((p,m)=>{h.addEventListener("load",p),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return i.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function mk(e){return e}function gk(e){return e}function Cs(){return e=>e}function yk(e){}function vk(e){throw new Error("Unexpected value in exhaustive check")}function bk(e){}function as(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Mu(e,t="|"){return e.map(n=>Ec(n)).join(t)}function us(e,t){return typeof t=="bigint"?t.toString():t}class wk{constructor(t){this._getter=t,this._value=void 0}get value(){const t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}}function xi(e){return new wk(e)}function kc(e){return e==null}function An(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Sc(e,t){const n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const mh=Symbol("evaluating");function _m(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==mh)return r===void 0&&(r=mh,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function _k(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function At(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function As(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function cn(e){return As(e._zod.def)??e._zod.def.shape}function km(e,t,n){Object.defineProperty(e,t,{get(){const r=n();return At(this,t,r),r},enumerable:!0,configurable:!0})}function Sm(e,t,n){t in e?At(e,t,n):e[t]=n}function Hn(e,t,n,r){const i=cn(t);for(const o of n){const s=Object.getOwnPropertyDescriptor(i,o);s.enumerable&&(s.get?km(e,o,()=>{const a=t._zod.def.shape[o];return r?r(a,o):a}):Sm(e,o,r?r(s.value,o):s.value))}}function kk(e,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?km(e,n,()=>t[n]):Sm(e,n,r.value))}}function dt(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Sk(e){return dt(e._zod.def)}function xk(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function Ek(e){const t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{const i={};for(let o=0;o<t.length;o++)i[t[o]]=r[o];return i})}function $k(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function $t(e){return JSON.stringify(e)}function xm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const xc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function cr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Em=xi(()=>{if(bt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ln(e){if(cr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(cr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ei(e){return ln(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Tk(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const Ck=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},cs=new Set(["string","number","symbol"]),$m=new Set(["string","number","bigint","boolean","symbol","undefined"]);function dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Be(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function R(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ak(e){let t;return new Proxy({},{get(n,r,i){return t??(t=e()),Reflect.get(t,r,i)},set(n,r,i,o){return t??(t=e()),Reflect.set(t,r,i,o)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??(t=e()),Reflect.defineProperty(t,r,i)}})}function Ec(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Tm(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}const $c={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Tc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Cm(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const o={};return Hn(o,e,Is(e,t)),Be(e,dt(n,{shape:o,checks:[]}))}function Is(e,t){const n=cn(e),r=[];for(const i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw new Error(`Unrecognized key: "${String(i)}"`);t[i]&&r.push(i)}return r}function Am(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=new Set(Is(e,t)),s={};return Hn(s,e,Reflect.ownKeys(cn(e)).filter(a=>!o.has(a))),Be(e,dt(n,{shape:s,checks:[]}))}function Im(e,t){if(!ln(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=cn(e);for(const o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(i,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Be(e,dt(e._zod.def,{shape:Nm(e,t)}))}function Nm(e,t){const n={};return Hn(n,e,Reflect.ownKeys(cn(e))),kk(n,t),n}function Rm(e,t){if(!ln(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Be(e,dt(e._zod.def,{shape:Nm(e,t)}))}function Lm(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};Hn(n,e,Reflect.ownKeys(cn(e))),Hn(n,t,Reflect.ownKeys(cn(t)));const r=dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Be(e,r)}function Fu(e,t,n,r="partial"){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);const a=n?new Set(Is(t,n)):void 0,u={};return Hn(u,t,Reflect.ownKeys(cn(t)),e&&((c,l)=>a&&!a.has(l)?c:new e({type:"optional",innerType:c}))),Be(t,dt(t._zod.def,{shape:u,checks:[]}))}function zm(e,t,n){const r=n?new Set(Is(t,n)):void 0,i={};return Hn(i,t,Reflect.ownKeys(cn(t)),(o,s)=>r&&!r.has(s)?o:new e({type:"nonoptional",innerType:o})),Be(t,dt(t._zod.def,{shape:i}))}function kt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Pm(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Pt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function rr(e){return typeof e=="string"?e:e?.message}function Uu(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Mt(e,t,n){var r;const i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);const o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:rr(e.inst?._zod.def?.error?.(e))??rr(o?.(e))??rr(t?.error?.(e))??rr(n.customError?.(e))??rr(n.localeError?.(e))??"Invalid input",a={};for(const u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=e[u]);return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=e.input),a}function Ns(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}const Ik=/[\uD800-\uDBFF]/;function $i(e){const t=e.length;if(!Ik.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320&&(n--,r++);return n}function Rs(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Dm(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function lr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function Nk(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Om(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Mm(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Rk(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return Om(t+n)}function Lk(e){return Mm(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zk(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function Pk(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class Dk{constructor(...t){}}function Fm(e,t){for(const n in t){const r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Ok(e,n,r.value)}}function fn(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ls(e,t,n){return fn(e,t,n,!1)}function Ti(e,t){for(const n in e){const r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return fn(this,n,r(this))},set(i){fn(this,n,i)}})}return t}function Ok(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:fn(this,t,n.bind(this))},set(r){fn(this,t,r)}})}function Mk(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let su,_n=!1;const Fk={configurable:!0,get(){_n=!0}};function $e(e,t,n){const r=Object.getPrototypeOf(e._zod);if(t in r&&su!==e._zod){su=void 0;return}su=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Fk);const i=_n;_n=!1;try{const o=n(this);return _n?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o}),_n=_n||i,o}catch(o){throw delete this[t],_n=_n||i,o}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function Um(e,t,n,r){const i=Mk(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){const o={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,o),o.value=n(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:o})}})}const Cc="~constantCatch";function Ac(e){const t=()=>e;return t[Cc]=!0,t}const Ic=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:Tc,CONSTANT_CATCH:Cc,Class:Dk,NUMBER_FORMAT_RANGES:$c,aborted:kt,allowsEval:Em,assert:bk,assertEqual:mk,assertIs:yk,assertNever:vk,assertNotEqual:gk,assignProp:At,attachSchema:Uu,base64ToUint8Array:Om,base64urlToUint8Array:Rk,cached:xi,captureStackTrace:xc,cleanEnum:Nk,cleanRegex:An,clone:Be,cloneDef:Sk,codePointLength:$i,constantCatch:Ac,createTransparentProxy:Ak,defineLazy:_m,defineLazyInternal:$e,derived:Ti,esc:$t,escapeRegex:dn,explicitlyAborted:Pm,extend:Im,finalizeIssue:Mt,floatSafeRemainder:Sc,getElementAtPath:xk,getEnumValues:as,getLengthableOrigin:Rs,getParsedType:Ck,getSizableOrigin:Ns,hexToUint8Array:zk,hide:Ls,installLazyProp:Um,isObject:cr,isPlainObject:ln,issue:lr,joinValues:Mu,jsonStringifyReplacer:us,members:Fm,merge:Lm,mergeDefs:dt,normalizeParams:R,nullish:kc,numKeys:Tk,objectClone:_k,omit:Am,optionalKeys:Tm,own:fn,parsedType:Dm,partial:Fu,pick:Cm,prefixIssues:Pt,primitiveTypes:$m,promiseAllObject:Ek,propertyKeyTypes:cs,randomString:$k,rawShape:As,required:zm,safeExtend:Rm,shallowClone:Ei,slugify:xm,stringifyPrimitive:Ec,toZod:Cs,uint8ArrayToBase64:Mm,uint8ArrayToBase64url:Lk,uint8ArrayToHex:Pk,unwrapMessage:rr},Symbol.toStringTag,{value:"Module"}));var gh;const Nc=Object.freeze({status:"aborted"}),au={value:void 0,enumerable:!1};let yh="captureStackTrace"in Error?Error:null;function Uk(e){const t=yh;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return yh=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function S(e,t,n,r){const i={};function o(f){this.def=f,this.constr=d,this.traits=new Set}o.prototype=i;const s=n,a=s&&new WeakSet;function u(f,h){if(f._zod){if(f._zod.traits.has(e))return}else{au.value=new o(h);try{Object.defineProperty(f,"_zod",au)}finally{au.value=void 0}}if(f._zod.traits.add(e),t(f,h),a){const m=Object.getPrototypeOf(f),y=f._zod.constr.prototype;let _=m;for(;_&&_!==y;)_=Object.getPrototypeOf(_);const g=_??m;a.has(g)||(a.add(g),Fm(g,s))}const p=d.prototype;for(const m in p)Object.prototype.hasOwnProperty.call(p,m)&&(m in f||(f[m]=p[m].bind(f)))}const c=r?.Parent??Object;class l extends c{}Object.defineProperty(l,"name",{value:e});function d(f){const h=r?.Parent?Uk(l):this;u(h,f);const p=h._zod.deferred;if(p){for(const y of p)y();h._zod.deferred=void 0}const m=globalThis.__zod_globalConfig?.postProcessor;return m&&m(h),h}return Object.defineProperty(d,"init",{value:u}),Object.defineProperty(d,Symbol.hasInstance,{value:f=>r?.Parent&&f instanceof r.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}const Rc=Symbol("zod_brand");class an extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class zs extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(gh=globalThis).__zod_globalConfig??(gh.__zod_globalConfig={});const bt=globalThis.__zod_globalConfig;function Qe(e){return e&&Object.assign(bt,e),bt}function Gk(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,us,2)),e.message}function jk(e){this._zod.message=e}const Zk={get:Gk,set:jk,enumerable:!0,configurable:!0},uu={value:void 0,enumerable:!1},vh=new WeakSet([Object.prototype,Error.prototype]),Gm=(e,t)=>{e.name="$ZodError",uu.value=t,Object.defineProperty(e,"issues",uu),uu.value=void 0,Object.defineProperty(e,"message",Zk);const n=Object.getPrototypeOf(e);vh.has(n)||(vh.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},jm=S("$ZodError",Gm),It=S("$ZodError",Gm,void 0,{Parent:Error});function Bk(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ps(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?Bk(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ds(e,t=n=>n.message){const n={_errors:[]},r=(i,o=[])=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>r({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{const a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,c=0;for(;c<a.length;){const l=a[c],d=c===a.length-1;if(l==="_errors"){d&&u._errors.push(t(s)),c++;continue}Object.prototype.hasOwnProperty.call(u,l)||Object.defineProperty(u,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const f=u[l];d&&f._errors.push(t(s)),u=f,c++}}}};return r(e),n}function Lc(e,t=n=>n.message){const n={errors:[]},r=(i,o=[])=>{var s;for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>r({issues:u},[...o,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...o,...a.path]);else{const u=[...o,...a.path];if(u.length===0){n.errors.push(t(a));continue}let c=n,l=0;for(;l<u.length;){const d=u[l],f=l===u.length-1;typeof d=="string"?(c.properties??(c.properties={}),Object.prototype.hasOwnProperty.call(c.properties,d)||Object.defineProperty(c.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),c=c.properties[d]):(c.items??(c.items=[]),(s=c.items)[d]??(s[d]={errors:[]}),c=c.items[d]),f&&c.errors.push(t(a)),l++}}};return r(e),n}function Zm(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function zc(e){const t=[],n=[...e.issues].sort((r,i)=>(r.path??[]).length-(i.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${Zm(r.path)}`);return t.join(`
10
+ `)}function Os(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Ci=e=>{const t=(n,r,i,o)=>{const s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new an;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(c=>Mt(c,s,Qe())));throw xc(u,o?.callee??t),u}return a.value};return t},Gu=Ci(It),Ai=e=>{const t=async(n,r,i,o)=>{const s=i?{...i,async:!0}:{async:!0};let a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(c=>Mt(c,s,Qe())));throw xc(u,o?.callee??t),u}return a.value};return t},ju=Ai(It),Ii=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new an;return o.issues.length?Vm(e,o.issues,i):{success:!0,data:o.value}},Bm=Ii(It);function Vm(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(i=>Mt(i,n,Qe()))),t=void 0,n=void 0),r},set error(i){r=i,t=void 0,n=void 0}}}const Ni=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?Vm(e,o.issues,i):{success:!0,data:o.value}},Vk=Ni(It),Hk=Symbol.for("zod.compile.invalid"),qk=Symbol.for("zod.compile.fallback"),Ms=((e,t,n)=>{const r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Hk)return!0;if(r.definite===!0&&n===void 0)return!1}return Wk(e,t,n)});function Wk(e,t,n){const r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun;let o;if(i?(r[qk]=!0,o=i({value:t,issues:[]},r)):o=e._zod.run({value:t,issues:[]},r),o instanceof Promise)throw new an;return o.issues.length===0}const Fs=async(e,t,n)=>{const r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},Pc=e=>{const t=Ci(e),n=(r,i,o,s)=>{const a=o?{...o,direction:"backward"}:{direction:"backward"};return t(r,i,a,Os(n,s))};return n},Kk=Pc(It),Dc=e=>{const t=Ci(e),n=(r,i,o,s)=>t(r,i,o,Os(n,s));return n},Jk=Dc(It),Oc=e=>{const t=Ai(e),n=async(r,i,o,s)=>{const a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(r,i,a,Os(n,s))};return n},Yk=Oc(It),Mc=e=>{const t=Ai(e),n=async(r,i,o,s)=>await t(r,i,o,Os(n,s));return n},Xk=Mc(It),Fc=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Ii(e)(t,n,i)},Qk=Fc(It),Uc=e=>(t,n,r)=>Ii(e)(t,n,r),eS=Uc(It),Gc=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Ni(e)(t,n,i)},tS=Gc(It),jc=e=>async(t,n,r)=>Ni(e)(t,n,r),nS=jc(It),Hm=/^[cC][0-9a-z]{6,}$/,qm=/^[0-9a-z]+$/,Wm=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Km=/^[0-9a-vA-V]{20}$/,Jm=/^[A-Za-z0-9]{27}$/,Ym=/^[a-zA-Z0-9_-]{21}$/;function Xm(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Qm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,rS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,eg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,dr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,iS=dr(4),oS=dr(6),sS=dr(7),tg=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,aS=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,uS=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,ng=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,cS=ng,lS=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dS="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function rg(){return new RegExp(dS,"u")}const ig=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,og=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,sg=e=>{const t=dn(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},ag=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ug=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,lg=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,dg=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,fg=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,Zc=/^https?$/,hg=/^\+[1-9]\d{6,14}$/,Bc=/^\d(?:[ -]?\d){11,18}$/,pg=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,Vc=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,mg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function fS(e){return new RegExp(`^${e}$`)}const gg=fS(mg);function Zu(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yg(e){return new RegExp(`^${Zu(e)}$`)}function vg(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${Zu({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Zu({precision:e.precision})}`:n;return new RegExp(`^${mg}T(?:${r})$`)}const bg=/^[\s\S]{0,}$/,wg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_g=/^-?\d+n?$/,Hc=/^-?\d+$/,xr=/^-?\d+(?:\.\d+)?$/,kg=/^(?:true|false)$/i,Sg=/^null$/i,xg=/^undefined$/i,Eg=/^[^A-Z]*$/,$g=/^[^a-z]*$/,Tg=/^[0-9a-fA-F]*$/;function Ri(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Li(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const hS=/^[0-9a-fA-F]{32}$/,pS=Ri(22,"=="),mS=Li(22),gS=/^[0-9a-fA-F]{40}$/,yS=Ri(27,"="),vS=Li(27),bS=/^[0-9a-fA-F]{64}$/,wS=Ri(43,"="),_S=Li(43),kS=/^[0-9a-fA-F]{96}$/,SS=Ri(64,""),xS=Li(64),ES=/^[0-9a-fA-F]{128}$/,$S=Ri(86,"=="),TS=Li(86),Us=Object.freeze(Object.defineProperty({__proto__:null,anyString:bg,base64:cg,base64url:lg,bigint:_g,boolean:kg,browserEmail:lS,cidrv4:ag,cidrv6:ug,creditCard:Bc,cuid:Hm,cuid2:qm,currencyCode:pg,date:gg,datetime:vg,domain:fg,duration:Qm,e164:hg,email:tg,emoji:rg,extendedDuration:rS,guid:eg,hex:Tg,hostname:dg,html5Email:aS,httpProtocol:Zc,iban:Vc,idnEmail:cS,integer:Hc,ipv4:ig,ipv6:og,ksuid:Jm,lowercase:Eg,mac:sg,md5_base64:pS,md5_base64url:mS,md5_hex:hS,nanoid:Ym,nanoidOfLength:Xm,null:Sg,number:xr,rfc5322Email:uS,sha1_base64:yS,sha1_base64url:vS,sha1_hex:gS,sha256_base64:wS,sha256_base64url:_S,sha256_hex:bS,sha384_base64:SS,sha384_base64url:xS,sha384_hex:kS,sha512_base64:$S,sha512_base64url:TS,sha512_hex:ES,string:wg,time:yg,ulid:Wm,undefined:xg,unicodeEmail:ng,uppercase:$g,uuid:dr,uuid4:iS,uuid6:oS,uuid7:sS,xid:Km},Symbol.toStringTag,{value:"Module"})),Ve=S("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qc=e=>{const t=e.value;return!kc(t)&&t.size!==void 0},Wc=e=>{const t=e.value;return!kc(t)&&t.length!==void 0},ls={number:"number",bigint:"bigint",object:"date"},Kc=S("$ZodCheckLessThan",(e,t)=>{Ve.init(e,t);const n=ls[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:ls[typeof r.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jc=S("$ZodCheckGreaterThan",(e,t)=>{Ve.init(e,t);const n=ls[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:ls[typeof r.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cg=S("$ZodCheckMultipleOf",(e,t)=>{Ve.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Sc(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ag=S("$ZodCheckNumberFormat",(e,t)=>{Ve.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=$c[t.format];e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ig=S("$ZodCheckBigIntFormat",(e,t)=>{Ve.init(e,t);const[n,r]=Tc[t.format];e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Ng=S("$ZodCheckMaxSize",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value;i.size<=t.maximum||r.issues.push({origin:Ns(i),code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Rg=S("$ZodCheckMinSize",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value;i.size>=t.minimum||r.issues.push({origin:Ns(i),code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Lg=S("$ZodCheckSizeEquals",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=qc),e._zod.check=r=>{const i=r.value,o=i.size;if(o===t.size)return;const s=o>t.size;r.issues.push({origin:Ns(i),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),zg=S("$ZodCheckMaxLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=Wc),e._zod.check=r=>{const i=r.value,o=i.length;if((typeof i=="string"&&o>t.maximum?$i(i):o)<=t.maximum)return;const a=Rs(i);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Pg=S("$ZodCheckMinLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=Wc),e._zod.check=r=>{const i=r.value,o=i.length;if((typeof i=="string"&&o>=t.minimum&&o<t.minimum*2?$i(i):o)>=t.minimum)return;const a=Rs(i);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Dg=S("$ZodCheckLengthEquals",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=Wc),e._zod.check=r=>{const i=r.value,o=i.length,s=typeof i=="string"&&o>=t.length&&o<=t.length*2?$i(i):o;if(s===t.length)return;const a=Rs(i),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),zi=S("$ZodCheckStringFormat",(e,t)=>{var n,r;Ve.init(e,t),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Og=S("$ZodCheckRegex",(e,t)=>{zi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Mg=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Eg),zi.init(e,t)}),Fg=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$g),zi.init(e,t)}),Ug=S("$ZodCheckIncludes",(e,t)=>{Ve.init(e,t);const n=dn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Gg=S("$ZodCheckStartsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`^${dn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),jg=S("$ZodCheckEndsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`.*${dn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function ds(e,t,n){e.issues.length&&t.issues.push(...Pt(n,e.issues))}const Zg=S("$ZodCheckProperty",(e,t)=>{Ve.init(e,t),e._zod.check=n=>{const r=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(i=>ds(i,n,t.property));ds(r,n,t.property)}}),Bg=S("$ZodCheckProperties",(e,t)=>{Ve.init(e,t),Ls(e,Symbol.iterator,function*(){yield e});let n;e._zod.check=r=>{if(r.value==null){r.issues.push({expected:"object",code:"invalid_type",input:r.value,inst:e});return}n??(n=Reflect.ownKeys(t.shape).map(s=>[s,t.shape[s]]));const i=r.value;let o;for(const[s,a]of n){const u=a._zod.run({value:i[s],issues:[]},{});u instanceof Promise?(o??(o=[]),o.push(u.then(c=>ds(c,r,s)))):ds(u,r,s)}if(o)return Promise.all(o).then(()=>{})}}),Vg=S("$ZodCheckMimeType",(e,t)=>{Ve.init(e,t);const n=new Set(t.mime);e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),Hg=S("$ZodCheckOverwrite",(e,t)=>{Ve.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Yc{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
11
11
  `).filter(s=>s),i=Math.min(...r.map(s=>s.length-s.trimStart().length)),o=r.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(const s of o)this.content.push(s)}compile(){const t=Function,n=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
12
12
  ${n.join(`
13
13
  `)}
14
- };`)(...Object.values(this.closed))}}const Hg={major:4,minor:6,patch:5},be=x("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Hg;const r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(const o of i)for(const s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(a,u,c)=>{if(a.memo)return a;let l=kt(a),d;for(const f of u){if(f._zod.def.when){if(Lm(a)||!f._zod.def.when(a))continue}else if(l)continue;const h=a.issues.length,p=f._zod.check(a);if(p instanceof Promise&&c?.async===!1)throw new an;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,a.issues.length!==h&&(Fu(a.issues,h,e),l||(l=kt(a,h)))});else{if(a.issues.length===h)continue;Fu(a.issues,h,e),l||(l=kt(a,h))}}return d?d.then(()=>a):a},s=(a,u,c)=>{if(kt(a))return a.aborted=!0,a;const l=o(u,i,c);if(l instanceof Promise){if(c.async===!1)throw new an;return l.then(d=>e._zod.parse(d,c))}return e._zod.parse(l,c)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return l instanceof Promise?l.then(d=>s(d,a,u)):s(l,a,u)}const c=e._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new an;return c.then(l=>o(l,i,u))}return o(c,i,u)}}},{get"~standard"(){return Ns(this,"~standard",Yc(this))},set"~standard"(e){fn(this,"~standard",e)}}),Vg=(e,t)=>e.issues.length?{issues:e.issues.map(n=>Mt(n,t,Qe()))}:{value:e.value};async function ES(e,t){const n={async:!0};return Vg(await e._zod.run({value:t,issues:[]},n),n)}function Yc(e){return{validate:t=>{const n={async:!1};try{const r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Vg(r,n)}catch{}return ES(e,t)},vendor:"zod",version:1}}const Li=x("$ZodString",(e,t)=>{be.init(e,t),e._zod.pattern=t.pattern??yg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ue=x("$ZodStringFormat",(e,t)=>{Ri.init(e,t),Li.init(e,t)}),qg=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xm),Ue.init(e,t)}),Wg=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=lr(r))}else t.pattern??(t.pattern=lr());Ue.init(e,t)}),Kg=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Qm),Ue.init(e,t)}),Xc=1,ci=2;function Qc(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function el(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?Qc(e)||ci:Jg(e,t)}function Jg(e,t){if(!t.normalize&&t.protocol?.source===jc.source&&!/^https?:\/\//i.test(e))return Xc;try{if(typeof URL<"u"){const n=URL;if(typeof n.parse=="function")return n.parse(e)??ci}return new URL(e)}catch{return ci}}const $S=/[\t\n\r]/g;function ls(e){return e.replace($S,"")}function tl(e,t){return t.lastIndex=0,t.test(e.hostname)}function nl(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}const Yg=x("$ZodURL",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=el(r,t);if(i===Xc){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===ci){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=ls(r);return}t.hostname&&!tl(i,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!nl(i,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:ls(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Xg=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=tg()),Ue.init(e,t)}),Qg=x("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Km:Jm(t.length)),Ue.init(e,t)}),ey=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Bm),Ue.init(e,t)}),ty=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Hm),Ue.init(e,t)}),ny=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Vm),Ue.init(e,t)}),ry=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=qm),Ue.init(e,t)}),iy=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wm),Ue.init(e,t)}),oy=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gg(t)),Ue.init(e,t)}),sy=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pg),Ue.init(e,t)}),ay=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=mg(t)),Ue.init(e,t)}),uy=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ym),Ue.init(e,t)}),cy=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ng),Ue.init(e,t)}),TS=/^[0-9a-fA-F:.]+$/;function Fs(e){return TS.test(e)?Qc(`http://[${e}]`):!1}const ly=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=rg),Ue.init(e,t),e._zod.check=n=>{Fs(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),dy=x("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=ig(t.delimiter)),Ue.init(e,t)}),fy=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=og),Ue.init(e,t)});function rl(e){const t=e.split("/");if(t.length!==2)return!1;const[n,r]=t;if(!r)return!1;const i=Number(r);return`${i}`!==r||i<0||i>128?!1:Fs(n)}const hy=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=sg),Ue.init(e,t),e._zod.check=n=>{rl(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Us(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const il=/^[0-9a-zA-Z+/]*={0,2}$/,py=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=il),Ue.init(e,t),e._zod.check=n=>{Us(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Gs=/^[A-Za-z0-9_-]*$/;function ol(e){if(!Gs.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Us(n)}const my=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gs),Ue.init(e,t),e._zod.check=n=>{ol(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),gy=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dg),Ue.init(e,t)}),CS=/[- ]/g;function AS(e){let t=e.length,n=1,r=0;for(;t;){const i=e.charCodeAt(--t)-48;n^=1,r+=n?[0,2,4,6,8,1,3,5,7,9][i]:i}return r%10===0}function sl(e){return Zc.test(e)?AS(e.replace(CS,"")):!1}const yy=x("$ZodCreditCard",(e,t)=>{t.pattern??(t.pattern=Zc),Ue.init(e,t),e._zod.check=n=>{sl(n.value)||n.issues.push({code:"invalid_format",format:"credit_card",input:n.value,inst:e,continue:!t.abort})}});function IS(e){let t=0;const n=e.length;for(let r=4;r<n;r++){const i=e.charCodeAt(r);t=(i>=65?t*100+(i-55):t*10+(i-48))%97}for(let r=0;r<4;r++){const i=e.charCodeAt(r);t=(i>=65?t*100+(i-55):t*10+(i-48))%97}return t===1}function al(e){return Bc.test(e)?IS(e):!1}const vy=x("$ZodIBAN",(e,t)=>{t.pattern??(t.pattern=Bc),Ue.init(e,t),e._zod.check=n=>{al(n.value)||n.issues.push({code:"invalid_format",format:"iban",input:n.value,inst:e,continue:!t.abort})}});function ul(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const by=x("$ZodJWT",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{ul(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),wy=x("$ZodCustomStringFormat",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),cl=x("$ZodNumber",(e,t)=>{be.init(e,t),e._zod.pattern=kr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),_y=x("$ZodNumberFormat",(e,t)=>{Tg.init(e,t),cl.init(e,t)}),ll=x("$ZodBoolean",(e,t)=>{be.init(e,t),e._zod.pattern=wg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),dl=x("$ZodBigInt",(e,t)=>{be.init(e,t),e._zod.pattern=bg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),ky=x("$ZodBigIntFormat",(e,t)=>{Cg.init(e,t),dl.init(e,t)}),Sy=x("$ZodSymbol",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return typeof i=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),n}}),xy=x("$ZodUndefined",(e,t)=>{be.init(e,t),e._zod.pattern=kg,e._zod.values=new Set([void 0]),e._zod.parse=(n,r)=>{const i=n.value;return typeof i>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),n}}),Ey=x("$ZodNull",(e,t)=>{be.init(e,t),e._zod.pattern=_g,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),$y=x("$ZodAny",(e,t)=>{be.init(e,t),e._zod.parse=n=>n}),Ty=x("$ZodUnknown",(e,t)=>{be.init(e,t),e._zod.parse=n=>n}),Cy=x("$ZodNever",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Ay=x("$ZodVoid",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return typeof i>"u"||n.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),n}}),Iy=x("$ZodDate",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function yh(e,t,n){e.issues.length&&t.issues.push(...Dt(n,e.issues)),t.value[n]=e.value}const Ny=x("$ZodArray",(e,t)=>{be.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);const s=[],a=i?.abortEarly;for(let u=0;u<o.length;u++){const c=o[u],l=t.element._zod.run({value:c,issues:[]},i);if(l instanceof Promise)s.push(l.then(d=>yh(d,r,u)));else if(yh(l,r,u),a&&l.issues.length!==0&&kt(l))break}return s.length?Promise.all(s).then(()=>r):r}});function ds(e,t,n,r,i,o){const s=n in r,a=o==="optional";if(!(!s&&a&&i==="optional")){if(e.issues.length){if(i!==void 0&&a&&!s)return;t.issues.push(...Dt(n,e.issues))}if(!s&&i===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(s||i==="defaulted"&&!a)&&(t.value[n]=void 0):t.value[n]=e.value}}const NS=[];function Ry(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:NS,i=r.length?[...t,...r]:t;for(const s of i)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);const o=Em(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Ly(e,t,n,r,i,o,s){const a=[],u=i.keySet,c=i.catchall._zod,l=c.def.type,d=c.optin,f=c.optout;let h=0;for(const p in t){if(s&&n.issues.length!==h){if(kt(n,h))break;h=n.issues.length}if(u.has(p))continue;if(p==="__proto__"){l==="never"&&a.push(p);continue}if(l==="never"){a.push(p);continue}const m=c.run({value:t[p],issues:[]},r);m instanceof Promise?e.push(m.then(y=>ds(y,n,p,t,d,f))):ds(m,n,p,t,d,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const zy=x("$ZodObject",(e,t)=>{be.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){const c=()=>{const l={...r};return Object.defineProperty(t,"shape",{value:l}),c.raw=l,l};c.raw=r,Object.defineProperty(t,"shape",{get:c})}const i=ki(()=>Ry(t));Te(e,"propValues",c=>{const l=c.def.shape,d={};for(const f in l){const h=l[f]._zod;if(h.values){Object.prototype.hasOwnProperty.call(d,f)||It(d,f,new Set);for(const p of h.values)d[f].add(p);h.optin!==void 0&&d[f].add(void 0)}}return d});const o=ur,s=t.catchall;let a;const u=bt.memoizer;u?.attach(e),e._zod.parse=(c,l)=>{a??(a=i.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value=u?u.alloc(e,c,{},l):{};const f=[],h=a.shape,p=l?.abortEarly;let m=c.issues.length;for(const y of a.allKeys){if(p&&c.issues.length!==m){if(kt(c,m))break;m=c.issues.length}if(y==="__proto__")continue;const w=h[y],g=w._zod.optin,b=w._zod.optout,v=w._zod.run({value:d[y],issues:[]},l);v instanceof Promise?f.push(v.then(k=>ds(k,c,y,d,g,b))):ds(v,c,y,d,g,b)}return s?Ly(f,d,c,l,i.value,e,p===!0):f.length?Promise.all(f).then(()=>c):c}}),Py=x("$ZodObjectJIT",(e,t)=>{zy.init(e,t);const n=e._zod.parse,r=ki(()=>Ry(t)),i=bt.memoizer,o=h=>{const p=r.value,m=p.symbolKeys,y=new Jc(["payload","ctx"],{shape:h,inst:e,memo:i,syms:m}),w=k=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,g=(k,S)=>`
15
- let ${k}_ab = false;
16
- for (let i = 0; i < ${k}.issues.length; i++) {
17
- const iss = ${k}.issues[i];
18
- iss.path = iss.path ? [${S}, ...iss.path] : [${S}];
14
+ };`)(...Object.values(this.closed))}}const qg={major:4,minor:6,patch:5},ye=S("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qg;const r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(const o of i)for(const s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(a,u,c)=>{if(a.memo)return a;let l=kt(a),d;for(const f of u){if(f._zod.def.when){if(Pm(a)||!f._zod.def.when(a))continue}else if(l)continue;const h=a.issues.length,p=f._zod.check(a);if(p instanceof Promise&&c?.async===!1)throw new an;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,a.issues.length!==h&&(Uu(a.issues,h,e),l||(l=kt(a,h)))});else{if(a.issues.length===h)continue;Uu(a.issues,h,e),l||(l=kt(a,h))}}return d?d.then(()=>a):a},s=(a,u,c)=>{if(kt(a))return a.aborted=!0,a;const l=o(u,i,c);if(l instanceof Promise){if(c.async===!1)throw new an;return l.then(d=>e._zod.parse(d,c))}return e._zod.parse(l,c)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return l instanceof Promise?l.then(d=>s(d,a,u)):s(l,a,u)}const c=e._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new an;return c.then(l=>o(l,i,u))}return o(c,i,u)}}},{get"~standard"(){return Ls(this,"~standard",Xc(this))},set"~standard"(e){fn(this,"~standard",e)}}),Wg=(e,t)=>e.issues.length?{issues:e.issues.map(n=>Mt(n,t,Qe()))}:{value:e.value};async function CS(e,t){const n={async:!0};return Wg(await e._zod.run({value:t,issues:[]},n),n)}function Xc(e){return{validate:t=>{const n={async:!1};try{const r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Wg(r,n)}catch{}return CS(e,t)},vendor:"zod",version:1}}const Pi=S("$ZodString",(e,t)=>{ye.init(e,t),e._zod.pattern=t.pattern??bg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ue=S("$ZodStringFormat",(e,t)=>{zi.init(e,t),Pi.init(e,t)}),Kg=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=eg),Ue.init(e,t)}),Jg=S("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=dr(r))}else t.pattern??(t.pattern=dr());Ue.init(e,t)}),Yg=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tg),Ue.init(e,t)}),Qc=1,di=2;function el(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function tl(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?el(e)||di:Xg(e,t)}function Xg(e,t){if(!t.normalize&&t.protocol?.source===Zc.source&&!/^https?:\/\//i.test(e))return Qc;try{if(typeof URL<"u"){const n=URL;if(typeof n.parse=="function")return n.parse(e)??di}return new URL(e)}catch{return di}}const AS=/[\t\n\r]/g;function fs(e){return e.replace(AS,"")}function nl(e,t){return t.lastIndex=0,t.test(e.hostname)}function rl(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}const Qg=S("$ZodURL",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=tl(r,t);if(i===Qc){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===di){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=fs(r);return}t.hostname&&!nl(i,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!rl(i,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:fs(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ey=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rg()),Ue.init(e,t)}),ty=S("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Ym:Xm(t.length)),Ue.init(e,t)}),ny=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hm),Ue.init(e,t)}),ry=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qm),Ue.init(e,t)}),iy=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Wm),Ue.init(e,t)}),oy=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Km),Ue.init(e,t)}),sy=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jm),Ue.init(e,t)}),ay=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=vg(t)),Ue.init(e,t)}),uy=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=gg),Ue.init(e,t)}),cy=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=yg(t)),Ue.init(e,t)}),ly=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qm),Ue.init(e,t)}),dy=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ig),Ue.init(e,t)}),IS=/^[0-9a-fA-F:.]+$/;function Gs(e){return IS.test(e)?el(`http://[${e}]`):!1}const fy=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=og),Ue.init(e,t),e._zod.check=n=>{Gs(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),hy=S("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=sg(t.delimiter)),Ue.init(e,t)}),py=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ag),Ue.init(e,t)});function il(e){const t=e.split("/");if(t.length!==2)return!1;const[n,r]=t;if(!r)return!1;const i=Number(r);return`${i}`!==r||i<0||i>128?!1:Gs(n)}const my=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ug),Ue.init(e,t),e._zod.check=n=>{il(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function js(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ol=/^[0-9a-zA-Z+/]*={0,2}$/,gy=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ol),Ue.init(e,t),e._zod.check=n=>{js(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Zs=/^[A-Za-z0-9_-]*$/;function sl(e){if(!Zs.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return js(n)}const yy=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Zs),Ue.init(e,t),e._zod.check=n=>{sl(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),vy=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hg),Ue.init(e,t)}),NS=/[- ]/g;function RS(e){let t=e.length,n=1,r=0;for(;t;){const i=e.charCodeAt(--t)-48;n^=1,r+=n?[0,2,4,6,8,1,3,5,7,9][i]:i}return r%10===0}function al(e){return Bc.test(e)?RS(e.replace(NS,"")):!1}const by=S("$ZodCreditCard",(e,t)=>{t.pattern??(t.pattern=Bc),Ue.init(e,t),e._zod.check=n=>{al(n.value)||n.issues.push({code:"invalid_format",format:"credit_card",input:n.value,inst:e,continue:!t.abort})}});function LS(e){let t=0;const n=e.length;for(let r=4;r<n;r++){const i=e.charCodeAt(r);t=(i>=65?t*100+(i-55):t*10+(i-48))%97}for(let r=0;r<4;r++){const i=e.charCodeAt(r);t=(i>=65?t*100+(i-55):t*10+(i-48))%97}return t===1}function ul(e){return Vc.test(e)?LS(e):!1}const wy=S("$ZodIBAN",(e,t)=>{t.pattern??(t.pattern=Vc),Ue.init(e,t),e._zod.check=n=>{ul(n.value)||n.issues.push({code:"invalid_format",format:"iban",input:n.value,inst:e,continue:!t.abort})}});function cl(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const _y=S("$ZodJWT",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{cl(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ky=S("$ZodCustomStringFormat",(e,t)=>{Ue.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),ll=S("$ZodNumber",(e,t)=>{ye.init(e,t),e._zod.pattern=xr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Sy=S("$ZodNumberFormat",(e,t)=>{Ag.init(e,t),ll.init(e,t)}),dl=S("$ZodBoolean",(e,t)=>{ye.init(e,t),e._zod.pattern=kg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),fl=S("$ZodBigInt",(e,t)=>{ye.init(e,t),e._zod.pattern=_g,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),xy=S("$ZodBigIntFormat",(e,t)=>{Ig.init(e,t),fl.init(e,t)}),Ey=S("$ZodSymbol",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return typeof i=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),n}}),$y=S("$ZodUndefined",(e,t)=>{ye.init(e,t),e._zod.pattern=xg,e._zod.values=new Set([void 0]),e._zod.parse=(n,r)=>{const i=n.value;return typeof i>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),n}}),Ty=S("$ZodNull",(e,t)=>{ye.init(e,t),e._zod.pattern=Sg,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),Cy=S("$ZodAny",(e,t)=>{ye.init(e,t),e._zod.parse=n=>n}),Ay=S("$ZodUnknown",(e,t)=>{ye.init(e,t),e._zod.parse=n=>n}),Iy=S("$ZodNever",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),Ny=S("$ZodVoid",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return typeof i>"u"||n.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),n}}),Ry=S("$ZodDate",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function bh(e,t,n){e.issues.length&&t.issues.push(...Pt(n,e.issues)),t.value[n]=e.value}const Ly=S("$ZodArray",(e,t)=>{ye.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);const s=[],a=i?.abortEarly;for(let u=0;u<o.length;u++){const c=o[u],l=t.element._zod.run({value:c,issues:[]},i);if(l instanceof Promise)s.push(l.then(d=>bh(d,r,u)));else if(bh(l,r,u),a&&l.issues.length!==0&&kt(l))break}return s.length?Promise.all(s).then(()=>r):r}});function hs(e,t,n,r,i,o){const s=n in r,a=o==="optional";if(!(!s&&a&&i==="optional")){if(e.issues.length){if(i!==void 0&&a&&!s)return;t.issues.push(...Pt(n,e.issues))}if(!s&&i===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(s||i==="defaulted"&&!a)&&(t.value[n]=void 0):t.value[n]=e.value}}const zS=[];function zy(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:zS,i=r.length?[...t,...r]:t;for(const s of i)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);const o=Tm(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Py(e,t,n,r,i,o,s){const a=[],u=i.keySet,c=i.catchall._zod,l=c.def.type,d=c.optin,f=c.optout;let h=0;for(const p in t){if(s&&n.issues.length!==h){if(kt(n,h))break;h=n.issues.length}if(u.has(p))continue;if(p==="__proto__"){l==="never"&&a.push(p);continue}if(l==="never"){a.push(p);continue}const m=c.run({value:t[p],issues:[]},r);m instanceof Promise?e.push(m.then(y=>hs(y,n,p,t,d,f))):hs(m,n,p,t,d,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Dy=S("$ZodObject",(e,t)=>{ye.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){const c=()=>{const l={...r};return Object.defineProperty(t,"shape",{value:l}),c.raw=l,l};c.raw=r,Object.defineProperty(t,"shape",{get:c})}const i=xi(()=>zy(t));$e(e,"propValues",c=>{const l=c.def.shape,d={};for(const f in l){const h=l[f]._zod;if(h.values){Object.prototype.hasOwnProperty.call(d,f)||At(d,f,new Set);for(const p of h.values)d[f].add(p);h.optin!==void 0&&d[f].add(void 0)}}return d});const o=cr,s=t.catchall;let a;const u=bt.memoizer;u?.attach(e),e._zod.parse=(c,l)=>{a??(a=i.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value=u?u.alloc(e,c,{},l):{};const f=[],h=a.shape,p=l?.abortEarly;let m=c.issues.length;for(const y of a.allKeys){if(p&&c.issues.length!==m){if(kt(c,m))break;m=c.issues.length}if(y==="__proto__")continue;const _=h[y],g=_._zod.optin,b=_._zod.optout,v=_._zod.run({value:d[y],issues:[]},l);v instanceof Promise?f.push(v.then(w=>hs(w,c,y,d,g,b))):hs(v,c,y,d,g,b)}return s?Py(f,d,c,l,i.value,e,p===!0):f.length?Promise.all(f).then(()=>c):c}}),Oy=S("$ZodObjectJIT",(e,t)=>{Dy.init(e,t);const n=e._zod.parse,r=xi(()=>zy(t)),i=bt.memoizer,o=h=>{const p=r.value,m=p.symbolKeys,y=new Yc(["payload","ctx"],{shape:h,inst:e,memo:i,syms:m}),_=w=>`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`,g=(w,k)=>`
15
+ let ${w}_ab = false;
16
+ for (let i = 0; i < ${w}.issues.length; i++) {
17
+ const iss = ${w}.issues[i];
18
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
19
19
  payload.issues.push(iss);
20
- if (iss.continue !== true) ${k}_ab = true;
20
+ if (iss.continue !== true) ${w}_ab = true;
21
21
  }
22
- if (${k}_ab && ctx && ctx.abortEarly) {
22
+ if (${w}_ab && ctx && ctx.abortEarly) {
23
23
  payload.value = newResult;
24
24
  return payload;
25
- }`;y.write("const input = payload.value;");const b=Object.create(null);let v=0;for(const k of p.allKeys)b[k]=`key_${v++}`;y.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const k of p.allKeys){if(k==="__proto__")continue;const S=b[k],_=typeof k=="symbol"?`syms[${m.indexOf(k)}]`:$t(k),N=`${_} in input`,P=h[k],z=P?._zod?.optin,j=z!==void 0,K=P?._zod?.optout==="optional";if(y.write(`const ${S} = ${w(_)};`),j&&K){const Y=z==="optional"?`${S}_present`:`${S}.value !== undefined || ${S}_present`;y.write(`
26
- const ${S}_present = ${N};
27
- if (!${S}.issues.length || ${S}_present) {
28
- if (${S}.issues.length) {${g(S,_)}
25
+ }`;y.write("const input = payload.value;");const b=Object.create(null);let v=0;for(const w of p.allKeys)b[w]=`key_${v++}`;y.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const w of p.allKeys){if(w==="__proto__")continue;const k=b[w],x=typeof w=="symbol"?`syms[${m.indexOf(w)}]`:$t(w),N=`${x} in input`,z=h[w],O=z?._zod?.optin,Z=O!==void 0,ee=z?._zod?.optout==="optional";if(y.write(`const ${k} = ${_(x)};`),Z&&ee){const ae=O==="optional"?`${k}_present`:`${k}.value !== undefined || ${k}_present`;y.write(`
26
+ const ${k}_present = ${N};
27
+ if (!${k}.issues.length || ${k}_present) {
28
+ if (${k}.issues.length) {${g(k,x)}
29
29
  }
30
30
 
31
- if (${Y}) {
32
- newResult[${_}] = ${S}.value;
31
+ if (${ae}) {
32
+ newResult[${x}] = ${k}.value;
33
33
  }
34
34
  }
35
35
 
36
- `)}else j?(y.write(`
37
- if (${S}.issues.length) {${g(S,_)}
36
+ `)}else Z?(y.write(`
37
+ if (${k}.issues.length) {${g(k,x)}
38
38
  }
39
- `),z==="defaulted"?y.write(`newResult[${_}] = ${S}.value;`):y.write(`
40
- if (${S}.value !== undefined || ${N}) {
41
- newResult[${_}] = ${S}.value;
39
+ `),O==="defaulted"?y.write(`newResult[${x}] = ${k}.value;`):y.write(`
40
+ if (${k}.value !== undefined || ${N}) {
41
+ newResult[${x}] = ${k}.value;
42
42
  }
43
43
  `)):y.write(`
44
- const ${S}_present = ${N};
45
- if (${S}.issues.length) {${g(S,_)}
44
+ const ${k}_present = ${N};
45
+ if (${k}.issues.length) {${g(k,x)}
46
46
  }
47
- if (!${S}_present && !${S}.issues.length) {
47
+ if (!${k}_present && !${k}.issues.length) {
48
48
  payload.issues.push({
49
49
  code: "invalid_type",
50
50
  expected: "nonoptional",
51
51
  input: undefined,
52
- path: [${_}]
52
+ path: [${x}]
53
53
  });
54
54
  if (ctx && ctx.abortEarly) {
55
55
  payload.value = newResult;
@@ -57,23 +57,23 @@ ${n.join(`
57
57
  }
58
58
  }
59
59
 
60
- if (${S}_present) {
61
- newResult[${_}] = ${S}.value;
60
+ if (${k}_present) {
61
+ newResult[${x}] = ${k}.value;
62
62
  }
63
63
 
64
- `)}return y.write("payload.value = newResult;"),y.write("return payload;"),y.compile()};let s;const a=ur,u=!bt.jitless,l=u&&Sm.value,d=t.catchall;let f;e._zod.parse=(h,p)=>{f??(f=r.value);const m=h.value;return a(m)?u&&l&&p?.async===!1&&p.jitless!==!0?(s||(s=o(t.shape)),h=s(h,p),d?Ly([],m,h,p,f,e,p?.abortEarly===!0):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h)}});function vh(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!kt(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Mt(s,r,Qe())))}),t)}const js=x("$ZodUnion",(e,t)=>{be.init(e,t),Te(e,"optin",r=>r.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),Te(e,"optout",r=>r.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Te(e,"values",r=>{if(r.def.options.every(i=>i._zod.values))return new Set(r.def.options.flatMap(i=>Array.from(i._zod.values)))}),Te(e,"pattern",r=>{if(r.def.options.every(i=>i._zod.pattern)){const i=r.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>Cn(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:r.value,issues:[]},i);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>vh(a,r,e,i)):vh(s,r,e,i)}});function bh(e,t,n,r){const i=[];for(let o=0;o<e.length;o++)e[o].issues.length===0&&i.push(o);return i.length===1?(t.value=e[i[0]].value,t):(i.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Mt(s,r,Qe())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1,matches:i}),t)}const Dy=x("$ZodXor",(e,t)=>{js.init(e,t),t.inclusive=!1;const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:r.value,issues:[]},i);u instanceof Promise?(s.push(u),o=!0):s.push(u)}return o?Promise.all(s).then(a=>bh(a,r,e,i)):bh(s,r,e,i)}});function fl(e,t){const n=e._zod;let r=n.bag.optionsMap;r||(r=Oy(n.def),n.bag.optionsMap=r);const i=r.get(t);if(i===null)throw new Error(`Ambiguous discriminator value "${String(t)}"`);return i}function Oy(e){const t=new Map;for(const n of e.options){const r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(const i of r)if(t.has(i)){if(i!==void 0)throw new Error(`Duplicate discriminator value "${String(i)}"`);t.set(i,null)}else t.set(i,n)}return t}const My=x("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,js.init(e,t);const n=e._zod.parse;Te(e,"propValues",i=>{const o={};let s=0;for(const a of i.def.options){const u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);u[i.def.discriminator]?.has(void 0)&&s++;for(const[c,l]of Object.entries(u)){Object.prototype.hasOwnProperty.call(o,c)||It(o,c,new Set);for(const d of l)o[c].add(d)}}return!i.def.unionFallback&&s>1&&o[i.def.discriminator]?.delete(void 0),o}),t.options.forEach((i,o)=>{const s=Ts(i._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw new Error(`Invalid discriminated union option at index "${o}"`)});const r=ki(()=>Oy(t));e._zod.parse=(i,o)=>{const s=i.value;if(!ur(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=s?.[t.discriminator],u=r.value.get(a);return u&&(a!==void 0||o.direction!=="backward")?u._zod.run(i,o):t.unionFallback||o.direction==="backward"?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(c=>r.value.get(c)!==null),input:s,path:[t.discriminator],inst:e}),i)}}),Fy=x("$ZodIntersection",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([u,c])=>wh(n,u,c)):wh(n,o,s)}});function li(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ln(e)&&ln(t)){const n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const o of r){if(o==="__proto__")continue;const s=li(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],o=t[r],s=li(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function wh(e,t,n){const r=new Map;let i;const o=new Map,s=(c,l)=>{let d;if(c.code==="unrecognized_keys"&&!c.path?.length)i??(i=c),d=c.keys;else if(c.code==="invalid_key"&&c.origin==="record"&&c.path?.length===1){const f=String(c.path[0]);o.has(f)||o.set(f,c),d=[f]}else return!1;for(const f of d)r.has(f)||r.set(f,{}),r.get(f)[l]=!0;return!0};for(const c of t.issues)s(c,"l")||e.issues.push(c);for(const c of n.issues)s(c,"r")||e.issues.push(c);const a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length){const c=i?a.filter(l=>i.keys.includes(l)):[];c.length&&e.issues.push({...i,keys:c});for(const l of a)!c.includes(l)&&o.has(l)&&e.issues.push(o.get(l))}const u=li(t.value,n.value);if(!u.valid){if(kt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}const hl=x("$ZodTuple",(e,t)=>{be.init(e,t);const n=t.items,r=bt.memoizer;r?.attach(e),e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=r?r.alloc(e,i,[],o):[];const a=[],u=_h(n,"optin"),c=_h(n,"optout");if(!t.rest){if(s.length<u)return i.issues.push({code:"too_small",minimum:u,inclusive:!0,input:s,inst:e,origin:"array"}),i;s.length>n.length&&i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:s,inst:e,origin:"array"})}const l=new Array(n.length),d=t.rest?o?.abortEarly:void 0;let f=!1;for(let h=0;h<n.length;h++){const p=n[h]._zod.run({value:s[h],issues:[]},o);p instanceof Promise?a.push(p.then(m=>{l[h]=m})):(l[h]=p,d&&!f&&p.issues.length&&(f=kt(p)))}if(t.rest&&!f){let h=n.length-1;const p=s.slice(n.length);let m=i.issues.length;for(const y of p){if(d&&i.issues.length!==m){if(kt(i,m))break;m=i.issues.length}h++;const w=t.rest._zod.run({value:y,issues:[]},o);w instanceof Promise?a.push(w.then(g=>kh(g,i,h))):kh(w,i,h)}}return a.length?Promise.all(a).then(()=>Sh(l,i,n,s,c)):Sh(l,i,n,s,c)}});function _h(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function kh(e,t,n){e.issues.length&&t.issues.push(...Dt(n,e.issues)),t.value[n]=e.value}function Sh(e,t,n,r,i){for(let o=0;o<n.length;o++){const s=e[o],a=o<r.length;if(!a&&o>=i&&n[o]._zod.optin==="optional"){t.value.length=o;break}if(s.issues.length){if(!a&&o>=i){t.value.length=o;break}t.issues.push(...Dt(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=r.length&&(n[o]._zod.optout==="optional"&&t.value[o]===void 0);o--)t.value.length=o;return t}const Uy=x("$ZodRecord",(e,t)=>{be.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!ln(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};const u=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){if(u.add(typeof l=="number"?l.toString():l),l==="__proto__")continue;const d=t.keyType._zod.run({value:l,issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>Mt(p,i,Qe())),input:l,path:[l],inst:e});continue}const f=d.value;if(f==="__proto__")continue;const h=t.valueType._zod.run({value:o[l],issues:[]},i);h instanceof Promise?s.push(h.then(p=>{p.issues.length&&r.issues.push(...Dt(l,p.issues)),r.value[f]=p.value})):(h.issues.length&&r.issues.push(...Dt(l,h.issues)),r.value[f]=h.value)}let c;for(const l in o)if(!u.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;r.value[l]=o[l]}else c=c??[],c.push(l);c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let u;for(const c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&kr.test(c)&&l.issues.length){const p=t.keyType._zod.run({value:Number(c),issues:[]},i);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(l=p)}if(l.issues.length){t.mode==="loose"?r.value[c]=o[c]:a?(u=u??[],u.push(c)):r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(p=>Mt(p,i,Qe())),input:c,path:[c],inst:e});continue}const f=l.value;if(f==="__proto__")continue;const h=t.valueType._zod.run({value:o[c],issues:[]},i);h instanceof Promise?s.push(h.then(p=>{p.issues.length&&r.issues.push(...Dt(c,p.issues)),r.value[f]=p.value})):(h.issues.length&&r.issues.push(...Dt(c,h.issues)),r.value[f]=h.value)}u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}}),Gy=x("$ZodMap",(e,t)=>{be.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;const s=[];r.value=n?n.alloc(e,r,new Map,i):new Map;const a=i?.abortEarly;let u=r.issues.length;for(const[c,l]of o){if(a&&r.issues.length!==u){if(kt(r,u))break;u=r.issues.length}const d=t.keyType._zod.run({value:c,issues:[]},i),f=t.valueType._zod.run({value:l,issues:[]},i);d instanceof Promise||f instanceof Promise?s.push(Promise.all([d,f]).then(([h,p])=>{xh(h,p,r,c,o,e,i)})):xh(d,f,r,c,o,e,i)}return s.length?Promise.all(s).then(()=>r):r}});function xh(e,t,n,r,i,o,s){e.issues.length&&(as.has(typeof r)?n.issues.push(...Dt(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(a=>Mt(a,s,Qe()))})),t.issues.length&&(as.has(typeof r)?n.issues.push(...Dt(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map(a=>Mt(a,s,Qe()))})),n.value.set(e.value,t.value)}const jy=x("$ZodSet",(e,t)=>{be.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;const s=[];r.value=n?n.alloc(e,r,new Set,i):new Set;const a=i?.abortEarly;let u=r.issues.length;for(const c of o){if(a&&r.issues.length!==u){if(kt(r,u))break;u=r.issues.length}const l=t.valueType._zod.run({value:c,issues:[]},i);l instanceof Promise?s.push(l.then(d=>Eh(d,r))):Eh(l,r)}return s.length?Promise.all(s).then(()=>r):r}});function Eh(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const Zy=x("$ZodEnum",(e,t)=>{be.init(e,t);const n=os(t.entries),r=new Set(n);e._zod.values=r,Te(e,"pattern",i=>{const o=os(i.def.entries).filter(s=>as.has(typeof s));return new RegExp(o.length?`^(${o.map(s=>dn(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{const s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),By=x("$ZodLiteral",(e,t)=>{be.init(e,t);const n=new Set(t.values);e._zod.values=n,Te(e,"pattern",r=>{const i=r.def.values;return new RegExp(i.length?`^(${i.map(o=>typeof o=="string"?dn(o):o?dn(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Hy=x("$ZodFile",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return i instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),n}}),Vy=x("$ZodTransform",(e,t)=>{be.init(e,t),e._zod.optin="optional",bt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rs(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n));if(i instanceof Promise)throw new an;return n.value=i,n}});function $h(e,t){return e.value=t.issues.length?void 0:t.value,e}const pl=x("$ZodOptional",(e,t)=>{be.init(e,t),Te(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Te(e,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Te(e,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Cn(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;const i=t.innerType._zod.run({value:n.value,issues:[]},r);return i instanceof Promise?i.then(o=>$h(n,o)):$h(n,i)}return t.innerType._zod.run(n,r)}}),qy=x("$ZodExactOptional",(e,t)=>{pl.init(e,t),Te(e,"values",n=>n.def.innerType._zod.values),Te(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Wy=x("$ZodNullable",(e,t)=>{be.init(e,t),Te(e,"optin",n=>n.def.innerType._zod.optin),Te(e,"optout",n=>n.def.innerType._zod.optout),Te(e,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Cn(r.source)}|null)$`):void 0}),Te(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Ky=x("$ZodDefault",(e,t)=>{be.init(e,t),e._zod.optin="defaulted",Te(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>Th(o,t)):Th(i,t)}});function Th(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Jy=x("$ZodPrefault",(e,t)=>{be.init(e,t),e._zod.optin="defaulted",Te(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Yy=x("$ZodNonOptional",(e,t)=>{be.init(e,t),Te(e,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>Ch(o,e)):Ch(i,e)}});function Ch(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Xy=x("$ZodSuccess",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rs("ZodSuccess");const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.issues.length===0,n)):(n.value=i.issues.length===0,n)}});function Ah(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(i=>Mt(i,r,Qe()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Qy=x("$ZodCatch",(e,t)=>{be.init(e,t),Te(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Te(e,"optout",n=>n.def.innerType._zod.optout),Te(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run({value:n.value,issues:[]},r);return i instanceof Promise?i.then(o=>Ah(n,o,t,r)):Ah(n,i,t,r)}}),ev=x("$ZodNaN",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),ml=x("$ZodPipe",(e,t)=>{be.init(e,t),Te(e,"values",n=>n.def.in._zod.values),Te(e,"optin",n=>n.def.in._zod.optin),Te(e,"optout",n=>n.def.out._zod.optout),Te(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Ro(s,t.in,r)):Ro(o,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Ro(o,t.out,r)):Ro(i,t.out,r)}});function Ro(e,t,n){return e.issues.some(r=>r.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const gl=x("$ZodCodec",(e,t)=>{be.init(e,t),Te(e,"values",n=>n.def.in._zod.values),Te(e,"optin",n=>n.def.in._zod.optin),Te(e,"optout",n=>n.def.out._zod.optout),Te(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Lo(s,t,r)):Lo(o,t,r)}else{const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Lo(s,t,r)):Lo(o,t,r)}}});function Lo(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){const i=t.transform(e.value,e);return i instanceof Promise?i.then(o=>zo(e,o,t.out,n)):zo(e,i,t.out,n)}else{const i=t.reverseTransform(e.value,e);return i instanceof Promise?i.then(o=>zo(e,o,t.in,n)):zo(e,i,t.in,n)}}function zo(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const tv=x("$ZodPreprocess",(e,t)=>{ml.init(e,t)}),nv=x("$ZodReadonly",(e,t)=>{be.init(e,t),Te(e,"propValues",n=>n.def.innerType._zod.propValues),Te(e,"values",n=>n.def.innerType._zod.values),Te(e,"optin",n=>n.def.innerType?._zod?.optin),Te(e,"optout",n=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(Ih):Ih(i)}});function Ih(e){return e.memo||(e.value=Object.freeze(e.value)),e}function RS(e){const t=e._zod.def;let n=t.pattern,r=!!t.format?.includes("int"),i,o;for(const a of t.checks??[]){const u=a._zod.def;u.pattern&&(n=u.pattern),r||(r=!!u.format?.includes("int"));const c=u.minimum??u.length,l=u.maximum??u.length;c!==void 0&&(i===void 0||c>i)&&(i=c),l!==void 0&&(o===void 0||l<o)&&(o=l)}if(n)return n.source;if(i!==void 0&&o!==void 0&&i>o)return"(?!)";if(i!==void 0||o!==void 0)return vg({minimum:i,maximum:o}).source;const s=e._zod.pattern;return(r&&s===kr?Hc:s)?.source}function Zu(e){const t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){const i=r._zod.pattern?.source,o=Zu(r);return n&&i&&o&&o!==i?n.replace(Cn(i),()=>Cn(o)):n}if(t.options){const i=t.options.map(Zu);if(i.every(Boolean))return`^(${i.map(o=>Cn(o)).join("|")})$`}return RS(e)}const rv=x("$ZodTemplateLiteral",(e,t)=>{be.init(e,t);const n=[];for(const r of t.parts)if(typeof r=="object"&&r!==null){const i=Zu(r);if(!i)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(Cn(i))}else if(r===null||xm.has(typeof r))n.push(dn(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,i)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),iv=x("$ZodFunction",(e,t)=>(be.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...r){const i=e._def.input?Uu(e._def.input,r):r,o=Reflect.apply(n,this,i);return e._def.output?Uu(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...r){const i=e._def.input?await Gu(e._def.input,r):r,o=await Reflect.apply(n,this,i);return e._def.output?await Gu(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{const r=e.constructor;return Array.isArray(n[0])?new r({type:"function",input:new hl({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new r({type:"function",input:n[0],output:e._def.output})},e.output=n=>{const r=e.constructor;return new r({type:"function",input:e._def.input,output:n})},e)),ov=x("$ZodPromise",(e,t)=>{be.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then(i=>t.innerType._zod.run({value:i,issues:[]},r))}),yl=x("$ZodLazy",(e,t)=>{be.init(e,t),bm(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),Te(e,"pattern",n=>n.innerType?._zod?.pattern),Te(e,"propValues",n=>n.innerType?._zod?.propValues),Te(e,"optin",n=>n.innerType?._zod?.optin??void 0),Te(e,"optout",n=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),sv=x("$ZodCustom",(e,t)=>{He.init(e,t),be.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(o=>Nh(o,n,r,e));Nh(i,n,r,e)}});function Nh(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(cr(i))}}class av extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const Bu="~memo",Rh=[];function uv(e){return e!==null&&typeof e=="object"}function uu(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const cv=new WeakMap,sr=0,es=1,ii=2;function oi(e,t,n){const r=cv.get(e);if(r!==void 0)return r?ii:sr;if(t.has(e))return ii;t.add(e);let i=sr;const o=l=>{if(i!==ii&&l?._zod){const d=oi(l,t,n);d>i&&(i=d)}},s=(l,d)=>{let f=sr;for(const h of Reflect.ownKeys(l)){const p=Object.getOwnPropertyDescriptor(l,h);if(!p.enumerable)continue;const m=p.get?es:p.value?._zod?oi(p.value,t,n):sr;m>f&&(f=m)}return f},a=l=>{l>i&&(i=l)},u=e._zod.def;switch(u.type){case"object":{const l=Ts(u);a(l?s(l):es),o(u.catchall);break}case"array":o(u.element);break;case"tuple":for(const l of u.items)o(l);o(u.rest);break;case"record":case"map":o(u.keyType),o(u.valueType);break;case"set":o(u.valueType);break;case"union":for(const l of u.options)o(l);break;case"intersection":o(u.left),o(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(u.innerType);break;case"pipe":o(u.in),o(u.out);break;case"function":o(u.input),o(u.output);break;case"lazy":{const l=u._cachedInner??(n?e._zod.innerType:void 0);a(l?oi(l,t,!1):es);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const l in u){const d=Object.getOwnPropertyDescriptor(u,l);if(!d||d.get)continue;const f=d.value;if(!(!f||typeof f!="object")){if(f._zod)o(f);else if(Array.isArray(f))for(const h of f)o(h)}}}return t.delete(e),LS(e,i)}function LS(e,t){return t!==es&&cv.set(e,t===ii),t}function vl(e){return oi(e,new Set,!0)!==sr}function zS(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let Po;const Do=[],PS={alloc(e,t,n){const r=Po;if(!r)return n;Po=void 0;const i={value:n,issues:null};return r.set(t.value,i),Do.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const n=e._zod.parse,r=(i,o)=>{if(o.direction!=="backward"&&bl(o,i.value))throw new av;return n(i,o)};e._zod.parse=r,e._zod.run===n&&(e._zod.run=r)})},attach(e){var t;let n,r=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const s=e._zod.parse,a=(u,c)=>{if(n===void 0){const w=oi(e,new Set,!1);if(w===sr)return e._zod.parse=s,e._zod.run===a&&(e._zod.run=s),s(u,c);w===ii||r?n=!0:r=!0}const l=u.value;if(!uv(l))return s(u,c);let d=c[Bu];d||(d={buckets:new WeakMap,backEdges:void 0},c[Bu]=d);let f;i===c?f=o:(f=zS(d,e),i=c,o=f);const h=f.get(l);if(h)return u.value=h.value,h.issues?h.issues.length&&u.issues.push(...uu(h.issues)):(u.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(h.value)),u;Po=f;const p=Do.length,m=s(u,c);Po=void 0;const y=Do.length>p?Do.pop():void 0;return m instanceof Promise?m.then(w=>(y&&(y.issues=w.issues.length?uu(w.issues):Rh),w)):(y&&(y.issues=m.issues.length?uu(m.issues):Rh),m)};e._zod.parse=a,e._zod.run===s&&(e._zod.run=a)})}};function Zs(){return PS}function bl(e,t){const n=e[Bu]?.backEdges;return n!==void 0&&uv(t)&&n.has(t)}const wl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var Lh;const _l=Symbol("ZodOutput"),kl=Symbol("ZodInput");class lv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Bs(){return new lv}(Lh=globalThis).__zod_globalRegistry??(Lh.__zod_globalRegistry=Bs());const Et=globalThis.__zod_globalRegistry,wt=Symbol.for("zod.compile.invalid"),zh=Symbol.for("zod.compile.fallback");class hn extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}}class Ie extends Error{constructor(t,n=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=n}}function DS(e,t){try{return Vs(e,{assertOnly:!0})}catch{return t}}function Sl(e,t){try{const n=Vs(e),r=Hs(e,n);return r._zod.bag.validator=DS(e,n),r}catch(n){if(t?.strict)throw n;return e}}function Hs(e,t){if(vl(e))throw new Ie("a schema whose subtree contains a reference cycle");const n=Be(e),r=e._zod.run,i=r.__originalRun??r,o=(s,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[zh]||a&&bl(a,s.value))return i(s,a);const u=t(s.value);return u!==wt?(s.value=u,s):(a&&(a[zh]=!0),i(s,a))};return o.__originalRun=i,n._zod.bag.fallbackRun=i,n._zod.bag.validator=t,n._zod.run=o,r.__originalRun||OS(n,e,t),n}function OS(e,t,n){const r=e,i=t;if(typeof i.safeParse=="function"){const o=i.safeParse;r.safeParse=(s,a)=>{const u=n(s);return u!==wt?{success:!0,data:u}:o(s,a)}}if(typeof i.parse=="function"){const o=i.parse;r.parse=(s,a)=>{const u=n(s);return u!==wt?u:o(s,a)}}}function Vs(e,t){let n=!0;try{n=vl(e)}catch{}if(n)throw new Ie("a schema whose subtree contains a reference cycle");const r={constants:new Map,constantCounter:0,varCounter:0,definite:!0},i=new Jc(["input"]),o=qe(i,r,e,"input",!t?.assertOnly);i.write(o===null?"return true;":`return ${o};`);const s=["INVALID",...r.constants.keys()],a=[wt,...r.constants.values()],u=i.content.join(`
64
+ `)}return y.write("payload.value = newResult;"),y.write("return payload;"),y.compile()};let s;const a=cr,u=!bt.jitless,l=u&&Em.value,d=t.catchall;let f;e._zod.parse=(h,p)=>{f??(f=r.value);const m=h.value;return a(m)?u&&l&&p?.async===!1&&p.jitless!==!0?(s||(s=o(t.shape)),h=s(h,p),d?Py([],m,h,p,f,e,p?.abortEarly===!0):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h)}});function wh(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!kt(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Mt(s,r,Qe())))}),t)}const Bs=S("$ZodUnion",(e,t)=>{ye.init(e,t),$e(e,"optin",r=>r.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),$e(e,"optout",r=>r.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),$e(e,"values",r=>{if(r.def.options.every(i=>i._zod.values))return new Set(r.def.options.flatMap(i=>Array.from(i._zod.values)))}),$e(e,"pattern",r=>{if(r.def.options.every(i=>i._zod.pattern)){const i=r.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>An(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:r.value,issues:[]},i);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>wh(a,r,e,i)):wh(s,r,e,i)}});function _h(e,t,n,r){const i=[];for(let o=0;o<e.length;o++)e[o].issues.length===0&&i.push(o);return i.length===1?(t.value=e[i[0]].value,t):(i.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Mt(s,r,Qe())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1,matches:i}),t)}const My=S("$ZodXor",(e,t)=>{Bs.init(e,t),t.inclusive=!1;const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:r.value,issues:[]},i);u instanceof Promise?(s.push(u),o=!0):s.push(u)}return o?Promise.all(s).then(a=>_h(a,r,e,i)):_h(s,r,e,i)}});function hl(e,t){const n=e._zod;let r=n.bag.optionsMap;r||(r=Fy(n.def),n.bag.optionsMap=r);const i=r.get(t);if(i===null)throw new Error(`Ambiguous discriminator value "${String(t)}"`);return i}function Fy(e){const t=new Map;for(const n of e.options){const r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(const i of r)if(t.has(i)){if(i!==void 0)throw new Error(`Duplicate discriminator value "${String(i)}"`);t.set(i,null)}else t.set(i,n)}return t}const Uy=S("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Bs.init(e,t);const n=e._zod.parse;$e(e,"propValues",i=>{const o={};let s=0;for(const a of i.def.options){const u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);u[i.def.discriminator]?.has(void 0)&&s++;for(const[c,l]of Object.entries(u)){Object.prototype.hasOwnProperty.call(o,c)||At(o,c,new Set);for(const d of l)o[c].add(d)}}return!i.def.unionFallback&&s>1&&o[i.def.discriminator]?.delete(void 0),o}),t.options.forEach((i,o)=>{const s=As(i._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw new Error(`Invalid discriminated union option at index "${o}"`)});const r=xi(()=>Fy(t));e._zod.parse=(i,o)=>{const s=i.value;if(!cr(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=s?.[t.discriminator],u=r.value.get(a);return u&&(a!==void 0||o.direction!=="backward")?u._zod.run(i,o):t.unionFallback||o.direction==="backward"?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(c=>r.value.get(c)!==null),input:s,path:[t.discriminator],inst:e}),i)}}),Gy=S("$ZodIntersection",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([u,c])=>kh(n,u,c)):kh(n,o,s)}});function fi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ln(e)&&ln(t)){const n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const o of r){if(o==="__proto__")continue;const s=fi(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],o=t[r],s=fi(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function kh(e,t,n){const r=new Map;let i;const o=new Map,s=(c,l)=>{let d;if(c.code==="unrecognized_keys"&&!c.path?.length)i??(i=c),d=c.keys;else if(c.code==="invalid_key"&&c.origin==="record"&&c.path?.length===1){const f=String(c.path[0]);o.has(f)||o.set(f,c),d=[f]}else return!1;for(const f of d)r.has(f)||r.set(f,{}),r.get(f)[l]=!0;return!0};for(const c of t.issues)s(c,"l")||e.issues.push(c);for(const c of n.issues)s(c,"r")||e.issues.push(c);const a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length){const c=i?a.filter(l=>i.keys.includes(l)):[];c.length&&e.issues.push({...i,keys:c});for(const l of a)!c.includes(l)&&o.has(l)&&e.issues.push(o.get(l))}const u=fi(t.value,n.value);if(!u.valid){if(kt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}const pl=S("$ZodTuple",(e,t)=>{ye.init(e,t);const n=t.items,r=bt.memoizer;r?.attach(e),e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=r?r.alloc(e,i,[],o):[];const a=[],u=Sh(n,"optin"),c=Sh(n,"optout");if(!t.rest){if(s.length<u)return i.issues.push({code:"too_small",minimum:u,inclusive:!0,input:s,inst:e,origin:"array"}),i;s.length>n.length&&i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:s,inst:e,origin:"array"})}const l=new Array(n.length),d=t.rest?o?.abortEarly:void 0;let f=!1;for(let h=0;h<n.length;h++){const p=n[h]._zod.run({value:s[h],issues:[]},o);p instanceof Promise?a.push(p.then(m=>{l[h]=m})):(l[h]=p,d&&!f&&p.issues.length&&(f=kt(p)))}if(t.rest&&!f){let h=n.length-1;const p=s.slice(n.length);let m=i.issues.length;for(const y of p){if(d&&i.issues.length!==m){if(kt(i,m))break;m=i.issues.length}h++;const _=t.rest._zod.run({value:y,issues:[]},o);_ instanceof Promise?a.push(_.then(g=>xh(g,i,h))):xh(_,i,h)}}return a.length?Promise.all(a).then(()=>Eh(l,i,n,s,c)):Eh(l,i,n,s,c)}});function Sh(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function xh(e,t,n){e.issues.length&&t.issues.push(...Pt(n,e.issues)),t.value[n]=e.value}function Eh(e,t,n,r,i){for(let o=0;o<n.length;o++){const s=e[o],a=o<r.length;if(!a&&o>=i&&n[o]._zod.optin==="optional"){t.value.length=o;break}if(s.issues.length){if(!a&&o>=i){t.value.length=o;break}t.issues.push(...Pt(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=r.length&&(n[o]._zod.optout==="optional"&&t.value[o]===void 0);o--)t.value.length=o;return t}const jy=S("$ZodRecord",(e,t)=>{ye.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!ln(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};const u=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){if(u.add(typeof l=="number"?l.toString():l),l==="__proto__")continue;const d=t.keyType._zod.run({value:l,issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>Mt(p,i,Qe())),input:l,path:[l],inst:e});continue}const f=d.value;if(f==="__proto__")continue;const h=t.valueType._zod.run({value:o[l],issues:[]},i);h instanceof Promise?s.push(h.then(p=>{p.issues.length&&r.issues.push(...Pt(l,p.issues)),r.value[f]=p.value})):(h.issues.length&&r.issues.push(...Pt(l,h.issues)),r.value[f]=h.value)}let c;for(const l in o)if(!u.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;r.value[l]=o[l]}else c=c??[],c.push(l);c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let u;for(const c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&xr.test(c)&&l.issues.length){const p=t.keyType._zod.run({value:Number(c),issues:[]},i);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(l=p)}if(l.issues.length){t.mode==="loose"?r.value[c]=o[c]:a?(u=u??[],u.push(c)):r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(p=>Mt(p,i,Qe())),input:c,path:[c],inst:e});continue}const f=l.value;if(f==="__proto__")continue;const h=t.valueType._zod.run({value:o[c],issues:[]},i);h instanceof Promise?s.push(h.then(p=>{p.issues.length&&r.issues.push(...Pt(c,p.issues)),r.value[f]=p.value})):(h.issues.length&&r.issues.push(...Pt(c,h.issues)),r.value[f]=h.value)}u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}}),Zy=S("$ZodMap",(e,t)=>{ye.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;const s=[];r.value=n?n.alloc(e,r,new Map,i):new Map;const a=i?.abortEarly;let u=r.issues.length;for(const[c,l]of o){if(a&&r.issues.length!==u){if(kt(r,u))break;u=r.issues.length}const d=t.keyType._zod.run({value:c,issues:[]},i),f=t.valueType._zod.run({value:l,issues:[]},i);d instanceof Promise||f instanceof Promise?s.push(Promise.all([d,f]).then(([h,p])=>{$h(h,p,r,c,o,e,i)})):$h(d,f,r,c,o,e,i)}return s.length?Promise.all(s).then(()=>r):r}});function $h(e,t,n,r,i,o,s){e.issues.length&&(cs.has(typeof r)?n.issues.push(...Pt(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(a=>Mt(a,s,Qe()))})),t.issues.length&&(cs.has(typeof r)?n.issues.push(...Pt(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map(a=>Mt(a,s,Qe()))})),n.value.set(e.value,t.value)}const By=S("$ZodSet",(e,t)=>{ye.init(e,t);const n=bt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{const o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;const s=[];r.value=n?n.alloc(e,r,new Set,i):new Set;const a=i?.abortEarly;let u=r.issues.length;for(const c of o){if(a&&r.issues.length!==u){if(kt(r,u))break;u=r.issues.length}const l=t.valueType._zod.run({value:c,issues:[]},i);l instanceof Promise?s.push(l.then(d=>Th(d,r))):Th(l,r)}return s.length?Promise.all(s).then(()=>r):r}});function Th(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const Vy=S("$ZodEnum",(e,t)=>{ye.init(e,t);const n=as(t.entries),r=new Set(n);e._zod.values=r,$e(e,"pattern",i=>{const o=as(i.def.entries).filter(s=>cs.has(typeof s));return new RegExp(o.length?`^(${o.map(s=>dn(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{const s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),Hy=S("$ZodLiteral",(e,t)=>{ye.init(e,t);const n=new Set(t.values);e._zod.values=n,$e(e,"pattern",r=>{const i=r.def.values;return new RegExp(i.length?`^(${i.map(o=>typeof o=="string"?dn(o):o?dn(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),qy=S("$ZodFile",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;return i instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),n}}),Wy=S("$ZodTransform",(e,t)=>{ye.init(e,t),e._zod.optin="optional",bt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zs(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n));if(i instanceof Promise)throw new an;return n.value=i,n}});function Ch(e,t){return e.value=t.issues.length?void 0:t.value,e}const ml=S("$ZodOptional",(e,t)=>{ye.init(e,t),$e(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",$e(e,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),$e(e,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${An(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;const i=t.innerType._zod.run({value:n.value,issues:[]},r);return i instanceof Promise?i.then(o=>Ch(n,o)):Ch(n,i)}return t.innerType._zod.run(n,r)}}),Ky=S("$ZodExactOptional",(e,t)=>{ml.init(e,t),$e(e,"values",n=>n.def.innerType._zod.values),$e(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Jy=S("$ZodNullable",(e,t)=>{ye.init(e,t),$e(e,"optin",n=>n.def.innerType._zod.optin),$e(e,"optout",n=>n.def.innerType._zod.optout),$e(e,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${An(r.source)}|null)$`):void 0}),$e(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Yy=S("$ZodDefault",(e,t)=>{ye.init(e,t),e._zod.optin="defaulted",$e(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>Ah(o,t)):Ah(i,t)}});function Ah(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Xy=S("$ZodPrefault",(e,t)=>{ye.init(e,t),e._zod.optin="defaulted",$e(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Qy=S("$ZodNonOptional",(e,t)=>{ye.init(e,t),$e(e,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>Ih(o,e)):Ih(i,e)}});function Ih(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const ev=S("$ZodSuccess",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zs("ZodSuccess");const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.issues.length===0,n)):(n.value=i.issues.length===0,n)}});function Nh(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(i=>Mt(i,r,Qe()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const tv=S("$ZodCatch",(e,t)=>{ye.init(e,t),$e(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),$e(e,"optout",n=>n.def.innerType._zod.optout),$e(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run({value:n.value,issues:[]},r);return i instanceof Promise?i.then(o=>Nh(n,o,t,r)):Nh(n,i,t,r)}}),nv=S("$ZodNaN",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),gl=S("$ZodPipe",(e,t)=>{ye.init(e,t),$e(e,"values",n=>n.def.in._zod.values),$e(e,"optin",n=>n.def.in._zod.optin),$e(e,"optout",n=>n.def.out._zod.optout),$e(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>zo(s,t.in,r)):zo(o,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(o=>zo(o,t.out,r)):zo(i,t.out,r)}});function zo(e,t,n){return e.issues.some(r=>r.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const yl=S("$ZodCodec",(e,t)=>{ye.init(e,t),$e(e,"values",n=>n.def.in._zod.values),$e(e,"optin",n=>n.def.in._zod.optin),$e(e,"optout",n=>n.def.out._zod.optout),$e(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Po(s,t,r)):Po(o,t,r)}else{const o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Po(s,t,r)):Po(o,t,r)}}});function Po(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){const i=t.transform(e.value,e);return i instanceof Promise?i.then(o=>Do(e,o,t.out,n)):Do(e,i,t.out,n)}else{const i=t.reverseTransform(e.value,e);return i instanceof Promise?i.then(o=>Do(e,o,t.in,n)):Do(e,i,t.in,n)}}function Do(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}const rv=S("$ZodPreprocess",(e,t)=>{gl.init(e,t)}),iv=S("$ZodReadonly",(e,t)=>{ye.init(e,t),$e(e,"propValues",n=>n.def.innerType._zod.propValues),$e(e,"values",n=>n.def.innerType._zod.values),$e(e,"optin",n=>n.def.innerType?._zod?.optin),$e(e,"optout",n=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(Rh):Rh(i)}});function Rh(e){return e.memo||(e.value=Object.freeze(e.value)),e}function PS(e){const t=e._zod.def;let n=t.pattern,r=!!t.format?.includes("int"),i,o;for(const a of t.checks??[]){const u=a._zod.def;u.pattern&&(n=u.pattern),r||(r=!!u.format?.includes("int"));const c=u.minimum??u.length,l=u.maximum??u.length;c!==void 0&&(i===void 0||c>i)&&(i=c),l!==void 0&&(o===void 0||l<o)&&(o=l)}if(n)return n.source;if(i!==void 0&&o!==void 0&&i>o)return"(?!)";if(i!==void 0||o!==void 0)return wg({minimum:i,maximum:o}).source;const s=e._zod.pattern;return(r&&s===xr?Hc:s)?.source}function Bu(e){const t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){const i=r._zod.pattern?.source,o=Bu(r);return n&&i&&o&&o!==i?n.replace(An(i),()=>An(o)):n}if(t.options){const i=t.options.map(Bu);if(i.every(Boolean))return`^(${i.map(o=>An(o)).join("|")})$`}return PS(e)}const ov=S("$ZodTemplateLiteral",(e,t)=>{ye.init(e,t);const n=[];for(const r of t.parts)if(typeof r=="object"&&r!==null){const i=Bu(r);if(!i)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(An(i))}else if(r===null||$m.has(typeof r))n.push(dn(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,i)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),sv=S("$ZodFunction",(e,t)=>(ye.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...r){const i=e._def.input?Gu(e._def.input,r):r,o=Reflect.apply(n,this,i);return e._def.output?Gu(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...r){const i=e._def.input?await ju(e._def.input,r):r,o=await Reflect.apply(n,this,i);return e._def.output?await ju(e._def.output,o):o},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{const r=e.constructor;return Array.isArray(n[0])?new r({type:"function",input:new pl({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new r({type:"function",input:n[0],output:e._def.output})},e.output=n=>{const r=e.constructor;return new r({type:"function",input:e._def.input,output:n})},e)),av=S("$ZodPromise",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then(i=>t.innerType._zod.run({value:i,issues:[]},r))}),vl=S("$ZodLazy",(e,t)=>{ye.init(e,t),_m(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),$e(e,"pattern",n=>n.innerType?._zod?.pattern),$e(e,"propValues",n=>n.innerType?._zod?.propValues),$e(e,"optin",n=>n.innerType?._zod?.optin??void 0),$e(e,"optout",n=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),uv=S("$ZodCustom",(e,t)=>{Ve.init(e,t),ye.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(o=>Lh(o,n,r,e));Lh(i,n,r,e)}});function Lh(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(lr(i))}}class cv extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const Vu="~memo",zh=[];function lv(e){return e!==null&&typeof e=="object"}function cu(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const dv=new WeakMap,ar=0,ns=1,si=2;function ai(e,t,n){const r=dv.get(e);if(r!==void 0)return r?si:ar;if(t.has(e))return si;t.add(e);let i=ar;const o=l=>{if(i!==si&&l?._zod){const d=ai(l,t,n);d>i&&(i=d)}},s=(l,d)=>{let f=ar;for(const h of Reflect.ownKeys(l)){const p=Object.getOwnPropertyDescriptor(l,h);if(!p.enumerable)continue;const m=p.get?ns:p.value?._zod?ai(p.value,t,n):ar;m>f&&(f=m)}return f},a=l=>{l>i&&(i=l)},u=e._zod.def;switch(u.type){case"object":{const l=As(u);a(l?s(l):ns),o(u.catchall);break}case"array":o(u.element);break;case"tuple":for(const l of u.items)o(l);o(u.rest);break;case"record":case"map":o(u.keyType),o(u.valueType);break;case"set":o(u.valueType);break;case"union":for(const l of u.options)o(l);break;case"intersection":o(u.left),o(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(u.innerType);break;case"pipe":o(u.in),o(u.out);break;case"function":o(u.input),o(u.output);break;case"lazy":{const l=u._cachedInner??(n?e._zod.innerType:void 0);a(l?ai(l,t,!1):ns);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const l in u){const d=Object.getOwnPropertyDescriptor(u,l);if(!d||d.get)continue;const f=d.value;if(!(!f||typeof f!="object")){if(f._zod)o(f);else if(Array.isArray(f))for(const h of f)o(h)}}}return t.delete(e),DS(e,i)}function DS(e,t){return t!==ns&&dv.set(e,t===si),t}function bl(e){return ai(e,new Set,!0)!==ar}function OS(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let Oo;const Mo=[],MS={alloc(e,t,n){const r=Oo;if(!r)return n;Oo=void 0;const i={value:n,issues:null};return r.set(t.value,i),Mo.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const n=e._zod.parse,r=(i,o)=>{if(o.direction!=="backward"&&wl(o,i.value))throw new cv;return n(i,o)};e._zod.parse=r,e._zod.run===n&&(e._zod.run=r)})},attach(e){var t;let n,r=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const s=e._zod.parse,a=(u,c)=>{if(n===void 0){const _=ai(e,new Set,!1);if(_===ar)return e._zod.parse=s,e._zod.run===a&&(e._zod.run=s),s(u,c);_===si||r?n=!0:r=!0}const l=u.value;if(!lv(l))return s(u,c);let d=c[Vu];d||(d={buckets:new WeakMap,backEdges:void 0},c[Vu]=d);let f;i===c?f=o:(f=OS(d,e),i=c,o=f);const h=f.get(l);if(h)return u.value=h.value,h.issues?h.issues.length&&u.issues.push(...cu(h.issues)):(u.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(h.value)),u;Oo=f;const p=Mo.length,m=s(u,c);Oo=void 0;const y=Mo.length>p?Mo.pop():void 0;return m instanceof Promise?m.then(_=>(y&&(y.issues=_.issues.length?cu(_.issues):zh),_)):(y&&(y.issues=m.issues.length?cu(m.issues):zh),m)};e._zod.parse=a,e._zod.run===s&&(e._zod.run=a)})}};function Vs(){return MS}function wl(e,t){const n=e[Vu]?.backEdges;return n!==void 0&&lv(t)&&n.has(t)}const _l=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var Ph;const kl=Symbol("ZodOutput"),Sl=Symbol("ZodInput");class fv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Hs(){return new fv}(Ph=globalThis).__zod_globalRegistry??(Ph.__zod_globalRegistry=Hs());const Et=globalThis.__zod_globalRegistry,wt=Symbol.for("zod.compile.invalid"),Dh=Symbol.for("zod.compile.fallback");class hn extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}}class Ae extends Error{constructor(t,n=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=n}}function FS(e,t){try{return Ws(e,{assertOnly:!0})}catch{return t}}function xl(e,t){try{const n=Ws(e),r=qs(e,n);return r._zod.bag.validator=FS(e,n),r}catch(n){if(t?.strict)throw n;return e}}function qs(e,t){if(bl(e))throw new Ae("a schema whose subtree contains a reference cycle");const n=Be(e),r=e._zod.run,i=r.__originalRun??r,o=(s,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[Dh]||a&&wl(a,s.value))return i(s,a);const u=t(s.value);return u!==wt?(s.value=u,s):(a&&(a[Dh]=!0),i(s,a))};return o.__originalRun=i,n._zod.bag.fallbackRun=i,n._zod.bag.validator=t,n._zod.run=o,r.__originalRun||US(n,e,t),n}function US(e,t,n){const r=e,i=t;if(typeof i.safeParse=="function"){const o=i.safeParse;r.safeParse=(s,a)=>{const u=n(s);return u!==wt?{success:!0,data:u}:o(s,a)}}if(typeof i.parse=="function"){const o=i.parse;r.parse=(s,a)=>{const u=n(s);return u!==wt?u:o(s,a)}}}function Ws(e,t){let n=!0;try{n=bl(e)}catch{}if(n)throw new Ae("a schema whose subtree contains a reference cycle");const r={constants:new Map,constantCounter:0,varCounter:0,definite:!0},i=new Yc(["input"]),o=qe(i,r,e,"input",!t?.assertOnly);i.write(o===null?"return true;":`return ${o};`);const s=["INVALID",...r.constants.keys()],a=[wt,...r.constants.values()],u=i.content.join(`
65
65
  `),c=t?.debug?s.length>0?`// Constants: ${s.join(", ")}
66
66
  ${u}`:u:"",l=Function,d=`return (input) => {
67
67
  ${u}
68
- }`;let f;try{f=new l(...s,d)(...a)}catch(h){throw new Ie(`this schema (generated code failed to evaluate: ${h.message})`)}return t?.debug&&(f.code=c),f.definite=r.definite,f}function fe(e,t){for(const[r,i]of e.constants)if(i===t)return r;const n=`c${e.constantCounter++}`;return e.constants.set(n,t),n}function Vn(e,t){return e.definite=!1,fe(e,t)}function oe(e){return`v${e.varCounter++}`}function MS(e,t){const n=e._zod.run({value:t,issues:[]},{});if(n&&typeof n.then=="function")return wt;const r=n;return r.issues.length===0?r.value:wt}function ft(e,t,n,r,i=!0){const o=e.content.length,s=t.constants.size,a=t.constantCounter,u=t.varCounter;try{return qe(e,t,n,r,i)}catch(c){if(!(c instanceof Ie)||!c.islandable)throw c;if(e.content.length=o,t.constants.size>s){const l=Array.from(t.constants.keys()).slice(s);for(const d of l)t.constants.delete(d)}return t.constantCounter=a,t.varCounter=u,FS(e,t,n,r)}}function FS(e,t,n,r){t.definite=!1;const i=fe(t,n),o=fe(t,MS),s=oe(t);return e.write(`const ${s} = ${o}(${i}, ${r});`),e.write(`if (${s} === INVALID) return INVALID;`),s}const US=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function GS(e,t,n,r){const i=n._zod.def.checks;if(!i||i.length===0)return r;let o=r;for(const s of i){const a=s._zod.def;if(a.when&&!US.has(a.check))throw new Ie('check with a custom "when" condition');switch(a.check){case"greater_than":jS(e,t,a,o);break;case"less_than":ZS(e,t,a,o);break;case"multiple_of":BS(e,t,a,o);break;case"number_format":fv(e,a,o);break;case"min_length":{const u=Un(a.minimum,"min_length"),c=cu(e,t,o,`${o}.length >= ${u} && ${o}.length < ${a.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{const u=Un(a.maximum,"max_length"),c=cu(e,t,o,`${o}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{const u=Un(a.length,"length_equals"),c=cu(e,t,o,`${o}.length >= ${u} && ${o}.length <= ${a.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Un(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Un(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Un(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=hv(e,t,a,o);break;case"custom":o=JS(e,t,s,o);break;case"bigint_format":HS(e,a,o);break;case"mime_type":VS(e,t,a,o);break;case"property":WS(e,t,a,o);break;case"properties":qS(e,t,a,o);break;case"overwrite":{const u=oe(t);KS(e,t,s,o,u),o=u;break}default:throw new Ie(`check type ${a.check}`)}}return o}function cu(e,t,n,r){const i=fe(t,xi),o=oe(t);return e.write(`const ${o} = typeof ${n} === "string" && ${r} ? ${i}(${n}) : ${n}.length;`),o}function Un(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Ie(`${t} bound of type ${typeof e}`);return`${e}`}function dv(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Ie("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Ie("comparison check with Invalid Date bound");return fe(e,t)}throw new Ie(`comparison check bound of type ${typeof t}`)}function jS(e,t,n,r){const i=n.inclusive?"<":"<=";e.write(`if (${r} ${i} ${dv(t,n.value)}) return INVALID;`)}function ZS(e,t,n,r){const i=n.inclusive?">":">=";e.write(`if (${r} ${i} ${dv(t,n.value)}) return INVALID;`)}function BS(e,t,n,r){if(typeof n.value=="bigint"){if(n.value===BigInt(0))throw new Ie("multiple_of check with a zero divisor");e.write(`if (${r} % ${n.value}n !== 0n) return INVALID;`)}else{const i=fe(t,kc);e.write(`if (${i}(${r}, ${Un(n.value,"multiple_of")}) !== 0) return INVALID;`)}}function fv(e,t,n){const r=t.format;switch(r){case"safeint":e.write(`if (!Number.isSafeInteger(${n})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${n}) || ${n} < -2147483648 || ${n} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${n}) || ${n} < 0 || ${n} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${n}) || ${n} < -3.4028234663852886e38 || ${n} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${n})) return INVALID;`);break;default:throw new Ie(`number format ${r}`)}}function HS(e,t,n){const r=t.format;if(r)switch(r){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break;default:throw new Ie(`bigint format ${r}`)}}function VS(e,t,n,r){const i=n.mime;if(i&&i.length>0){const o=fe(t,new Set(i));e.write(`if (!${o}.has(${r}.type)) return INVALID;`)}}function qS(e,t,n,r){if(n.when)throw new Ie('check with a custom "when" condition');e.write(`if (${r} == null) return INVALID;`);const i=n.shape;for(const o of Reflect.ownKeys(i)){const s=typeof o=="symbol"?fe(t,o):$t(o),a=oe(t);e.write(`const ${a} = ${r}[${s}];`),ft(e,t,i[o],a,!1)}}function WS(e,t,n,r){const i=`${r}[${JSON.stringify(n.property)}]`;qe(e,t,n.schema,i)}function KS(e,t,n,r,i){const o=n._zod.def.tx;if(!o)throw new Ie("overwrite check without a transform function");if(qn(o))throw new hn("z.compile: async overwrite transforms are not supported");const s=fe(t,o);e.write(`const ${i} = ${s}(${r});`)}function Hu(){throw new an}function xl(e){this.issues.push(e)}function JS(e,t,n,r){const i=n._zod.def;if(i.fn){if(qn(i.fn))throw new hn("z.compile: async .refine() predicates are not supported");const o=Vn(t,i.fn),s=fe(t,Hu),a=oe(t);return e.write(`const ${a} = ${o}(${r});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`),r}if(n._zod.check){if(qn(n._zod.check))throw new hn("z.compile: async .superRefine() / check functions are not supported");const o=n._zod.check,a=Vn(t,c=>{const l={value:c,issues:[],addIssue:xl};return o(l)instanceof Promise&&Hu(),l.issues.length===0?l.value:wt}),u=oe(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new Ie("custom check without a predicate or check function")}const YS=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function hv(e,t,n,r,i=!0){const o=n.format;if(o==="base64"){const c=fe(t,Us);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="base64url"){const c=fe(t,ol);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="jwt"){const c=fe(t,ul),l=fe(t,n.alg??null);return e.write(`if (!${c}(${r}, ${l})) return INVALID;`),r}if(o==="ipv6"){const c=fe(t,Fs);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="cidrv6"){const c=fe(t,rl);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="credit_card"){const c=fe(t,sl);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="iban"){const c=fe(t,al);return e.write(`if (!${c}(${r})) return INVALID;`),r}const s=n;if(o==="url"||o==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){const c=fe(t,el),l=fe(t,n),d=oe(t),f=oe(t);if(e.write(`const ${d} = ${r}.trim();`),e.write(`const ${f} = ${c}(${d}, ${l});`),e.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){const m=fe(t,tl);e.write(`if (!${m}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){const m=fe(t,nl);e.write(`if (!${m}(${f}, ${l}.protocol)) return INVALID;`)}if(!i)return null;const h=oe(t),p=s.normalize?`${f}.href`:`${fe(t,ls)}(${d})`;return e.write(`const ${h} = ${p};`),h}const a=n.fn;if(a){if(qn(a))throw new Ie(`async string format ${o}`);const c=fe(t,a);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(YS.has(o)&&n.pattern){const c=fe(t,n.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${r})) return INVALID;`),r}const u=n.format;switch(u){case"regex":throw new Ie("regex format without a pattern");case"lowercase":e.write(`if (${r} !== ${r}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${r} !== ${r}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${r}.includes(${$t(n.includes)})) return INVALID;`);break;case"starts_with":{const c=n.prefix;e.write(`if (${r}.slice(0, ${c.length}) !== ${$t(c)}) return INVALID;`);break}case"ends_with":{const c=n.suffix;e.write(`if (${r}.slice(-${c.length}) !== ${$t(c)}) return INVALID;`);break}default:throw new Ie(`string format ${u}`)}return r}function qe(e,t,n,r,i=!0){const o=n._zod.def,s=o.type;if(o.coerce)throw new Ie(`coercion (z.coerce.${s}())`);const a=i||!!o.checks?.length;let u;switch(s){case"string":u=XS(e,t,n,r,a);break;case"number":u=QS(e,n,r);break;case"boolean":u=ex(e,r);break;case"bigint":u=tx(e,n,r);break;case"symbol":u=nx(e,r);break;case"undefined":u=rx(e,r);break;case"null":u=ix(e,r);break;case"any":case"unknown":u=r;break;case"never":e.write("return INVALID;"),u=r;break;case"void":u=ox(e,r);break;case"nan":u=sx(e,r);break;case"date":u=ax(e,r);break;case"object":u=ux(e,t,n,r,a);break;case"optional":u=cx(e,t,n,r,a);break;case"nullable":u=fx(e,t,n,r,a);break;case"array":u=hx(e,t,n,r,a);break;case"literal":u=px(e,t,n,r);break;case"enum":u=mx(e,t,n,r);break;case"readonly":{const c=Dh(e,t,n,r),l=oe(t);e.write(`const ${l} = Object.freeze(${c});`),u=l;break}case"success":Dh(e,t,n,r),u="true";break;case"default":case"prefault":u=gx(e,t,n,r);break;case"nonoptional":u=yx(e,t,n,r);break;case"tuple":u=vx(e,t,n,r);break;case"union":u=bx(e,t,n,r);break;case"intersection":u=kx(e,t,n,r);break;case"record":u=Sx(e,t,n,r);break;case"map":u=Ex(e,t,n,r);break;case"set":u=$x(e,t,n,r);break;case"file":u=Tx(e,r);break;case"template_literal":u=Cx(e,t,n,r);break;case"lazy":u=Ax(e,t,n,r);break;case"pipe":u=Ix(e,t,n,r);break;case"custom":u=Nx(e,t,n,r);break;case"transform":u=zx(e,t,n,r);break;case"catch":u=Lx(e,t,n,r);break;default:throw new Ie(`schema type ${s}`)}return u===null?null:GS(e,t,n,u)}function XS(e,t,n,r,i=!0){e.write(`if (typeof ${r} !== "string") return INVALID;`);const o=n._zod.def;return o.format===void 0?r:hv(e,t,o,r,i)}function QS(e,t,n){e.write(`if (typeof ${n} !== "number" || !Number.isFinite(${n})) return INVALID;`);const r=t._zod.def;return r.check==="number_format"&&r.format&&fv(e,{format:r.format},n),n}function ex(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function tx(e,t,n){e.write(`if (typeof ${n} !== "bigint") return INVALID;`);const r=t._zod.def;if(r.format)switch(r.format){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break}return n}function nx(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function rx(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function ix(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function ox(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function sx(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function ax(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function ux(e,t,n,r,i=!0){const o=n._zod.def;e.write(`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return INVALID;`);const s=o.shape,a=Object.keys(s),u=Object.getOwnPropertySymbols(s),c=u.length?[...a,...u]:a,l=g=>typeof g=="symbol"?fe(t,g):$t(g),d=g=>typeof g=="symbol"?`[${l(g)}]`:$t(g),f=s;if(a.includes("__proto__"))throw new Ie('object shape key "__proto__"');const h=new Map;for(const g of c){const b=f[g],v=l(g),k=oe(t);if(e.write(`const ${k} = ${r}[${v}];`),b._zod.optin!==void 0){const S=oe(t);e.write(`let ${S} = (() => {`),e.indented(_=>{const N=ft(_,t,b,k);_.write(`return ${N};`)}),e.write("})();"),b._zod.optout==="optional"?(e.write(`if (${S} === INVALID) {`),e.indented(_=>{_.write(`if (${v} in ${r}) return INVALID;`),_.write(`${S} = undefined;`)}),e.write("}")):e.write(`if (${S} === INVALID) return INVALID;`),h.set(g,S)}else{dx(b)&&e.write(`if (!(${v} in ${r})) return INVALID;`);const S=ft(e,t,b,k,i);S!==null&&h.set(g,S)}}const p=o.catchall;let m="none";if(p){const g=p._zod.def.type;if(g==="never"){const b=a.map(v=>`k !== ${$t(v)}`).join(" && ")||"true";e.write(`for (const k in ${r}) {`),e.indented(v=>{v.write(`if (${b}) return INVALID;`)}),e.write("}")}else(g==="unknown"||g==="any")&&!p._zod.def.checks?.length?m="passthrough":m="schema"}const y=oe(t),w=c.some(g=>Ph(f[g])||Vu(f[g]));if(!i){if(m==="schema"){const g=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(b=>{b.write('if (k === "__proto__") continue;'),g&&b.write(`if (${g}.has(k)) continue;`);const v=oe(t);b.write(`const ${v} = ${r}[k];`),ft(b,t,p,v,!1)}),e.write("}")}return null}if(w){e.write(`const ${y} = {};`);for(const g of c){const b=l(g),v=h.get(g);Vu(f[g])?e.write(`if (${b} in ${r}) ${y}[${b}] = ${v};`):Ph(f[g])?e.write(`if (${v} !== undefined || ${b} in ${r}) ${y}[${b}] = ${v};`):e.write(`${y}[${b}] = ${v};`)}}else{const g=c.map(b=>`${d(b)}: ${h.get(b)}`).join(", ");e.write(`const ${y} = { ${g} };`)}if(m!=="none"){const g=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(b=>{if(b.write('if (k === "__proto__") continue;'),g&&b.write(`if (${g}.has(k)) continue;`),m==="passthrough")b.write(`${y}[k] = ${r}[k];`);else{const v=oe(t);b.write(`const ${v} = ${r}[k];`);const k=ft(b,t,p,v);b.write(`${y}[k] = ${k};`)}}),e.write("}")}return y}function cx(e,t,n,r,i=!0){const o=n._zod.def;if(lx(n))return qe(e,t,o.innerType,r,i);if(o.innerType._zod.optin==="defaulted"){const a=oe(t),u=oe(t);return e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(l=>{const d=qe(l,t,o.innerType,r);l.write(`return ${d};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${a} = ${u};`)}),e.write("} else {"),e.indented(c=>{const l=qe(c,t,o.innerType,r);c.write(`${a} = ${l};`)}),e.write("}"),a}const s=i?oe(t):null;return s&&e.write(`let ${s};`),e.write(`if (${r} !== undefined) {`),e.indented(a=>{const u=qe(a,t,o.innerType,r,i);s&&u!==null&&a.write(`${s} = ${u};`)}),e.write("}"),s}function lx(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function dx(e){return e._zod.optin===void 0&&Gn(e)}function Gn(e){if(e._zod.def.coerce)return!0;const t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Gn(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Gn(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Gn):!0;case"intersection":return!t.left||!t.right?!0:Gn(t.left)&&Gn(t.right);case"pipe":return t.in?Gn(t.in):!0;default:return!0}}function Vu(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Ph(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&rr(e)}function rr(e){const t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?rr(t.innerType):!0;case"union":return t.options?t.options.some(rr):!0;case"intersection":return!t.left||!t.right||rr(t.left)||rr(t.right);case"pipe":return t.out?rr(t.out):!0;default:return!0}}function fx(e,t,n,r,i=!0){const o=n._zod.def,s=i?oe(t):null;return s&&e.write(`let ${s} = null;`),e.write(`if (${r} !== null) {`),e.indented(a=>{const u=qe(a,t,o.innerType,r,i);s&&u!==null&&a.write(`${s} = ${u};`)}),e.write("}"),s}function hx(e,t,n,r,i=!0){const o=n._zod.def;e.write(`if (!Array.isArray(${r})) return INVALID;`);const s=i?oe(t):null,a=oe(t),u=oe(t);return s&&e.write(`const ${s} = new Array(${r}.length);`),e.write(`for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {`),e.indented(c=>{c.write(`const ${u} = ${r}[${a}];`);const l=ft(c,t,o.element,u,i);s&&l!==null&&c.write(`${s}[${a}] = ${l};`)}),e.write("}"),s}function px(e,t,n,r){const o=n._zod.def.values;if(o.length!==1){const a=fe(t,new Set(o));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}const s=o[0];if(typeof s=="number"&&Number.isNaN(s)){const a=fe(t,new Set(o));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}if(typeof s=="string")e.write(`if (${r} !== ${$t(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")e.write(`if (${r} !== ${s}) return INVALID;`);else if(s===null)e.write(`if (${r} !== null) return INVALID;`);else if(s===void 0)e.write(`if (${r} !== undefined) return INVALID;`);else if(typeof s=="bigint")e.write(`if (${r} !== ${s}n) return INVALID;`);else throw new Ie(`literal type ${typeof s}`);return r}function mx(e,t,n,r){const i=n._zod.values;if(!i)throw new Ie("enum schema without enumerated values");const o=fe(t,i);return e.write(`if (!${o}.has(${r})) return INVALID;`),r}function Dh(e,t,n,r){const i=n._zod.def;return qe(e,t,i.innerType,r)}function gx(e,t,n,r){const i=n._zod.def,s=Object.getOwnPropertyDescriptor(n._zod.def,"defaultValue")?()=>n._zod.def.defaultValue:void 0;if(n._zod.def.type==="prefault"){if(!s)return qe(e,t,i.innerType,r);const u=fe(t,s),c=oe(t);return e.write(`let ${c} = ${r};`),e.write(`if (${r} === undefined) ${c} = ${u}();`),qe(e,t,i.innerType,c)}const a=oe(t);if(s){const u=fe(t,s),c=fe(t,Si);e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(l=>{l.write(`${a} = ${c}(${u}());`)}),e.write("} else {"),e.indented(l=>{const d=qe(l,t,i.innerType,r);l.write(`${a} = ${d} === undefined ? ${c}(${u}()) : ${d};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${r} !== undefined) {`),e.indented(u=>{const c=qe(u,t,i.innerType,r);u.write(`${a} = ${c};`)}),e.write("}");return a}function yx(e,t,n,r){const i=n._zod.def,o=qe(e,t,i.innerType,r),s=oe(t);return e.write(`const ${s} = ${o};`),e.write(`if (${s} === undefined) return INVALID;`),s}function vx(e,t,n,r){const i=n._zod.def,o=i.items,s=i.rest;e.write(`if (!Array.isArray(${r})) return INVALID;`);const a=Oh(o,"optin"),u=Oh(o,"optout");s?e.write(`if (${r}.length < ${a}) return INVALID;`):e.write(`if (${r}.length < ${a} || ${r}.length > ${o.length}) return INVALID;`);const c=oe(t);e.write(`const ${c} = [];`);for(let l=0;l<o.length;l++){const d=o[l];if(l>=u)e.write(`if (${c}.length === ${l}) {`),e.indented(f=>{f.write(`if (${l} < ${r}.length) {`),f.indented(h=>{const p=oe(t);h.write(`const ${p} = ${r}[${l}];`);const m=ft(h,t,d,p);h.write(`${c}[${l}] = ${m};`)}),f.write("} else {"),f.indented(h=>{if(Vu(d)){h.write(`${c}.length = ${l};`);return}const p=oe(t),m=oe(t);h.write(`const ${p} = undefined;`),h.write(`const ${m} = (() => {`),h.indented(y=>{const w=ft(y,t,d,p);y.write(`return ${w};`)}),h.write("})();"),h.write(`if (${m} === INVALID || ${m} === undefined) ${c}.length = ${l};`),h.write(`else ${c}[${l}] = ${m};`)}),f.write("}")}),e.write("}");else{const f=oe(t);e.write(`const ${f} = ${r}[${l}];`);const h=ft(e,t,d,f);e.write(`${c}[${l}] = ${h};`)}}if(s){const l=oe(t),d=oe(t);e.write(`for (let ${l} = ${o.length}; ${l} < ${r}.length; ${l}++) {`),e.indented(f=>{f.write(`const ${d} = ${r}[${l}];`);const h=ft(f,t,s,d);f.write(`${c}[${l}] = ${h};`)}),e.write("}")}return c}function Oh(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function bx(e,t,n,r){const i=n._zod.def,o=i.options;if(i.discriminator)return wx(e,t,i,r);if(i.inclusive===!1)throw new Ie("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),r;if(o.length===1)return qe(e,t,o[0],r);if(o.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){const u=new Set(o.flatMap(l=>l._zod.def.values)),c=fe(t,u);return e.write(`if (!${c}.has(${r})) return INVALID;`),r}const a=oe(t);e.write(`let ${a};`);for(let u=0;u<o.length;u++){const c=o[u];u===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(l=>{const d=qe(l,t,c,r);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function wx(e,t,n,r){if(n.unionFallback)throw new Ie("discriminated union with unionFallback");if(n.options.length===0)return e.write("return INVALID;"),r;const i=oe(t),o=oe(t);e.write(`const ${i} = ${r}?.[${$t(n.discriminator)}];`),e.write(`let ${o};`);let s=!0;const a=new Set;for(const u of n.options){const c=u._zod.propValues?.[n.discriminator];if(!c||c.size===0)throw new Ie("discriminated union option without static discriminator values");for(const f of c){if(a.has(f))throw new Ie(`duplicate discriminator value ${String(f)}`);a.add(f)}const l=Array.from(c,f=>_x(t,i,f)),d=s?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(f=>{const h=qe(f,t,u,r);f.write(`${o} = ${h};`)}),e.write("}"),s=!1}return e.write("else { return INVALID; }"),o}function _x(e,t,n){if(typeof n=="string")return`${t} === ${$t(n)}`;if(typeof n=="number")return Number.isNaN(n)?`Number.isNaN(${t})`:`${t} === ${n}`;if(typeof n=="boolean")return`${t} === ${n}`;if(n===null)return`${t} === null`;if(n===void 0)return`${t} === undefined`;if(typeof n=="bigint")return`${t} === ${n}n`;if(typeof n=="symbol"){const r=fe(e,n);return`${t} === ${r}`}throw new Ie(`literal discriminator value ${String(n)}`)}function kx(e,t,n,r){const i=n._zod.def;t.definite=!1;const o=ft(e,t,i.left,r),s=ft(e,t,i.right,r),a=fe(t,li),u=oe(t);return e.write(`const ${u} = ${a}(${o}, ${s});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function Sx(e,t,n,r){const i=n._zod.def,o=fe(t,ln);e.write(`if (!${o}(${r})) return INVALID;`);const s=oe(t),a=oe(t),u=oe(t);e.write(`const ${s} = {};`);const c=i,l=c.partial?void 0:i.keyType._zod.values;if(l){const h=[];for(const m of l){if(!(typeof m=="string"||typeof m=="number"||typeof m=="symbol"))throw new Ie(`record key value ${String(m)}`);const y=typeof m=="number"?m.toString():m;if(y==="__proto__")throw new Ie('record key "__proto__"');h.push(y);const w=fe(t,m),g=qe(e,t,i.keyType,w),b=oe(t);e.write(`const ${b} = ${r}[${xx(t,y)}];`);const v=ft(e,t,i.valueType,b);e.write(`${s}[${g}] = ${v};`)}const p=fe(t,new Set(h));return e.write(`for (const ${a} in ${r}) {`),e.indented(m=>{m.write(`if (${p}.has(${a})) continue;`),c.mode==="loose"?m.write(`if (${a} !== "__proto__") ${s}[${a}] = ${r}[${a}];`):m.write("return INVALID;")}),e.write("}"),s}const d=i.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){const h=i.mode==="loose",p=Vs(i.keyType);p.definite===!1&&(t.definite=!1);const m=fe(t,p),y=fe(t,kr),w=oe(t);return Mh(e,t,r,a,g=>{g.write(`let ${w} = ${m}(${a});`),g.write(`if (${w} === INVALID && typeof ${a} === "string" && ${y}.test(${a})) ${w} = ${m}(Number(${a}));`),h?g.write(`if (${w} === INVALID) { ${s}[${a}] = ${r}[${a}]; continue; }`):g.write(`if (${w} === INVALID) return INVALID;`),g.write(`if (${w} === "__proto__") continue;`);const b=oe(t);g.write(`const ${b} = ${r}[${a}];`);const v=ft(g,t,i.valueType,b);g.write(`${s}[${w}] = ${v};`)}),s}return Mh(e,t,r,a,h=>{h.write(`const ${u} = ${r}[${a}];`);const p=ft(h,t,i.valueType,u);h.write(`${s}[${a}] = ${p};`)},"return INVALID;"),s}function Mh(e,t,n,r,i,o){const s=fe(t,Object.prototype.propertyIsEnumerable),a=oe(t),u=oe(t),c=oe(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${n});`),e.write(`const ${u} = Object.getOwnPropertyNames(${n});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${r} = ${u}[${c}];`),l.write(`if (${r} === "__proto__" || !${s}.call(${n}, ${r})) continue;`),i(l)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${a}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${r} = ${a}[${c}];`),l.write(`if (!${s}.call(${n}, ${r})) continue;`),o?l.write(o):i(l)}),e.write("}")}function xx(e,t){return typeof t=="string"?$t(t):fe(e,t)}function Ex(e,t,n,r){const i=n._zod.def;e.write(`if (!(${r} instanceof Map)) return INVALID;`);const o=oe(t),s=oe(t),a=oe(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${s}, ${a}] of ${r}) {`),e.indented(u=>{const c=qe(u,t,i.keyType,s),l=qe(u,t,i.valueType,a);u.write(`${o}.set(${c}, ${l});`)}),e.write("}"),o}function $x(e,t,n,r){const i=n._zod.def;e.write(`if (!(${r} instanceof Set)) return INVALID;`);const o=oe(t),s=oe(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${s} of ${r}) {`),e.indented(a=>{const u=qe(a,t,i.valueType,s);a.write(`${o}.add(${u});`)}),e.write("}"),o}function Tx(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function Cx(e,t,n,r){e.write(`if (typeof ${r} !== "string") return INVALID;`);const i=n._zod.pattern;if(i){const o=fe(t,i);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${r})) return INVALID;`)}return r}function Ax(e,t,n,r){const i=n._zod.def,o=Vn(t,i.getter),s=fe(t,{parser:null});e.write(`if (!${s}.parser) {`),e.indented(u=>{u.write(`const inner = ${o}();`),u.write(`${s}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");const a=oe(t);return e.write(`const ${a} = ${s}.parser(${r});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function Ix(e,t,n,r){const i=n._zod.def,o=qe(e,t,i.in,r);if(i.transform){if(qn(i.transform))throw new hn("z.compile: async transforms in pipes are not supported");const s=i.transform,u=Vn(t,l=>{const d={value:l,issues:[],addIssue:xl},f=s(l,d);return f instanceof Promise?wt:d.issues.length===0?f:wt}),c=oe(t);return e.write(`const ${c} = ${u}(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),qe(e,t,i.out,c)}else return qe(e,t,i.out,o)}function qn(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function Nx(e,t,n,r){const i=n._zod.def;if(i.fn){if(qn(i.fn))throw new hn("z.compile: async custom predicates are not supported");const o=Vn(t,i.fn),s=fe(t,Hu),a=oe(t);e.write(`const ${a} = ${o}(${r});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Ie("custom schema without a predicate function");return r}function Rx(e,t,n){const r=e._zod.run({value:n,issues:[]},{});if(r&&typeof r.then=="function")return wt;const i=r;return i.issues.length===0?i.value:t()}function Lx(e,t,n,r){const i=n._zod.def;if(!i.catchValue[Tc])throw new Ie("catch with a callback (only a constant catch value compiles)",!1);const o=oe(t);e.write(`let ${o} = (() => {`),e.indented(c=>{const l=ft(c,t,i.innerType,r);c.write(`return ${l};`)}),e.write("})();");const s=fe(t,i.innerType),a=Vn(t,i.catchValue),u=fe(t,Rx);return e.write(`if (${o} === INVALID) {`),e.indented(c=>{c.write(`${o} = ${u}(${s}, ${a}, ${r});`),c.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function zx(e,t,n,r){const i=n._zod.def;if(i.transform){if(qn(i.transform))throw new hn("z.compile: async transforms are not supported");const o=i.transform,a=Vn(t,c=>{const l={value:c,issues:[],addIssue:xl},d=o(c,l);return d instanceof Promise?wt:l.issues.length===0?d:wt}),u=oe(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return r}function qs(e){return e.checks&&(e.checks=[...e.checks]),e}function pv(e,t){return new e(qs({type:"string",...R(t)}))}function mv(e,t){return new e(qs({type:"string",coerce:!0,...R(t)}))}function El(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function $l(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Tl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function Cl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Al(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Il(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function Ws(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Nl(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Rl(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function Ll(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function zl(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Pl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function Dl(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function Ol(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function Ml(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function Fl(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function gv(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...R(t)})}function Ul(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function Gl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function jl(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Zl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Bl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function yv(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...R(t)})}function vv(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...R(t)})}function Hl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}const Vl={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ql(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function Wl(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Kl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Jl(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function bv(e,t){return new e(qs({type:"number",checks:[],...R(t)}))}function wv(e,t){return new e(qs({type:"number",coerce:!0,checks:[],...R(t)}))}function _v(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function kv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...R(t)})}function Sv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...R(t)})}function xv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...R(t)})}function Ev(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...R(t)})}function $v(e,t){return new e({type:"boolean",...R(t)})}function Tv(e,t){return new e({type:"boolean",coerce:!0,...R(t)})}function Cv(e,t){return new e({type:"bigint",...R(t)})}function Av(e,t){return new e({type:"bigint",coerce:!0,...R(t)})}function Iv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...R(t)})}function Nv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...R(t)})}function Rv(e,t){return new e({type:"symbol",...R(t)})}function Lv(e,t){return new e({type:"undefined",...R(t)})}function zv(e,t){return new e({type:"null",...R(t)})}function Pv(e){return new e({type:"any"})}function Dv(e){return new e({type:"unknown"})}function Ov(e,t){return new e({type:"never",...R(t)})}function Mv(e,t){return new e({type:"void",...R(t)})}function Fv(e,t){return new e({type:"date",...R(t)})}function Uv(e,t){return new e({type:"date",coerce:!0,...R(t)})}function Gv(e,t){return new e({type:"nan",...R(t)})}function pn(e,t){return new Wc({check:"less_than",...R(t),value:e,inclusive:!1})}function Tt(e,t){return new Wc({check:"less_than",...R(t),value:e,inclusive:!0})}function mn(e,t){return new Kc({check:"greater_than",...R(t),value:e,inclusive:!1})}function Ct(e,t){return new Kc({check:"greater_than",...R(t),value:e,inclusive:!0})}function Ks(e){return mn(0,e)}function Js(e){return pn(0,e)}function Ys(e){return Tt(0,e)}function Xs(e){return Ct(0,e)}function Wn(e,t){return new $g({check:"multiple_of",...R(t),value:e})}function Xn(e,t){return new Ag({check:"max_size",...R(t),maximum:e})}function gn(e,t){return new Ig({check:"min_size",...R(t),minimum:e})}function Sr(e,t){return new Ng({check:"size_equals",...R(t),size:e})}function xr(e,t){return new Rg({check:"max_length",...R(t),maximum:e})}function In(e,t){return new Lg({check:"min_length",...R(t),minimum:e})}function Er(e,t){return new zg({check:"length_equals",...R(t),length:e})}function zi(e,t){return new Pg({check:"string_format",format:"regex",...R(t),pattern:e})}function Pi(e){return new Dg({check:"string_format",format:"lowercase",...R(e)})}function Di(e){return new Og({check:"string_format",format:"uppercase",...R(e)})}function Oi(e,t){return new Mg({check:"string_format",format:"includes",...R(t),includes:e})}function Mi(e,t){return new Fg({check:"string_format",format:"starts_with",...R(t),prefix:e})}function Fi(e,t){return new Ug({check:"string_format",format:"ends_with",...R(t),suffix:e})}function Qs(e,t,n){return new Gg({check:"property",property:e,schema:t,...R(n)})}function Ui(e,t){return new jg({check:"properties",shape:e,...R(t)})}function Gi(e,t){return new Zg({check:"mime_type",mime:e,...R(t)})}function tn(e){return new Bg({check:"overwrite",tx:e})}function ji(e){return tn(t=>t.normalize(e))}function Zi(){return tn(e=>e.trim())}function Bi(){return tn(e=>e.toLowerCase())}function Hi(){return tn(e=>e.toUpperCase())}function Vi(){return tn(e=>km(e))}function jv(e,t,n){return new e({type:"array",element:t,...R(n)})}function Px(e,t,n){return new e({type:"union",options:t,...R(n)})}function Dx(e,t,n){return new e({type:"union",options:t,inclusive:!1,...R(n)})}function Ox(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...R(r)})}function Mx(e,t,n){return new e({type:"intersection",left:t,right:n})}function Fx(e,t,n,r){const i=n instanceof be,o=i?r:n,s=i?n:null;return new e({type:"tuple",items:t,rest:s,...R(o)})}function Ux(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...R(r)})}function Gx(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...R(r)})}function jx(e,t,n){return new e({type:"set",valueType:t,...R(n)})}function Zx(e,t,n){const r=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new e({type:"enum",entries:r,...R(n)})}function Bx(e,t,n){return new e({type:"enum",entries:t,...R(n)})}function Hx(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...R(n)})}function Zv(e,t){return new e({type:"file",...R(t)})}function Vx(e,t){return new e({type:"transform",transform:t})}function qx(e,t){return new e({type:"optional",innerType:t})}function Wx(e,t){return new e({type:"nullable",innerType:t})}function Kx(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Si(n)}})}function Jx(e,t,n){return new e({type:"nonoptional",innerType:t,...R(n)})}function Yx(e,t){return new e({type:"success",innerType:t})}function Xx(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:Cc(n)})}function Qx(e,t,n){return new e({type:"pipe",in:t,out:n})}function e0(e,t){return new e({type:"readonly",innerType:t})}function t0(e,t,n){return new e({type:"template_literal",parts:t,...R(n)})}function n0(e,t){return new e({type:"lazy",getter:t})}function r0(e,t){return new e({type:"promise",innerType:t})}function Bv(e,t,n){const r=R(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function Hv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}function Vv(e,t){const n=qv(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(cr(i,r.value,n._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(cr(o))}},e(r.value,r)),t);return n}function qv(e,t){const n=new He({check:"custom",...R(t)});return n._zod.check=e,n}function Wv(e){const t=new He({check:"describe"});return t._zod.onattach=[n=>{const r=Et.get(n)??{};Et.add(n,{...r,description:e})}],t._zod.check=()=>{},t}function Kv(e){const t=new He({check:"meta"});return t._zod.onattach=[n=>{const r=Et.get(n)??{};Et.add(n,{...r,...e})}],t._zod.check=()=>{},t}function Jv(e,t){const n=R(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(h=>typeof h=="string"?h.toLowerCase():h),i=i.map(h=>typeof h=="string"?h.toLowerCase():h));const o=new Set(r),s=new Set(i),a=e.Codec??gl,u=e.Boolean??ll,c=e.String??Li,l=new c({type:"string",error:n.error}),d=new u({type:"boolean",error:n.error}),f=new a({type:"pipe",in:l,out:d,transform:((h,p)=>{let m=h;return n.case!=="sensitive"&&(m=m.toLowerCase()),o.has(m)?!0:s.has(m)?!1:(p.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:p.value,inst:f,continue:!1}),{})}),reverseTransform:((h,p)=>h===!0?r[0]||"true":i[0]||"false"),error:n.error});return f._zod.bag.truthy=r,f._zod.bag.falsy=i,f._zod.bag.case=n.case??"insensitive",f}function $r(e,t,n,r={}){const i=R(r),o={check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...i};return n instanceof RegExp&&(o.pattern=n),new e(o)}function si(e,...t){for(const n of t)for(const r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&It(e,r,n[r]);return e}function dr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Et,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function nt(e,t,n,r,i){const o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(i);return Object.assign(n,o),!0}function Me(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{const f=s.schema,h=t.processors[i.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,f,l)}const d=e._zod.parent;d&&(s.ref||(s.ref=d),Me(d,t,l),t.seen.get(d).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&si(s.schema,u),t.io==="input"&&gt(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Fh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function fr(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const r=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const u=r.get(a);if(u&&u!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}const i=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(s[0])?.id,f=e.external.uri??(p=>p);if(d)return{ref:f(d)};const h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${f("__shared")}#/${a}/${Fh(h)}`}}const u="#",c=`${u}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:u};const l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+Fh(l)}},o=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:u,defId:c}=i(s);a.def={...a.schema},c&&(a.defId=c);const l=a.schema;for(const d in l)delete l[d];l.$ref=u};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
68
+ }`;let f;try{f=new l(...s,d)(...a)}catch(h){throw new Ae(`this schema (generated code failed to evaluate: ${h.message})`)}return t?.debug&&(f.code=c),f.definite=r.definite,f}function de(e,t){for(const[r,i]of e.constants)if(i===t)return r;const n=`c${e.constantCounter++}`;return e.constants.set(n,t),n}function qn(e,t){return e.definite=!1,de(e,t)}function re(e){return`v${e.varCounter++}`}function GS(e,t){const n=e._zod.run({value:t,issues:[]},{});if(n&&typeof n.then=="function")return wt;const r=n;return r.issues.length===0?r.value:wt}function ft(e,t,n,r,i=!0){const o=e.content.length,s=t.constants.size,a=t.constantCounter,u=t.varCounter;try{return qe(e,t,n,r,i)}catch(c){if(!(c instanceof Ae)||!c.islandable)throw c;if(e.content.length=o,t.constants.size>s){const l=Array.from(t.constants.keys()).slice(s);for(const d of l)t.constants.delete(d)}return t.constantCounter=a,t.varCounter=u,jS(e,t,n,r)}}function jS(e,t,n,r){t.definite=!1;const i=de(t,n),o=de(t,GS),s=re(t);return e.write(`const ${s} = ${o}(${i}, ${r});`),e.write(`if (${s} === INVALID) return INVALID;`),s}const ZS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function BS(e,t,n,r){const i=n._zod.def.checks;if(!i||i.length===0)return r;let o=r;for(const s of i){const a=s._zod.def;if(a.when&&!ZS.has(a.check))throw new Ae('check with a custom "when" condition');switch(a.check){case"greater_than":VS(e,t,a,o);break;case"less_than":HS(e,t,a,o);break;case"multiple_of":qS(e,t,a,o);break;case"number_format":pv(e,a,o);break;case"min_length":{const u=Gn(a.minimum,"min_length"),c=lu(e,t,o,`${o}.length >= ${u} && ${o}.length < ${a.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{const u=Gn(a.maximum,"max_length"),c=lu(e,t,o,`${o}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{const u=Gn(a.length,"length_equals"),c=lu(e,t,o,`${o}.length >= ${u} && ${o}.length <= ${a.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Gn(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Gn(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Gn(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=mv(e,t,a,o);break;case"custom":o=QS(e,t,s,o);break;case"bigint_format":WS(e,a,o);break;case"mime_type":KS(e,t,a,o);break;case"property":YS(e,t,a,o);break;case"properties":JS(e,t,a,o);break;case"overwrite":{const u=re(t);XS(e,t,s,o,u),o=u;break}default:throw new Ae(`check type ${a.check}`)}}return o}function lu(e,t,n,r){const i=de(t,$i),o=re(t);return e.write(`const ${o} = typeof ${n} === "string" && ${r} ? ${i}(${n}) : ${n}.length;`),o}function Gn(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Ae(`${t} bound of type ${typeof e}`);return`${e}`}function hv(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Ae("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Ae("comparison check with Invalid Date bound");return de(e,t)}throw new Ae(`comparison check bound of type ${typeof t}`)}function VS(e,t,n,r){const i=n.inclusive?"<":"<=";e.write(`if (${r} ${i} ${hv(t,n.value)}) return INVALID;`)}function HS(e,t,n,r){const i=n.inclusive?">":">=";e.write(`if (${r} ${i} ${hv(t,n.value)}) return INVALID;`)}function qS(e,t,n,r){if(typeof n.value=="bigint"){if(n.value===BigInt(0))throw new Ae("multiple_of check with a zero divisor");e.write(`if (${r} % ${n.value}n !== 0n) return INVALID;`)}else{const i=de(t,Sc);e.write(`if (${i}(${r}, ${Gn(n.value,"multiple_of")}) !== 0) return INVALID;`)}}function pv(e,t,n){const r=t.format;switch(r){case"safeint":e.write(`if (!Number.isSafeInteger(${n})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${n}) || ${n} < -2147483648 || ${n} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${n}) || ${n} < 0 || ${n} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${n}) || ${n} < -3.4028234663852886e38 || ${n} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${n})) return INVALID;`);break;default:throw new Ae(`number format ${r}`)}}function WS(e,t,n){const r=t.format;if(r)switch(r){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break;default:throw new Ae(`bigint format ${r}`)}}function KS(e,t,n,r){const i=n.mime;if(i&&i.length>0){const o=de(t,new Set(i));e.write(`if (!${o}.has(${r}.type)) return INVALID;`)}}function JS(e,t,n,r){if(n.when)throw new Ae('check with a custom "when" condition');e.write(`if (${r} == null) return INVALID;`);const i=n.shape;for(const o of Reflect.ownKeys(i)){const s=typeof o=="symbol"?de(t,o):$t(o),a=re(t);e.write(`const ${a} = ${r}[${s}];`),ft(e,t,i[o],a,!1)}}function YS(e,t,n,r){const i=`${r}[${JSON.stringify(n.property)}]`;qe(e,t,n.schema,i)}function XS(e,t,n,r,i){const o=n._zod.def.tx;if(!o)throw new Ae("overwrite check without a transform function");if(Wn(o))throw new hn("z.compile: async overwrite transforms are not supported");const s=de(t,o);e.write(`const ${i} = ${s}(${r});`)}function Hu(){throw new an}function El(e){this.issues.push(e)}function QS(e,t,n,r){const i=n._zod.def;if(i.fn){if(Wn(i.fn))throw new hn("z.compile: async .refine() predicates are not supported");const o=qn(t,i.fn),s=de(t,Hu),a=re(t);return e.write(`const ${a} = ${o}(${r});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`),r}if(n._zod.check){if(Wn(n._zod.check))throw new hn("z.compile: async .superRefine() / check functions are not supported");const o=n._zod.check,a=qn(t,c=>{const l={value:c,issues:[],addIssue:El};return o(l)instanceof Promise&&Hu(),l.issues.length===0?l.value:wt}),u=re(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new Ae("custom check without a predicate or check function")}const e0=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function mv(e,t,n,r,i=!0){const o=n.format;if(o==="base64"){const c=de(t,js);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="base64url"){const c=de(t,sl);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="jwt"){const c=de(t,cl),l=de(t,n.alg??null);return e.write(`if (!${c}(${r}, ${l})) return INVALID;`),r}if(o==="ipv6"){const c=de(t,Gs);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="cidrv6"){const c=de(t,il);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="credit_card"){const c=de(t,al);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(o==="iban"){const c=de(t,ul);return e.write(`if (!${c}(${r})) return INVALID;`),r}const s=n;if(o==="url"||o==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){const c=de(t,tl),l=de(t,n),d=re(t),f=re(t);if(e.write(`const ${d} = ${r}.trim();`),e.write(`const ${f} = ${c}(${d}, ${l});`),e.write(`if (typeof ${f} === "number") return INVALID;`),s.hostname!==void 0){const m=de(t,nl);e.write(`if (!${m}(${f}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){const m=de(t,rl);e.write(`if (!${m}(${f}, ${l}.protocol)) return INVALID;`)}if(!i)return null;const h=re(t),p=s.normalize?`${f}.href`:`${de(t,fs)}(${d})`;return e.write(`const ${h} = ${p};`),h}const a=n.fn;if(a){if(Wn(a))throw new Ae(`async string format ${o}`);const c=de(t,a);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(e0.has(o)&&n.pattern){const c=de(t,n.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${r})) return INVALID;`),r}const u=n.format;switch(u){case"regex":throw new Ae("regex format without a pattern");case"lowercase":e.write(`if (${r} !== ${r}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${r} !== ${r}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${r}.includes(${$t(n.includes)})) return INVALID;`);break;case"starts_with":{const c=n.prefix;e.write(`if (${r}.slice(0, ${c.length}) !== ${$t(c)}) return INVALID;`);break}case"ends_with":{const c=n.suffix;e.write(`if (${r}.slice(-${c.length}) !== ${$t(c)}) return INVALID;`);break}default:throw new Ae(`string format ${u}`)}return r}function qe(e,t,n,r,i=!0){const o=n._zod.def,s=o.type;if(o.coerce)throw new Ae(`coercion (z.coerce.${s}())`);const a=i||!!o.checks?.length;let u;switch(s){case"string":u=t0(e,t,n,r,a);break;case"number":u=n0(e,n,r);break;case"boolean":u=r0(e,r);break;case"bigint":u=i0(e,n,r);break;case"symbol":u=o0(e,r);break;case"undefined":u=s0(e,r);break;case"null":u=a0(e,r);break;case"any":case"unknown":u=r;break;case"never":e.write("return INVALID;"),u=r;break;case"void":u=u0(e,r);break;case"nan":u=c0(e,r);break;case"date":u=l0(e,r);break;case"object":u=d0(e,t,n,r,a);break;case"optional":u=f0(e,t,n,r,a);break;case"nullable":u=m0(e,t,n,r,a);break;case"array":u=g0(e,t,n,r,a);break;case"literal":u=y0(e,t,n,r);break;case"enum":u=v0(e,t,n,r);break;case"readonly":{const c=Mh(e,t,n,r),l=re(t);e.write(`const ${l} = Object.freeze(${c});`),u=l;break}case"success":Mh(e,t,n,r),u="true";break;case"default":case"prefault":u=b0(e,t,n,r);break;case"nonoptional":u=w0(e,t,n,r);break;case"tuple":u=_0(e,t,n,r);break;case"union":u=k0(e,t,n,r);break;case"intersection":u=E0(e,t,n,r);break;case"record":u=$0(e,t,n,r);break;case"map":u=C0(e,t,n,r);break;case"set":u=A0(e,t,n,r);break;case"file":u=I0(e,r);break;case"template_literal":u=N0(e,t,n,r);break;case"lazy":u=R0(e,t,n,r);break;case"pipe":u=L0(e,t,n,r);break;case"custom":u=z0(e,t,n,r);break;case"transform":u=O0(e,t,n,r);break;case"catch":u=D0(e,t,n,r);break;default:throw new Ae(`schema type ${s}`)}return u===null?null:BS(e,t,n,u)}function t0(e,t,n,r,i=!0){e.write(`if (typeof ${r} !== "string") return INVALID;`);const o=n._zod.def;return o.format===void 0?r:mv(e,t,o,r,i)}function n0(e,t,n){e.write(`if (typeof ${n} !== "number" || !Number.isFinite(${n})) return INVALID;`);const r=t._zod.def;return r.check==="number_format"&&r.format&&pv(e,{format:r.format},n),n}function r0(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function i0(e,t,n){e.write(`if (typeof ${n} !== "bigint") return INVALID;`);const r=t._zod.def;if(r.format)switch(r.format){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break}return n}function o0(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function s0(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function a0(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function u0(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function c0(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function l0(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function d0(e,t,n,r,i=!0){const o=n._zod.def;e.write(`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return INVALID;`);const s=o.shape,a=Object.keys(s),u=Object.getOwnPropertySymbols(s),c=u.length?[...a,...u]:a,l=g=>typeof g=="symbol"?de(t,g):$t(g),d=g=>typeof g=="symbol"?`[${l(g)}]`:$t(g),f=s;if(a.includes("__proto__"))throw new Ae('object shape key "__proto__"');const h=new Map;for(const g of c){const b=f[g],v=l(g),w=re(t);if(e.write(`const ${w} = ${r}[${v}];`),b._zod.optin!==void 0){const k=re(t);e.write(`let ${k} = (() => {`),e.indented(x=>{const N=ft(x,t,b,w);x.write(`return ${N};`)}),e.write("})();"),b._zod.optout==="optional"?(e.write(`if (${k} === INVALID) {`),e.indented(x=>{x.write(`if (${v} in ${r}) return INVALID;`),x.write(`${k} = undefined;`)}),e.write("}")):e.write(`if (${k} === INVALID) return INVALID;`),h.set(g,k)}else{p0(b)&&e.write(`if (!(${v} in ${r})) return INVALID;`);const k=ft(e,t,b,w,i);k!==null&&h.set(g,k)}}const p=o.catchall;let m="none";if(p){const g=p._zod.def.type;if(g==="never"){const b=a.map(v=>`k !== ${$t(v)}`).join(" && ")||"true";e.write(`for (const k in ${r}) {`),e.indented(v=>{v.write(`if (${b}) return INVALID;`)}),e.write("}")}else(g==="unknown"||g==="any")&&!p._zod.def.checks?.length?m="passthrough":m="schema"}const y=re(t),_=c.some(g=>Oh(f[g])||qu(f[g]));if(!i){if(m==="schema"){const g=a.length>0?de(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(b=>{b.write('if (k === "__proto__") continue;'),g&&b.write(`if (${g}.has(k)) continue;`);const v=re(t);b.write(`const ${v} = ${r}[k];`),ft(b,t,p,v,!1)}),e.write("}")}return null}if(_){e.write(`const ${y} = {};`);for(const g of c){const b=l(g),v=h.get(g);qu(f[g])?e.write(`if (${b} in ${r}) ${y}[${b}] = ${v};`):Oh(f[g])?e.write(`if (${v} !== undefined || ${b} in ${r}) ${y}[${b}] = ${v};`):e.write(`${y}[${b}] = ${v};`)}}else{const g=c.map(b=>`${d(b)}: ${h.get(b)}`).join(", ");e.write(`const ${y} = { ${g} };`)}if(m!=="none"){const g=a.length>0?de(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(b=>{if(b.write('if (k === "__proto__") continue;'),g&&b.write(`if (${g}.has(k)) continue;`),m==="passthrough")b.write(`${y}[k] = ${r}[k];`);else{const v=re(t);b.write(`const ${v} = ${r}[k];`);const w=ft(b,t,p,v);b.write(`${y}[k] = ${w};`)}}),e.write("}")}return y}function f0(e,t,n,r,i=!0){const o=n._zod.def;if(h0(n))return qe(e,t,o.innerType,r,i);if(o.innerType._zod.optin==="defaulted"){const a=re(t),u=re(t);return e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(l=>{const d=qe(l,t,o.innerType,r);l.write(`return ${d};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${a} = ${u};`)}),e.write("} else {"),e.indented(c=>{const l=qe(c,t,o.innerType,r);c.write(`${a} = ${l};`)}),e.write("}"),a}const s=i?re(t):null;return s&&e.write(`let ${s};`),e.write(`if (${r} !== undefined) {`),e.indented(a=>{const u=qe(a,t,o.innerType,r,i);s&&u!==null&&a.write(`${s} = ${u};`)}),e.write("}"),s}function h0(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function p0(e){return e._zod.optin===void 0&&jn(e)}function jn(e){if(e._zod.def.coerce)return!0;const t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?jn(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?jn(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(jn):!0;case"intersection":return!t.left||!t.right?!0:jn(t.left)&&jn(t.right);case"pipe":return t.in?jn(t.in):!0;default:return!0}}function qu(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Oh(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&ir(e)}function ir(e){const t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?ir(t.innerType):!0;case"union":return t.options?t.options.some(ir):!0;case"intersection":return!t.left||!t.right||ir(t.left)||ir(t.right);case"pipe":return t.out?ir(t.out):!0;default:return!0}}function m0(e,t,n,r,i=!0){const o=n._zod.def,s=i?re(t):null;return s&&e.write(`let ${s} = null;`),e.write(`if (${r} !== null) {`),e.indented(a=>{const u=qe(a,t,o.innerType,r,i);s&&u!==null&&a.write(`${s} = ${u};`)}),e.write("}"),s}function g0(e,t,n,r,i=!0){const o=n._zod.def;e.write(`if (!Array.isArray(${r})) return INVALID;`);const s=i?re(t):null,a=re(t),u=re(t);return s&&e.write(`const ${s} = new Array(${r}.length);`),e.write(`for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {`),e.indented(c=>{c.write(`const ${u} = ${r}[${a}];`);const l=ft(c,t,o.element,u,i);s&&l!==null&&c.write(`${s}[${a}] = ${l};`)}),e.write("}"),s}function y0(e,t,n,r){const o=n._zod.def.values;if(o.length!==1){const a=de(t,new Set(o));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}const s=o[0];if(typeof s=="number"&&Number.isNaN(s)){const a=de(t,new Set(o));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}if(typeof s=="string")e.write(`if (${r} !== ${$t(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")e.write(`if (${r} !== ${s}) return INVALID;`);else if(s===null)e.write(`if (${r} !== null) return INVALID;`);else if(s===void 0)e.write(`if (${r} !== undefined) return INVALID;`);else if(typeof s=="bigint")e.write(`if (${r} !== ${s}n) return INVALID;`);else throw new Ae(`literal type ${typeof s}`);return r}function v0(e,t,n,r){const i=n._zod.values;if(!i)throw new Ae("enum schema without enumerated values");const o=de(t,i);return e.write(`if (!${o}.has(${r})) return INVALID;`),r}function Mh(e,t,n,r){const i=n._zod.def;return qe(e,t,i.innerType,r)}function b0(e,t,n,r){const i=n._zod.def,s=Object.getOwnPropertyDescriptor(n._zod.def,"defaultValue")?()=>n._zod.def.defaultValue:void 0;if(n._zod.def.type==="prefault"){if(!s)return qe(e,t,i.innerType,r);const u=de(t,s),c=re(t);return e.write(`let ${c} = ${r};`),e.write(`if (${r} === undefined) ${c} = ${u}();`),qe(e,t,i.innerType,c)}const a=re(t);if(s){const u=de(t,s),c=de(t,Ei);e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(l=>{l.write(`${a} = ${c}(${u}());`)}),e.write("} else {"),e.indented(l=>{const d=qe(l,t,i.innerType,r);l.write(`${a} = ${d} === undefined ? ${c}(${u}()) : ${d};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${r} !== undefined) {`),e.indented(u=>{const c=qe(u,t,i.innerType,r);u.write(`${a} = ${c};`)}),e.write("}");return a}function w0(e,t,n,r){const i=n._zod.def,o=qe(e,t,i.innerType,r),s=re(t);return e.write(`const ${s} = ${o};`),e.write(`if (${s} === undefined) return INVALID;`),s}function _0(e,t,n,r){const i=n._zod.def,o=i.items,s=i.rest;e.write(`if (!Array.isArray(${r})) return INVALID;`);const a=Fh(o,"optin"),u=Fh(o,"optout");s?e.write(`if (${r}.length < ${a}) return INVALID;`):e.write(`if (${r}.length < ${a} || ${r}.length > ${o.length}) return INVALID;`);const c=re(t);e.write(`const ${c} = [];`);for(let l=0;l<o.length;l++){const d=o[l];if(l>=u)e.write(`if (${c}.length === ${l}) {`),e.indented(f=>{f.write(`if (${l} < ${r}.length) {`),f.indented(h=>{const p=re(t);h.write(`const ${p} = ${r}[${l}];`);const m=ft(h,t,d,p);h.write(`${c}[${l}] = ${m};`)}),f.write("} else {"),f.indented(h=>{if(qu(d)){h.write(`${c}.length = ${l};`);return}const p=re(t),m=re(t);h.write(`const ${p} = undefined;`),h.write(`const ${m} = (() => {`),h.indented(y=>{const _=ft(y,t,d,p);y.write(`return ${_};`)}),h.write("})();"),h.write(`if (${m} === INVALID || ${m} === undefined) ${c}.length = ${l};`),h.write(`else ${c}[${l}] = ${m};`)}),f.write("}")}),e.write("}");else{const f=re(t);e.write(`const ${f} = ${r}[${l}];`);const h=ft(e,t,d,f);e.write(`${c}[${l}] = ${h};`)}}if(s){const l=re(t),d=re(t);e.write(`for (let ${l} = ${o.length}; ${l} < ${r}.length; ${l}++) {`),e.indented(f=>{f.write(`const ${d} = ${r}[${l}];`);const h=ft(f,t,s,d);f.write(`${c}[${l}] = ${h};`)}),e.write("}")}return c}function Fh(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function k0(e,t,n,r){const i=n._zod.def,o=i.options;if(i.discriminator)return S0(e,t,i,r);if(i.inclusive===!1)throw new Ae("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),r;if(o.length===1)return qe(e,t,o[0],r);if(o.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){const u=new Set(o.flatMap(l=>l._zod.def.values)),c=de(t,u);return e.write(`if (!${c}.has(${r})) return INVALID;`),r}const a=re(t);e.write(`let ${a};`);for(let u=0;u<o.length;u++){const c=o[u];u===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(l=>{const d=qe(l,t,c,r);l.write(`return ${d};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function S0(e,t,n,r){if(n.unionFallback)throw new Ae("discriminated union with unionFallback");if(n.options.length===0)return e.write("return INVALID;"),r;const i=re(t),o=re(t);e.write(`const ${i} = ${r}?.[${$t(n.discriminator)}];`),e.write(`let ${o};`);let s=!0;const a=new Set;for(const u of n.options){const c=u._zod.propValues?.[n.discriminator];if(!c||c.size===0)throw new Ae("discriminated union option without static discriminator values");for(const f of c){if(a.has(f))throw new Ae(`duplicate discriminator value ${String(f)}`);a.add(f)}const l=Array.from(c,f=>x0(t,i,f)),d=s?"if":"else if";e.write(`${d} (${l.join(" || ")}) {`),e.indented(f=>{const h=qe(f,t,u,r);f.write(`${o} = ${h};`)}),e.write("}"),s=!1}return e.write("else { return INVALID; }"),o}function x0(e,t,n){if(typeof n=="string")return`${t} === ${$t(n)}`;if(typeof n=="number")return Number.isNaN(n)?`Number.isNaN(${t})`:`${t} === ${n}`;if(typeof n=="boolean")return`${t} === ${n}`;if(n===null)return`${t} === null`;if(n===void 0)return`${t} === undefined`;if(typeof n=="bigint")return`${t} === ${n}n`;if(typeof n=="symbol"){const r=de(e,n);return`${t} === ${r}`}throw new Ae(`literal discriminator value ${String(n)}`)}function E0(e,t,n,r){const i=n._zod.def;t.definite=!1;const o=ft(e,t,i.left,r),s=ft(e,t,i.right,r),a=de(t,fi),u=re(t);return e.write(`const ${u} = ${a}(${o}, ${s});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function $0(e,t,n,r){const i=n._zod.def,o=de(t,ln);e.write(`if (!${o}(${r})) return INVALID;`);const s=re(t),a=re(t),u=re(t);e.write(`const ${s} = {};`);const c=i,l=c.partial?void 0:i.keyType._zod.values;if(l){const h=[];for(const m of l){if(!(typeof m=="string"||typeof m=="number"||typeof m=="symbol"))throw new Ae(`record key value ${String(m)}`);const y=typeof m=="number"?m.toString():m;if(y==="__proto__")throw new Ae('record key "__proto__"');h.push(y);const _=de(t,m),g=qe(e,t,i.keyType,_),b=re(t);e.write(`const ${b} = ${r}[${T0(t,y)}];`);const v=ft(e,t,i.valueType,b);e.write(`${s}[${g}] = ${v};`)}const p=de(t,new Set(h));return e.write(`for (const ${a} in ${r}) {`),e.indented(m=>{m.write(`if (${p}.has(${a})) continue;`),c.mode==="loose"?m.write(`if (${a} !== "__proto__") ${s}[${a}] = ${r}[${a}];`):m.write("return INVALID;")}),e.write("}"),s}const d=i.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){const h=i.mode==="loose",p=Ws(i.keyType);p.definite===!1&&(t.definite=!1);const m=de(t,p),y=de(t,xr),_=re(t);return Uh(e,t,r,a,g=>{g.write(`let ${_} = ${m}(${a});`),g.write(`if (${_} === INVALID && typeof ${a} === "string" && ${y}.test(${a})) ${_} = ${m}(Number(${a}));`),h?g.write(`if (${_} === INVALID) { ${s}[${a}] = ${r}[${a}]; continue; }`):g.write(`if (${_} === INVALID) return INVALID;`),g.write(`if (${_} === "__proto__") continue;`);const b=re(t);g.write(`const ${b} = ${r}[${a}];`);const v=ft(g,t,i.valueType,b);g.write(`${s}[${_}] = ${v};`)}),s}return Uh(e,t,r,a,h=>{h.write(`const ${u} = ${r}[${a}];`);const p=ft(h,t,i.valueType,u);h.write(`${s}[${a}] = ${p};`)},"return INVALID;"),s}function Uh(e,t,n,r,i,o){const s=de(t,Object.prototype.propertyIsEnumerable),a=re(t),u=re(t),c=re(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${n});`),e.write(`const ${u} = Object.getOwnPropertyNames(${n});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${r} = ${u}[${c}];`),l.write(`if (${r} === "__proto__" || !${s}.call(${n}, ${r})) continue;`),i(l)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${a}.length; ${c}++) {`),e.indented(l=>{l.write(`const ${r} = ${a}[${c}];`),l.write(`if (!${s}.call(${n}, ${r})) continue;`),o?l.write(o):i(l)}),e.write("}")}function T0(e,t){return typeof t=="string"?$t(t):de(e,t)}function C0(e,t,n,r){const i=n._zod.def;e.write(`if (!(${r} instanceof Map)) return INVALID;`);const o=re(t),s=re(t),a=re(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${s}, ${a}] of ${r}) {`),e.indented(u=>{const c=qe(u,t,i.keyType,s),l=qe(u,t,i.valueType,a);u.write(`${o}.set(${c}, ${l});`)}),e.write("}"),o}function A0(e,t,n,r){const i=n._zod.def;e.write(`if (!(${r} instanceof Set)) return INVALID;`);const o=re(t),s=re(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${s} of ${r}) {`),e.indented(a=>{const u=qe(a,t,i.valueType,s);a.write(`${o}.add(${u});`)}),e.write("}"),o}function I0(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function N0(e,t,n,r){e.write(`if (typeof ${r} !== "string") return INVALID;`);const i=n._zod.pattern;if(i){const o=de(t,i);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${r})) return INVALID;`)}return r}function R0(e,t,n,r){const i=n._zod.def,o=qn(t,i.getter),s=de(t,{parser:null});e.write(`if (!${s}.parser) {`),e.indented(u=>{u.write(`const inner = ${o}();`),u.write(`${s}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");const a=re(t);return e.write(`const ${a} = ${s}.parser(${r});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function L0(e,t,n,r){const i=n._zod.def,o=qe(e,t,i.in,r);if(i.transform){if(Wn(i.transform))throw new hn("z.compile: async transforms in pipes are not supported");const s=i.transform,u=qn(t,l=>{const d={value:l,issues:[],addIssue:El},f=s(l,d);return f instanceof Promise?wt:d.issues.length===0?f:wt}),c=re(t);return e.write(`const ${c} = ${u}(${o});`),e.write(`if (${c} === INVALID) return INVALID;`),qe(e,t,i.out,c)}else return qe(e,t,i.out,o)}function Wn(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function z0(e,t,n,r){const i=n._zod.def;if(i.fn){if(Wn(i.fn))throw new hn("z.compile: async custom predicates are not supported");const o=qn(t,i.fn),s=de(t,Hu),a=re(t);e.write(`const ${a} = ${o}(${r});`),e.write(`if (${a} instanceof Promise) ${s}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Ae("custom schema without a predicate function");return r}function P0(e,t,n){const r=e._zod.run({value:n,issues:[]},{});if(r&&typeof r.then=="function")return wt;const i=r;return i.issues.length===0?i.value:t()}function D0(e,t,n,r){const i=n._zod.def;if(!i.catchValue[Cc])throw new Ae("catch with a callback (only a constant catch value compiles)",!1);const o=re(t);e.write(`let ${o} = (() => {`),e.indented(c=>{const l=ft(c,t,i.innerType,r);c.write(`return ${l};`)}),e.write("})();");const s=de(t,i.innerType),a=qn(t,i.catchValue),u=de(t,P0);return e.write(`if (${o} === INVALID) {`),e.indented(c=>{c.write(`${o} = ${u}(${s}, ${a}, ${r});`),c.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function O0(e,t,n,r){const i=n._zod.def;if(i.transform){if(Wn(i.transform))throw new hn("z.compile: async transforms are not supported");const o=i.transform,a=qn(t,c=>{const l={value:c,issues:[],addIssue:El},d=o(c,l);return d instanceof Promise?wt:l.issues.length===0?d:wt}),u=re(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return r}function Ks(e){return e.checks&&(e.checks=[...e.checks]),e}function gv(e,t){return new e(Ks({type:"string",...R(t)}))}function yv(e,t){return new e(Ks({type:"string",coerce:!0,...R(t)}))}function $l(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function Tl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Cl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function Al(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Il(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Nl(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function Js(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Rl(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Ll(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function zl(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Pl(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Dl(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function Ol(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function Ml(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function Fl(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function Ul(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function vv(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...R(t)})}function Gl(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function jl(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function Zl(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Bl(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Vl(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function bv(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...R(t)})}function wv(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...R(t)})}function Hl(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}const ql={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Wl(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function Kl(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Jl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Yl(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function _v(e,t){return new e(Ks({type:"number",checks:[],...R(t)}))}function kv(e,t){return new e(Ks({type:"number",coerce:!0,checks:[],...R(t)}))}function Sv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function xv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...R(t)})}function Ev(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...R(t)})}function $v(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...R(t)})}function Tv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...R(t)})}function Cv(e,t){return new e({type:"boolean",...R(t)})}function Av(e,t){return new e({type:"boolean",coerce:!0,...R(t)})}function Iv(e,t){return new e({type:"bigint",...R(t)})}function Nv(e,t){return new e({type:"bigint",coerce:!0,...R(t)})}function Rv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...R(t)})}function Lv(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...R(t)})}function zv(e,t){return new e({type:"symbol",...R(t)})}function Pv(e,t){return new e({type:"undefined",...R(t)})}function Dv(e,t){return new e({type:"null",...R(t)})}function Ov(e){return new e({type:"any"})}function Mv(e){return new e({type:"unknown"})}function Fv(e,t){return new e({type:"never",...R(t)})}function Uv(e,t){return new e({type:"void",...R(t)})}function Gv(e,t){return new e({type:"date",...R(t)})}function jv(e,t){return new e({type:"date",coerce:!0,...R(t)})}function Zv(e,t){return new e({type:"nan",...R(t)})}function pn(e,t){return new Kc({check:"less_than",...R(t),value:e,inclusive:!1})}function Tt(e,t){return new Kc({check:"less_than",...R(t),value:e,inclusive:!0})}function mn(e,t){return new Jc({check:"greater_than",...R(t),value:e,inclusive:!1})}function Ct(e,t){return new Jc({check:"greater_than",...R(t),value:e,inclusive:!0})}function Ys(e){return mn(0,e)}function Xs(e){return pn(0,e)}function Qs(e){return Tt(0,e)}function ea(e){return Ct(0,e)}function Kn(e,t){return new Cg({check:"multiple_of",...R(t),value:e})}function Qn(e,t){return new Ng({check:"max_size",...R(t),maximum:e})}function gn(e,t){return new Rg({check:"min_size",...R(t),minimum:e})}function Er(e,t){return new Lg({check:"size_equals",...R(t),size:e})}function $r(e,t){return new zg({check:"max_length",...R(t),maximum:e})}function Nn(e,t){return new Pg({check:"min_length",...R(t),minimum:e})}function Tr(e,t){return new Dg({check:"length_equals",...R(t),length:e})}function Di(e,t){return new Og({check:"string_format",format:"regex",...R(t),pattern:e})}function Oi(e){return new Mg({check:"string_format",format:"lowercase",...R(e)})}function Mi(e){return new Fg({check:"string_format",format:"uppercase",...R(e)})}function Fi(e,t){return new Ug({check:"string_format",format:"includes",...R(t),includes:e})}function Ui(e,t){return new Gg({check:"string_format",format:"starts_with",...R(t),prefix:e})}function Gi(e,t){return new jg({check:"string_format",format:"ends_with",...R(t),suffix:e})}function ta(e,t,n){return new Zg({check:"property",property:e,schema:t,...R(n)})}function ji(e,t){return new Bg({check:"properties",shape:e,...R(t)})}function Zi(e,t){return new Vg({check:"mime_type",mime:e,...R(t)})}function tn(e){return new Hg({check:"overwrite",tx:e})}function Bi(e){return tn(t=>t.normalize(e))}function Vi(){return tn(e=>e.trim())}function Hi(){return tn(e=>e.toLowerCase())}function qi(){return tn(e=>e.toUpperCase())}function Wi(){return tn(e=>xm(e))}function Bv(e,t,n){return new e({type:"array",element:t,...R(n)})}function M0(e,t,n){return new e({type:"union",options:t,...R(n)})}function F0(e,t,n){return new e({type:"union",options:t,inclusive:!1,...R(n)})}function U0(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...R(r)})}function G0(e,t,n){return new e({type:"intersection",left:t,right:n})}function j0(e,t,n,r){const i=n instanceof ye,o=i?r:n,s=i?n:null;return new e({type:"tuple",items:t,rest:s,...R(o)})}function Z0(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...R(r)})}function B0(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...R(r)})}function V0(e,t,n){return new e({type:"set",valueType:t,...R(n)})}function H0(e,t,n){const r=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new e({type:"enum",entries:r,...R(n)})}function q0(e,t,n){return new e({type:"enum",entries:t,...R(n)})}function W0(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...R(n)})}function Vv(e,t){return new e({type:"file",...R(t)})}function K0(e,t){return new e({type:"transform",transform:t})}function J0(e,t){return new e({type:"optional",innerType:t})}function Y0(e,t){return new e({type:"nullable",innerType:t})}function X0(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Ei(n)}})}function Q0(e,t,n){return new e({type:"nonoptional",innerType:t,...R(n)})}function ex(e,t){return new e({type:"success",innerType:t})}function tx(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:Ac(n)})}function nx(e,t,n){return new e({type:"pipe",in:t,out:n})}function rx(e,t){return new e({type:"readonly",innerType:t})}function ix(e,t,n){return new e({type:"template_literal",parts:t,...R(n)})}function ox(e,t){return new e({type:"lazy",getter:t})}function sx(e,t){return new e({type:"promise",innerType:t})}function Hv(e,t,n){const r=R(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function qv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}function Wv(e,t){const n=Kv(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(lr(i,r.value,n._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(lr(o))}},e(r.value,r)),t);return n}function Kv(e,t){const n=new Ve({check:"custom",...R(t)});return n._zod.check=e,n}function Jv(e){const t=new Ve({check:"describe"});return t._zod.onattach=[n=>{const r=Et.get(n)??{};Et.add(n,{...r,description:e})}],t._zod.check=()=>{},t}function Yv(e){const t=new Ve({check:"meta"});return t._zod.onattach=[n=>{const r=Et.get(n)??{};Et.add(n,{...r,...e})}],t._zod.check=()=>{},t}function Xv(e,t){const n=R(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(h=>typeof h=="string"?h.toLowerCase():h),i=i.map(h=>typeof h=="string"?h.toLowerCase():h));const o=new Set(r),s=new Set(i),a=e.Codec??yl,u=e.Boolean??dl,c=e.String??Pi,l=new c({type:"string",error:n.error}),d=new u({type:"boolean",error:n.error}),f=new a({type:"pipe",in:l,out:d,transform:((h,p)=>{let m=h;return n.case!=="sensitive"&&(m=m.toLowerCase()),o.has(m)?!0:s.has(m)?!1:(p.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:p.value,inst:f,continue:!1}),{})}),reverseTransform:((h,p)=>h===!0?r[0]||"true":i[0]||"false"),error:n.error});return f._zod.bag.truthy=r,f._zod.bag.falsy=i,f._zod.bag.case=n.case??"insensitive",f}function Cr(e,t,n,r={}){const i=R(r),o={check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...i};return n instanceof RegExp&&(o.pattern=n),new e(o)}function ui(e,...t){for(const n of t)for(const r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&At(e,r,n[r]);return e}function fr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Et,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function nt(e,t,n,r,i){const o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(i);return Object.assign(n,o),!0}function Me(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{const f=s.schema,h=t.processors[i.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,f,l)}const d=e._zod.parent;d&&(s.ref||(s.ref=d),Me(d,t,l),t.seen.get(d).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&ui(s.schema,u),t.io==="input"&&gt(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Gh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function hr(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const r=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const u=r.get(a);if(u&&u!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}const i=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(s[0])?.id,f=e.external.uri??(p=>p);if(d)return{ref:f(d)};const h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${f("__shared")}#/${a}/${Gh(h)}`}}const u="#",c=`${u}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:u};const l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+Gh(l)}},o=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:u,defId:c}=i(s);a.def={...a.schema},c&&(a.defId=c);const l=a.schema;for(const d in l)delete l[d];l.$ref=u};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
69
69
 
70
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){o(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Yv(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const n=[];for(const r of t){if(!r||typeof r!="object")return;Yv(r);const i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;const o=r.type;for(const s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;n.includes(s)||n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Xv=new Set(["type","properties","required","additionalProperties"]),Uh=["oneOf","anyOf"];function Gh(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function qu(e){const t=[];for(const o of e){if(typeof o!="object"||o.type!=="object")return null;for(const s in o)if(!Xv.has(s))return null;t.push(o)}const n={},r=new Set;for(const o of t){for(const s in o.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;const a=[];for(const c of t){const l=c.properties?.[s]??Gh(c);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}const u=a.length===1?a[0]:qu(a)??{allOf:a};It(n,s,u)}for(const s of o.required??[])r.add(s)}const i={type:"object",properties:n};if(r.size&&(i.required=[...r]),t.every(o=>o.additionalProperties===!1))i.additionalProperties=!1;else{const o=[];for(const s of t){const a=Gh(s);a&&!o.some(u=>JSON.stringify(u)===JSON.stringify(a))&&o.push(a)}o.length===1?i.additionalProperties=o[0]:o.length>1&&(i.additionalProperties={allOf:o})}return i}function i0(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const i of Xv)if(i in e)return;const n=t.filter(i=>Uh.some(o=>Array.isArray(i[o])));let r=null;if(!n.length)r=qu(t);else{const i=n[0],o=Uh.find(u=>Array.isArray(i[u]));if(Object.keys(i).length!==1)return;const s=t.filter(u=>u!==i),a=i[o].map(u=>qu([...s,u]));if(a.some(u=>!u))return;r={[o]:a}}r&&(delete e.allOf,si(e,r))}function hr(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const u=e.seen.get(a);if(u.ref===null)return;const c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){r(d);const h=e.seen.get(d),p=h.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):si(c,p),si(c,l),a._zod.parent===d)for(const y in c)y==="$ref"||y==="allOf"||y in l||delete c[y];if(p.$ref&&h.def)for(const y in c)y==="$ref"||y==="allOf"||y in h.def&&JSON.stringify(c[y])===JSON.stringify(h.def[y])&&delete c[y]}const f=a._zod.parent;if(f&&f!==d){r(f);const h=e.seen.get(f);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const p in c)p==="$ref"||p==="allOf"||p in h.def&&JSON.stringify(c[p])===JSON.stringify(h.def[p])&&delete c[p]}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())Yv(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const u of e.seen.values())for(const c of[u.schema,u.def]){const l=c?.allOf;if(!Array.isArray(l))continue;const d=a.get(l);d?d.push(c):a.set(l,[c])}for(const u of e.intersections)for(const c of a.get(u)??[])i0(c)}}const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}si(i,n.defId?n.schema:n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,It(s,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:di(t,"input",e.processors),output:di(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function gt(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return gt(r.element,n);if(r.type==="set")return gt(r.valueType,n);if(r.type==="lazy")return gt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return gt(r.innerType,n);if(r.type==="intersection")return gt(r.left,n)||gt(r.right,n);if(r.type==="record"||r.type==="map")return gt(r.keyType,n)||gt(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:gt(r.in,n)||gt(r.out,n);if(r.type==="object"){for(const i in r.shape)if(gt(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(gt(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(gt(i,n))return!0;return!!(r.rest&&gt(r.rest,n))}return!1}const Qv=(e,t={})=>n=>{const r=dr({...n,processors:t});return Me(e,r),fr(r,e),hr(r,e)},di=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=dr({...i??{},target:o,io:t,processors:n});return Me(e,s),fr(s,e),hr(s,e)},pr=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},mr=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},jh=(e,t)=>{pr(e,"minimum",t),mr(e,"maximum",t)},eb=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},tb=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},nb=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},rb=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Zh=(e,t)=>pr(e,"minimum",t.minimum),Bh=(e,t)=>mr(e,"maximum",t.maximum),Hh=e=>(t,n)=>{rb(t,n.format);const[r,i]=e[n.format];pr(t,"minimum",r),mr(t,"maximum",i)},o0={greater_than:(e,t)=>pr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>mr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>eb(e,t.value),number_format:Hh(Ec),bigint_format:Hh($c),min_length:Zh,max_length:Bh,length_equals:(e,t)=>jh(e,t.length),min_size:Zh,max_size:Bh,size_equals:(e,t)=>jh(e,t.size),string_format:(e,t)=>{rb(e,t.format),t.pattern&&tb(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>nb(e,t.mime)};function tt(e){const t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(const o of r)o0[o._zod.def.check]?.(t,o._zod.def);const i=e._zod.bag;i.minimum!==void 0&&pr(t,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&pr(t,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&mr(t,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&mr(t,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&eb(t,i.multipleOf),i.format!==void 0&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&nb(t,i.mime);for(const o of i.patterns??[])tb(t,o);return t}const s0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a0=new Map([[il,ag],[Gs,ug]]),ib=e=>a0.get(e)??e,ob=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c,laxFormat:l}=tt(e);if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=s0[a]??a,i.format===""&&delete i.format,(a==="time"||l)&&delete i.format),c&&(i.contentEncoding=c),u&&u.size>0){const d=[...u].map(ib);d.length===1?i.pattern=d[0].source:d.length>1&&(i.allOf=[...d.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},sb=(e,t,n,r)=>{const i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:l}=tt(e);i.type=l?"integer":"number";const d=typeof c=="number"&&c>=(o??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(d?h?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:typeof o=="number"&&(i.minimum=o),f?h?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof s=="number"&&(i.maximum=s),a){const p=new Set;for(const w of a)Number.isFinite(w)&&w!==0?p.add(Math.abs(w)):nt(e,t,i,r,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);const[m,...y]=p;m!==void 0&&(i.multipleOf=m),y.length&&(i.allOf=[...i.allOf??[],...y.map(w=>({multipleOf:w}))])}},ab=(e,t,n,r)=>{n.type="boolean"},ub=(e,t,n,r)=>{nt(e,t,n,r,"BigInt cannot be represented in JSON Schema")},cb=(e,t,n,r)=>{nt(e,t,n,r,"Symbols cannot be represented in JSON Schema")},lb=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},db=(e,t,n,r)=>{nt(e,t,n,r,"Undefined cannot be represented in JSON Schema")},fb=(e,t,n,r)=>{nt(e,t,n,r,"Void cannot be represented in JSON Schema")},hb=(e,t,n,r)=>{n.not={}},pb=(e,t,n,r)=>{},mb=(e,t,n,r)=>{},gb=(e,t,n,r)=>{nt(e,t,n,r,"Date cannot be represented in JSON Schema")},yb=(e,t,n,r)=>{const i=e._zod.def,o=os(i.entries);if(o.length===0){n.not={};return}o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),n.enum=o},vb=(e,t,n,r)=>{const i=e._zod.def;if(i.values.length===0){n.not={};return}const o=[];for(const s of i.values)if(s===void 0){if(nt(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(nt(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){const s=o[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),o.every(s=>typeof s=="boolean")&&(n.type="boolean"),o.every(s=>s===null)&&(n.type="null"),n.enum=o},bb=(e,t,n,r)=>{nt(e,t,n,r,"NaN cannot be represented in JSON Schema")},wb=(e,t,n,r)=>{const i=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},_b=(e,t,n,r)=>{const i=n;i.type="string",i.format="binary",i.contentEncoding="binary";const{minimum:o,maximum:s,mime:a}=tt(e);o!==void 0&&(i.minLength=o),s!==void 0&&(i.maxLength=s),a&&(a.length===0?i.not={}:a.length===1?i.contentMediaType=a[0]:i.anyOf=a.map(u=>({contentMediaType:u})))},kb=(e,t,n,r)=>{n.type="boolean"},Sb=(e,t,n,r)=>{nt(e,t,n,r,"Custom types cannot be represented in JSON Schema")},xb=(e,t,n,r)=>{nt(e,t,n,r,"Function types cannot be represented in JSON Schema")},Eb=(e,t,n,r)=>{nt(e,t,n,r,"Transforms cannot be represented in JSON Schema")},$b=(e,t,n,r)=>{nt(e,t,n,r,"Map cannot be represented in JSON Schema")},Tb=(e,t,n,r)=>{nt(e,t,n,r,"Set cannot be represented in JSON Schema")},Cb=(e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=tt(e);typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=Me(o.element,t,{...r,path:[...r.path,"items"]})};function fi(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?fi(t.out):t.type==="catch"?fi(t.innerType):e._zod.optin}const Ab=(e,t,n,r)=>{const i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&nt(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const c in s)It(i.properties,c,Me(s[c],t,{...r,path:[...r.path,"properties",c]}));const u=[];for(const c of Object.keys(s)){const l=o.shape[c];(t.io==="input"?fi(l)===void 0:l._zod.optout===void 0)&&u.push(c)}u.length>0&&(i.required=u),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Me(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Yl=(e,t,n,r)=>{const i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,u)=>Me(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));o?n.oneOf=s:n.anyOf=s},Ib=(e,t,n,r)=>{const i=e._zod.def,o=Me(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Me(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u,t.intersections.push(u)},Nb=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((m,y)=>Me(m,t,{...r,path:[...r.path,s,y]})),c=o.rest?Me(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;let l=o.items.length;for(;l>0;){const m=o.items[l-1];if(!(t.io==="input"?fi(m)!==void 0:m._zod.optout==="optional"))break;l--}const d=o.items.length,f=!o.rest;t.target==="draft-2020-12"?(i.prefixItems=u,f?i.items=!1:c&&(i.items=c),l>0&&(i.minItems=l),f&&(i.maxItems=d)):t.target==="openapi-3.0"?(i.items={anyOf:u},c&&i.items.anyOf.push(c),l>0&&(i.minItems=l),f&&(i.maxItems=d)):(i.items=u,f?i.additionalItems=!1:c&&(i.additionalItems=c),l>0&&(i.minItems=l),f&&(i.maxItems=d));const{minimum:h,maximum:p}=tt(e);typeof h=="number"&&(i.minItems=h),typeof p=="number"&&(i.maxItems=p)};function Wu(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const p=e.get(t)?.def;if(!p)return t;const m=Wu(e,p,n);return m===p?t:m}for(const p of["anyOf","oneOf"]){const m=t[p];if(!Array.isArray(m))continue;const y=m.map(w=>Wu(e,w,n));y.some((w,g)=>w!==m[g])&&(t={...t,[p]:y})}const r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some(p=>p==="number"||p==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some(p=>typeof p=="number"))return t;const{minimum:s,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:l,format:d,id:f,...h}=t;return h.enum?h.enum=h.enum.map(p=>typeof p=="number"?String(p):p):typeof h.const=="number"&&(h.const=String(h.const)),i&&(h.type="string",o||(h.pattern=(r.includes("number")?kr:Hc).source)),h}const Ku=new WeakMap;function u0(e){const t=new Map;for(const r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);const n=new Map;for(const r of Ku.get(e)??[]){const i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;const s=Wu(t,o,new Set);s!==o&&n.set(o,s)}if(n.size)for(const r of e.seen.values())for(const i of[r.schema,r.def]){const o=i&&n.get(i.propertyNames);o&&(i.propertyNames=o)}}const Rb=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=tt(s).patterns;if(o.mode==="loose"&&a&&a.size>0){const l=Me(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const d of a)It(i.patternProperties,ib(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=Me(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let l=Ku.get(t);l||(l=[],Ku.set(t,l),t.deferred.push(()=>u0(t))),l.push(e)}i.additionalProperties=Me(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}const u=s._zod.values,c=t.io==="input"&&fi(o.valueType)!==void 0;if(u&&!o.partial&&!c){const l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l.map(String))}},Lb=(e,t,n,r)=>{const i=e._zod.def,o=Me(i.innerType,t,r),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},zb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},Xl=Symbol();function Pb(e,t,n,r,i){let o=!1;const s=JSON.stringify(e,(a,u)=>typeof u!="bigint"?u:(o=!0,null));return o?(nt(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),Xl):JSON.parse(s)}const Db=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;const s=Pb(i.defaultValue,e,t,n,r);s!==Xl&&(n.default=s)},Ob=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;const s=Pb(i.defaultValue,e,t,n,r);s!==Xl&&(n._prefault=s)},Mb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{nt(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},Fb=(e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;Me(s,t,r);const a=t.seen.get(e);a.ref=s},Ub=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Gb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},Ql=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},jb=(e,t,n,r)=>{const i=e._zod.innerType;Me(i,t,r);const o=t.seen.get(e);o.ref=i},Ju={string:ob,number:sb,boolean:ab,bigint:ub,symbol:cb,null:lb,undefined:db,void:fb,never:hb,any:pb,unknown:mb,date:gb,enum:yb,literal:vb,nan:bb,template_literal:wb,file:_b,success:kb,custom:Sb,function:xb,transform:Eb,map:$b,set:Tb,array:Cb,object:Ab,union:Yl,intersection:Ib,tuple:Nb,record:Rb,nullable:Lb,nonoptional:zb,default:Db,prefault:Ob,catch:Mb,pipe:Fb,readonly:Ub,promise:Gb,optional:Ql,lazy:jb};function ed(e,t){if("_idmap"in e){const r=e,i=dr({...t,processors:Ju}),o={};for(const u of r._idmap.entries()){const[c,l]=u;Me(l,i)}const s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(const u of r._idmap.entries()){const[c,l]=u;fr(i,l),It(s,c,hr(i,l))}if(Object.keys(o).length>0){const u=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=dr({...t,processors:Ju});return Me(e,n),fr(n,e),hr(n,e)}class c0{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=dr({processors:Ju,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return Me(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,fr(this.ctx,t);const r=hr(this.ctx,t),{"~standard":i,...o}=r;return o}}const l0=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Zb=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:$y,$ZodArray:Ny,$ZodAsyncError:an,$ZodBase64:py,$ZodBase64URL:my,$ZodBigInt:dl,$ZodBigIntFormat:ky,$ZodBoolean:ll,$ZodCIDRv4:fy,$ZodCIDRv6:hy,$ZodCUID:ey,$ZodCUID2:ty,$ZodCatch:Qy,$ZodCheck:He,$ZodCheckBigIntFormat:Cg,$ZodCheckEndsWith:Ug,$ZodCheckGreaterThan:Kc,$ZodCheckIncludes:Mg,$ZodCheckLengthEquals:zg,$ZodCheckLessThan:Wc,$ZodCheckLowerCase:Dg,$ZodCheckMaxLength:Rg,$ZodCheckMaxSize:Ag,$ZodCheckMimeType:Zg,$ZodCheckMinLength:Lg,$ZodCheckMinSize:Ig,$ZodCheckMultipleOf:$g,$ZodCheckNumberFormat:Tg,$ZodCheckOverwrite:Bg,$ZodCheckProperties:jg,$ZodCheckProperty:Gg,$ZodCheckRegex:Pg,$ZodCheckSizeEquals:Ng,$ZodCheckStartsWith:Fg,$ZodCheckStringFormat:Ri,$ZodCheckUpperCase:Og,$ZodCodec:gl,$ZodCreditCard:yy,$ZodCustom:sv,$ZodCustomStringFormat:wy,$ZodCyclicError:av,$ZodDate:Iy,$ZodDefault:Ky,$ZodDiscriminatedUnion:My,$ZodE164:gy,$ZodEmail:Kg,$ZodEmoji:Xg,$ZodEncodeError:Rs,$ZodEnum:Zy,$ZodError:Um,$ZodExactOptional:qy,$ZodFile:Hy,$ZodFunction:iv,$ZodGUID:qg,$ZodIBAN:vy,$ZodIPv4:cy,$ZodIPv6:ly,$ZodISODate:sy,$ZodISODateTime:oy,$ZodISODuration:uy,$ZodISOTime:ay,$ZodIntersection:Fy,$ZodJWT:by,$ZodKSUID:iy,$ZodLazy:yl,$ZodLiteral:By,$ZodMAC:dy,$ZodMap:Gy,$ZodNaN:ev,$ZodNanoID:Qg,$ZodNever:Cy,$ZodNonOptional:Yy,$ZodNull:Ey,$ZodNullable:Wy,$ZodNumber:cl,$ZodNumberFormat:_y,$ZodObject:zy,$ZodObjectJIT:Py,$ZodOptional:pl,$ZodPipe:ml,$ZodPrefault:Jy,$ZodPreprocess:tv,$ZodPromise:ov,$ZodReadonly:nv,$ZodRealError:Nt,$ZodRecord:Uy,$ZodRegistry:lv,$ZodSet:jy,$ZodString:Li,$ZodStringFormat:Ue,$ZodSuccess:Xy,$ZodSymbol:Sy,$ZodTemplateLiteral:rv,$ZodTransform:Vy,$ZodTuple:hl,$ZodType:be,$ZodULID:ny,$ZodURL:Yg,$ZodUUID:Wg,$ZodUndefined:xy,$ZodUnion:js,$ZodUnknown:Ty,$ZodVoid:Ay,$ZodXID:ry,$ZodXor:Dy,$brand:Nc,$constructor:x,$input:kl,$output:_l,Doc:Jc,INVALID:wt,JSONSchema:l0,JSONSchemaGenerator:c0,NEVER:Ic,TimePrecision:Vl,URL_BAD_FORMAT:Xc,URL_UNPARSEABLE:ci,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ie,_any:Pv,_array:jv,_base64:jl,_base64url:Zl,_bigint:Cv,_boolean:$v,_catch:Xx,_check:qv,_cidrv4:Ul,_cidrv6:Gl,_coercedBigint:Av,_coercedBoolean:Tv,_coercedDate:Uv,_coercedNumber:wv,_coercedString:mv,_creditCard:yv,_cuid:Ll,_cuid2:zl,_custom:Bv,_date:Fv,_decode:Pc,_decodeAsync:Oc,_default:Kx,_discriminatedUnion:Ox,_e164:Bl,_email:El,_emoji:Nl,_encode:zc,_encodeAsync:Dc,_endsWith:Fi,_enum:Zx,_file:Zv,_float32:kv,_float64:Sv,_gt:mn,_gte:Ct,_guid:$l,_iban:vv,_includes:Oi,_int:_v,_int32:xv,_int64:Iv,_intersection:Mx,_ipv4:Ml,_ipv6:Fl,_isoDate:Wl,_isoDateTime:ql,_isoDuration:Jl,_isoTime:Kl,_jwt:Hl,_ksuid:Ol,_lazy:n0,_length:Er,_literal:Hx,_lowercase:Pi,_lt:pn,_lte:Tt,_mac:gv,_map:Gx,_max:Tt,_maxLength:xr,_maxSize:Xn,_mime:Gi,_min:Ct,_minLength:In,_minSize:gn,_multipleOf:Wn,_nan:Gv,_nanoid:Rl,_nativeEnum:Bx,_negative:Js,_never:Ov,_nonnegative:Xs,_nonoptional:Jx,_nonpositive:Ys,_normalize:ji,_null:zv,_nullable:Wx,_number:bv,_optional:qx,_overwrite:tn,_parse:$i,_parseAsync:Ti,_pipe:Qx,_positive:Ks,_promise:r0,_properties:Ui,_property:Qs,_readonly:e0,_record:Ux,_refine:Hv,_regex:zi,_safeDecode:Fc,_safeDecodeAsync:Gc,_safeEncode:Mc,_safeEncodeAsync:Uc,_safeParse:Ci,_safeParseAsync:Ai,_set:jx,_size:Sr,_slugify:Vi,_startsWith:Mi,_string:pv,_stringFormat:$r,_stringbool:Jv,_success:Yx,_superRefine:Vv,_symbol:Rv,_templateLiteral:t0,_toLowerCase:Bi,_toUpperCase:Hi,_transform:Vx,_trim:Zi,_tuple:Fx,_uint32:Ev,_uint64:Nv,_ulid:Pl,_undefined:Lv,_union:Px,_unknown:Dv,_uppercase:Di,_url:Ws,_uuid:Tl,_uuidv4:Cl,_uuidv6:Al,_uuidv7:Il,_void:Mv,_xid:Dl,_xor:Dx,base64Charset:il,base64urlCharset:Gs,canParseURL:Qc,clone:Be,compile:Sl,compileFn:Vs,config:Qe,createStandardJSONSchemaMethod:di,createToJSONSchemaMethod:Qv,decode:qk,decodeAsync:Kk,describe:Wv,encode:Vk,encodeAsync:Wk,extractDefs:fr,finalize:hr,flattenError:Ls,formatError:zs,getDiscriminatedOption:fl,globalConfig:bt,globalRegistry:Et,handleUnrepresentable:nt,initializeContext:dr,isBackEdge:bl,isRecursiveSchema:vl,isValidBase64:Us,isValidBase64URL:ol,isValidCIDRv6:rl,isValidCreditCard:sl,isValidIBAN:al,isValidIPv6:Fs,isValidJWT:ul,locales:wl,memoizer:Zs,mergeValues:li,meta:Kv,parse:Uu,parseAsync:Gu,parseURLObject:Jg,prettifyError:Lc,process:Me,processSchema:Me,regexes:Ms,registry:Bs,safeDecode:Yk,safeDecodeAsync:Qk,safeEncode:Jk,safeEncodeAsync:Xk,safeParse:jm,safeParseAsync:jk,standardProps:Yc,stripTabAndNewline:ls,toDotPath:Gm,toJSONSchema:ed,toZod:$s,treeifyError:Rc,urlHostnameOk:tl,urlProtocolOk:nl,util:Ac,validate:Ds,validateAsync:Os,validateURL:el,version:Hg,withParser:Hs},Symbol.toStringTag,{value:"Module"})),Vh=Symbol("z.visit/resolving");function td(e,t){const n=typeof t=="function"?t:(s,a)=>{const u=t[s._zod.def.type];return u?u(s,a):s},r=new Map;function i(s){const a=r.get(s);if(a===Vh)return new yl({type:"lazy",getter:()=>r.get(s)});if(a!==void 0)return a;r.set(s,Vh);const u=o(s),c=n(u,u!==s);return r.set(s,c),c}function o(s){const a=s._zod.def;switch(a.type){case"object":{const c=a.shape,l=Object.keys(c);let d=!1;const f={};for(const p of l){const m=i(c[p]);m!==c[p]&&(d=!0),f[p]=m}let h=a.catchall;return a.catchall&&(h=i(a.catchall),h!==a.catchall&&(d=!0)),d?Be(s,{...a,shape:f,catchall:h}):s}case"array":{const c=i(a.element);return c===a.element?s:Be(s,{...a,element:c})}case"tuple":{const c=a.items;let l=!1;const d=[];for(const h of c){const p=i(h);p!==h&&(l=!0),d.push(p)}let f=a.rest;return a.rest&&(f=i(a.rest),f!==a.rest&&(l=!0)),l?Be(s,{...a,items:d,rest:f}):s}case"record":case"map":{const c=i(a.keyType),l=i(a.valueType);return c===a.keyType&&l===a.valueType?s:Be(s,{...a,keyType:c,valueType:l})}case"set":{const c=i(a.valueType);return c===a.valueType?s:Be(s,{...a,valueType:c})}case"union":{const c=a.options;let l=!1;const d=[];for(const f of c){const h=i(f);h!==f&&(l=!0),d.push(h)}return l?Be(s,{...a,options:d}):s}case"intersection":{const c=i(a.left),l=i(a.right);return c===a.left&&l===a.right?s:Be(s,{...a,left:c,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const c=i(a.innerType);return c===a.innerType?s:Be(s,{...a,innerType:c})}case"pipe":{const c=i(a.in),l=i(a.out);return c===a.in&&l===a.out?s:Be(s,{...a,in:c,out:l})}case"function":{const c=i(a.input),l=i(a.output);return c===a.input&&l===a.output?s:Be(s,{...a,input:c,output:l})}case"lazy":{const c=a.getter,{_cachedInner:l,...d}=a;return Be(s,{...d,getter:()=>i(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return i(e)}function nd(e){return!!e._zod}function Bb(e,t){return nd(e)?jm(e,t):e.safeParse(t)}function d0(e){if(!e)return;let t;if(nd(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function f0(e){if(nd(e)){const o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const r=e.value;if(r!==void 0)return r}const h0=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(o,s){return o==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):r[o]??o}return o=>{switch(o.code){case"invalid_type":{const s=i(o.expected),a=zm(o.input),u=i(a,o.input);return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${xc(o.values[0])}`:`Invalid option: expected one of ${Ou(o.values,"|")}`;case"too_big":{const s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{const s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Ou(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(a=>`'${a}'`).join(" | ")}`:o.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function p0(){return{localeError:h0()}}const m0=Object.freeze(Object.defineProperty({__proto__:null,endsWith:Fi,gt:mn,gte:Ct,includes:Oi,length:Er,lowercase:Pi,lt:pn,lte:Tt,maxLength:xr,maxSize:Xn,mime:Gi,minLength:In,minSize:gn,multipleOf:Wn,negative:Js,nonnegative:Xs,nonpositive:Ys,normalize:ji,overwrite:tn,positive:Ks,properties:Ui,property:Qs,regex:zi,size:Sr,slugify:Vi,startsWith:Mi,toLowerCase:Bi,toUpperCase:Hi,trim:Zi,uppercase:Di},Symbol.toStringTag,{value:"Module"})),qh=new WeakSet([Object.prototype,Error.prototype]);function Oo(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}const Hb=(e,t)=>{Um.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);qh.has(n)||(qh.add(n),Oo(n,"format",r=>i=>zs(r,i)),Oo(n,"flatten",r=>i=>Ls(r,i)),Oo(n,"addIssue",r=>i=>{r.issues.push(i),r.message=JSON.stringify(r.issues,ss,2)}),Oo(n,"addIssues",r=>i=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,ss,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Vb=x("ZodError",Hb),St=x("ZodError",Hb,void 0,{Parent:Error}),rd=$i(St),id=Ti(St),od=Ci(St),sd=Ai(St),ad=zc(St),ud=Pc(St),cd=Dc(St),ld=Oc(St),dd=Mc(St),fd=Fc(St),hd=Uc(St),pd=Gc(St);function g0(){bt.localeError||Qe(p0())}function Qn(){bt.memoizer||Qe({memoizer:Zs()})}const _e=x("ZodType",(e,t)=>(g0(),be.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(dt(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Be(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Ga(e,t))},superRefine(e,t){return this.check(ja(e,t))},overwrite(e){return this.check(tn(e))},optional(){return Ge(this)},exactOptional(){return _a(this)},nullable(){return yr(this)},nullish(){return Ge(yr(this))},nonoptional(e){return Ta(this,e)},array(){return de(this)},or(e){return $e([this,e])},and(e){return Mr(this,e)},transform(e){return pi(this,yo(e))},default(e){return xa(this,e)},prefault(e){return $a(this,e)},catch(e){return Ia(this,e)},pipe(e){return pi(this,e)},readonly(){return za(this)},describe(e){const t=this.clone();return Et.add(t,{description:e}),t},meta(...e){if(e.length===0)return Et.get(this);const t=this.clone();return Et.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Ns(this,"~standard",{...Yc(this),jsonSchema:{input:di(this,"input"),output:di(this,"output")}})},set"~standard"(e){fn(this,"~standard",e)},parse:function e(t,n){return rd(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await id(this,t,n,{callee:e})},safeParse(e,t){return od(this,e,t)},async safeParseAsync(e,t){return sd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){fn(this,"spa",e)},validate(e,t){return Ds(this,e,t)},validateAsync(e,t){return Os(this,e,t)},encode:function e(t,n){return ad(this,t,n,{callee:e})},decode:function e(t,n){return ud(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await cd(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await ld(this,t,n,{callee:e})},safeEncode(e,t){return dd(this,e,t)},safeDecode(e,t){return fd(this,e,t)},async safeEncodeAsync(e,t){return hd(this,e,t)},async safeDecodeAsync(e,t){return pd(this,e,t)},toJSONSchema(e){return Qv(this,{})(e)},get description(){return Et.get(this)?.description},get _def(){return this._zod.def}}),qi=x("_ZodString",(e,t)=>{Li.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ob(e,n,r)},Ei({format:e=>tt(e).format??null,minLength:e=>tt(e).minimum??null,maxLength:e=>tt(e).maximum??null},{regex(...e){return this.check(zi(...e))},includes(...e){return this.check(Oi(...e))},startsWith(...e){return this.check(Mi(...e))},endsWith(...e){return this.check(Fi(...e))},min(...e){return this.check(In(...e))},max(...e){return this.check(xr(...e))},length(...e){return this.check(Er(...e))},nonempty(...e){return this.check(In(1,...e))},lowercase(e){return this.check(Pi(e))},uppercase(e){return this.check(Di(e))},trim(){return this.check(Zi())},normalize(...e){return this.check(ji(...e))},toLowerCase(){return this.check(Bi())},toUpperCase(){return this.check(Hi())},slugify(){return this.check(Vi())}})),Tr=x("ZodString",(e,t)=>{Li.init(e,t),qi.init(e,t)},{email(e){return this.check(El(Wi,e))},url(e){return this.check(Ws(Rr,e))},jwt(e){return this.check(Hl(lo,e))},emoji(e){return this.check(Nl(Ji,e))},guid(e){return this.check($l(Ki,e))},uuid(e){return this.check(Tl(Kt,e))},uuidv4(e){return this.check(Cl(Kt,e))},uuidv6(e){return this.check(Al(Kt,e))},uuidv7(e){return this.check(Il(Kt,e))},nanoid(e){return this.check(Rl(Yi,e))},cuid(e){return this.check(Ll(Xi,e))},cuid2(e){return this.check(zl(Qi,e))},ulid(e){return this.check(Pl(eo,e))},base64(e){return this.check(jl(ao,e))},base64url(e){return this.check(Zl(uo,e))},xid(e){return this.check(Dl(to,e))},ksuid(e){return this.check(Ol(no,e))},ipv4(e){return this.check(Ml(ro,e))},ipv6(e){return this.check(Fl(io,e))},cidrv4(e){return this.check(Ul(oo,e))},cidrv6(e){return this.check(Gl(so,e))},e164(e){return this.check(Bl(co,e))},datetime(e){return this.check(ql(Cr,e))},date(e){return this.check(Wl(Ar,e))},time(e){return this.check(Kl(Ir,e))},duration(e){return this.check(Jl(Nr,e))}});function E(e){return pv(Tr,e)}const De=x("ZodStringFormat",(e,t)=>{Ue.init(e,t),qi.init(e,t)}),Cr=x("ZodISODateTime",(e,t)=>{oy.init(e,t),De.init(e,t)}),Ar=x("ZodISODate",(e,t)=>{sy.init(e,t),De.init(e,t)}),Ir=x("ZodISOTime",(e,t)=>{ay.init(e,t),De.init(e,t)}),Nr=x("ZodISODuration",(e,t)=>{uy.init(e,t),De.init(e,t)}),Wi=x("ZodEmail",(e,t)=>{Kg.init(e,t),De.init(e,t)});function md(e){return El(Wi,e)}const Ki=x("ZodGUID",(e,t)=>{qg.init(e,t),De.init(e,t)});function gd(e){return $l(Ki,e)}const Kt=x("ZodUUID",(e,t)=>{Wg.init(e,t),De.init(e,t)});function yd(e){return Tl(Kt,e)}function vd(e){return Cl(Kt,e)}function bd(e){return Al(Kt,e)}function wd(e){return Il(Kt,e)}const Rr=x("ZodURL",(e,t)=>{Yg.init(e,t),De.init(e,t)});function _d(e){return Ws(Rr,e)}function kd(e){return Ws(Rr,{protocol:jc,hostname:lg,...R(e)})}const Ji=x("ZodEmoji",(e,t)=>{Xg.init(e,t),De.init(e,t)});function Sd(e){return Nl(Ji,e)}const Yi=x("ZodNanoID",(e,t)=>{Qg.init(e,t),De.init(e,t)});function xd(e){return Rl(Yi,e)}const Xi=x("ZodCUID",(e,t)=>{ey.init(e,t),De.init(e,t)});function Ed(e){return Ll(Xi,e)}const Qi=x("ZodCUID2",(e,t)=>{ty.init(e,t),De.init(e,t)});function $d(e){return zl(Qi,e)}const eo=x("ZodULID",(e,t)=>{ny.init(e,t),De.init(e,t)});function Td(e){return Pl(eo,e)}const to=x("ZodXID",(e,t)=>{ry.init(e,t),De.init(e,t)});function Cd(e){return Dl(to,e)}const no=x("ZodKSUID",(e,t)=>{iy.init(e,t),De.init(e,t)});function Ad(e){return Ol(no,e)}const ro=x("ZodIPv4",(e,t)=>{cy.init(e,t),De.init(e,t)});function Id(e){return Ml(ro,e)}const ea=x("ZodMAC",(e,t)=>{dy.init(e,t),De.init(e,t)});function Nd(e){return gv(ea,e)}const io=x("ZodIPv6",(e,t)=>{ly.init(e,t),De.init(e,t)});function Rd(e){return Fl(io,e)}const oo=x("ZodCIDRv4",(e,t)=>{fy.init(e,t),De.init(e,t)});function Ld(e){return Ul(oo,e)}const so=x("ZodCIDRv6",(e,t)=>{hy.init(e,t),De.init(e,t)});function zd(e){return Gl(so,e)}const ao=x("ZodBase64",(e,t)=>{py.init(e,t),De.init(e,t)});function Pd(e){return jl(ao,e)}const uo=x("ZodBase64URL",(e,t)=>{my.init(e,t),De.init(e,t)});function Dd(e){return Zl(uo,e)}const co=x("ZodE164",(e,t)=>{gy.init(e,t),De.init(e,t)});function Od(e){return Bl(co,e)}const ta=x("ZodCreditCard",(e,t)=>{yy.init(e,t),De.init(e,t)});function Md(e){return yv(ta,e)}const na=x("ZodIBAN",(e,t)=>{vy.init(e,t),De.init(e,t)});function Fd(e){return vv(na,e)}const lo=x("ZodJWT",(e,t)=>{by.init(e,t),De.init(e,t)});function Ud(e){return Hl(lo,e)}const Rn=x("ZodCustomStringFormat",(e,t)=>{wy.init(e,t),De.init(e,t)});function Gd(e,t,n={}){return $r(Rn,e,t,n)}function jd(e){return $r(Rn,"hostname",cg,e)}function Zd(e){return $r(Rn,"hex",Eg,e)}function Bd(e){return $r(Rn,"currency_code",fg,e)}function Hd(e,t){const n=t?.enc??"hex",r=`${e}_${n}`,i=Ms[r];if(!i)throw new Error(`Unrecognized hash format: ${r}`);return $r(Rn,r,i,t)}const Lr=x("ZodNumber",(e,t)=>{cl.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sb(e,n,r,i),e.isFinite=!0},Ei({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=tt(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=tt(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=tt(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>tt(e).format??null},{gt(e,t){return this.check(mn(e,t))},gte(e,t){return this.check(Ct(e,t))},min(e,t){return this.check(Ct(e,t))},lt(e,t){return this.check(pn(e,t))},lte(e,t){return this.check(Tt(e,t))},max(e,t){return this.check(Tt(e,t))},int(e){return this.check(hi(e))},safe(e){return this.check(hi(e))},positive(e){return this.check(mn(0,e))},nonnegative(e){return this.check(Ct(0,e))},negative(e){return this.check(pn(0,e))},nonpositive(e){return this.check(Tt(0,e))},multipleOf(e,t){return this.check(Wn(e,t))},step(e,t){return this.check(Wn(e,t))},finite(){return this}}));function we(e){return bv(Lr,e)}const Ln=x("ZodNumberFormat",(e,t)=>{_y.init(e,t),Lr.init(e,t)});function hi(e){return _v(Ln,e)}function Vd(e){return kv(Ln,e)}function qd(e){return Sv(Ln,e)}function Wd(e){return xv(Ln,e)}function Kd(e){return Ev(Ln,e)}const zr=x("ZodBoolean",(e,t)=>{ll.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ab(e,n,r)});function Pe(e){return $v(zr,e)}const Pr=x("ZodBigInt",(e,t)=>{dl.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ub(e,n,r,i)},Ei({minValue:e=>tt(e).minimum??null,maxValue:e=>tt(e).maximum??null,format:e=>tt(e).format??null},{gte(e,t){return this.check(Ct(e,t))},min(e,t){return this.check(Ct(e,t))},gt(e,t){return this.check(mn(e,t))},lt(e,t){return this.check(pn(e,t))},lte(e,t){return this.check(Tt(e,t))},max(e,t){return this.check(Tt(e,t))},positive(e){return this.check(mn(BigInt(0),e))},negative(e){return this.check(pn(BigInt(0),e))},nonpositive(e){return this.check(Tt(BigInt(0),e))},nonnegative(e){return this.check(Ct(BigInt(0),e))},multipleOf(e,t){return this.check(Wn(e,t))}}));function Jd(e){return Cv(Pr,e)}const fo=x("ZodBigIntFormat",(e,t)=>{ky.init(e,t),Pr.init(e,t)});function Yd(e){return Iv(fo,e)}function Xd(e){return Nv(fo,e)}const ra=x("ZodSymbol",(e,t)=>{Sy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>cb(e,n,r,i)});function Qd(e){return Rv(ra,e)}const ia=x("ZodUndefined",(e,t)=>{xy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>db(e,n,r,i)});function gr(e){return Lv(ia,e)}const oa=x("ZodNull",(e,t)=>{Ey.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lb(e,n,r)});function ho(e){return zv(oa,e)}const sa=x("ZodAny",(e,t)=>{$y.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pb()});function po(){return Pv(sa)}const aa=x("ZodUnknown",(e,t)=>{Ty.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mb()});function Re(){return Dv(aa)}const ua=x("ZodNever",(e,t)=>{Cy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hb(e,n,r)});function Kn(e){return Ov(ua,e)}const ca=x("ZodVoid",(e,t)=>{Ay.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fb(e,n,r,i)});function ef(e){return Mv(ca,e)}const mo=x("ZodDate",(e,t)=>{Iy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gb(e,n,r,i),e.min=(n,r)=>e.check(Ct(n,r)),e.max=(n,r)=>e.check(Tt(n,r))},Ei({minDate:e=>{const{minimum:t}=tt(e);return t?new Date(t):null},maxDate:e=>{const{maximum:t}=tt(e);return t?new Date(t):null}},{}));function tf(e){return Fv(mo,e)}const la=x("ZodArray",(e,t)=>{Qn(),Ny.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Cb(e,n,r,i),e.element=t.element},{min(e,t){return this.check(In(e,t))},nonempty(e){return this.check(In(1,e))},max(e,t){return this.check(xr(e,t))},length(e,t){return this.check(Er(e,t))},unwrap(){return this.element}});function de(e,t){return jv(la,e,t)}function nf(e){const t=e._zod.def.shape;return at(Object.keys(t))}const Dr=x("ZodObject",(e,t)=>{Qn(),Py.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ab(e,n,r,i),Mm(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return at(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(dt(this._zod.def,{catchall:Re()}))},loose(){return this.clone(dt(this._zod.def,{catchall:Re()}))},strict(){return this.clone(dt(this._zod.def,{catchall:Kn()}))},strip(){return this.clone(dt(this._zod.def,{catchall:void 0}))},extend(e){return Cm(this,e)},safeExtend(e){return Im(this,e)},merge(e){return Nm(this,e)},pick(e){return $m(this,e)},omit(e){return Tm(this,e)},partial(...e){return Mu(Fr,this,e[0])},exactPartial(...e){return Mu(vo,this,e[0],"exactPartial")},required(...e){return Rm(bo,this,e[0])}});function C(e,t){const n={type:"object",shape:e??{},...R(t)};return new Dr(n)}function rf(e,t){return new Dr({type:"object",shape:e,catchall:Kn(),...R(t)})}function st(e,t){return new Dr({type:"object",shape:e,catchall:Re(),...R(t)})}const Or=x("ZodUnion",(e,t)=>{js.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yl(e,n,r,i),e.options=t.options});function $e(e,t){return new Or({type:"union",options:e,...R(t)})}const da=x("ZodXor",(e,t)=>{Or.init(e,t),Dy.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Yl(e,n,r,i),e.options=t.options});function of(e,t){return new da({type:"union",options:e,inclusive:!1,...R(t)})}const fa=x("ZodDiscriminatedUnion",(e,t)=>{Or.init(e,t),My.init(e,t)});function go(e,t,n){return new fa({type:"union",options:t,discriminator:e,...R(n)})}const ha=x("ZodIntersection",(e,t)=>{Fy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ib(e,n,r,i)});function Mr(e,t){return new ha({type:"intersection",left:e,right:t})}const pa=x("ZodTuple",(e,t)=>{Qn(),hl.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nb(e,n,r,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){const e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Fr({type:"optional",innerType:t}))})}});function ma(e,t,n){const r=t instanceof be,i=r?n:t,o=r?t:null;return new pa({type:"tuple",items:e,rest:o,...R(i)})}const Jn=x("ZodRecord",(e,t)=>{Qn(),Uy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rb(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Ce(e,t,n){return!t||!t._zod?new Jn({type:"record",keyType:E(),valueType:e,...R(t)}):new Jn({type:"record",keyType:e,valueType:t,...R(n)})}function sf(e,t,n){return new Jn({type:"record",keyType:e,valueType:t,...R(n),partial:!0})}function af(e,t,n){return new Jn({type:"record",keyType:e,valueType:t,mode:"loose",...R(n)})}const ga=x("ZodMap",(e,t)=>{Qn(),Gy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$b(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(gn(...n)),e.nonempty=n=>e.check(gn(1,n)),e.max=(...n)=>e.check(Xn(...n)),e.size=(...n)=>e.check(Sr(...n))});function uf(e,t,n){return new ga({type:"map",keyType:e,valueType:t,...R(n)})}const ya=x("ZodSet",(e,t)=>{Qn(),jy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Tb(e,n,r,i),e.min=(...n)=>e.check(gn(...n)),e.nonempty=n=>e.check(gn(1,n)),e.max=(...n)=>e.check(Xn(...n)),e.size=(...n)=>e.check(Sr(...n))});function cf(e,t){return new ya({type:"set",valueType:e,...R(t)})}const Yn=x("ZodEnum",(e,t)=>{Zy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(r,i,o)=>yb(e,r,i),e.enum=t.entries,e.options=[...e._zod.values];const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const o={};for(const s of r)if(n.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Yn({...t,checks:[],...R(i),entries:o})},e.exclude=(r,i)=>{const o={...t.entries};for(const s of r)if(n.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Yn({...t,checks:[],...R(i),entries:o})}});function at(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Yn({type:"enum",entries:n,...R(t)})}function lf(e,t){return new Yn({type:"enum",entries:e,...R(t)})}const va=x("ZodLiteral",(e,t)=>{By.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vb(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function $(e,t){return new va({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}const ba=x("ZodFile",(e,t)=>{Hy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_b(e,n,r),e.min=(n,r)=>e.check(gn(n,r)),e.max=(n,r)=>e.check(Xn(n,r)),e.mime=(n,r)=>e.check(Gi(Array.isArray(n)?n:[n],r))});function df(e){return Zv(ba,e)}const wa=x("ZodTransform",(e,t)=>{Qn(),Vy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Eb(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Rs(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(cr(o,n.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=n.value),s.inst??(s.inst=e),n.issues.push(cr(s))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function yo(e){return new wa({type:"transform",transform:e})}const Fr=x("ZodOptional",(e,t)=>{pl.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ql(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ge(e){return new Fr({type:"optional",innerType:e})}const vo=x("ZodExactOptional",(e,t)=>{qy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ql(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function _a(e){return new vo({type:"optional",innerType:e})}const ka=x("ZodNullable",(e,t)=>{Wy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new ka({type:"nullable",innerType:e})}function ff(e){return Ge(yr(e))}const Sa=x("ZodDefault",(e,t)=>{Ky.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Db(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function xa(e,t){return new Sa({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Si(t)}})}const Ea=x("ZodPrefault",(e,t)=>{Jy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ob(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function $a(e,t){return new Ea({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Si(t)}})}const bo=x("ZodNonOptional",(e,t)=>{Yy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ta(e,t){return new bo({type:"nonoptional",innerType:e,...R(t)})}const Ca=x("ZodSuccess",(e,t)=>{Xy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kb(e,n,r),e.unwrap=()=>e._zod.def.innerType});function hf(e){return new Ca({type:"success",innerType:e})}const Aa=x("ZodCatch",(e,t)=>{Qy.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ia(e,t){return new Aa({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Cc(t)})}const Na=x("ZodNaN",(e,t)=>{ev.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bb(e,n,r,i)});function pf(e){return Gv(Na,e)}const Ur=x("ZodPipe",(e,t)=>{ml.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fb(e,n,r,i),e.in=t.in,e.out=t.out});function pi(e,t){return new Ur({type:"pipe",in:e,out:t})}const Gr=x("ZodCodec",(e,t)=>{Ur.init(e,t),gl.init(e,t)});function mf(e,t,n){return new Gr({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}function gf(e){const t=e._zod.def;return new Gr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}const Ra=x("ZodPreprocess",(e,t)=>{Ur.init(e,t),tv.init(e,t)}),La=x("ZodReadonly",(e,t)=>{nv.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ub(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function za(e){return new La({type:"readonly",innerType:e})}const Pa=x("ZodTemplateLiteral",(e,t)=>{rv.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wb(e,n,r)});function yf(e,t){return new Pa({type:"template_literal",parts:e,...R(t)})}const Da=x("ZodLazy",(e,t)=>{yl.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jb(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Oa(e){return new Da({type:"lazy",getter:e})}const Ma=x("ZodPromise",(e,t)=>{ov.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function vf(e){return new Ma({type:"promise",innerType:e})}const Fa=x("ZodFunction",(e,t)=>{iv.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xb(e,n,r,i)});function vr(e){return new Fa({type:"function",input:Array.isArray(e?.input)?ma(e?.input):e?.input??de(Re()),output:e?.output??Re()})}const jr=x("ZodCustom",(e,t)=>{sv.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sb(e,n,r,i)});function bf(e){const t=new He({check:"custom"});return t._zod.check=e,t}function Ua(e,t){return Bv(jr,e??(()=>!0),t)}function Ga(e,t={}){return Hv(jr,e,t)}function ja(e,t){return Vv(e,t)}const wf=Wv,_f=Kv,Za=x("ZodInstanceOf",(e,t)=>{jr.init(e,t)},{properties(e,t){return this.check(Ui(e,t))}});function kf(e,t={}){const n=new Za({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...R(t)});return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}const Sf=(...e)=>Jv({Codec:Gr,Boolean:zr,String:Tr},...e);function xf(e){const t=Oa(()=>$e([E(e),we(),Pe(),ho(),de(t),Ce(E(),t)]));return t}function wo(e,t){return new Ra({type:"pipe",in:yo(e),out:t})}const y0=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:sa,ZodArray:la,ZodBase64:ao,ZodBase64URL:uo,ZodBigInt:Pr,ZodBigIntFormat:fo,ZodBoolean:zr,ZodCIDRv4:oo,ZodCIDRv6:so,ZodCUID:Xi,ZodCUID2:Qi,ZodCatch:Aa,ZodCodec:Gr,ZodCreditCard:ta,ZodCustom:jr,ZodCustomStringFormat:Rn,ZodDate:mo,ZodDefault:Sa,ZodDiscriminatedUnion:fa,ZodE164:co,ZodEmail:Wi,ZodEmoji:Ji,ZodEnum:Yn,ZodExactOptional:vo,ZodFile:ba,ZodFunction:Fa,ZodGUID:Ki,ZodIBAN:na,ZodIPv4:ro,ZodIPv6:io,ZodISODate:Ar,ZodISODateTime:Cr,ZodISODuration:Nr,ZodISOTime:Ir,ZodInstanceOf:Za,ZodIntersection:ha,ZodJWT:lo,ZodKSUID:no,ZodLazy:Da,ZodLiteral:va,ZodMAC:ea,ZodMap:ga,ZodNaN:Na,ZodNanoID:Yi,ZodNever:ua,ZodNonOptional:bo,ZodNull:oa,ZodNullable:ka,ZodNumber:Lr,ZodNumberFormat:Ln,ZodObject:Dr,ZodOptional:Fr,ZodPipe:Ur,ZodPrefault:Ea,ZodPreprocess:Ra,ZodPromise:Ma,ZodReadonly:La,ZodRecord:Jn,ZodSet:ya,ZodString:Tr,ZodStringFormat:De,ZodSuccess:Ca,ZodSymbol:ra,ZodTemplateLiteral:Pa,ZodTransform:wa,ZodTuple:pa,ZodType:_e,ZodULID:eo,ZodURL:Rr,ZodUUID:Kt,ZodUndefined:ia,ZodUnion:Or,ZodUnknown:aa,ZodVoid:ca,ZodXID:to,ZodXor:da,_ZodString:qi,_default:xa,_function:vr,any:po,array:de,base64:Pd,base64url:Dd,bigint:Jd,boolean:Pe,catch:Ia,check:bf,cidrv4:Ld,cidrv6:zd,codec:mf,creditCard:Md,cuid:Ed,cuid2:$d,currencyCode:Bd,custom:Ua,date:tf,describe:wf,discriminatedUnion:go,e164:Od,email:md,emoji:Sd,enum:at,exactOptional:_a,file:df,float32:Vd,float64:qd,function:vr,guid:gd,hash:Hd,hex:Zd,hostname:jd,httpUrl:kd,iban:Fd,instanceof:kf,int:hi,int32:Wd,int64:Yd,intersection:Mr,invertCodec:gf,ipv4:Id,ipv6:Rd,json:xf,jwt:Ud,keyof:nf,ksuid:Ad,lazy:Oa,literal:$,looseObject:st,looseRecord:af,mac:Nd,map:uf,meta:_f,nan:pf,nanoid:xd,nativeEnum:lf,never:Kn,nonoptional:Ta,null:ho,nullable:yr,nullish:ff,number:we,object:C,optional:Ge,partialRecord:sf,pipe:pi,prefault:$a,preprocess:wo,promise:vf,readonly:za,record:Ce,refine:Ga,set:cf,strictObject:rf,string:E,stringFormat:Gd,stringbool:Sf,success:hf,superRefine:ja,symbol:Qd,templateLiteral:yf,transform:yo,tuple:ma,uint32:Kd,uint64:Xd,ulid:Td,undefined:gr,union:$e,unknown:Re,url:_d,uuid:yd,uuidv4:vd,uuidv6:bd,uuidv7:wd,void:ef,xid:Cd,xor:of},Symbol.toStringTag,{value:"Module"})),qb={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function Wb(e){Qe({customError:e})}function Kb(){return Qe().customError}var fs;fs||(fs={});function Jb(e){return ql(Cr,e)}function v0(e){return Wl(Ar,e)}function b0(e){return Kl(Ir,e)}function w0(e){return Jl(Nr,e)}const Ef=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:Ar,ZodISODateTime:Cr,ZodISODuration:Nr,ZodISOTime:Ir,date:v0,datetime:Jb,duration:w0,time:b0},Symbol.toStringTag,{value:"Module"})),q={...y0,...m0,iso:Ef},_0=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function k0(e,t){const n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function Wh(e,t){return e.map((n,r)=>r<t?n:n.optional())}function S0(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function x0(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;const r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){const i=n[1]===void 0?void 0:S0(n[1]);if(!i||!t.defs[i])throw new Error(`Reference not found: ${e}`);return t.defs[i]}throw new Error(`Reference not found: ${e}`)}function E0(e,t){return q.transform(r=>r).check(r=>{const i=r.value;if(typeof i!="object"||i===null||Array.isArray(i))return;const o=Object.getOwnPropertyNames(i);if(t.minProperties!==void 0&&o.length<t.minProperties&&r.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:i,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&r.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:i,inst:e,continue:!0}),t.keySchema)for(const s of o){const a=t.keySchema.safeParse(s);a.success||r.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function Yu(e,t){if(e===null)return"z";const n=typeof e;if(n!=="object"){if(n==="number"&&Number.isNaN(e))return null;const r=String(e);return`${n[0]}${r.length}:${r}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){const o=[];for(const s of e){const a=Yu(s,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}const r=Object.keys(e).sort(),i=[];for(const o of r){const s=Yu(e[o],t);if(s===null)return null;i.push(`${o.length}:${o}=${s}`)}return`o${i.length}:{${i.join(",")}}`}finally{t.delete(e)}}const $0=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),T0=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ai(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(ai):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,n])=>$0.has(t)?ai(n):!T0.has(t)||typeof n!="object"||n===null?!1:Object.values(n).some(ai))}function Kh(e){return e===1?"element":"elements"}function C0(e,t){return q.transform(r=>r).check(r=>{const i=r.value;if(Array.isArray(i)){if(t.uniqueItems===!0){const o=new Map;for(let s=0;s<i.length;s++){const a=Yu(i[s],new Set);if(a===null)continue;const u=o.get(a);if(u===void 0){o.set(a,s);continue}r.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${u}`,input:i,path:[s],continue:!0})}}if(t.containsSchema){const o=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY;let a=0;for(const u of i)if(t.containsSchema.safeParse(u).success&&++a>=s)break;a<o&&r.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${Kh(o)}; found ${a}`,input:i,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&r.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${Kh(t.maxContains)}`,input:i,continue:!0})}}}).pipe(e)}function Jh(e,t){if(e!==!1)return e===void 0||e===!0?q.any():vt(e,t)}const A0=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Yb(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return q.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){const i=e.$ref;if(t.refs.has(i))return t.refs.get(i);if(t.processing.has(i))return q.lazy(()=>{if(!t.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return t.refs.get(i)});t.processing.add(i);const o=x0(i,t),s=vt(o,t);return t.refs.set(i,s),t.processing.delete(i),s}if(e.enum!==void 0){const i=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&i.length===1&&i[0]===null)return q.null();if(i.length===0)return q.never();if(i.length===1)return q.literal(i[0]);if(i.every(s=>typeof s=="string"))return q.enum(i);const o=i.map(s=>q.literal(s));return o.length<2?o[0]:q.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return q.literal(e.const);const n=e.type;if(Array.isArray(n)){const i=n.map(o=>{const s={...e,type:o};return Yb(s,t)});return i.length===0?q.never():i.length===1?i[0]:q.union(i)}if(!n)return q.any();let r;switch(n){case"string":{let i=q.string();if(e.format){const o=e.format;o==="email"?i=i.check(q.email()):o==="uri"||o==="uri-reference"?i=i.check(q.url()):o==="uuid"||o==="guid"?i=i.check(q.uuid()):o==="date-time"?i=i.check(q.iso.datetime({offset:!0})):o==="date"?i=i.check(q.iso.date()):o==="time"?i=i.check(q.regex(A0)):o==="duration"?i=i.check(q.iso.duration()):o==="hostname"?i=i.check(q.hostname()):o==="ipv4"?i=i.check(q.ipv4()):o==="ipv6"?i=i.check(q.ipv6()):o==="mac"?i=i.check(q.mac()):o==="cidr"?i=i.check(q.cidrv4()):o==="cidr-v6"?i=i.check(q.cidrv6()):o==="base64"?i=i.check(q.base64()):o==="base64url"?i=i.check(q.base64url()):o==="e164"?i=i.check(q.e164()):o==="credit_card"?i=i.check(q.creditCard()):o==="iban"?i=i.check(q.iban()):o==="jwt"?i=i.check(q.jwt()):o==="emoji"?i=i.check(q.emoji()):o==="nanoid"?i=i.check(q.nanoid()):o==="cuid"?i=i.check(q.cuid()):o==="cuid2"?i=i.check(q.cuid2()):o==="ulid"?i=i.check(q.ulid()):o==="xid"?i=i.check(q.xid()):o==="ksuid"&&(i=i.check(q.ksuid()))}typeof e.minLength=="number"&&(i=i.min(e.minLength)),typeof e.maxLength=="number"&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),r=i;break}case"number":case"integer":{let i=n==="integer"?q.number().int():q.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(i=i.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(i=i.max(e.maximum)),typeof e.exclusiveMinimum=="number"?i=i.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(i=i.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?i=i.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(i=i.lt(e.maximum)),typeof e.multipleOf=="number"&&(i=i.multipleOf(e.multipleOf)),r=i;break}case"boolean":{r=q.boolean();break}case"null":{r=q.null();break}case"object":{const i={},o=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?vt(e.additionalProperties,t):void 0;for(const[d,f]of Object.entries(o)){const h=vt(f,t);It(i,d,s.has(d)?h:h.optional())}if(e.patternProperties){const d=e.patternProperties,f=Object.keys(d),h=[];for(const m of f){const y=vt(d[m],t),w=q.string().regex(new RegExp(m));h.push(q.looseRecord(w,y))}const p=[];if(Object.keys(i).length>0&&p.push(q.object(i).passthrough()),p.push(...h),p.length===0)r=q.object({}).passthrough();else if(p.length===1)r=p[0];else{let m=q.intersection(p[0],p[1]);for(let y=2;y<p.length;y++)m=q.intersection(m,p[y]);r=m}if(e.additionalProperties===!1){const m=Object.keys(i),y=f.map(g=>new RegExp(g)),w=r;r=r.check(g=>{if(!ln(g.value))return;const b=[];for(const v of Object.keys(g.value))m.includes(v)||y.some(k=>k.test(v))||b.push(v);b.length&&g.issues.push({code:"unrecognized_keys",keys:b,input:g.value,inst:w})})}}else{const d=q.object(i);e.additionalProperties===!1?r=d.strict():a?r=d.catchall(a):r=d.passthrough()}const u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||l!==void 0){let d;if(u){const f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=vt(f,t)}r=E0(r,{keySchema:d,minProperties:c,maxProperties:l})}break}case"array":{const i=e.prefixItems,o=e.items;if(i&&Array.isArray(i)){const s=typeof e.minItems=="number"?e.minItems:0,a=i.map(d=>vt(d,t)),u=Wh(a,s),c=Array.isArray(o)?void 0:Jh(o,t),l=q.tuple(u);r=c?l.rest(c):l,typeof e.minItems=="number"&&(r=r.check(q.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(q.maxLength(e.maxItems)))}else if(Array.isArray(o)){const s=typeof e.minItems=="number"?e.minItems:0,a=o.map(d=>vt(d,t)),u=Wh(a,s),c=Jh(e.additionalItems,t),l=q.tuple(u);r=c?l.rest(c):l,typeof e.minItems=="number"&&(r=r.check(q.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(q.maxLength(e.maxItems)))}else if(o!==void 0){const s=vt(o,t);let a=q.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),r=a}else r=q.array(q.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=C0(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?vt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${n}`)}return r}function vt(e,t){if(typeof e=="boolean")return e?q.any():q.never();let n=Yb(e,t);const r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const a=e.anyOf.map(c=>vt(c,t)),u=q.union(a);n=r?q.intersection(n,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>vt(c,t)),u=q.xor(a);n=r?q.intersection(n,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:q.any();else{let a=r?n:vt(e.allOf[0],t);const u=r?0:1;for(let c=u;c<e.allOf.length;c++)a=q.intersection(a,vt(e.allOf[c],t));n=a}e.nullable===!0&&t.version==="openapi-3.0"&&(n=q.nullable(n)),e.readOnly===!0&&(n=q.readonly(n)),e.default!==void 0&&(n=n.default(e.default));const i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of o)a in e&&(i[a]=e[a]);const s=["contentEncoding","contentMediaType","contentSchema"];for(const a of s)a in e&&(i[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!ai(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(const a of["minProperties","maxProperties"])e[a]!==void 0&&(i[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!ai(e.contains)&&(i.contains=e.contains);for(const a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(i[a]=e[a])}for(const a of Object.keys(e))_0.has(a)||It(i,a,e[a]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function Xb(e,t){if(typeof e=="boolean")return e?q.any():q.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const r=k0(n,t?.defaultTarget),i=n.$defs||n.definitions||{},o={version:r,defs:i,refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??Et};return vt(n,o)}function Qb(e){return td(e,{object:t=>t.partial(),union:t=>{const n=t._zod.def;return n.discriminator===void 0?t:$e(n.options)}})}function I0(e,t){if(!t?.length)return e;const n=e._zod.def;return Be(e,dt(n,{checks:[...n.checks??[],...t]}),{parent:!0})}function ew(e){return I0(e.out,e.checks)}function N0(e){return e.in._zod.traits.has("$ZodTransform")?ew(e):e.in}function tw(e){return td(e,{pipe:t=>N0(t._zod.def),default:(t,n)=>n?Ge(t._zod.def.innerType):t,catch:(t,n)=>n?t._zod.def.innerType:t})}function nw(e){return td(e,{pipe:t=>ew(t._zod.def),prefault:(t,n)=>n?t._zod.def.innerType:t})}function R0(e){return mv(Tr,e)}function L0(e){return wv(Lr,e)}function z0(e){return Tv(zr,e)}function P0(e){return Av(Pr,e)}function D0(e){return Uv(mo,e)}const rw=Object.freeze(Object.defineProperty({__proto__:null,bigint:P0,boolean:z0,date:D0,number:L0,string:R0},Symbol.toStringTag,{value:"Module"})),Yh=Object.freeze(Object.defineProperty({__proto__:null,$brand:Nc,$input:kl,$output:_l,INVALID:wt,NEVER:Ic,TimePrecision:Vl,ZodAny:sa,ZodArray:la,ZodBase64:ao,ZodBase64URL:uo,ZodBigInt:Pr,ZodBigIntFormat:fo,ZodBoolean:zr,ZodCIDRv4:oo,ZodCIDRv6:so,ZodCUID:Xi,ZodCUID2:Qi,ZodCatch:Aa,ZodCodec:Gr,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ie,ZodCreditCard:ta,ZodCustom:jr,ZodCustomStringFormat:Rn,ZodDate:mo,ZodDefault:Sa,ZodDiscriminatedUnion:fa,ZodE164:co,ZodEmail:Wi,ZodEmoji:Ji,ZodEnum:Yn,ZodError:Vb,ZodExactOptional:vo,ZodFile:ba,get ZodFirstPartyTypeKind(){return fs},ZodFunction:Fa,ZodGUID:Ki,ZodIBAN:na,ZodIPv4:ro,ZodIPv6:io,ZodISODate:Ar,ZodISODateTime:Cr,ZodISODuration:Nr,ZodISOTime:Ir,ZodInstanceOf:Za,ZodIntersection:ha,ZodIssueCode:qb,ZodJWT:lo,ZodKSUID:no,ZodLazy:Da,ZodLiteral:va,ZodMAC:ea,ZodMap:ga,ZodNaN:Na,ZodNanoID:Yi,ZodNever:ua,ZodNonOptional:bo,ZodNull:oa,ZodNullable:ka,ZodNumber:Lr,ZodNumberFormat:Ln,ZodObject:Dr,ZodOptional:Fr,ZodPipe:Ur,ZodPrefault:Ea,ZodPreprocess:Ra,ZodPromise:Ma,ZodReadonly:La,ZodRealError:St,ZodRecord:Jn,ZodSet:ya,ZodString:Tr,ZodStringFormat:De,ZodSuccess:Ca,ZodSymbol:ra,ZodTemplateLiteral:Pa,ZodTransform:wa,ZodTuple:pa,ZodType:_e,ZodULID:eo,ZodURL:Rr,ZodUUID:Kt,ZodUndefined:ia,ZodUnion:Or,ZodUnknown:aa,ZodVoid:ca,ZodXID:to,ZodXor:da,_ZodString:qi,_default:xa,_function:vr,any:po,array:de,base64:Pd,base64url:Dd,bigint:Jd,boolean:Pe,catch:Ia,check:bf,cidrv4:Ld,cidrv6:zd,clone:Be,codec:mf,coerce:rw,compile:Sl,config:Qe,core:Zb,creditCard:Md,cuid:Ed,cuid2:$d,currencyCode:Bd,custom:Ua,date:tf,decode:ud,decodeAsync:ld,deepPartial:Qb,describe:wf,discriminatedUnion:go,e164:Od,email:md,emoji:Sd,encode:ad,encodeAsync:cd,endsWith:Fi,enum:at,exactOptional:_a,file:df,flattenError:Ls,float32:Vd,float64:qd,formatError:zs,fromJSONSchema:Xb,function:vr,getDiscriminatedOption:fl,getErrorMap:Kb,globalRegistry:Et,gt:mn,gte:Ct,guid:gd,hash:Hd,hex:Zd,hostname:jd,httpUrl:kd,iban:Fd,includes:Oi,input:tw,instanceof:kf,int:hi,int32:Wd,int64:Yd,intersection:Mr,invertCodec:gf,ipv4:Id,ipv6:Rd,iso:Ef,json:xf,jwt:Ud,keyof:nf,ksuid:Ad,lazy:Oa,length:Er,literal:$,locales:wl,looseObject:st,looseRecord:af,lowercase:Pi,lt:pn,lte:Tt,mac:Nd,map:uf,maxLength:xr,maxSize:Xn,memoizer:Zs,meta:_f,mime:Gi,minLength:In,minSize:gn,multipleOf:Wn,nan:pf,nanoid:xd,nativeEnum:lf,negative:Js,never:Kn,nonnegative:Xs,nonoptional:Ta,nonpositive:Ys,normalize:ji,null:ho,nullable:yr,nullish:ff,number:we,object:C,optional:Ge,output:nw,overwrite:tn,parse:rd,parseAsync:id,partialRecord:sf,pipe:pi,positive:Ks,prefault:$a,preprocess:wo,prettifyError:Lc,promise:vf,properties:Ui,property:Qs,readonly:za,record:Ce,refine:Ga,regex:zi,regexes:Ms,registry:Bs,safeDecode:fd,safeDecodeAsync:pd,safeEncode:dd,safeEncodeAsync:hd,safeParse:od,safeParseAsync:sd,set:cf,setErrorMap:Wb,size:Sr,slugify:Vi,startsWith:Mi,strictObject:rf,string:E,stringFormat:Gd,stringbool:Sf,success:hf,superRefine:ja,symbol:Qd,templateLiteral:yf,toJSONSchema:ed,toLowerCase:Bi,toUpperCase:Hi,toZod:$s,transform:yo,treeifyError:Rc,trim:Zi,tuple:ma,uint32:Kd,uint64:Xd,ulid:Td,undefined:gr,union:$e,unknown:Re,uppercase:Di,url:_d,util:Ac,uuid:yd,uuidv4:vd,uuidv6:bd,uuidv7:wd,validate:Ds,validateAsync:Os,void:ef,withParser:Hs,xid:Cd,xor:of},Symbol.toStringTag,{value:"Module"})),O0=Object.freeze(Object.defineProperty({__proto__:null,$brand:Nc,$input:kl,$output:_l,INVALID:wt,NEVER:Ic,TimePrecision:Vl,ZodAny:sa,ZodArray:la,ZodBase64:ao,ZodBase64URL:uo,ZodBigInt:Pr,ZodBigIntFormat:fo,ZodBoolean:zr,ZodCIDRv4:oo,ZodCIDRv6:so,ZodCUID:Xi,ZodCUID2:Qi,ZodCatch:Aa,ZodCodec:Gr,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ie,ZodCreditCard:ta,ZodCustom:jr,ZodCustomStringFormat:Rn,ZodDate:mo,ZodDefault:Sa,ZodDiscriminatedUnion:fa,ZodE164:co,ZodEmail:Wi,ZodEmoji:Ji,ZodEnum:Yn,ZodError:Vb,ZodExactOptional:vo,ZodFile:ba,get ZodFirstPartyTypeKind(){return fs},ZodFunction:Fa,ZodGUID:Ki,ZodIBAN:na,ZodIPv4:ro,ZodIPv6:io,ZodISODate:Ar,ZodISODateTime:Cr,ZodISODuration:Nr,ZodISOTime:Ir,ZodInstanceOf:Za,ZodIntersection:ha,ZodIssueCode:qb,ZodJWT:lo,ZodKSUID:no,ZodLazy:Da,ZodLiteral:va,ZodMAC:ea,ZodMap:ga,ZodNaN:Na,ZodNanoID:Yi,ZodNever:ua,ZodNonOptional:bo,ZodNull:oa,ZodNullable:ka,ZodNumber:Lr,ZodNumberFormat:Ln,ZodObject:Dr,ZodOptional:Fr,ZodPipe:Ur,ZodPrefault:Ea,ZodPreprocess:Ra,ZodPromise:Ma,ZodReadonly:La,ZodRealError:St,ZodRecord:Jn,ZodSet:ya,ZodString:Tr,ZodStringFormat:De,ZodSuccess:Ca,ZodSymbol:ra,ZodTemplateLiteral:Pa,ZodTransform:wa,ZodTuple:pa,ZodType:_e,ZodULID:eo,ZodURL:Rr,ZodUUID:Kt,ZodUndefined:ia,ZodUnion:Or,ZodUnknown:aa,ZodVoid:ca,ZodXID:to,ZodXor:da,_ZodString:qi,_default:xa,_function:vr,any:po,array:de,base64:Pd,base64url:Dd,bigint:Jd,boolean:Pe,catch:Ia,check:bf,cidrv4:Ld,cidrv6:zd,clone:Be,codec:mf,coerce:rw,compile:Sl,config:Qe,core:Zb,creditCard:Md,cuid:Ed,cuid2:$d,currencyCode:Bd,custom:Ua,date:tf,decode:ud,decodeAsync:ld,deepPartial:Qb,default:Yh,describe:wf,discriminatedUnion:go,e164:Od,email:md,emoji:Sd,encode:ad,encodeAsync:cd,endsWith:Fi,enum:at,exactOptional:_a,file:df,flattenError:Ls,float32:Vd,float64:qd,formatError:zs,fromJSONSchema:Xb,function:vr,getDiscriminatedOption:fl,getErrorMap:Kb,globalRegistry:Et,gt:mn,gte:Ct,guid:gd,hash:Hd,hex:Zd,hostname:jd,httpUrl:kd,iban:Fd,includes:Oi,input:tw,instanceof:kf,int:hi,int32:Wd,int64:Yd,intersection:Mr,invertCodec:gf,ipv4:Id,ipv6:Rd,iso:Ef,json:xf,jwt:Ud,keyof:nf,ksuid:Ad,lazy:Oa,length:Er,literal:$,locales:wl,looseObject:st,looseRecord:af,lowercase:Pi,lt:pn,lte:Tt,mac:Nd,map:uf,maxLength:xr,maxSize:Xn,memoizer:Zs,meta:_f,mime:Gi,minLength:In,minSize:gn,multipleOf:Wn,nan:pf,nanoid:xd,nativeEnum:lf,negative:Js,never:Kn,nonnegative:Xs,nonoptional:Ta,nonpositive:Ys,normalize:ji,null:ho,nullable:yr,nullish:ff,number:we,object:C,optional:Ge,output:nw,overwrite:tn,parse:rd,parseAsync:id,partialRecord:sf,pipe:pi,positive:Ks,prefault:$a,preprocess:wo,prettifyError:Lc,promise:vf,properties:Ui,property:Qs,readonly:za,record:Ce,refine:Ga,regex:zi,regexes:Ms,registry:Bs,safeDecode:fd,safeDecodeAsync:pd,safeEncode:dd,safeEncodeAsync:hd,safeParse:od,safeParseAsync:sd,set:cf,setErrorMap:Wb,size:Sr,slugify:Vi,startsWith:Mi,strictObject:rf,string:E,stringFormat:Gd,stringbool:Sf,success:hf,superRefine:ja,symbol:Qd,templateLiteral:yf,toJSONSchema:ed,toLowerCase:Bi,toUpperCase:Hi,toZod:$s,transform:yo,treeifyError:Rc,trim:Zi,tuple:ma,uint32:Kd,uint64:Xd,ulid:Td,undefined:gr,union:$e,unknown:Re,uppercase:Di,url:_d,util:Ac,uuid:yd,uuidv4:vd,uuidv6:bd,uuidv7:wd,validate:Ds,validateAsync:Os,void:ef,withParser:Hs,xid:Cd,xor:of,z:Yh},Symbol.toStringTag,{value:"Module"})),jn="io.modelcontextprotocol/related-task",Ba="2.0",Xe=Ua(e=>e!==null&&(typeof e=="object"||typeof e=="function")),iw=$e([E(),we().int()]),ow=E();st({ttl:we().optional(),pollInterval:we().optional()});const M0=C({ttl:we().optional()}),F0=C({taskId:E()}),$f=st({progressToken:iw.optional(),[jn]:F0.optional()}),Rt=C({_meta:$f.optional()}),_o=Rt.extend({task:M0.optional()}),U0=e=>_o.safeParse(e).success,ut=C({method:E(),params:Rt.loose().optional()}),Ft=C({_meta:$f.optional()}),Ut=C({method:E(),params:Ft.loose().optional()}),ct=st({_meta:$f.optional()}),ko=$e([E(),we().int()]),sw=C({jsonrpc:$(Ba),id:ko,...ut.shape}).strict(),Xh=e=>sw.safeParse(e).success,aw=C({jsonrpc:$(Ba),...Ut.shape}).strict(),G0=e=>aw.safeParse(e).success,Tf=C({jsonrpc:$(Ba),id:ko,result:ct}).strict(),Mo=e=>Tf.safeParse(e).success;var Ne;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ne||(Ne={}));const Cf=C({jsonrpc:$(Ba),id:ko.optional(),error:C({code:we().int(),message:E(),data:Re().optional()})}).strict(),j0=e=>Cf.safeParse(e).success,Z0=$e([sw,aw,Tf,Cf]);$e([Tf,Cf]);const Af=ct.strict(),B0=Ft.extend({requestId:ko.optional(),reason:E().optional()}),If=Ut.extend({method:$("notifications/cancelled"),params:B0}),H0=C({src:E(),mimeType:E().optional(),sizes:de(E()).optional(),theme:at(["light","dark"]).optional()}),So=C({icons:de(H0).optional()}),br=C({name:E(),title:E().optional()}),Ha=br.extend({...br.shape,...So.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),V0=Mr(C({applyDefaults:Pe().optional()}),Ce(E(),Re())),q0=wo(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Mr(C({form:V0.optional(),url:Xe.optional()}),Ce(E(),Re()).optional())),W0=st({list:Xe.optional(),cancel:Xe.optional(),requests:st({sampling:st({createMessage:Xe.optional()}).optional(),elicitation:st({create:Xe.optional()}).optional()}).optional()}),K0=st({list:Xe.optional(),cancel:Xe.optional(),requests:st({tools:st({call:Xe.optional()}).optional()}).optional()}),J0=C({experimental:Ce(E(),Xe).optional(),sampling:C({context:Xe.optional(),tools:Xe.optional()}).optional(),elicitation:q0.optional(),roots:C({listChanged:Pe().optional()}).optional(),tasks:W0.optional(),extensions:Ce(E(),Xe).optional()}),Y0=Rt.extend({protocolVersion:E(),capabilities:J0,clientInfo:Ha}),X0=ut.extend({method:$("initialize"),params:Y0}),Q0=C({experimental:Ce(E(),Xe).optional(),logging:Xe.optional(),completions:Xe.optional(),prompts:C({listChanged:Pe().optional()}).optional(),resources:C({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:C({listChanged:Pe().optional()}).optional(),tasks:K0.optional(),extensions:Ce(E(),Xe).optional()}),eE=ct.extend({protocolVersion:E(),capabilities:Q0,serverInfo:Ha,instructions:E().optional()}),tE=Ut.extend({method:$("notifications/initialized"),params:Ft.optional()}),Va=ut.extend({method:$("ping"),params:Rt.optional()}),nE=C({progress:we(),total:Ge(we()),message:Ge(E())}),rE=C({...Ft.shape,...nE.shape,progressToken:iw}),Nf=Ut.extend({method:$("notifications/progress"),params:rE}),iE=Rt.extend({cursor:ow.optional()}),xo=ut.extend({params:iE.optional()}),Eo=ct.extend({nextCursor:ow.optional()}),oE=at(["working","input_required","completed","failed","cancelled"]),$o=C({taskId:E(),status:oE,ttl:$e([we(),ho()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:Ge(we()),statusMessage:Ge(E())}),Rf=ct.extend({task:$o}),sE=Ft.merge($o),hs=Ut.extend({method:$("notifications/tasks/status"),params:sE}),Lf=ut.extend({method:$("tasks/get"),params:Rt.extend({taskId:E()})}),zf=ct.merge($o),Pf=ut.extend({method:$("tasks/result"),params:Rt.extend({taskId:E()})});ct.loose();const Df=xo.extend({method:$("tasks/list")}),Of=Eo.extend({tasks:de($o)}),Mf=ut.extend({method:$("tasks/cancel"),params:Rt.extend({taskId:E()})}),aE=ct.merge($o),uw=C({uri:E(),mimeType:Ge(E()),_meta:Ce(E(),Re()).optional()}),cw=uw.extend({text:E()}),Ff=E().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),lw=uw.extend({blob:Ff}),To=at(["user","assistant"]),Zr=C({audience:de(To).optional(),priority:we().min(0).max(1).optional(),lastModified:Jb({offset:!0}).optional()}),dw=C({...br.shape,...So.shape,uri:E(),description:Ge(E()),mimeType:Ge(E()),size:Ge(we()),annotations:Zr.optional(),_meta:Ge(st({}))}),uE=C({...br.shape,...So.shape,uriTemplate:E(),description:Ge(E()),mimeType:Ge(E()),annotations:Zr.optional(),_meta:Ge(st({}))}),cE=xo.extend({method:$("resources/list")}),fw=Eo.extend({resources:de(dw)}),lE=xo.extend({method:$("resources/templates/list")}),dE=Eo.extend({resourceTemplates:de(uE)}),Uf=Rt.extend({uri:E()}),fE=Uf,hE=ut.extend({method:$("resources/read"),params:fE}),hw=ct.extend({contents:de($e([cw,lw]))}),pE=Ut.extend({method:$("notifications/resources/list_changed"),params:Ft.optional()}),mE=Uf,gE=ut.extend({method:$("resources/subscribe"),params:mE}),yE=Uf,vE=ut.extend({method:$("resources/unsubscribe"),params:yE}),bE=Ft.extend({uri:E()}),wE=Ut.extend({method:$("notifications/resources/updated"),params:bE}),_E=C({name:E(),description:Ge(E()),required:Ge(Pe())}),kE=C({...br.shape,...So.shape,description:Ge(E()),arguments:Ge(de(_E)),_meta:Ge(st({}))}),SE=xo.extend({method:$("prompts/list")}),xE=Eo.extend({prompts:de(kE)}),EE=Rt.extend({name:E(),arguments:Ce(E(),E()).optional()}),$E=ut.extend({method:$("prompts/get"),params:EE}),Gf=C({type:$("text"),text:E(),annotations:Zr.optional(),_meta:Ce(E(),Re()).optional()}),jf=C({type:$("image"),data:Ff,mimeType:E(),annotations:Zr.optional(),_meta:Ce(E(),Re()).optional()}),Zf=C({type:$("audio"),data:Ff,mimeType:E(),annotations:Zr.optional(),_meta:Ce(E(),Re()).optional()}),TE=C({type:$("tool_use"),name:E(),id:E(),input:Ce(E(),Re()),_meta:Ce(E(),Re()).optional()}),pw=C({type:$("resource"),resource:$e([cw,lw]),annotations:Zr.optional(),_meta:Ce(E(),Re()).optional()}),mw=dw.extend({type:$("resource_link")}),Co=$e([Gf,jf,Zf,mw,pw]),CE=C({role:To,content:Co}),AE=ct.extend({description:E().optional(),messages:de(CE)}),IE=Ut.extend({method:$("notifications/prompts/list_changed"),params:Ft.optional()}),NE=C({title:E().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),RE=C({taskSupport:at(["required","optional","forbidden"]).optional()}),Bf=C({...br.shape,...So.shape,description:E().optional(),inputSchema:C({type:$("object"),properties:Ce(E(),Xe).optional(),required:de(E()).optional()}).catchall(Re()),outputSchema:C({type:$("object"),properties:Ce(E(),Xe).optional(),required:de(E()).optional()}).catchall(Re()).optional(),annotations:NE.optional(),execution:RE.optional(),_meta:Ce(E(),Re()).optional()}),gw=xo.extend({method:$("tools/list")}),LE=Eo.extend({tools:de(Bf)}),qa=ct.extend({content:de(Co).default([]),structuredContent:Ce(E(),Re()).optional(),isError:Pe().optional()});qa.or(ct.extend({toolResult:Re()}));const zE=_o.extend({name:E(),arguments:Ce(E(),Re()).optional()}),yw=ut.extend({method:$("tools/call"),params:zE}),PE=Ut.extend({method:$("notifications/tools/list_changed"),params:Ft.optional()});C({autoRefresh:Pe().default(!0),debounceMs:we().int().nonnegative().default(300)});const vw=at(["debug","info","notice","warning","error","critical","alert","emergency"]),DE=Rt.extend({level:vw}),OE=ut.extend({method:$("logging/setLevel"),params:DE}),ME=Ft.extend({level:vw,logger:E().optional(),data:Re()}),FE=Ut.extend({method:$("notifications/message"),params:ME}),UE=C({name:E().optional()}),GE=C({hints:de(UE).optional(),costPriority:we().min(0).max(1).optional(),speedPriority:we().min(0).max(1).optional(),intelligencePriority:we().min(0).max(1).optional()}),jE=C({mode:at(["auto","required","none"]).optional()}),ZE=C({type:$("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:de(Co).default([]),structuredContent:C({}).loose().optional(),isError:Pe().optional(),_meta:Ce(E(),Re()).optional()}),BE=go("type",[Gf,jf,Zf]),ps=go("type",[Gf,jf,Zf,TE,ZE]),HE=C({role:To,content:$e([ps,de(ps)]),_meta:Ce(E(),Re()).optional()}),VE=_o.extend({messages:de(HE),modelPreferences:GE.optional(),systemPrompt:E().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:we().optional(),maxTokens:we().int(),stopSequences:de(E()).optional(),metadata:Xe.optional(),tools:de(Bf).optional(),toolChoice:jE.optional()}),qE=ut.extend({method:$("sampling/createMessage"),params:VE}),bw=ct.extend({model:E(),stopReason:Ge(at(["endTurn","stopSequence","maxTokens"]).or(E())),role:To,content:BE}),ww=ct.extend({model:E(),stopReason:Ge(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:To,content:$e([ps,de(ps)])}),WE=C({type:$("boolean"),title:E().optional(),description:E().optional(),default:Pe().optional()}),KE=C({type:$("string"),title:E().optional(),description:E().optional(),minLength:we().optional(),maxLength:we().optional(),format:at(["email","uri","date","date-time"]).optional(),default:E().optional()}),JE=C({type:at(["number","integer"]),title:E().optional(),description:E().optional(),minimum:we().optional(),maximum:we().optional(),default:we().optional()}),YE=C({type:$("string"),title:E().optional(),description:E().optional(),enum:de(E()),default:E().optional()}),XE=C({type:$("string"),title:E().optional(),description:E().optional(),oneOf:de(C({const:E(),title:E()})),default:E().optional()}),QE=C({type:$("string"),title:E().optional(),description:E().optional(),enum:de(E()),enumNames:de(E()).optional(),default:E().optional()}),e$=$e([YE,XE]),t$=C({type:$("array"),title:E().optional(),description:E().optional(),minItems:we().optional(),maxItems:we().optional(),items:C({type:$("string"),enum:de(E())}),default:de(E()).optional()}),n$=C({type:$("array"),title:E().optional(),description:E().optional(),minItems:we().optional(),maxItems:we().optional(),items:C({anyOf:de(C({const:E(),title:E()}))}),default:de(E()).optional()}),r$=$e([t$,n$]),i$=$e([QE,e$,r$]),o$=$e([i$,WE,KE,JE]),s$=_o.extend({mode:$("form").optional(),message:E(),requestedSchema:C({type:$("object"),properties:Ce(E(),o$),required:de(E()).optional()})}),a$=_o.extend({mode:$("url"),message:E(),elicitationId:E(),url:E().url()}),u$=$e([s$,a$]),c$=ut.extend({method:$("elicitation/create"),params:u$}),l$=Ft.extend({elicitationId:E()}),d$=Ut.extend({method:$("notifications/elicitation/complete"),params:l$}),f$=ct.extend({action:at(["accept","decline","cancel"]),content:wo(e=>e===null?void 0:e,Ce(E(),$e([E(),we(),Pe(),de(E())])).optional())}),h$=C({type:$("ref/resource"),uri:E()}),p$=C({type:$("ref/prompt"),name:E()}),m$=Rt.extend({ref:$e([p$,h$]),argument:C({name:E(),value:E()}),context:C({arguments:Ce(E(),E()).optional()}).optional()}),g$=ut.extend({method:$("completion/complete"),params:m$}),y$=ct.extend({completion:st({values:de(E()).max(100),total:Ge(we().int()),hasMore:Ge(Pe())})}),v$=C({uri:E().startsWith("file://"),name:E().optional(),_meta:Ce(E(),Re()).optional()}),b$=ut.extend({method:$("roots/list"),params:Rt.optional()}),w$=ct.extend({roots:de(v$)}),_$=Ut.extend({method:$("notifications/roots/list_changed"),params:Ft.optional()});$e([Va,X0,g$,OE,$E,SE,cE,lE,hE,gE,vE,yw,gw,Lf,Pf,Df,Mf]);$e([If,Nf,tE,_$,hs]);$e([Af,bw,ww,f$,w$,zf,Of,Rf]);$e([Va,qE,c$,b$,Lf,Pf,Df,Mf]);$e([If,Nf,FE,wE,pE,PE,IE,hs,d$]);$e([Af,eE,y$,AE,xE,fw,dE,hw,qa,LE,zf,Of,Rf]);class Ae extends Error{constructor(t,n,r){super(`MCP error ${t}: ${n}`),this.code=t,this.data=r,this.name="McpError"}static fromError(t,n,r){if(t===Ne.UrlElicitationRequired&&r){const i=r;if(i.elicitations)return new k$(i.elicitations,n)}return new Ae(t,n,r)}}class k$ extends Ae{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(Ne.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}function Mn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qh(e){const n=d0(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const r=f0(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function ep(e,t){const n=Bb(e,t);if(!n.success)throw n.error;return n.data}const S$=6e4;class x${constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(If,n=>{this._oncancel(n)}),this.setNotificationHandler(Nf,n=>{this._onprogress(n)}),this.setRequestHandler(Va,n=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Lf,async(n,r)=>{const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new Ae(Ne.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Pf,async(n,r)=>{const i=async()=>{const o=n.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ae(Ne.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){const u=a.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),a.type==="response")l(u);else{const d=u,f=new Ae(d.error.code,d.error.message,d.error.data);l(f)}else{const d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new Ae(Ne.InvalidParams,`Task not found: ${o}`);if(!Mn(s.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await i();if(Mn(s.status)){const a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...a,_meta:{...a._meta,[jn]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Df,async(n,r)=>{try{const{tasks:i,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new Ae(Ne.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Mf,async(n,r)=>{try{const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new Ae(Ne.InvalidParams,`Task not found: ${n.params.taskId}`);if(Mn(i.status))throw new Ae(Ne.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId,r.sessionId);const o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Ae(Ne.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof Ae?i:new Ae(Ne.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,n,r,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){const n=this._timeoutInfo.get(t);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),Ae.fromError(Ne.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){const n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),Mo(o)||j0(o)?this._onresponse(o):Xh(o)?this._onrequest(o,s):G0(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const n=Ae.fromError(Ne.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of t.values())r(n)}_onerror(t){this.onerror?.(t)}_onnotification(t){const n=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(t,n){const r=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[jn]?.taskId,s=i?.sessionId,a=this._taskStore;let u=!0,c;if(o&&a&&this._taskMessageQueue&&s!==void 0&&(u=!1,c=(async()=>{if(!await a.getTask(o,s))throw new Ae(Ne.InvalidParams,`Task not found: ${o}`);u=!0})()),r===void 0){const p={jsonrpc:"2.0",id:t.id,error:{code:Ne.MethodNotFound,message:"Method not found"}};if(o&&c){const m={type:"error",message:p,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,m,s),()=>i?.send(p)).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):i?.send(p).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(t.id,l);const d=U0(t.params)?t.params.task:void 0,f=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,h={signal:l.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async p=>{if(l.signal.aborted)return;const m={relatedRequestId:t.id};o&&(m.relatedTask={taskId:o}),await this.notification(p,m)},sendRequest:async(p,m,y)=>{if(l.signal.aborted)throw new Ae(Ne.ConnectionClosed,"Request was cancelled");const w={...y,relatedRequestId:t.id};o&&!w.relatedTask&&(w.relatedTask={taskId:o});const g=w.relatedTask?.taskId??o;return g&&f&&await f.updateTaskStatus(g,"input_required"),await this.request(p,m,w)},authInfo:n?.authInfo,requestId:t.id,requestInfo:n?.requestInfo,taskId:o,taskStore:f,taskRequestedTtl:d?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Ae(Ne.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(t.method)}).then(()=>r(t,h)).then(async p=>{if(l.signal.aborted)return;const m={result:p,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:m,timestamp:Date.now()},i?.sessionId):await i?.send(m)},async p=>{if(l.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(p.code)?p.code:Ne.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue&&u?await this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},i?.sessionId):await i?.send(m)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===l&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:n,...r}=t.params,i=Number(n),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(u){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(u);return}o(r)}_onresponse(t){const n=Number(t.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Mo(t))r(t);else{const s=new Ae(t.error.code,t.error.message,t.error.data);r(s)}return}const i=this._responseHandlers.get(n);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Mo(t)&&t.result&&typeof t.result=="object"){const s=t.result;if(s.task&&typeof s.task=="object"){const a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,n))}}if(o||this._progressHandlers.delete(n),Mo(t))i(t);else{const s=Ae.fromError(t.error.code,t.error.message,t.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,n,r){const{task:i}=r??{};if(!i){try{yield{type:"result",result:await this.request(t,n,r)}}catch(s){yield{type:"error",error:s instanceof Ae?s:new Ae(Ne.InternalError,String(s))}}return}let o;try{const s=await this.request(t,Rf,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Ae(Ne.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Mn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new Ae(Ne.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Ae(Ne.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}const u=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Ae?s:new Ae(Ne.InternalError,String(s))}}}request(t,n,r){const{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:u}=r??{};return new Promise((c,l)=>{const d=g=>{l(g)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(g){d(g);return}r?.signal?.throwIfAborted();const f=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(h.params={...h.params,task:a}),u&&(h.params={...h.params,_meta:{...h.params?._meta||{},[jn]:u}});const p=g=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(g)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));const b=g instanceof Ae?g:new Ae(Ne.RequestTimeout,String(g));l(b)};this._responseHandlers.set(f,g=>{if(!r?.signal?.aborted){if(g instanceof Error)return l(g);try{const b=Bb(n,g.result);b.success?c(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const m=r?.timeout??S$,y=()=>p(Ae.fromError(Ne.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);const w=u?.taskId;if(w){const g=b=>{const v=this._responseHandlers.get(f);v?v(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,g),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),l(b)})}else this._transport.send(h,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(g=>{this._cleanupTimeout(f),l(g)})})}async getTask(t,n){return this.request({method:"tasks/get",params:t},zf,n)}async getTaskResult(t,n,r){return this.request({method:"tasks/result",params:t},n,r)}async listTasks(t,n){return this.request({method:"tasks/list",params:t},Of,n)}async cancelTask(t,n){return this.request({method:"tasks/cancel",params:t},aE,n)}async notification(t,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const r=n?.relatedTask?.taskId;if(r){const a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[jn]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[jn]:n.relatedTask}}}),this._transport?.send(a,n).catch(u=>this._onerror(u))});return}let s={...t,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[jn]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(t,n){const r=Qh(t);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(i,o)=>{const s=ep(t,i);return Promise.resolve(n(s,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){const r=Qh(t);this._notificationHandlers.set(r,i=>{const o=ep(t,i);return Promise.resolve(n(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const n=this._taskProgressTokens.get(t);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,n,r??this._transport?.sessionId,i)}async _clearTaskQueue(t,n){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(t,n);for(const i of r)if(i.type==="request"&&Xh(i.message)){const o=i.message.id,s=this._requestResolvers.get(o);s?(s(new Ae(Ne.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,n,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t,r);o?.pollInterval&&(i=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Ae(Ne.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,i);n.addEventListener("abort",()=>{clearTimeout(a),s(new Ae(Ne.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,n){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await r.createTask(i,t.id,{method:t.method,params:t.params},n)},getTask:async i=>{const o=await r.getTask(i,n);if(!o)throw new Ae(Ne.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await r.storeTaskResult(i,o,s,n);const a=await r.getTask(i,n);if(a){const u=hs.parse({method:"notifications/tasks/status",params:a});await this.notification(u),Mn(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>r.getTaskResult(i,n),updateTaskStatus:async(i,o,s)=>{const a=await r.getTask(i,n);if(!a)throw new Ae(Ne.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Mn(a.status))throw new Ae(Ne.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(i,o,s,n);const u=await r.getTask(i,n);if(u){const c=hs.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Mn(u.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>r.listTasks(i,n)}}}function tp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function E$(e,t){const n={...e};for(const r in t){const i=r,o=t[i];if(o===void 0)continue;const s=n[i];tp(s)&&tp(o)?n[i]={...s,...o}:n[i]=o}return n}(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});class $$ extends x${_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(t,n){}_ensureEventSlot(t){let n=this._eventSlots.get(t);if(!n){let r=this.eventSchemas[t];if(!r)throw Error(`Unknown event: ${String(t)}`);n={listeners:[]},this._eventSlots.set(t,n);let i=r.shape.method.value;this._registeredMethods.add(i);let o=n;super.setNotificationHandler(r,s=>{let a=s.params;this.onEventDispatch(t,a),o.onHandler?.(a);for(let u of[...o.listeners])u(a)})}return n}setEventHandler(t,n){let r=this._ensureEventSlot(t);r.onHandler&&n&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", …) to add multiple listeners without replacing.`),r.onHandler=n}getEventHandler(t){return this._eventSlots.get(t)?.onHandler}addEventListener(t,n){this._ensureEventSlot(t).listeners.push(n)}removeEventListener(t,n){let r=this._eventSlots.get(t);if(!r)return;let i=r.listeners.indexOf(n);i!==-1&&r.listeners.splice(i,1)}setRequestHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setRequestHandler"),super.setRequestHandler(t,n)};setNotificationHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setNotificationHandler"),super.setNotificationHandler(t,n)};warnIfRequestHandlerReplaced(t,n,r){n&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(t,n)=>{let r=t.shape.method.value;this._registeredMethods.add(r),super.setRequestHandler(t,n)};_assertMethodNotRegistered(t,n){let r=t.shape.method.value;if(this._registeredMethods.has(r))throw Error(`Handler for "${r}" already registered (via ${n}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(r)}}var T$="2026-01-26",C$="ui/notifications/tool-input-partial";class _w{eventTarget;eventSource;messageListener;constructor(t=window.parent,n){this.eventTarget=t,this.eventSource=n,this.messageListener=r=>{if(n&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let i=Z0.safeParse(r.data);i.success?(console.debug("Parsed message",i.data),this.onmessage?.(i.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",i.error.message,r):(console.error("Failed to parse message",i.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+i.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,n){t.method!==C$&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var A$=$e([$("light"),$("dark")]).describe("Color theme preference for the host environment."),mi=$e([$("inline"),$("fullscreen"),$("pip")]).describe("Display mode for UI presentation."),I$=$e([$("--color-background-primary"),$("--color-background-secondary"),$("--color-background-tertiary"),$("--color-background-inverse"),$("--color-background-ghost"),$("--color-background-info"),$("--color-background-danger"),$("--color-background-success"),$("--color-background-warning"),$("--color-background-disabled"),$("--color-text-primary"),$("--color-text-secondary"),$("--color-text-tertiary"),$("--color-text-inverse"),$("--color-text-ghost"),$("--color-text-info"),$("--color-text-danger"),$("--color-text-success"),$("--color-text-warning"),$("--color-text-disabled"),$("--color-border-primary"),$("--color-border-secondary"),$("--color-border-tertiary"),$("--color-border-inverse"),$("--color-border-ghost"),$("--color-border-info"),$("--color-border-danger"),$("--color-border-success"),$("--color-border-warning"),$("--color-border-disabled"),$("--color-ring-primary"),$("--color-ring-secondary"),$("--color-ring-inverse"),$("--color-ring-info"),$("--color-ring-danger"),$("--color-ring-success"),$("--color-ring-warning"),$("--font-sans"),$("--font-mono"),$("--font-weight-normal"),$("--font-weight-medium"),$("--font-weight-semibold"),$("--font-weight-bold"),$("--font-text-xs-size"),$("--font-text-sm-size"),$("--font-text-md-size"),$("--font-text-lg-size"),$("--font-heading-xs-size"),$("--font-heading-sm-size"),$("--font-heading-md-size"),$("--font-heading-lg-size"),$("--font-heading-xl-size"),$("--font-heading-2xl-size"),$("--font-heading-3xl-size"),$("--font-text-xs-line-height"),$("--font-text-sm-line-height"),$("--font-text-md-line-height"),$("--font-text-lg-line-height"),$("--font-heading-xs-line-height"),$("--font-heading-sm-line-height"),$("--font-heading-md-line-height"),$("--font-heading-lg-line-height"),$("--font-heading-xl-line-height"),$("--font-heading-2xl-line-height"),$("--font-heading-3xl-line-height"),$("--border-radius-xs"),$("--border-radius-sm"),$("--border-radius-md"),$("--border-radius-lg"),$("--border-radius-xl"),$("--border-radius-full"),$("--border-width-regular"),$("--shadow-hairline"),$("--shadow-sm"),$("--shadow-md"),$("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),N$=Ce(I$.describe(`Style variables for theming MCP apps.
70
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){o(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}a.count>1&&e.reused==="ref"&&o(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Qv(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const n=[];for(const r of t){if(!r||typeof r!="object")return;Qv(r);const i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;const o=r.type;for(const s of Array.isArray(o)?o:[o]){if(typeof s!="string")return;n.includes(s)||n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const eb=new Set(["type","properties","required","additionalProperties"]),jh=["oneOf","anyOf"];function Zh(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Wu(e){const t=[];for(const o of e){if(typeof o!="object"||o.type!=="object")return null;for(const s in o)if(!eb.has(s))return null;t.push(o)}const n={},r=new Set;for(const o of t){for(const s in o.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;const a=[];for(const c of t){const l=c.properties?.[s]??Zh(c);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}const u=a.length===1?a[0]:Wu(a)??{allOf:a};At(n,s,u)}for(const s of o.required??[])r.add(s)}const i={type:"object",properties:n};if(r.size&&(i.required=[...r]),t.every(o=>o.additionalProperties===!1))i.additionalProperties=!1;else{const o=[];for(const s of t){const a=Zh(s);a&&!o.some(u=>JSON.stringify(u)===JSON.stringify(a))&&o.push(a)}o.length===1?i.additionalProperties=o[0]:o.length>1&&(i.additionalProperties={allOf:o})}return i}function ax(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const i of eb)if(i in e)return;const n=t.filter(i=>jh.some(o=>Array.isArray(i[o])));let r=null;if(!n.length)r=Wu(t);else{const i=n[0],o=jh.find(u=>Array.isArray(i[u]));if(Object.keys(i).length!==1)return;const s=t.filter(u=>u!==i),a=i[o].map(u=>Wu([...s,u]));if(a.some(u=>!u))return;r={[o]:a}}r&&(delete e.allOf,ui(e,r))}function pr(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=a=>{const u=e.seen.get(a);if(u.ref===null)return;const c=u.def??u.schema,l={...c},d=u.ref;if(u.ref=null,d){r(d);const h=e.seen.get(d),p=h.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):ui(c,p),ui(c,l),a._zod.parent===d)for(const y in c)y==="$ref"||y==="allOf"||y in l||delete c[y];if(p.$ref&&h.def)for(const y in c)y==="$ref"||y==="allOf"||y in h.def&&JSON.stringify(c[y])===JSON.stringify(h.def[y])&&delete c[y]}const f=a._zod.parent;if(f&&f!==d){r(f);const h=e.seen.get(f);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const p in c)p==="$ref"||p==="allOf"||p in h.def&&JSON.stringify(c[p])===JSON.stringify(h.def[p])&&delete c[p]}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())Qv(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const u of e.seen.values())for(const c of[u.schema,u.def]){const l=c?.allOf;if(!Array.isArray(l))continue;const d=a.get(l);d?d.push(c):a.set(l,[c])}for(const u of e.intersections)for(const c of a.get(u)??[])ax(c)}}const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}ui(i,n.defId?n.schema:n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&i.id===o&&delete i.id;const s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,At(s,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:hi(t,"input",e.processors),output:hi(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function gt(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return gt(r.element,n);if(r.type==="set")return gt(r.valueType,n);if(r.type==="lazy")return gt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return gt(r.innerType,n);if(r.type==="intersection")return gt(r.left,n)||gt(r.right,n);if(r.type==="record"||r.type==="map")return gt(r.keyType,n)||gt(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:gt(r.in,n)||gt(r.out,n);if(r.type==="object"){for(const i in r.shape)if(gt(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(gt(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(gt(i,n))return!0;return!!(r.rest&&gt(r.rest,n))}return!1}const tb=(e,t={})=>n=>{const r=fr({...n,processors:t});return Me(e,r),hr(r,e),pr(r,e)},hi=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=fr({...i??{},target:o,io:t,processors:n});return Me(e,s),hr(s,e),pr(s,e)},mr=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},gr=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Bh=(e,t)=>{mr(e,"minimum",t),gr(e,"maximum",t)},nb=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},rb=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ib=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},ob=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Vh=(e,t)=>mr(e,"minimum",t.minimum),Hh=(e,t)=>gr(e,"maximum",t.maximum),qh=e=>(t,n)=>{ob(t,n.format);const[r,i]=e[n.format];mr(t,"minimum",r),gr(t,"maximum",i)},ux={greater_than:(e,t)=>mr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>gr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>nb(e,t.value),number_format:qh($c),bigint_format:qh(Tc),min_length:Vh,max_length:Hh,length_equals:(e,t)=>Bh(e,t.length),min_size:Vh,max_size:Hh,size_equals:(e,t)=>Bh(e,t.size),string_format:(e,t)=>{ob(e,t.format),t.pattern&&rb(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>ib(e,t.mime)};function tt(e){const t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(const o of r)ux[o._zod.def.check]?.(t,o._zod.def);const i=e._zod.bag;i.minimum!==void 0&&mr(t,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&mr(t,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&gr(t,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&gr(t,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&nb(t,i.multipleOf),i.format!==void 0&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&ib(t,i.mime);for(const o of i.patterns??[])rb(t,o);return t}const cx={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lx=new Map([[ol,cg],[Zs,lg]]),sb=e=>lx.get(e)??e,ab=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:o,maximum:s,format:a,patterns:u,contentEncoding:c,laxFormat:l}=tt(e);if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=cx[a]??a,i.format===""&&delete i.format,(a==="time"||l)&&delete i.format),c&&(i.contentEncoding=c),u&&u.size>0){const d=[...u].map(sb);d.length===1?i.pattern=d[0].source:d.length>1&&(i.allOf=[...d.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},ub=(e,t,n,r)=>{const i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:l}=tt(e);i.type=l?"integer":"number";const d=typeof c=="number"&&c>=(o??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(d?h?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:typeof o=="number"&&(i.minimum=o),f?h?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof s=="number"&&(i.maximum=s),a){const p=new Set;for(const _ of a)Number.isFinite(_)&&_!==0?p.add(Math.abs(_)):nt(e,t,i,r,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);const[m,...y]=p;m!==void 0&&(i.multipleOf=m),y.length&&(i.allOf=[...i.allOf??[],...y.map(_=>({multipleOf:_}))])}},cb=(e,t,n,r)=>{n.type="boolean"},lb=(e,t,n,r)=>{nt(e,t,n,r,"BigInt cannot be represented in JSON Schema")},db=(e,t,n,r)=>{nt(e,t,n,r,"Symbols cannot be represented in JSON Schema")},fb=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},hb=(e,t,n,r)=>{nt(e,t,n,r,"Undefined cannot be represented in JSON Schema")},pb=(e,t,n,r)=>{nt(e,t,n,r,"Void cannot be represented in JSON Schema")},mb=(e,t,n,r)=>{n.not={}},gb=(e,t,n,r)=>{},yb=(e,t,n,r)=>{},vb=(e,t,n,r)=>{nt(e,t,n,r,"Date cannot be represented in JSON Schema")},bb=(e,t,n,r)=>{const i=e._zod.def,o=as(i.entries);if(o.length===0){n.not={};return}o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),n.enum=o},wb=(e,t,n,r)=>{const i=e._zod.def;if(i.values.length===0){n.not={};return}const o=[];for(const s of i.values)if(s===void 0){if(nt(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(nt(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){const s=o[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),o.every(s=>typeof s=="boolean")&&(n.type="boolean"),o.every(s=>s===null)&&(n.type="null"),n.enum=o},_b=(e,t,n,r)=>{nt(e,t,n,r,"NaN cannot be represented in JSON Schema")},kb=(e,t,n,r)=>{const i=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},Sb=(e,t,n,r)=>{const i=n;i.type="string",i.format="binary",i.contentEncoding="binary";const{minimum:o,maximum:s,mime:a}=tt(e);o!==void 0&&(i.minLength=o),s!==void 0&&(i.maxLength=s),a&&(a.length===0?i.not={}:a.length===1?i.contentMediaType=a[0]:i.anyOf=a.map(u=>({contentMediaType:u})))},xb=(e,t,n,r)=>{n.type="boolean"},Eb=(e,t,n,r)=>{nt(e,t,n,r,"Custom types cannot be represented in JSON Schema")},$b=(e,t,n,r)=>{nt(e,t,n,r,"Function types cannot be represented in JSON Schema")},Tb=(e,t,n,r)=>{nt(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Cb=(e,t,n,r)=>{nt(e,t,n,r,"Map cannot be represented in JSON Schema")},Ab=(e,t,n,r)=>{nt(e,t,n,r,"Set cannot be represented in JSON Schema")},Ib=(e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=tt(e);typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=Me(o.element,t,{...r,path:[...r.path,"items"]})};function pi(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?pi(t.out):t.type==="catch"?pi(t.innerType):e._zod.optin}const Nb=(e,t,n,r)=>{const i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&nt(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const c in s)At(i.properties,c,Me(s[c],t,{...r,path:[...r.path,"properties",c]}));const u=[];for(const c of Object.keys(s)){const l=o.shape[c];(t.io==="input"?pi(l)===void 0:l._zod.optout===void 0)&&u.push(c)}u.length>0&&(i.required=u),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Me(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Xl=(e,t,n,r)=>{const i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,u)=>Me(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",u]}));o?n.oneOf=s:n.anyOf=s},Rb=(e,t,n,r)=>{const i=e._zod.def,o=Me(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Me(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=u,t.intersections.push(u)},Lb=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((m,y)=>Me(m,t,{...r,path:[...r.path,s,y]})),c=o.rest?Me(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;let l=o.items.length;for(;l>0;){const m=o.items[l-1];if(!(t.io==="input"?pi(m)!==void 0:m._zod.optout==="optional"))break;l--}const d=o.items.length,f=!o.rest;t.target==="draft-2020-12"?(i.prefixItems=u,f?i.items=!1:c&&(i.items=c),l>0&&(i.minItems=l),f&&(i.maxItems=d)):t.target==="openapi-3.0"?(i.items={anyOf:u},c&&i.items.anyOf.push(c),l>0&&(i.minItems=l),f&&(i.maxItems=d)):(i.items=u,f?i.additionalItems=!1:c&&(i.additionalItems=c),l>0&&(i.minItems=l),f&&(i.maxItems=d));const{minimum:h,maximum:p}=tt(e);typeof h=="number"&&(i.minItems=h),typeof p=="number"&&(i.maxItems=p)};function Ku(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const p=e.get(t)?.def;if(!p)return t;const m=Ku(e,p,n);return m===p?t:m}for(const p of["anyOf","oneOf"]){const m=t[p];if(!Array.isArray(m))continue;const y=m.map(_=>Ku(e,_,n));y.some((_,g)=>_!==m[g])&&(t={...t,[p]:y})}const r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some(p=>p==="number"||p==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some(p=>typeof p=="number"))return t;const{minimum:s,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:l,format:d,id:f,...h}=t;return h.enum?h.enum=h.enum.map(p=>typeof p=="number"?String(p):p):typeof h.const=="number"&&(h.const=String(h.const)),i&&(h.type="string",o||(h.pattern=(r.includes("number")?xr:Hc).source)),h}const Ju=new WeakMap;function dx(e){const t=new Map;for(const r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);const n=new Map;for(const r of Ju.get(e)??[]){const i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;const s=Ku(t,o,new Set);s!==o&&n.set(o,s)}if(n.size)for(const r of e.seen.values())for(const i of[r.schema,r.def]){const o=i&&n.get(i.propertyNames);o&&(i.propertyNames=o)}}const zb=(e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=tt(s).patterns;if(o.mode==="loose"&&a&&a.size>0){const l=Me(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const d of a)At(i.patternProperties,sb(d).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=Me(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let l=Ju.get(t);l||(l=[],Ju.set(t,l),t.deferred.push(()=>dx(t))),l.push(e)}i.additionalProperties=Me(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}const u=s._zod.values,c=t.io==="input"&&pi(o.valueType)!==void 0;if(u&&!o.partial&&!c){const l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l.map(String))}},Pb=(e,t,n,r)=>{const i=e._zod.def,o=Me(i.innerType,t,r),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Db=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},Ql=Symbol();function Ob(e,t,n,r,i){let o=!1;const s=JSON.stringify(e,(a,u)=>typeof u!="bigint"?u:(o=!0,null));return o?(nt(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),Ql):JSON.parse(s)}const Mb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;const s=Ob(i.defaultValue,e,t,n,r);s!==Ql&&(n.default=s)},Fb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;const s=Ob(i.defaultValue,e,t,n,r);s!==Ql&&(n._prefault=s)},Ub=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{nt(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},Gb=(e,t,n,r)=>{const i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;Me(s,t,r);const a=t.seen.get(e);a.ref=s},jb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Zb=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},ed=(e,t,n,r)=>{const i=e._zod.def;Me(i.innerType,t,r);const o=t.seen.get(e);o.ref=i.innerType},Bb=(e,t,n,r)=>{const i=e._zod.innerType;Me(i,t,r);const o=t.seen.get(e);o.ref=i},Yu={string:ab,number:ub,boolean:cb,bigint:lb,symbol:db,null:fb,undefined:hb,void:pb,never:mb,any:gb,unknown:yb,date:vb,enum:bb,literal:wb,nan:_b,template_literal:kb,file:Sb,success:xb,custom:Eb,function:$b,transform:Tb,map:Cb,set:Ab,array:Ib,object:Nb,union:Xl,intersection:Rb,tuple:Lb,record:zb,nullable:Pb,nonoptional:Db,default:Mb,prefault:Fb,catch:Ub,pipe:Gb,readonly:jb,promise:Zb,optional:ed,lazy:Bb};function td(e,t){if("_idmap"in e){const r=e,i=fr({...t,processors:Yu}),o={};for(const u of r._idmap.entries()){const[c,l]=u;Me(l,i)}const s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(const u of r._idmap.entries()){const[c,l]=u;hr(i,l),At(s,c,pr(i,l))}if(Object.keys(o).length>0){const u=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=fr({...t,processors:Yu});return Me(e,n),hr(n,e),pr(n,e)}class fx{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=fr({processors:Yu,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return Me(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,hr(this.ctx,t);const r=pr(this.ctx,t),{"~standard":i,...o}=r;return o}}const hx=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Vb=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Cy,$ZodArray:Ly,$ZodAsyncError:an,$ZodBase64:gy,$ZodBase64URL:yy,$ZodBigInt:fl,$ZodBigIntFormat:xy,$ZodBoolean:dl,$ZodCIDRv4:py,$ZodCIDRv6:my,$ZodCUID:ny,$ZodCUID2:ry,$ZodCatch:tv,$ZodCheck:Ve,$ZodCheckBigIntFormat:Ig,$ZodCheckEndsWith:jg,$ZodCheckGreaterThan:Jc,$ZodCheckIncludes:Ug,$ZodCheckLengthEquals:Dg,$ZodCheckLessThan:Kc,$ZodCheckLowerCase:Mg,$ZodCheckMaxLength:zg,$ZodCheckMaxSize:Ng,$ZodCheckMimeType:Vg,$ZodCheckMinLength:Pg,$ZodCheckMinSize:Rg,$ZodCheckMultipleOf:Cg,$ZodCheckNumberFormat:Ag,$ZodCheckOverwrite:Hg,$ZodCheckProperties:Bg,$ZodCheckProperty:Zg,$ZodCheckRegex:Og,$ZodCheckSizeEquals:Lg,$ZodCheckStartsWith:Gg,$ZodCheckStringFormat:zi,$ZodCheckUpperCase:Fg,$ZodCodec:yl,$ZodCreditCard:by,$ZodCustom:uv,$ZodCustomStringFormat:ky,$ZodCyclicError:cv,$ZodDate:Ry,$ZodDefault:Yy,$ZodDiscriminatedUnion:Uy,$ZodE164:vy,$ZodEmail:Yg,$ZodEmoji:ey,$ZodEncodeError:zs,$ZodEnum:Vy,$ZodError:jm,$ZodExactOptional:Ky,$ZodFile:qy,$ZodFunction:sv,$ZodGUID:Kg,$ZodIBAN:wy,$ZodIPv4:dy,$ZodIPv6:fy,$ZodISODate:uy,$ZodISODateTime:ay,$ZodISODuration:ly,$ZodISOTime:cy,$ZodIntersection:Gy,$ZodJWT:_y,$ZodKSUID:sy,$ZodLazy:vl,$ZodLiteral:Hy,$ZodMAC:hy,$ZodMap:Zy,$ZodNaN:nv,$ZodNanoID:ty,$ZodNever:Iy,$ZodNonOptional:Qy,$ZodNull:Ty,$ZodNullable:Jy,$ZodNumber:ll,$ZodNumberFormat:Sy,$ZodObject:Dy,$ZodObjectJIT:Oy,$ZodOptional:ml,$ZodPipe:gl,$ZodPrefault:Xy,$ZodPreprocess:rv,$ZodPromise:av,$ZodReadonly:iv,$ZodRealError:It,$ZodRecord:jy,$ZodRegistry:fv,$ZodSet:By,$ZodString:Pi,$ZodStringFormat:Ue,$ZodSuccess:ev,$ZodSymbol:Ey,$ZodTemplateLiteral:ov,$ZodTransform:Wy,$ZodTuple:pl,$ZodType:ye,$ZodULID:iy,$ZodURL:Qg,$ZodUUID:Jg,$ZodUndefined:$y,$ZodUnion:Bs,$ZodUnknown:Ay,$ZodVoid:Ny,$ZodXID:oy,$ZodXor:My,$brand:Rc,$constructor:S,$input:Sl,$output:kl,Doc:Yc,INVALID:wt,JSONSchema:hx,JSONSchemaGenerator:fx,NEVER:Nc,TimePrecision:ql,URL_BAD_FORMAT:Qc,URL_UNPARSEABLE:di,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ae,_any:Ov,_array:Bv,_base64:Zl,_base64url:Bl,_bigint:Iv,_boolean:Cv,_catch:tx,_check:Kv,_cidrv4:Gl,_cidrv6:jl,_coercedBigint:Nv,_coercedBoolean:Av,_coercedDate:jv,_coercedNumber:kv,_coercedString:yv,_creditCard:bv,_cuid:zl,_cuid2:Pl,_custom:Hv,_date:Gv,_decode:Dc,_decodeAsync:Mc,_default:X0,_discriminatedUnion:U0,_e164:Vl,_email:$l,_emoji:Rl,_encode:Pc,_encodeAsync:Oc,_endsWith:Gi,_enum:H0,_file:Vv,_float32:xv,_float64:Ev,_gt:mn,_gte:Ct,_guid:Tl,_iban:wv,_includes:Fi,_int:Sv,_int32:$v,_int64:Rv,_intersection:G0,_ipv4:Fl,_ipv6:Ul,_isoDate:Kl,_isoDateTime:Wl,_isoDuration:Yl,_isoTime:Jl,_jwt:Hl,_ksuid:Ml,_lazy:ox,_length:Tr,_literal:W0,_lowercase:Oi,_lt:pn,_lte:Tt,_mac:vv,_map:B0,_max:Tt,_maxLength:$r,_maxSize:Qn,_mime:Zi,_min:Ct,_minLength:Nn,_minSize:gn,_multipleOf:Kn,_nan:Zv,_nanoid:Ll,_nativeEnum:q0,_negative:Xs,_never:Fv,_nonnegative:ea,_nonoptional:Q0,_nonpositive:Qs,_normalize:Bi,_null:Dv,_nullable:Y0,_number:_v,_optional:J0,_overwrite:tn,_parse:Ci,_parseAsync:Ai,_pipe:nx,_positive:Ys,_promise:sx,_properties:ji,_property:ta,_readonly:rx,_record:Z0,_refine:qv,_regex:Di,_safeDecode:Uc,_safeDecodeAsync:jc,_safeEncode:Fc,_safeEncodeAsync:Gc,_safeParse:Ii,_safeParseAsync:Ni,_set:V0,_size:Er,_slugify:Wi,_startsWith:Ui,_string:gv,_stringFormat:Cr,_stringbool:Xv,_success:ex,_superRefine:Wv,_symbol:zv,_templateLiteral:ix,_toLowerCase:Hi,_toUpperCase:qi,_transform:K0,_trim:Vi,_tuple:j0,_uint32:Tv,_uint64:Lv,_ulid:Dl,_undefined:Pv,_union:M0,_unknown:Mv,_uppercase:Mi,_url:Js,_uuid:Cl,_uuidv4:Al,_uuidv6:Il,_uuidv7:Nl,_void:Uv,_xid:Ol,_xor:F0,base64Charset:ol,base64urlCharset:Zs,canParseURL:el,clone:Be,compile:xl,compileFn:Ws,config:Qe,createStandardJSONSchemaMethod:hi,createToJSONSchemaMethod:tb,decode:Jk,decodeAsync:Xk,describe:Jv,encode:Kk,encodeAsync:Yk,extractDefs:hr,finalize:pr,flattenError:Ps,formatError:Ds,getDiscriminatedOption:hl,globalConfig:bt,globalRegistry:Et,handleUnrepresentable:nt,initializeContext:fr,isBackEdge:wl,isRecursiveSchema:bl,isValidBase64:js,isValidBase64URL:sl,isValidCIDRv6:il,isValidCreditCard:al,isValidIBAN:ul,isValidIPv6:Gs,isValidJWT:cl,locales:_l,memoizer:Vs,mergeValues:fi,meta:Yv,parse:Gu,parseAsync:ju,parseURLObject:Xg,prettifyError:zc,process:Me,processSchema:Me,regexes:Us,registry:Hs,safeDecode:eS,safeDecodeAsync:nS,safeEncode:Qk,safeEncodeAsync:tS,safeParse:Bm,safeParseAsync:Vk,standardProps:Xc,stripTabAndNewline:fs,toDotPath:Zm,toJSONSchema:td,toZod:Cs,treeifyError:Lc,urlHostnameOk:nl,urlProtocolOk:rl,util:Ic,validate:Ms,validateAsync:Fs,validateURL:tl,version:qg,withParser:qs},Symbol.toStringTag,{value:"Module"})),Wh=Symbol("z.visit/resolving");function nd(e,t){const n=typeof t=="function"?t:(s,a)=>{const u=t[s._zod.def.type];return u?u(s,a):s},r=new Map;function i(s){const a=r.get(s);if(a===Wh)return new vl({type:"lazy",getter:()=>r.get(s)});if(a!==void 0)return a;r.set(s,Wh);const u=o(s),c=n(u,u!==s);return r.set(s,c),c}function o(s){const a=s._zod.def;switch(a.type){case"object":{const c=a.shape,l=Object.keys(c);let d=!1;const f={};for(const p of l){const m=i(c[p]);m!==c[p]&&(d=!0),f[p]=m}let h=a.catchall;return a.catchall&&(h=i(a.catchall),h!==a.catchall&&(d=!0)),d?Be(s,{...a,shape:f,catchall:h}):s}case"array":{const c=i(a.element);return c===a.element?s:Be(s,{...a,element:c})}case"tuple":{const c=a.items;let l=!1;const d=[];for(const h of c){const p=i(h);p!==h&&(l=!0),d.push(p)}let f=a.rest;return a.rest&&(f=i(a.rest),f!==a.rest&&(l=!0)),l?Be(s,{...a,items:d,rest:f}):s}case"record":case"map":{const c=i(a.keyType),l=i(a.valueType);return c===a.keyType&&l===a.valueType?s:Be(s,{...a,keyType:c,valueType:l})}case"set":{const c=i(a.valueType);return c===a.valueType?s:Be(s,{...a,valueType:c})}case"union":{const c=a.options;let l=!1;const d=[];for(const f of c){const h=i(f);h!==f&&(l=!0),d.push(h)}return l?Be(s,{...a,options:d}):s}case"intersection":{const c=i(a.left),l=i(a.right);return c===a.left&&l===a.right?s:Be(s,{...a,left:c,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const c=i(a.innerType);return c===a.innerType?s:Be(s,{...a,innerType:c})}case"pipe":{const c=i(a.in),l=i(a.out);return c===a.in&&l===a.out?s:Be(s,{...a,in:c,out:l})}case"function":{const c=i(a.input),l=i(a.output);return c===a.input&&l===a.output?s:Be(s,{...a,input:c,output:l})}case"lazy":{const c=a.getter,{_cachedInner:l,...d}=a;return Be(s,{...d,getter:()=>i(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return i(e)}function rd(e){return!!e._zod}function Hb(e,t){return rd(e)?Bm(e,t):e.safeParse(t)}function px(e){if(!e)return;let t;if(rd(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function mx(e){if(rd(e)){const o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const r=e.value;if(r!==void 0)return r}const gx=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(o,s){return o==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):r[o]??o}return o=>{switch(o.code){case"invalid_type":{const s=i(o.expected),a=Dm(o.input),u=i(a,o.input);return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Ec(o.values[0])}`:`Invalid option: expected one of ${Mu(o.values,"|")}`;case"too_big":{const s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{const s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Mu(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(a=>`'${a}'`).join(" | ")}`:o.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function yx(){return{localeError:gx()}}const vx=Object.freeze(Object.defineProperty({__proto__:null,endsWith:Gi,gt:mn,gte:Ct,includes:Fi,length:Tr,lowercase:Oi,lt:pn,lte:Tt,maxLength:$r,maxSize:Qn,mime:Zi,minLength:Nn,minSize:gn,multipleOf:Kn,negative:Xs,nonnegative:ea,nonpositive:Qs,normalize:Bi,overwrite:tn,positive:Ys,properties:ji,property:ta,regex:Di,size:Er,slugify:Wi,startsWith:Ui,toLowerCase:Hi,toUpperCase:qi,trim:Vi,uppercase:Mi},Symbol.toStringTag,{value:"Module"})),Kh=new WeakSet([Object.prototype,Error.prototype]);function Fo(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}const qb=(e,t)=>{jm.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);Kh.has(n)||(Kh.add(n),Fo(n,"format",r=>i=>Ds(r,i)),Fo(n,"flatten",r=>i=>Ps(r,i)),Fo(n,"addIssue",r=>i=>{r.issues.push(i),r.message=JSON.stringify(r.issues,us,2)}),Fo(n,"addIssues",r=>i=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,us,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Wb=S("ZodError",qb),St=S("ZodError",qb,void 0,{Parent:Error}),id=Ci(St),od=Ai(St),sd=Ii(St),ad=Ni(St),ud=Pc(St),cd=Dc(St),ld=Oc(St),dd=Mc(St),fd=Fc(St),hd=Uc(St),pd=Gc(St),md=jc(St);function bx(){bt.localeError||Qe(yx())}function er(){bt.memoizer||Qe({memoizer:Vs()})}const be=S("ZodType",(e,t)=>(bx(),ye.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(dt(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Be(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Za(e,t))},superRefine(e,t){return this.check(Ba(e,t))},overwrite(e){return this.check(tn(e))},optional(){return Ge(this)},exactOptional(){return Sa(this)},nullable(){return vr(this)},nullish(){return Ge(vr(this))},nonoptional(e){return Aa(this,e)},array(){return le(this)},or(e){return Ee([this,e])},and(e){return Ur(this,e)},transform(e){return gi(this,bo(e))},default(e){return $a(this,e)},prefault(e){return Ca(this,e)},catch(e){return Ra(this,e)},pipe(e){return gi(this,e)},readonly(){return Da(this)},describe(e){const t=this.clone();return Et.add(t,{description:e}),t},meta(...e){if(e.length===0)return Et.get(this);const t=this.clone();return Et.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Ls(this,"~standard",{...Xc(this),jsonSchema:{input:hi(this,"input"),output:hi(this,"output")}})},set"~standard"(e){fn(this,"~standard",e)},parse:function e(t,n){return id(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await od(this,t,n,{callee:e})},safeParse(e,t){return sd(this,e,t)},async safeParseAsync(e,t){return ad(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){fn(this,"spa",e)},validate(e,t){return Ms(this,e,t)},validateAsync(e,t){return Fs(this,e,t)},encode:function e(t,n){return ud(this,t,n,{callee:e})},decode:function e(t,n){return cd(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await ld(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await dd(this,t,n,{callee:e})},safeEncode(e,t){return fd(this,e,t)},safeDecode(e,t){return hd(this,e,t)},async safeEncodeAsync(e,t){return pd(this,e,t)},async safeDecodeAsync(e,t){return md(this,e,t)},toJSONSchema(e){return tb(this,{})(e)},get description(){return Et.get(this)?.description},get _def(){return this._zod.def}}),Ki=S("_ZodString",(e,t)=>{Pi.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ab(e,n,r)},Ti({format:e=>tt(e).format??null,minLength:e=>tt(e).minimum??null,maxLength:e=>tt(e).maximum??null},{regex(...e){return this.check(Di(...e))},includes(...e){return this.check(Fi(...e))},startsWith(...e){return this.check(Ui(...e))},endsWith(...e){return this.check(Gi(...e))},min(...e){return this.check(Nn(...e))},max(...e){return this.check($r(...e))},length(...e){return this.check(Tr(...e))},nonempty(...e){return this.check(Nn(1,...e))},lowercase(e){return this.check(Oi(e))},uppercase(e){return this.check(Mi(e))},trim(){return this.check(Vi())},normalize(...e){return this.check(Bi(...e))},toLowerCase(){return this.check(Hi())},toUpperCase(){return this.check(qi())},slugify(){return this.check(Wi())}})),Ar=S("ZodString",(e,t)=>{Pi.init(e,t),Ki.init(e,t)},{email(e){return this.check($l(Ji,e))},url(e){return this.check(Js(zr,e))},jwt(e){return this.check(Hl(ho,e))},emoji(e){return this.check(Rl(Xi,e))},guid(e){return this.check(Tl(Yi,e))},uuid(e){return this.check(Cl(Kt,e))},uuidv4(e){return this.check(Al(Kt,e))},uuidv6(e){return this.check(Il(Kt,e))},uuidv7(e){return this.check(Nl(Kt,e))},nanoid(e){return this.check(Ll(Qi,e))},cuid(e){return this.check(zl(eo,e))},cuid2(e){return this.check(Pl(to,e))},ulid(e){return this.check(Dl(no,e))},base64(e){return this.check(Zl(co,e))},base64url(e){return this.check(Bl(lo,e))},xid(e){return this.check(Ol(ro,e))},ksuid(e){return this.check(Ml(io,e))},ipv4(e){return this.check(Fl(oo,e))},ipv6(e){return this.check(Ul(so,e))},cidrv4(e){return this.check(Gl(ao,e))},cidrv6(e){return this.check(jl(uo,e))},e164(e){return this.check(Vl(fo,e))},datetime(e){return this.check(Wl(Ir,e))},date(e){return this.check(Kl(Nr,e))},time(e){return this.check(Jl(Rr,e))},duration(e){return this.check(Yl(Lr,e))}});function E(e){return gv(Ar,e)}const De=S("ZodStringFormat",(e,t)=>{Ue.init(e,t),Ki.init(e,t)}),Ir=S("ZodISODateTime",(e,t)=>{ay.init(e,t),De.init(e,t)}),Nr=S("ZodISODate",(e,t)=>{uy.init(e,t),De.init(e,t)}),Rr=S("ZodISOTime",(e,t)=>{cy.init(e,t),De.init(e,t)}),Lr=S("ZodISODuration",(e,t)=>{ly.init(e,t),De.init(e,t)}),Ji=S("ZodEmail",(e,t)=>{Yg.init(e,t),De.init(e,t)});function gd(e){return $l(Ji,e)}const Yi=S("ZodGUID",(e,t)=>{Kg.init(e,t),De.init(e,t)});function yd(e){return Tl(Yi,e)}const Kt=S("ZodUUID",(e,t)=>{Jg.init(e,t),De.init(e,t)});function vd(e){return Cl(Kt,e)}function bd(e){return Al(Kt,e)}function wd(e){return Il(Kt,e)}function _d(e){return Nl(Kt,e)}const zr=S("ZodURL",(e,t)=>{Qg.init(e,t),De.init(e,t)});function kd(e){return Js(zr,e)}function Sd(e){return Js(zr,{protocol:Zc,hostname:fg,...R(e)})}const Xi=S("ZodEmoji",(e,t)=>{ey.init(e,t),De.init(e,t)});function xd(e){return Rl(Xi,e)}const Qi=S("ZodNanoID",(e,t)=>{ty.init(e,t),De.init(e,t)});function Ed(e){return Ll(Qi,e)}const eo=S("ZodCUID",(e,t)=>{ny.init(e,t),De.init(e,t)});function $d(e){return zl(eo,e)}const to=S("ZodCUID2",(e,t)=>{ry.init(e,t),De.init(e,t)});function Td(e){return Pl(to,e)}const no=S("ZodULID",(e,t)=>{iy.init(e,t),De.init(e,t)});function Cd(e){return Dl(no,e)}const ro=S("ZodXID",(e,t)=>{oy.init(e,t),De.init(e,t)});function Ad(e){return Ol(ro,e)}const io=S("ZodKSUID",(e,t)=>{sy.init(e,t),De.init(e,t)});function Id(e){return Ml(io,e)}const oo=S("ZodIPv4",(e,t)=>{dy.init(e,t),De.init(e,t)});function Nd(e){return Fl(oo,e)}const na=S("ZodMAC",(e,t)=>{hy.init(e,t),De.init(e,t)});function Rd(e){return vv(na,e)}const so=S("ZodIPv6",(e,t)=>{fy.init(e,t),De.init(e,t)});function Ld(e){return Ul(so,e)}const ao=S("ZodCIDRv4",(e,t)=>{py.init(e,t),De.init(e,t)});function zd(e){return Gl(ao,e)}const uo=S("ZodCIDRv6",(e,t)=>{my.init(e,t),De.init(e,t)});function Pd(e){return jl(uo,e)}const co=S("ZodBase64",(e,t)=>{gy.init(e,t),De.init(e,t)});function Dd(e){return Zl(co,e)}const lo=S("ZodBase64URL",(e,t)=>{yy.init(e,t),De.init(e,t)});function Od(e){return Bl(lo,e)}const fo=S("ZodE164",(e,t)=>{vy.init(e,t),De.init(e,t)});function Md(e){return Vl(fo,e)}const ra=S("ZodCreditCard",(e,t)=>{by.init(e,t),De.init(e,t)});function Fd(e){return bv(ra,e)}const ia=S("ZodIBAN",(e,t)=>{wy.init(e,t),De.init(e,t)});function Ud(e){return wv(ia,e)}const ho=S("ZodJWT",(e,t)=>{_y.init(e,t),De.init(e,t)});function Gd(e){return Hl(ho,e)}const Ln=S("ZodCustomStringFormat",(e,t)=>{ky.init(e,t),De.init(e,t)});function jd(e,t,n={}){return Cr(Ln,e,t,n)}function Zd(e){return Cr(Ln,"hostname",dg,e)}function Bd(e){return Cr(Ln,"hex",Tg,e)}function Vd(e){return Cr(Ln,"currency_code",pg,e)}function Hd(e,t){const n=t?.enc??"hex",r=`${e}_${n}`,i=Us[r];if(!i)throw new Error(`Unrecognized hash format: ${r}`);return Cr(Ln,r,i,t)}const Pr=S("ZodNumber",(e,t)=>{ll.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ub(e,n,r,i),e.isFinite=!0},Ti({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=tt(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=tt(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=tt(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>tt(e).format??null},{gt(e,t){return this.check(mn(e,t))},gte(e,t){return this.check(Ct(e,t))},min(e,t){return this.check(Ct(e,t))},lt(e,t){return this.check(pn(e,t))},lte(e,t){return this.check(Tt(e,t))},max(e,t){return this.check(Tt(e,t))},int(e){return this.check(mi(e))},safe(e){return this.check(mi(e))},positive(e){return this.check(mn(0,e))},nonnegative(e){return this.check(Ct(0,e))},negative(e){return this.check(pn(0,e))},nonpositive(e){return this.check(Tt(0,e))},multipleOf(e,t){return this.check(Kn(e,t))},step(e,t){return this.check(Kn(e,t))},finite(){return this}}));function ve(e){return _v(Pr,e)}const zn=S("ZodNumberFormat",(e,t)=>{Sy.init(e,t),Pr.init(e,t)});function mi(e){return Sv(zn,e)}function qd(e){return xv(zn,e)}function Wd(e){return Ev(zn,e)}function Kd(e){return $v(zn,e)}function Jd(e){return Tv(zn,e)}const Dr=S("ZodBoolean",(e,t)=>{dl.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>cb(e,n,r)});function Pe(e){return Cv(Dr,e)}const Or=S("ZodBigInt",(e,t)=>{fl.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lb(e,n,r,i)},Ti({minValue:e=>tt(e).minimum??null,maxValue:e=>tt(e).maximum??null,format:e=>tt(e).format??null},{gte(e,t){return this.check(Ct(e,t))},min(e,t){return this.check(Ct(e,t))},gt(e,t){return this.check(mn(e,t))},lt(e,t){return this.check(pn(e,t))},lte(e,t){return this.check(Tt(e,t))},max(e,t){return this.check(Tt(e,t))},positive(e){return this.check(mn(BigInt(0),e))},negative(e){return this.check(pn(BigInt(0),e))},nonpositive(e){return this.check(Tt(BigInt(0),e))},nonnegative(e){return this.check(Ct(BigInt(0),e))},multipleOf(e,t){return this.check(Kn(e,t))}}));function Yd(e){return Iv(Or,e)}const po=S("ZodBigIntFormat",(e,t)=>{xy.init(e,t),Or.init(e,t)});function Xd(e){return Rv(po,e)}function Qd(e){return Lv(po,e)}const oa=S("ZodSymbol",(e,t)=>{Ey.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>db(e,n,r,i)});function ef(e){return zv(oa,e)}const sa=S("ZodUndefined",(e,t)=>{$y.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hb(e,n,r,i)});function yr(e){return Pv(sa,e)}const aa=S("ZodNull",(e,t)=>{Ty.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fb(e,n,r)});function mo(e){return Dv(aa,e)}const ua=S("ZodAny",(e,t)=>{Cy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gb()});function go(){return Ov(ua)}const ca=S("ZodUnknown",(e,t)=>{Ay.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yb()});function Ne(){return Mv(ca)}const la=S("ZodNever",(e,t)=>{Iy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mb(e,n,r)});function Jn(e){return Fv(la,e)}const da=S("ZodVoid",(e,t)=>{Ny.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pb(e,n,r,i)});function tf(e){return Uv(da,e)}const yo=S("ZodDate",(e,t)=>{Ry.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vb(e,n,r,i),e.min=(n,r)=>e.check(Ct(n,r)),e.max=(n,r)=>e.check(Tt(n,r))},Ti({minDate:e=>{const{minimum:t}=tt(e);return t?new Date(t):null},maxDate:e=>{const{maximum:t}=tt(e);return t?new Date(t):null}},{}));function nf(e){return Gv(yo,e)}const fa=S("ZodArray",(e,t)=>{er(),Ly.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ib(e,n,r,i),e.element=t.element},{min(e,t){return this.check(Nn(e,t))},nonempty(e){return this.check(Nn(1,e))},max(e,t){return this.check($r(e,t))},length(e,t){return this.check(Tr(e,t))},unwrap(){return this.element}});function le(e,t){return Bv(fa,e,t)}function rf(e){const t=e._zod.def.shape;return at(Object.keys(t))}const Mr=S("ZodObject",(e,t)=>{er(),Oy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nb(e,n,r,i),Um(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return at(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(dt(this._zod.def,{catchall:Ne()}))},loose(){return this.clone(dt(this._zod.def,{catchall:Ne()}))},strict(){return this.clone(dt(this._zod.def,{catchall:Jn()}))},strip(){return this.clone(dt(this._zod.def,{catchall:void 0}))},extend(e){return Im(this,e)},safeExtend(e){return Rm(this,e)},merge(e){return Lm(this,e)},pick(e){return Cm(this,e)},omit(e){return Am(this,e)},partial(...e){return Fu(Gr,this,e[0])},exactPartial(...e){return Fu(wo,this,e[0],"exactPartial")},required(...e){return zm(_o,this,e[0])}});function C(e,t){const n={type:"object",shape:e??{},...R(t)};return new Mr(n)}function of(e,t){return new Mr({type:"object",shape:e,catchall:Jn(),...R(t)})}function st(e,t){return new Mr({type:"object",shape:e,catchall:Ne(),...R(t)})}const Fr=S("ZodUnion",(e,t)=>{Bs.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xl(e,n,r,i),e.options=t.options});function Ee(e,t){return new Fr({type:"union",options:e,...R(t)})}const ha=S("ZodXor",(e,t)=>{Fr.init(e,t),My.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xl(e,n,r,i),e.options=t.options});function sf(e,t){return new ha({type:"union",options:e,inclusive:!1,...R(t)})}const pa=S("ZodDiscriminatedUnion",(e,t)=>{Fr.init(e,t),Uy.init(e,t)});function vo(e,t,n){return new pa({type:"union",options:t,discriminator:e,...R(n)})}const ma=S("ZodIntersection",(e,t)=>{Gy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rb(e,n,r,i)});function Ur(e,t){return new ma({type:"intersection",left:e,right:t})}const ga=S("ZodTuple",(e,t)=>{er(),pl.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lb(e,n,r,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){const e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Gr({type:"optional",innerType:t}))})}});function ya(e,t,n){const r=t instanceof ye,i=r?n:t,o=r?t:null;return new ga({type:"tuple",items:e,rest:o,...R(i)})}const Yn=S("ZodRecord",(e,t)=>{er(),jy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zb(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Te(e,t,n){return!t||!t._zod?new Yn({type:"record",keyType:E(),valueType:e,...R(t)}):new Yn({type:"record",keyType:e,valueType:t,...R(n)})}function af(e,t,n){return new Yn({type:"record",keyType:e,valueType:t,...R(n),partial:!0})}function uf(e,t,n){return new Yn({type:"record",keyType:e,valueType:t,mode:"loose",...R(n)})}const va=S("ZodMap",(e,t)=>{er(),Zy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Cb(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(gn(...n)),e.nonempty=n=>e.check(gn(1,n)),e.max=(...n)=>e.check(Qn(...n)),e.size=(...n)=>e.check(Er(...n))});function cf(e,t,n){return new va({type:"map",keyType:e,valueType:t,...R(n)})}const ba=S("ZodSet",(e,t)=>{er(),By.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ab(e,n,r,i),e.min=(...n)=>e.check(gn(...n)),e.nonempty=n=>e.check(gn(1,n)),e.max=(...n)=>e.check(Qn(...n)),e.size=(...n)=>e.check(Er(...n))});function lf(e,t){return new ba({type:"set",valueType:e,...R(t)})}const Xn=S("ZodEnum",(e,t)=>{Vy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(r,i,o)=>bb(e,r,i),e.enum=t.entries,e.options=[...e._zod.values];const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const o={};for(const s of r)if(n.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Xn({...t,checks:[],...R(i),entries:o})},e.exclude=(r,i)=>{const o={...t.entries};for(const s of r)if(n.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Xn({...t,checks:[],...R(i),entries:o})}});function at(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Xn({type:"enum",entries:n,...R(t)})}function df(e,t){return new Xn({type:"enum",entries:e,...R(t)})}const wa=S("ZodLiteral",(e,t)=>{Hy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wb(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function $(e,t){return new wa({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}const _a=S("ZodFile",(e,t)=>{qy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sb(e,n,r),e.min=(n,r)=>e.check(gn(n,r)),e.max=(n,r)=>e.check(Qn(n,r)),e.mime=(n,r)=>e.check(Zi(Array.isArray(n)?n:[n],r))});function ff(e){return Vv(_a,e)}const ka=S("ZodTransform",(e,t)=>{er(),Wy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Tb(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zs(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(lr(o,n.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=n.value),s.inst??(s.inst=e),n.issues.push(lr(s))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function bo(e){return new ka({type:"transform",transform:e})}const Gr=S("ZodOptional",(e,t)=>{ml.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ed(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ge(e){return new Gr({type:"optional",innerType:e})}const wo=S("ZodExactOptional",(e,t)=>{Ky.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ed(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Sa(e){return new wo({type:"optional",innerType:e})}const xa=S("ZodNullable",(e,t)=>{Jy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Pb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function vr(e){return new xa({type:"nullable",innerType:e})}function hf(e){return Ge(vr(e))}const Ea=S("ZodDefault",(e,t)=>{Yy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $a(e,t){return new Ea({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ei(t)}})}const Ta=S("ZodPrefault",(e,t)=>{Xy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ca(e,t){return new Ta({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ei(t)}})}const _o=S("ZodNonOptional",(e,t)=>{Qy.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Db(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Aa(e,t){return new _o({type:"nonoptional",innerType:e,...R(t)})}const Ia=S("ZodSuccess",(e,t)=>{ev.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xb(e,n,r),e.unwrap=()=>e._zod.def.innerType});function pf(e){return new Ia({type:"success",innerType:e})}const Na=S("ZodCatch",(e,t)=>{tv.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ub(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ra(e,t){return new Na({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Ac(t)})}const La=S("ZodNaN",(e,t)=>{nv.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_b(e,n,r,i)});function mf(e){return Zv(La,e)}const jr=S("ZodPipe",(e,t)=>{gl.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gb(e,n,r,i),e.in=t.in,e.out=t.out});function gi(e,t){return new jr({type:"pipe",in:e,out:t})}const Zr=S("ZodCodec",(e,t)=>{jr.init(e,t),yl.init(e,t)});function gf(e,t,n){return new Zr({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}function yf(e){const t=e._zod.def;return new Zr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}const za=S("ZodPreprocess",(e,t)=>{jr.init(e,t),rv.init(e,t)}),Pa=S("ZodReadonly",(e,t)=>{iv.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Da(e){return new Pa({type:"readonly",innerType:e})}const Oa=S("ZodTemplateLiteral",(e,t)=>{ov.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kb(e,n,r)});function vf(e,t){return new Oa({type:"template_literal",parts:e,...R(t)})}const Ma=S("ZodLazy",(e,t)=>{vl.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Bb(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Fa(e){return new Ma({type:"lazy",getter:e})}const Ua=S("ZodPromise",(e,t)=>{av.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zb(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function bf(e){return new Ua({type:"promise",innerType:e})}const Ga=S("ZodFunction",(e,t)=>{sv.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$b(e,n,r,i)});function br(e){return new Ga({type:"function",input:Array.isArray(e?.input)?ya(e?.input):e?.input??le(Ne()),output:e?.output??Ne()})}const Br=S("ZodCustom",(e,t)=>{uv.init(e,t),be.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Eb(e,n,r,i)});function wf(e){const t=new Ve({check:"custom"});return t._zod.check=e,t}function ja(e,t){return Hv(Br,e??(()=>!0),t)}function Za(e,t={}){return qv(Br,e,t)}function Ba(e,t){return Wv(e,t)}const _f=Jv,kf=Yv,Va=S("ZodInstanceOf",(e,t)=>{Br.init(e,t)},{properties(e,t){return this.check(ji(e,t))}});function Sf(e,t={}){const n=new Va({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...R(t)});return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}const xf=(...e)=>Xv({Codec:Zr,Boolean:Dr,String:Ar},...e);function Ef(e){const t=Fa(()=>Ee([E(e),ve(),Pe(),mo(),le(t),Te(E(),t)]));return t}function ko(e,t){return new za({type:"pipe",in:bo(e),out:t})}const wx=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:ua,ZodArray:fa,ZodBase64:co,ZodBase64URL:lo,ZodBigInt:Or,ZodBigIntFormat:po,ZodBoolean:Dr,ZodCIDRv4:ao,ZodCIDRv6:uo,ZodCUID:eo,ZodCUID2:to,ZodCatch:Na,ZodCodec:Zr,ZodCreditCard:ra,ZodCustom:Br,ZodCustomStringFormat:Ln,ZodDate:yo,ZodDefault:Ea,ZodDiscriminatedUnion:pa,ZodE164:fo,ZodEmail:Ji,ZodEmoji:Xi,ZodEnum:Xn,ZodExactOptional:wo,ZodFile:_a,ZodFunction:Ga,ZodGUID:Yi,ZodIBAN:ia,ZodIPv4:oo,ZodIPv6:so,ZodISODate:Nr,ZodISODateTime:Ir,ZodISODuration:Lr,ZodISOTime:Rr,ZodInstanceOf:Va,ZodIntersection:ma,ZodJWT:ho,ZodKSUID:io,ZodLazy:Ma,ZodLiteral:wa,ZodMAC:na,ZodMap:va,ZodNaN:La,ZodNanoID:Qi,ZodNever:la,ZodNonOptional:_o,ZodNull:aa,ZodNullable:xa,ZodNumber:Pr,ZodNumberFormat:zn,ZodObject:Mr,ZodOptional:Gr,ZodPipe:jr,ZodPrefault:Ta,ZodPreprocess:za,ZodPromise:Ua,ZodReadonly:Pa,ZodRecord:Yn,ZodSet:ba,ZodString:Ar,ZodStringFormat:De,ZodSuccess:Ia,ZodSymbol:oa,ZodTemplateLiteral:Oa,ZodTransform:ka,ZodTuple:ga,ZodType:be,ZodULID:no,ZodURL:zr,ZodUUID:Kt,ZodUndefined:sa,ZodUnion:Fr,ZodUnknown:ca,ZodVoid:da,ZodXID:ro,ZodXor:ha,_ZodString:Ki,_default:$a,_function:br,any:go,array:le,base64:Dd,base64url:Od,bigint:Yd,boolean:Pe,catch:Ra,check:wf,cidrv4:zd,cidrv6:Pd,codec:gf,creditCard:Fd,cuid:$d,cuid2:Td,currencyCode:Vd,custom:ja,date:nf,describe:_f,discriminatedUnion:vo,e164:Md,email:gd,emoji:xd,enum:at,exactOptional:Sa,file:ff,float32:qd,float64:Wd,function:br,guid:yd,hash:Hd,hex:Bd,hostname:Zd,httpUrl:Sd,iban:Ud,instanceof:Sf,int:mi,int32:Kd,int64:Xd,intersection:Ur,invertCodec:yf,ipv4:Nd,ipv6:Ld,json:Ef,jwt:Gd,keyof:rf,ksuid:Id,lazy:Fa,literal:$,looseObject:st,looseRecord:uf,mac:Rd,map:cf,meta:kf,nan:mf,nanoid:Ed,nativeEnum:df,never:Jn,nonoptional:Aa,null:mo,nullable:vr,nullish:hf,number:ve,object:C,optional:Ge,partialRecord:af,pipe:gi,prefault:Ca,preprocess:ko,promise:bf,readonly:Da,record:Te,refine:Za,set:lf,strictObject:of,string:E,stringFormat:jd,stringbool:xf,success:pf,superRefine:Ba,symbol:ef,templateLiteral:vf,transform:bo,tuple:ya,uint32:Jd,uint64:Qd,ulid:Cd,undefined:yr,union:Ee,unknown:Ne,url:kd,uuid:vd,uuidv4:bd,uuidv6:wd,uuidv7:_d,void:tf,xid:Ad,xor:sf},Symbol.toStringTag,{value:"Module"})),Kb={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function Jb(e){Qe({customError:e})}function Yb(){return Qe().customError}var ps;ps||(ps={});function Xb(e){return Wl(Ir,e)}function _x(e){return Kl(Nr,e)}function kx(e){return Jl(Rr,e)}function Sx(e){return Yl(Lr,e)}const $f=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:Nr,ZodISODateTime:Ir,ZodISODuration:Lr,ZodISOTime:Rr,date:_x,datetime:Xb,duration:Sx,time:kx},Symbol.toStringTag,{value:"Module"})),H={...wx,...vx,iso:$f},xx=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Ex(e,t){const n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function Jh(e,t){return e.map((n,r)=>r<t?n:n.optional())}function $x(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Tx(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;const r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){const i=n[1]===void 0?void 0:$x(n[1]);if(!i||!t.defs[i])throw new Error(`Reference not found: ${e}`);return t.defs[i]}throw new Error(`Reference not found: ${e}`)}function Cx(e,t){return H.transform(r=>r).check(r=>{const i=r.value;if(typeof i!="object"||i===null||Array.isArray(i))return;const o=Object.getOwnPropertyNames(i);if(t.minProperties!==void 0&&o.length<t.minProperties&&r.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:i,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&r.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:i,inst:e,continue:!0}),t.keySchema)for(const s of o){const a=t.keySchema.safeParse(s);a.success||r.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(e)}function Xu(e,t){if(e===null)return"z";const n=typeof e;if(n!=="object"){if(n==="number"&&Number.isNaN(e))return null;const r=String(e);return`${n[0]}${r.length}:${r}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){const o=[];for(const s of e){const a=Xu(s,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}const r=Object.keys(e).sort(),i=[];for(const o of r){const s=Xu(e[o],t);if(s===null)return null;i.push(`${o.length}:${o}=${s}`)}return`o${i.length}:{${i.join(",")}}`}finally{t.delete(e)}}const Ax=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Ix=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function ci(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(ci):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,n])=>Ax.has(t)?ci(n):!Ix.has(t)||typeof n!="object"||n===null?!1:Object.values(n).some(ci))}function Yh(e){return e===1?"element":"elements"}function Nx(e,t){return H.transform(r=>r).check(r=>{const i=r.value;if(Array.isArray(i)){if(t.uniqueItems===!0){const o=new Map;for(let s=0;s<i.length;s++){const a=Xu(i[s],new Set);if(a===null)continue;const u=o.get(a);if(u===void 0){o.set(a,s);continue}r.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${u}`,input:i,path:[s],continue:!0})}}if(t.containsSchema){const o=t.minContains??1,s=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY;let a=0;for(const u of i)if(t.containsSchema.safeParse(u).success&&++a>=s)break;a<o&&r.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${Yh(o)}; found ${a}`,input:i,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&r.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${Yh(t.maxContains)}`,input:i,continue:!0})}}}).pipe(e)}function Xh(e,t){if(e!==!1)return e===void 0||e===!0?H.any():vt(e,t)}const Rx=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Qb(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return H.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){const i=e.$ref;if(t.refs.has(i))return t.refs.get(i);if(t.processing.has(i))return H.lazy(()=>{if(!t.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return t.refs.get(i)});t.processing.add(i);const o=Tx(i,t),s=vt(o,t);return t.refs.set(i,s),t.processing.delete(i),s}if(e.enum!==void 0){const i=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&i.length===1&&i[0]===null)return H.null();if(i.length===0)return H.never();if(i.length===1)return H.literal(i[0]);if(i.every(s=>typeof s=="string"))return H.enum(i);const o=i.map(s=>H.literal(s));return o.length<2?o[0]:H.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return H.literal(e.const);const n=e.type;if(Array.isArray(n)){const i=n.map(o=>{const s={...e,type:o};return Qb(s,t)});return i.length===0?H.never():i.length===1?i[0]:H.union(i)}if(!n)return H.any();let r;switch(n){case"string":{let i=H.string();if(e.format){const o=e.format;o==="email"?i=i.check(H.email()):o==="uri"||o==="uri-reference"?i=i.check(H.url()):o==="uuid"||o==="guid"?i=i.check(H.uuid()):o==="date-time"?i=i.check(H.iso.datetime({offset:!0})):o==="date"?i=i.check(H.iso.date()):o==="time"?i=i.check(H.regex(Rx)):o==="duration"?i=i.check(H.iso.duration()):o==="hostname"?i=i.check(H.hostname()):o==="ipv4"?i=i.check(H.ipv4()):o==="ipv6"?i=i.check(H.ipv6()):o==="mac"?i=i.check(H.mac()):o==="cidr"?i=i.check(H.cidrv4()):o==="cidr-v6"?i=i.check(H.cidrv6()):o==="base64"?i=i.check(H.base64()):o==="base64url"?i=i.check(H.base64url()):o==="e164"?i=i.check(H.e164()):o==="credit_card"?i=i.check(H.creditCard()):o==="iban"?i=i.check(H.iban()):o==="jwt"?i=i.check(H.jwt()):o==="emoji"?i=i.check(H.emoji()):o==="nanoid"?i=i.check(H.nanoid()):o==="cuid"?i=i.check(H.cuid()):o==="cuid2"?i=i.check(H.cuid2()):o==="ulid"?i=i.check(H.ulid()):o==="xid"?i=i.check(H.xid()):o==="ksuid"&&(i=i.check(H.ksuid()))}typeof e.minLength=="number"&&(i=i.min(e.minLength)),typeof e.maxLength=="number"&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),r=i;break}case"number":case"integer":{let i=n==="integer"?H.number().int():H.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(i=i.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(i=i.max(e.maximum)),typeof e.exclusiveMinimum=="number"?i=i.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(i=i.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?i=i.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(i=i.lt(e.maximum)),typeof e.multipleOf=="number"&&(i=i.multipleOf(e.multipleOf)),r=i;break}case"boolean":{r=H.boolean();break}case"null":{r=H.null();break}case"object":{const i={},o=e.properties||{},s=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?vt(e.additionalProperties,t):void 0;for(const[d,f]of Object.entries(o)){const h=vt(f,t);At(i,d,s.has(d)?h:h.optional())}if(e.patternProperties){const d=e.patternProperties,f=Object.keys(d),h=[];for(const m of f){const y=vt(d[m],t),_=H.string().regex(new RegExp(m));h.push(H.looseRecord(_,y))}const p=[];if(Object.keys(i).length>0&&p.push(H.object(i).passthrough()),p.push(...h),p.length===0)r=H.object({}).passthrough();else if(p.length===1)r=p[0];else{let m=H.intersection(p[0],p[1]);for(let y=2;y<p.length;y++)m=H.intersection(m,p[y]);r=m}if(e.additionalProperties===!1){const m=Object.keys(i),y=f.map(g=>new RegExp(g)),_=r;r=r.check(g=>{if(!ln(g.value))return;const b=[];for(const v of Object.keys(g.value))m.includes(v)||y.some(w=>w.test(v))||b.push(v);b.length&&g.issues.push({code:"unrecognized_keys",keys:b,input:g.value,inst:_})})}}else{const d=H.object(i);e.additionalProperties===!1?r=d.strict():a?r=d.catchall(a):r=d.passthrough()}const u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,l=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||l!==void 0){let d;if(u){const f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;d=vt(f,t)}r=Cx(r,{keySchema:d,minProperties:c,maxProperties:l})}break}case"array":{const i=e.prefixItems,o=e.items;if(i&&Array.isArray(i)){const s=typeof e.minItems=="number"?e.minItems:0,a=i.map(d=>vt(d,t)),u=Jh(a,s),c=Array.isArray(o)?void 0:Xh(o,t),l=H.tuple(u);r=c?l.rest(c):l,typeof e.minItems=="number"&&(r=r.check(H.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(H.maxLength(e.maxItems)))}else if(Array.isArray(o)){const s=typeof e.minItems=="number"?e.minItems:0,a=o.map(d=>vt(d,t)),u=Jh(a,s),c=Xh(e.additionalItems,t),l=H.tuple(u);r=c?l.rest(c):l,typeof e.minItems=="number"&&(r=r.check(H.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(H.maxLength(e.maxItems)))}else if(o!==void 0){const s=vt(o,t);let a=H.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),r=a}else r=H.array(H.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=Nx(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?vt(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${n}`)}return r}function vt(e,t){if(typeof e=="boolean")return e?H.any():H.never();let n=Qb(e,t);const r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const a=e.anyOf.map(c=>vt(c,t)),u=H.union(a);n=r?H.intersection(n,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>vt(c,t)),u=H.xor(a);n=r?H.intersection(n,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:H.any();else{let a=r?n:vt(e.allOf[0],t);const u=r?0:1;for(let c=u;c<e.allOf.length;c++)a=H.intersection(a,vt(e.allOf[c],t));n=a}e.nullable===!0&&t.version==="openapi-3.0"&&(n=H.nullable(n)),e.readOnly===!0&&(n=H.readonly(n)),e.default!==void 0&&(n=n.default(e.default));const i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of o)a in e&&(i[a]=e[a]);const s=["contentEncoding","contentMediaType","contentSchema"];for(const a of s)a in e&&(i[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!ci(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(const a of["minProperties","maxProperties"])e[a]!==void 0&&(i[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!ci(e.contains)&&(i.contains=e.contains);for(const a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(i[a]=e[a])}for(const a of Object.keys(e))xx.has(a)||At(i,a,e[a]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function ew(e,t){if(typeof e=="boolean")return e?H.any():H.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const r=Ex(n,t?.defaultTarget),i=n.$defs||n.definitions||{},o={version:r,defs:i,refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??Et};return vt(n,o)}function tw(e){return nd(e,{object:t=>t.partial(),union:t=>{const n=t._zod.def;return n.discriminator===void 0?t:Ee(n.options)}})}function Lx(e,t){if(!t?.length)return e;const n=e._zod.def;return Be(e,dt(n,{checks:[...n.checks??[],...t]}),{parent:!0})}function nw(e){return Lx(e.out,e.checks)}function zx(e){return e.in._zod.traits.has("$ZodTransform")?nw(e):e.in}function rw(e){return nd(e,{pipe:t=>zx(t._zod.def),default:(t,n)=>n?Ge(t._zod.def.innerType):t,catch:(t,n)=>n?t._zod.def.innerType:t})}function iw(e){return nd(e,{pipe:t=>nw(t._zod.def),prefault:(t,n)=>n?t._zod.def.innerType:t})}function Px(e){return yv(Ar,e)}function Dx(e){return kv(Pr,e)}function Ox(e){return Av(Dr,e)}function Mx(e){return Nv(Or,e)}function Fx(e){return jv(yo,e)}const ow=Object.freeze(Object.defineProperty({__proto__:null,bigint:Mx,boolean:Ox,date:Fx,number:Dx,string:Px},Symbol.toStringTag,{value:"Module"})),Qh=Object.freeze(Object.defineProperty({__proto__:null,$brand:Rc,$input:Sl,$output:kl,INVALID:wt,NEVER:Nc,TimePrecision:ql,ZodAny:ua,ZodArray:fa,ZodBase64:co,ZodBase64URL:lo,ZodBigInt:Or,ZodBigIntFormat:po,ZodBoolean:Dr,ZodCIDRv4:ao,ZodCIDRv6:uo,ZodCUID:eo,ZodCUID2:to,ZodCatch:Na,ZodCodec:Zr,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ae,ZodCreditCard:ra,ZodCustom:Br,ZodCustomStringFormat:Ln,ZodDate:yo,ZodDefault:Ea,ZodDiscriminatedUnion:pa,ZodE164:fo,ZodEmail:Ji,ZodEmoji:Xi,ZodEnum:Xn,ZodError:Wb,ZodExactOptional:wo,ZodFile:_a,get ZodFirstPartyTypeKind(){return ps},ZodFunction:Ga,ZodGUID:Yi,ZodIBAN:ia,ZodIPv4:oo,ZodIPv6:so,ZodISODate:Nr,ZodISODateTime:Ir,ZodISODuration:Lr,ZodISOTime:Rr,ZodInstanceOf:Va,ZodIntersection:ma,ZodIssueCode:Kb,ZodJWT:ho,ZodKSUID:io,ZodLazy:Ma,ZodLiteral:wa,ZodMAC:na,ZodMap:va,ZodNaN:La,ZodNanoID:Qi,ZodNever:la,ZodNonOptional:_o,ZodNull:aa,ZodNullable:xa,ZodNumber:Pr,ZodNumberFormat:zn,ZodObject:Mr,ZodOptional:Gr,ZodPipe:jr,ZodPrefault:Ta,ZodPreprocess:za,ZodPromise:Ua,ZodReadonly:Pa,ZodRealError:St,ZodRecord:Yn,ZodSet:ba,ZodString:Ar,ZodStringFormat:De,ZodSuccess:Ia,ZodSymbol:oa,ZodTemplateLiteral:Oa,ZodTransform:ka,ZodTuple:ga,ZodType:be,ZodULID:no,ZodURL:zr,ZodUUID:Kt,ZodUndefined:sa,ZodUnion:Fr,ZodUnknown:ca,ZodVoid:da,ZodXID:ro,ZodXor:ha,_ZodString:Ki,_default:$a,_function:br,any:go,array:le,base64:Dd,base64url:Od,bigint:Yd,boolean:Pe,catch:Ra,check:wf,cidrv4:zd,cidrv6:Pd,clone:Be,codec:gf,coerce:ow,compile:xl,config:Qe,core:Vb,creditCard:Fd,cuid:$d,cuid2:Td,currencyCode:Vd,custom:ja,date:nf,decode:cd,decodeAsync:dd,deepPartial:tw,describe:_f,discriminatedUnion:vo,e164:Md,email:gd,emoji:xd,encode:ud,encodeAsync:ld,endsWith:Gi,enum:at,exactOptional:Sa,file:ff,flattenError:Ps,float32:qd,float64:Wd,formatError:Ds,fromJSONSchema:ew,function:br,getDiscriminatedOption:hl,getErrorMap:Yb,globalRegistry:Et,gt:mn,gte:Ct,guid:yd,hash:Hd,hex:Bd,hostname:Zd,httpUrl:Sd,iban:Ud,includes:Fi,input:rw,instanceof:Sf,int:mi,int32:Kd,int64:Xd,intersection:Ur,invertCodec:yf,ipv4:Nd,ipv6:Ld,iso:$f,json:Ef,jwt:Gd,keyof:rf,ksuid:Id,lazy:Fa,length:Tr,literal:$,locales:_l,looseObject:st,looseRecord:uf,lowercase:Oi,lt:pn,lte:Tt,mac:Rd,map:cf,maxLength:$r,maxSize:Qn,memoizer:Vs,meta:kf,mime:Zi,minLength:Nn,minSize:gn,multipleOf:Kn,nan:mf,nanoid:Ed,nativeEnum:df,negative:Xs,never:Jn,nonnegative:ea,nonoptional:Aa,nonpositive:Qs,normalize:Bi,null:mo,nullable:vr,nullish:hf,number:ve,object:C,optional:Ge,output:iw,overwrite:tn,parse:id,parseAsync:od,partialRecord:af,pipe:gi,positive:Ys,prefault:Ca,preprocess:ko,prettifyError:zc,promise:bf,properties:ji,property:ta,readonly:Da,record:Te,refine:Za,regex:Di,regexes:Us,registry:Hs,safeDecode:hd,safeDecodeAsync:md,safeEncode:fd,safeEncodeAsync:pd,safeParse:sd,safeParseAsync:ad,set:lf,setErrorMap:Jb,size:Er,slugify:Wi,startsWith:Ui,strictObject:of,string:E,stringFormat:jd,stringbool:xf,success:pf,superRefine:Ba,symbol:ef,templateLiteral:vf,toJSONSchema:td,toLowerCase:Hi,toUpperCase:qi,toZod:Cs,transform:bo,treeifyError:Lc,trim:Vi,tuple:ya,uint32:Jd,uint64:Qd,ulid:Cd,undefined:yr,union:Ee,unknown:Ne,uppercase:Mi,url:kd,util:Ic,uuid:vd,uuidv4:bd,uuidv6:wd,uuidv7:_d,validate:Ms,validateAsync:Fs,void:tf,withParser:qs,xid:Ad,xor:sf},Symbol.toStringTag,{value:"Module"})),Ux=Object.freeze(Object.defineProperty({__proto__:null,$brand:Rc,$input:Sl,$output:kl,INVALID:wt,NEVER:Nc,TimePrecision:ql,ZodAny:ua,ZodArray:fa,ZodBase64:co,ZodBase64URL:lo,ZodBigInt:Or,ZodBigIntFormat:po,ZodBoolean:Dr,ZodCIDRv4:ao,ZodCIDRv6:uo,ZodCUID:eo,ZodCUID2:to,ZodCatch:Na,ZodCodec:Zr,ZodCompileAsyncError:hn,ZodCompileUnsupportedError:Ae,ZodCreditCard:ra,ZodCustom:Br,ZodCustomStringFormat:Ln,ZodDate:yo,ZodDefault:Ea,ZodDiscriminatedUnion:pa,ZodE164:fo,ZodEmail:Ji,ZodEmoji:Xi,ZodEnum:Xn,ZodError:Wb,ZodExactOptional:wo,ZodFile:_a,get ZodFirstPartyTypeKind(){return ps},ZodFunction:Ga,ZodGUID:Yi,ZodIBAN:ia,ZodIPv4:oo,ZodIPv6:so,ZodISODate:Nr,ZodISODateTime:Ir,ZodISODuration:Lr,ZodISOTime:Rr,ZodInstanceOf:Va,ZodIntersection:ma,ZodIssueCode:Kb,ZodJWT:ho,ZodKSUID:io,ZodLazy:Ma,ZodLiteral:wa,ZodMAC:na,ZodMap:va,ZodNaN:La,ZodNanoID:Qi,ZodNever:la,ZodNonOptional:_o,ZodNull:aa,ZodNullable:xa,ZodNumber:Pr,ZodNumberFormat:zn,ZodObject:Mr,ZodOptional:Gr,ZodPipe:jr,ZodPrefault:Ta,ZodPreprocess:za,ZodPromise:Ua,ZodReadonly:Pa,ZodRealError:St,ZodRecord:Yn,ZodSet:ba,ZodString:Ar,ZodStringFormat:De,ZodSuccess:Ia,ZodSymbol:oa,ZodTemplateLiteral:Oa,ZodTransform:ka,ZodTuple:ga,ZodType:be,ZodULID:no,ZodURL:zr,ZodUUID:Kt,ZodUndefined:sa,ZodUnion:Fr,ZodUnknown:ca,ZodVoid:da,ZodXID:ro,ZodXor:ha,_ZodString:Ki,_default:$a,_function:br,any:go,array:le,base64:Dd,base64url:Od,bigint:Yd,boolean:Pe,catch:Ra,check:wf,cidrv4:zd,cidrv6:Pd,clone:Be,codec:gf,coerce:ow,compile:xl,config:Qe,core:Vb,creditCard:Fd,cuid:$d,cuid2:Td,currencyCode:Vd,custom:ja,date:nf,decode:cd,decodeAsync:dd,deepPartial:tw,default:Qh,describe:_f,discriminatedUnion:vo,e164:Md,email:gd,emoji:xd,encode:ud,encodeAsync:ld,endsWith:Gi,enum:at,exactOptional:Sa,file:ff,flattenError:Ps,float32:qd,float64:Wd,formatError:Ds,fromJSONSchema:ew,function:br,getDiscriminatedOption:hl,getErrorMap:Yb,globalRegistry:Et,gt:mn,gte:Ct,guid:yd,hash:Hd,hex:Bd,hostname:Zd,httpUrl:Sd,iban:Ud,includes:Fi,input:rw,instanceof:Sf,int:mi,int32:Kd,int64:Xd,intersection:Ur,invertCodec:yf,ipv4:Nd,ipv6:Ld,iso:$f,json:Ef,jwt:Gd,keyof:rf,ksuid:Id,lazy:Fa,length:Tr,literal:$,locales:_l,looseObject:st,looseRecord:uf,lowercase:Oi,lt:pn,lte:Tt,mac:Rd,map:cf,maxLength:$r,maxSize:Qn,memoizer:Vs,meta:kf,mime:Zi,minLength:Nn,minSize:gn,multipleOf:Kn,nan:mf,nanoid:Ed,nativeEnum:df,negative:Xs,never:Jn,nonnegative:ea,nonoptional:Aa,nonpositive:Qs,normalize:Bi,null:mo,nullable:vr,nullish:hf,number:ve,object:C,optional:Ge,output:iw,overwrite:tn,parse:id,parseAsync:od,partialRecord:af,pipe:gi,positive:Ys,prefault:Ca,preprocess:ko,prettifyError:zc,promise:bf,properties:ji,property:ta,readonly:Da,record:Te,refine:Za,regex:Di,regexes:Us,registry:Hs,safeDecode:hd,safeDecodeAsync:md,safeEncode:fd,safeEncodeAsync:pd,safeParse:sd,safeParseAsync:ad,set:lf,setErrorMap:Jb,size:Er,slugify:Wi,startsWith:Ui,strictObject:of,string:E,stringFormat:jd,stringbool:xf,success:pf,superRefine:Ba,symbol:ef,templateLiteral:vf,toJSONSchema:td,toLowerCase:Hi,toUpperCase:qi,toZod:Cs,transform:bo,treeifyError:Lc,trim:Vi,tuple:ya,uint32:Jd,uint64:Qd,ulid:Cd,undefined:yr,union:Ee,unknown:Ne,uppercase:Mi,url:kd,util:Ic,uuid:vd,uuidv4:bd,uuidv6:wd,uuidv7:_d,validate:Ms,validateAsync:Fs,void:tf,withParser:qs,xid:Ad,xor:sf,z:Qh},Symbol.toStringTag,{value:"Module"})),Zn="io.modelcontextprotocol/related-task",Ha="2.0",Xe=ja(e=>e!==null&&(typeof e=="object"||typeof e=="function")),sw=Ee([E(),ve().int()]),aw=E();st({ttl:ve().optional(),pollInterval:ve().optional()});const Gx=C({ttl:ve().optional()}),jx=C({taskId:E()}),Tf=st({progressToken:sw.optional(),[Zn]:jx.optional()}),Nt=C({_meta:Tf.optional()}),So=Nt.extend({task:Gx.optional()}),Zx=e=>So.safeParse(e).success,ut=C({method:E(),params:Nt.loose().optional()}),Ft=C({_meta:Tf.optional()}),Ut=C({method:E(),params:Ft.loose().optional()}),ct=st({_meta:Tf.optional()}),xo=Ee([E(),ve().int()]),uw=C({jsonrpc:$(Ha),id:xo,...ut.shape}).strict(),ep=e=>uw.safeParse(e).success,cw=C({jsonrpc:$(Ha),...Ut.shape}).strict(),Bx=e=>cw.safeParse(e).success,Cf=C({jsonrpc:$(Ha),id:xo,result:ct}).strict(),Uo=e=>Cf.safeParse(e).success;var Ie;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ie||(Ie={}));const Af=C({jsonrpc:$(Ha),id:xo.optional(),error:C({code:ve().int(),message:E(),data:Ne().optional()})}).strict(),Vx=e=>Af.safeParse(e).success,Hx=Ee([uw,cw,Cf,Af]);Ee([Cf,Af]);const If=ct.strict(),qx=Ft.extend({requestId:xo.optional(),reason:E().optional()}),Nf=Ut.extend({method:$("notifications/cancelled"),params:qx}),Wx=C({src:E(),mimeType:E().optional(),sizes:le(E()).optional(),theme:at(["light","dark"]).optional()}),Eo=C({icons:le(Wx).optional()}),wr=C({name:E(),title:E().optional()}),qa=wr.extend({...wr.shape,...Eo.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),Kx=Ur(C({applyDefaults:Pe().optional()}),Te(E(),Ne())),Jx=ko(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ur(C({form:Kx.optional(),url:Xe.optional()}),Te(E(),Ne()).optional())),Yx=st({list:Xe.optional(),cancel:Xe.optional(),requests:st({sampling:st({createMessage:Xe.optional()}).optional(),elicitation:st({create:Xe.optional()}).optional()}).optional()}),Xx=st({list:Xe.optional(),cancel:Xe.optional(),requests:st({tools:st({call:Xe.optional()}).optional()}).optional()}),Qx=C({experimental:Te(E(),Xe).optional(),sampling:C({context:Xe.optional(),tools:Xe.optional()}).optional(),elicitation:Jx.optional(),roots:C({listChanged:Pe().optional()}).optional(),tasks:Yx.optional(),extensions:Te(E(),Xe).optional()}),eE=Nt.extend({protocolVersion:E(),capabilities:Qx,clientInfo:qa}),tE=ut.extend({method:$("initialize"),params:eE}),nE=C({experimental:Te(E(),Xe).optional(),logging:Xe.optional(),completions:Xe.optional(),prompts:C({listChanged:Pe().optional()}).optional(),resources:C({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:C({listChanged:Pe().optional()}).optional(),tasks:Xx.optional(),extensions:Te(E(),Xe).optional()}),rE=ct.extend({protocolVersion:E(),capabilities:nE,serverInfo:qa,instructions:E().optional()}),iE=Ut.extend({method:$("notifications/initialized"),params:Ft.optional()}),Wa=ut.extend({method:$("ping"),params:Nt.optional()}),oE=C({progress:ve(),total:Ge(ve()),message:Ge(E())}),sE=C({...Ft.shape,...oE.shape,progressToken:sw}),Rf=Ut.extend({method:$("notifications/progress"),params:sE}),aE=Nt.extend({cursor:aw.optional()}),$o=ut.extend({params:aE.optional()}),To=ct.extend({nextCursor:aw.optional()}),uE=at(["working","input_required","completed","failed","cancelled"]),Co=C({taskId:E(),status:uE,ttl:Ee([ve(),mo()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:Ge(ve()),statusMessage:Ge(E())}),Lf=ct.extend({task:Co}),cE=Ft.merge(Co),ms=Ut.extend({method:$("notifications/tasks/status"),params:cE}),zf=ut.extend({method:$("tasks/get"),params:Nt.extend({taskId:E()})}),Pf=ct.merge(Co),Df=ut.extend({method:$("tasks/result"),params:Nt.extend({taskId:E()})});ct.loose();const Of=$o.extend({method:$("tasks/list")}),Mf=To.extend({tasks:le(Co)}),Ff=ut.extend({method:$("tasks/cancel"),params:Nt.extend({taskId:E()})}),lE=ct.merge(Co),lw=C({uri:E(),mimeType:Ge(E()),_meta:Te(E(),Ne()).optional()}),dw=lw.extend({text:E()}),Uf=E().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),fw=lw.extend({blob:Uf}),Ao=at(["user","assistant"]),Vr=C({audience:le(Ao).optional(),priority:ve().min(0).max(1).optional(),lastModified:Xb({offset:!0}).optional()}),hw=C({...wr.shape,...Eo.shape,uri:E(),description:Ge(E()),mimeType:Ge(E()),size:Ge(ve()),annotations:Vr.optional(),_meta:Ge(st({}))}),dE=C({...wr.shape,...Eo.shape,uriTemplate:E(),description:Ge(E()),mimeType:Ge(E()),annotations:Vr.optional(),_meta:Ge(st({}))}),fE=$o.extend({method:$("resources/list")}),pw=To.extend({resources:le(hw)}),hE=$o.extend({method:$("resources/templates/list")}),pE=To.extend({resourceTemplates:le(dE)}),Gf=Nt.extend({uri:E()}),mE=Gf,gE=ut.extend({method:$("resources/read"),params:mE}),mw=ct.extend({contents:le(Ee([dw,fw]))}),yE=Ut.extend({method:$("notifications/resources/list_changed"),params:Ft.optional()}),vE=Gf,bE=ut.extend({method:$("resources/subscribe"),params:vE}),wE=Gf,_E=ut.extend({method:$("resources/unsubscribe"),params:wE}),kE=Ft.extend({uri:E()}),SE=Ut.extend({method:$("notifications/resources/updated"),params:kE}),xE=C({name:E(),description:Ge(E()),required:Ge(Pe())}),EE=C({...wr.shape,...Eo.shape,description:Ge(E()),arguments:Ge(le(xE)),_meta:Ge(st({}))}),$E=$o.extend({method:$("prompts/list")}),TE=To.extend({prompts:le(EE)}),CE=Nt.extend({name:E(),arguments:Te(E(),E()).optional()}),AE=ut.extend({method:$("prompts/get"),params:CE}),jf=C({type:$("text"),text:E(),annotations:Vr.optional(),_meta:Te(E(),Ne()).optional()}),Zf=C({type:$("image"),data:Uf,mimeType:E(),annotations:Vr.optional(),_meta:Te(E(),Ne()).optional()}),Bf=C({type:$("audio"),data:Uf,mimeType:E(),annotations:Vr.optional(),_meta:Te(E(),Ne()).optional()}),IE=C({type:$("tool_use"),name:E(),id:E(),input:Te(E(),Ne()),_meta:Te(E(),Ne()).optional()}),gw=C({type:$("resource"),resource:Ee([dw,fw]),annotations:Vr.optional(),_meta:Te(E(),Ne()).optional()}),yw=hw.extend({type:$("resource_link")}),Io=Ee([jf,Zf,Bf,yw,gw]),NE=C({role:Ao,content:Io}),RE=ct.extend({description:E().optional(),messages:le(NE)}),LE=Ut.extend({method:$("notifications/prompts/list_changed"),params:Ft.optional()}),zE=C({title:E().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),PE=C({taskSupport:at(["required","optional","forbidden"]).optional()}),Vf=C({...wr.shape,...Eo.shape,description:E().optional(),inputSchema:C({type:$("object"),properties:Te(E(),Xe).optional(),required:le(E()).optional()}).catchall(Ne()),outputSchema:C({type:$("object"),properties:Te(E(),Xe).optional(),required:le(E()).optional()}).catchall(Ne()).optional(),annotations:zE.optional(),execution:PE.optional(),_meta:Te(E(),Ne()).optional()}),vw=$o.extend({method:$("tools/list")}),DE=To.extend({tools:le(Vf)}),Ka=ct.extend({content:le(Io).default([]),structuredContent:Te(E(),Ne()).optional(),isError:Pe().optional()});Ka.or(ct.extend({toolResult:Ne()}));const OE=So.extend({name:E(),arguments:Te(E(),Ne()).optional()}),bw=ut.extend({method:$("tools/call"),params:OE}),ME=Ut.extend({method:$("notifications/tools/list_changed"),params:Ft.optional()});C({autoRefresh:Pe().default(!0),debounceMs:ve().int().nonnegative().default(300)});const ww=at(["debug","info","notice","warning","error","critical","alert","emergency"]),FE=Nt.extend({level:ww}),UE=ut.extend({method:$("logging/setLevel"),params:FE}),GE=Ft.extend({level:ww,logger:E().optional(),data:Ne()}),jE=Ut.extend({method:$("notifications/message"),params:GE}),ZE=C({name:E().optional()}),BE=C({hints:le(ZE).optional(),costPriority:ve().min(0).max(1).optional(),speedPriority:ve().min(0).max(1).optional(),intelligencePriority:ve().min(0).max(1).optional()}),VE=C({mode:at(["auto","required","none"]).optional()}),HE=C({type:$("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:le(Io).default([]),structuredContent:C({}).loose().optional(),isError:Pe().optional(),_meta:Te(E(),Ne()).optional()}),qE=vo("type",[jf,Zf,Bf]),gs=vo("type",[jf,Zf,Bf,IE,HE]),WE=C({role:Ao,content:Ee([gs,le(gs)]),_meta:Te(E(),Ne()).optional()}),KE=So.extend({messages:le(WE),modelPreferences:BE.optional(),systemPrompt:E().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:ve().optional(),maxTokens:ve().int(),stopSequences:le(E()).optional(),metadata:Xe.optional(),tools:le(Vf).optional(),toolChoice:VE.optional()}),JE=ut.extend({method:$("sampling/createMessage"),params:KE}),_w=ct.extend({model:E(),stopReason:Ge(at(["endTurn","stopSequence","maxTokens"]).or(E())),role:Ao,content:qE}),kw=ct.extend({model:E(),stopReason:Ge(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:Ao,content:Ee([gs,le(gs)])}),YE=C({type:$("boolean"),title:E().optional(),description:E().optional(),default:Pe().optional()}),XE=C({type:$("string"),title:E().optional(),description:E().optional(),minLength:ve().optional(),maxLength:ve().optional(),format:at(["email","uri","date","date-time"]).optional(),default:E().optional()}),QE=C({type:at(["number","integer"]),title:E().optional(),description:E().optional(),minimum:ve().optional(),maximum:ve().optional(),default:ve().optional()}),e$=C({type:$("string"),title:E().optional(),description:E().optional(),enum:le(E()),default:E().optional()}),t$=C({type:$("string"),title:E().optional(),description:E().optional(),oneOf:le(C({const:E(),title:E()})),default:E().optional()}),n$=C({type:$("string"),title:E().optional(),description:E().optional(),enum:le(E()),enumNames:le(E()).optional(),default:E().optional()}),r$=Ee([e$,t$]),i$=C({type:$("array"),title:E().optional(),description:E().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:C({type:$("string"),enum:le(E())}),default:le(E()).optional()}),o$=C({type:$("array"),title:E().optional(),description:E().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:C({anyOf:le(C({const:E(),title:E()}))}),default:le(E()).optional()}),s$=Ee([i$,o$]),a$=Ee([n$,r$,s$]),u$=Ee([a$,YE,XE,QE]),c$=So.extend({mode:$("form").optional(),message:E(),requestedSchema:C({type:$("object"),properties:Te(E(),u$),required:le(E()).optional()})}),l$=So.extend({mode:$("url"),message:E(),elicitationId:E(),url:E().url()}),d$=Ee([c$,l$]),f$=ut.extend({method:$("elicitation/create"),params:d$}),h$=Ft.extend({elicitationId:E()}),p$=Ut.extend({method:$("notifications/elicitation/complete"),params:h$}),m$=ct.extend({action:at(["accept","decline","cancel"]),content:ko(e=>e===null?void 0:e,Te(E(),Ee([E(),ve(),Pe(),le(E())])).optional())}),g$=C({type:$("ref/resource"),uri:E()}),y$=C({type:$("ref/prompt"),name:E()}),v$=Nt.extend({ref:Ee([y$,g$]),argument:C({name:E(),value:E()}),context:C({arguments:Te(E(),E()).optional()}).optional()}),b$=ut.extend({method:$("completion/complete"),params:v$}),w$=ct.extend({completion:st({values:le(E()).max(100),total:Ge(ve().int()),hasMore:Ge(Pe())})}),_$=C({uri:E().startsWith("file://"),name:E().optional(),_meta:Te(E(),Ne()).optional()}),k$=ut.extend({method:$("roots/list"),params:Nt.optional()}),S$=ct.extend({roots:le(_$)}),x$=Ut.extend({method:$("notifications/roots/list_changed"),params:Ft.optional()});Ee([Wa,tE,b$,UE,AE,$E,fE,hE,gE,bE,_E,bw,vw,zf,Df,Of,Ff]);Ee([Nf,Rf,iE,x$,ms]);Ee([If,_w,kw,m$,S$,Pf,Mf,Lf]);Ee([Wa,JE,f$,k$,zf,Df,Of,Ff]);Ee([Nf,Rf,jE,SE,yE,ME,LE,ms,p$]);Ee([If,rE,w$,RE,TE,pw,pE,mw,Ka,DE,Pf,Mf,Lf]);class Ce extends Error{constructor(t,n,r){super(`MCP error ${t}: ${n}`),this.code=t,this.data=r,this.name="McpError"}static fromError(t,n,r){if(t===Ie.UrlElicitationRequired&&r){const i=r;if(i.elicitations)return new E$(i.elicitations,n)}return new Ce(t,n,r)}}class E$ extends Ce{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(Ie.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}function Fn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tp(e){const n=px(e)?.method;if(!n)throw new Error("Schema is missing a method literal");const r=mx(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function np(e,t){const n=Hb(e,t);if(!n.success)throw n.error;return n.data}const $$=6e4;class T${constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Nf,n=>{this._oncancel(n)}),this.setNotificationHandler(Rf,n=>{this._onprogress(n)}),this.setRequestHandler(Wa,n=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zf,async(n,r)=>{const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new Ce(Ie.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Df,async(n,r)=>{const i=async()=>{const o=n.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ce(Ie.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){const u=a.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),a.type==="response")l(u);else{const d=u,f=new Ce(d.error.code,d.error.message,d.error.data);l(f)}else{const d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new Ce(Ie.InvalidParams,`Task not found: ${o}`);if(!Fn(s.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await i();if(Fn(s.status)){const a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...a,_meta:{...a._meta,[Zn]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Of,async(n,r)=>{try{const{tasks:i,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new Ce(Ie.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Ff,async(n,r)=>{try{const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new Ce(Ie.InvalidParams,`Task not found: ${n.params.taskId}`);if(Fn(i.status))throw new Ce(Ie.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId,r.sessionId);const o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Ce(Ie.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof Ce?i:new Ce(Ie.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,n,r,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){const n=this._timeoutInfo.get(t);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),Ce.fromError(Ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){const n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),Uo(o)||Vx(o)?this._onresponse(o):ep(o)?this._onrequest(o,s):Bx(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const n=Ce.fromError(Ie.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of t.values())r(n)}_onerror(t){this.onerror?.(t)}_onnotification(t){const n=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(t,n){const r=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[Zn]?.taskId,s=i?.sessionId,a=this._taskStore;let u=!0,c;if(o&&a&&this._taskMessageQueue&&s!==void 0&&(u=!1,c=(async()=>{if(!await a.getTask(o,s))throw new Ce(Ie.InvalidParams,`Task not found: ${o}`);u=!0})()),r===void 0){const p={jsonrpc:"2.0",id:t.id,error:{code:Ie.MethodNotFound,message:"Method not found"}};if(o&&c){const m={type:"error",message:p,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,m,s),()=>i?.send(p)).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)))}else o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):i?.send(p).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(t.id,l);const d=Zx(t.params)?t.params.task:void 0,f=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,h={signal:l.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async p=>{if(l.signal.aborted)return;const m={relatedRequestId:t.id};o&&(m.relatedTask={taskId:o}),await this.notification(p,m)},sendRequest:async(p,m,y)=>{if(l.signal.aborted)throw new Ce(Ie.ConnectionClosed,"Request was cancelled");const _={...y,relatedRequestId:t.id};o&&!_.relatedTask&&(_.relatedTask={taskId:o});const g=_.relatedTask?.taskId??o;return g&&f&&await f.updateTaskStatus(g,"input_required"),await this.request(p,m,_)},authInfo:n?.authInfo,requestId:t.id,requestInfo:n?.requestInfo,taskId:o,taskStore:f,taskRequestedTtl:d?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Ce(Ie.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(t.method)}).then(()=>r(t,h)).then(async p=>{if(l.signal.aborted)return;const m={result:p,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:m,timestamp:Date.now()},i?.sessionId):await i?.send(m)},async p=>{if(l.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(p.code)?p.code:Ie.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue&&u?await this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},i?.sessionId):await i?.send(m)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===l&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:n,...r}=t.params,i=Number(n),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(u){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(u);return}o(r)}_onresponse(t){const n=Number(t.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Uo(t))r(t);else{const s=new Ce(t.error.code,t.error.message,t.error.data);r(s)}return}const i=this._responseHandlers.get(n);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Uo(t)&&t.result&&typeof t.result=="object"){const s=t.result;if(s.task&&typeof s.task=="object"){const a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,n))}}if(o||this._progressHandlers.delete(n),Uo(t))i(t);else{const s=Ce.fromError(t.error.code,t.error.message,t.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,n,r){const{task:i}=r??{};if(!i){try{yield{type:"result",result:await this.request(t,n,r)}}catch(s){yield{type:"error",error:s instanceof Ce?s:new Ce(Ie.InternalError,String(s))}}return}let o;try{const s=await this.request(t,Lf,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Ce(Ie.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Fn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new Ce(Ie.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Ce(Ie.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}const u=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Ce?s:new Ce(Ie.InternalError,String(s))}}}request(t,n,r){const{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:u}=r??{};return new Promise((c,l)=>{const d=g=>{l(g)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(g){d(g);return}r?.signal?.throwIfAborted();const f=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(h.params={...h.params,task:a}),u&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Zn]:u}});const p=g=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(g)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));const b=g instanceof Ce?g:new Ce(Ie.RequestTimeout,String(g));l(b)};this._responseHandlers.set(f,g=>{if(!r?.signal?.aborted){if(g instanceof Error)return l(g);try{const b=Hb(n,g.result);b.success?c(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const m=r?.timeout??$$,y=()=>p(Ce.fromError(Ie.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);const _=u?.taskId;if(_){const g=b=>{const v=this._responseHandlers.get(f);v?v(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,g),this._enqueueTaskMessage(_,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),l(b)})}else this._transport.send(h,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(g=>{this._cleanupTimeout(f),l(g)})})}async getTask(t,n){return this.request({method:"tasks/get",params:t},Pf,n)}async getTaskResult(t,n,r){return this.request({method:"tasks/result",params:t},n,r)}async listTasks(t,n){return this.request({method:"tasks/list",params:t},Mf,n)}async cancelTask(t,n){return this.request({method:"tasks/cancel",params:t},lE,n)}async notification(t,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const r=n?.relatedTask?.taskId;if(r){const a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Zn]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Zn]:n.relatedTask}}}),this._transport?.send(a,n).catch(u=>this._onerror(u))});return}let s={...t,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Zn]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(t,n){const r=tp(t);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(i,o)=>{const s=np(t,i);return Promise.resolve(n(s,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){const r=tp(t);this._notificationHandlers.set(r,i=>{const o=np(t,i);return Promise.resolve(n(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const n=this._taskProgressTokens.get(t);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,n,r??this._transport?.sessionId,i)}async _clearTaskQueue(t,n){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(t,n);for(const i of r)if(i.type==="request"&&ep(i.message)){const o=i.message.id,s=this._requestResolvers.get(o);s?(s(new Ce(Ie.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,n,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t,r);o?.pollInterval&&(i=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Ce(Ie.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,i);n.addEventListener("abort",()=>{clearTimeout(a),s(new Ce(Ie.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,n){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await r.createTask(i,t.id,{method:t.method,params:t.params},n)},getTask:async i=>{const o=await r.getTask(i,n);if(!o)throw new Ce(Ie.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await r.storeTaskResult(i,o,s,n);const a=await r.getTask(i,n);if(a){const u=ms.parse({method:"notifications/tasks/status",params:a});await this.notification(u),Fn(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>r.getTaskResult(i,n),updateTaskStatus:async(i,o,s)=>{const a=await r.getTask(i,n);if(!a)throw new Ce(Ie.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Fn(a.status))throw new Ce(Ie.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(i,o,s,n);const u=await r.getTask(i,n);if(u){const c=ms.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Fn(u.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>r.listTasks(i,n)}}}function rp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function C$(e,t){const n={...e};for(const r in t){const i=r,o=t[i];if(o===void 0)continue;const s=n[i];rp(s)&&rp(o)?n[i]={...s,...o}:n[i]=o}return n}(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});class A$ extends T${_registeredMethods=new Set;_eventSlots=new Map;onEventDispatch(t,n){}_ensureEventSlot(t){let n=this._eventSlots.get(t);if(!n){let r=this.eventSchemas[t];if(!r)throw Error(`Unknown event: ${String(t)}`);n={listeners:[]},this._eventSlots.set(t,n);let i=r.shape.method.value;this._registeredMethods.add(i);let o=n;super.setNotificationHandler(r,s=>{let a=s.params;this.onEventDispatch(t,a),o.onHandler?.(a);for(let u of[...o.listeners])u(a)})}return n}setEventHandler(t,n){let r=this._ensureEventSlot(t);r.onHandler&&n&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", …) to add multiple listeners without replacing.`),r.onHandler=n}getEventHandler(t){return this._eventSlots.get(t)?.onHandler}addEventListener(t,n){this._ensureEventSlot(t).listeners.push(n)}removeEventListener(t,n){let r=this._eventSlots.get(t);if(!r)return;let i=r.listeners.indexOf(n);i!==-1&&r.listeners.splice(i,1)}setRequestHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setRequestHandler"),super.setRequestHandler(t,n)};setNotificationHandler=(t,n)=>{this._assertMethodNotRegistered(t,"setNotificationHandler"),super.setNotificationHandler(t,n)};warnIfRequestHandlerReplaced(t,n,r){n&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}replaceRequestHandler=(t,n)=>{let r=t.shape.method.value;this._registeredMethods.add(r),super.setRequestHandler(t,n)};_assertMethodNotRegistered(t,n){let r=t.shape.method.value;if(this._registeredMethods.has(r))throw Error(`Handler for "${r}" already registered (via ${n}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(r)}}var I$="2026-01-26",N$="ui/notifications/tool-input-partial";class Sw{eventTarget;eventSource;messageListener;constructor(t=window.parent,n){this.eventTarget=t,this.eventSource=n,this.messageListener=r=>{if(n&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let i=Hx.safeParse(r.data);i.success?(console.debug("Parsed message",i.data),this.onmessage?.(i.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",i.error.message,r):(console.error("Failed to parse message",i.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+i.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,n){t.method!==N$&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var R$=Ee([$("light"),$("dark")]).describe("Color theme preference for the host environment."),yi=Ee([$("inline"),$("fullscreen"),$("pip")]).describe("Display mode for UI presentation."),L$=Ee([$("--color-background-primary"),$("--color-background-secondary"),$("--color-background-tertiary"),$("--color-background-inverse"),$("--color-background-ghost"),$("--color-background-info"),$("--color-background-danger"),$("--color-background-success"),$("--color-background-warning"),$("--color-background-disabled"),$("--color-text-primary"),$("--color-text-secondary"),$("--color-text-tertiary"),$("--color-text-inverse"),$("--color-text-ghost"),$("--color-text-info"),$("--color-text-danger"),$("--color-text-success"),$("--color-text-warning"),$("--color-text-disabled"),$("--color-border-primary"),$("--color-border-secondary"),$("--color-border-tertiary"),$("--color-border-inverse"),$("--color-border-ghost"),$("--color-border-info"),$("--color-border-danger"),$("--color-border-success"),$("--color-border-warning"),$("--color-border-disabled"),$("--color-ring-primary"),$("--color-ring-secondary"),$("--color-ring-inverse"),$("--color-ring-info"),$("--color-ring-danger"),$("--color-ring-success"),$("--color-ring-warning"),$("--font-sans"),$("--font-mono"),$("--font-weight-normal"),$("--font-weight-medium"),$("--font-weight-semibold"),$("--font-weight-bold"),$("--font-text-xs-size"),$("--font-text-sm-size"),$("--font-text-md-size"),$("--font-text-lg-size"),$("--font-heading-xs-size"),$("--font-heading-sm-size"),$("--font-heading-md-size"),$("--font-heading-lg-size"),$("--font-heading-xl-size"),$("--font-heading-2xl-size"),$("--font-heading-3xl-size"),$("--font-text-xs-line-height"),$("--font-text-sm-line-height"),$("--font-text-md-line-height"),$("--font-text-lg-line-height"),$("--font-heading-xs-line-height"),$("--font-heading-sm-line-height"),$("--font-heading-md-line-height"),$("--font-heading-lg-line-height"),$("--font-heading-xl-line-height"),$("--font-heading-2xl-line-height"),$("--font-heading-3xl-line-height"),$("--border-radius-xs"),$("--border-radius-sm"),$("--border-radius-md"),$("--border-radius-lg"),$("--border-radius-xl"),$("--border-radius-full"),$("--border-width-regular"),$("--shadow-hairline"),$("--shadow-sm"),$("--shadow-md"),$("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),z$=Te(L$.describe(`Style variables for theming MCP apps.
71
71
 
72
72
  Individual style keys are optional - hosts may provide any subset of these values.
73
73
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
74
74
 
75
75
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
76
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),$e([E(),gr()]).describe(`Style variables for theming MCP apps.
76
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Ee([E(),yr()]).describe(`Style variables for theming MCP apps.
77
77
 
78
78
  Individual style keys are optional - hosts may provide any subset of these values.
79
79
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -85,10 +85,10 @@ Individual style keys are optional - hosts may provide any subset of these value
85
85
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
86
86
 
87
87
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
88
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);C({method:$("ui/open-link"),params:C({url:E().describe("URL to open in the host's browser")})});var R$=C({isError:Pe().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),L$=C({isError:Pe().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),z$=C({isError:Pe().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();C({method:$("ui/notifications/sandbox-proxy-ready"),params:C({})});var Hf=C({connectDomains:de(E()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
88
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);C({method:$("ui/open-link"),params:C({url:E().describe("URL to open in the host's browser")})});var P$=C({isError:Pe().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),D$=C({isError:Pe().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),O$=C({isError:Pe().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();C({method:$("ui/notifications/sandbox-proxy-ready"),params:C({})});var Hf=C({connectDomains:le(E()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
89
89
 
90
90
  - Maps to CSP \`connect-src\` directive
91
- - Empty or omitted → no network connections (secure default)`),resourceDomains:de(E()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:de(E()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:de(E()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Vf=C({camera:C({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:C({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:C({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:C({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")});C({method:$("ui/notifications/size-changed"),params:C({width:we().optional().describe("New width in pixels."),height:we().optional().describe("New height in pixels.")})});var P$=C({method:$("ui/notifications/tool-input"),params:C({arguments:Ce(E(),Re().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),D$=C({method:$("ui/notifications/tool-input-partial"),params:C({arguments:Ce(E(),Re().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),O$=C({method:$("ui/notifications/tool-cancelled"),params:C({reason:E().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),M$=C({fonts:E().optional()}),F$=C({variables:N$.optional().describe("CSS variables for theming the app."),css:M$.optional().describe("CSS blocks that apps can inject.")}),U$=C({method:$("ui/resource-teardown"),params:C({})});Ce(E(),Re());var np=C({text:C({}).optional().describe("Host supports text content blocks."),image:C({}).optional().describe("Host supports image content blocks."),audio:C({}).optional().describe("Host supports audio content blocks."),resource:C({}).optional().describe("Host supports resource content blocks."),resourceLink:C({}).optional().describe("Host supports resource link content blocks."),structuredContent:C({}).optional().describe("Host supports structured content.")});C({method:$("ui/notifications/request-teardown"),params:C({}).optional()});var G$=C({experimental:Ce(E(),Ce(E(),po()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:C({}).optional().describe("Host supports opening external URLs."),downloadFile:C({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:C({listChanged:Pe().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:C({listChanged:Pe().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:C({}).optional().describe("Host accepts log messages."),sandbox:C({permissions:Vf.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Hf.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:np.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:np.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:C({tools:C({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),j$=C({experimental:Ce(E(),Ce(E(),po()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:C({listChanged:Pe().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:de(mi).optional().describe("Display modes the app supports.")});C({method:$("ui/notifications/initialized"),params:C({}).optional()});C({csp:Hf.optional().describe("Content Security Policy configuration for UI resources."),permissions:Vf.optional().describe("Sandbox permissions requested by the UI resource."),domain:E().optional().describe(`Dedicated origin for view sandbox.
91
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:le(E()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:le(E()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:le(E()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),qf=C({camera:C({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:C({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:C({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:C({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")});C({method:$("ui/notifications/size-changed"),params:C({width:ve().optional().describe("New width in pixels."),height:ve().optional().describe("New height in pixels.")})});var M$=C({method:$("ui/notifications/tool-input"),params:C({arguments:Te(E(),Ne().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),F$=C({method:$("ui/notifications/tool-input-partial"),params:C({arguments:Te(E(),Ne().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),U$=C({method:$("ui/notifications/tool-cancelled"),params:C({reason:E().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),G$=C({fonts:E().optional()}),j$=C({variables:z$.optional().describe("CSS variables for theming the app."),css:G$.optional().describe("CSS blocks that apps can inject.")}),Z$=C({method:$("ui/resource-teardown"),params:C({})});Te(E(),Ne());var ip=C({text:C({}).optional().describe("Host supports text content blocks."),image:C({}).optional().describe("Host supports image content blocks."),audio:C({}).optional().describe("Host supports audio content blocks."),resource:C({}).optional().describe("Host supports resource content blocks."),resourceLink:C({}).optional().describe("Host supports resource link content blocks."),structuredContent:C({}).optional().describe("Host supports structured content.")});C({method:$("ui/notifications/request-teardown"),params:C({}).optional()});var B$=C({experimental:Te(E(),Te(E(),go()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:C({}).optional().describe("Host supports opening external URLs."),downloadFile:C({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:C({listChanged:Pe().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:C({listChanged:Pe().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:C({}).optional().describe("Host accepts log messages."),sandbox:C({permissions:qf.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Hf.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:ip.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:ip.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:C({tools:C({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),V$=C({experimental:Te(E(),Te(E(),go()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:C({listChanged:Pe().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:le(yi).optional().describe("Display modes the app supports.")});C({method:$("ui/notifications/initialized"),params:C({}).optional()});C({csp:Hf.optional().describe("Content Security Policy configuration for UI resources."),permissions:qf.optional().describe("Sandbox permissions requested by the UI resource."),domain:E().optional().describe(`Dedicated origin for view sandbox.
92
92
 
93
93
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
94
94
 
@@ -102,16 +102,16 @@ Boolean requesting whether a visible border and background is provided by the ho
102
102
 
103
103
  - \`true\`: request visible border + background
104
104
  - \`false\`: request no visible border + background
105
- - omitted: host decides border`)});C({method:$("ui/request-display-mode"),params:C({mode:mi.describe("The display mode being requested.")})});var Z$=C({mode:mi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),B$=$e([$("model"),$("app")]).describe("Tool visibility scope - who can access the tool.");C({resourceUri:E().optional(),visibility:de(B$).optional().describe(`Who can access this tool. Default: ["model", "app"]
105
+ - omitted: host decides border`)});C({method:$("ui/request-display-mode"),params:C({mode:yi.describe("The display mode being requested.")})});var H$=C({mode:yi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),q$=Ee([$("model"),$("app")]).describe("Tool visibility scope - who can access the tool.");C({resourceUri:E().optional(),visibility:le(q$).optional().describe(`Who can access this tool. Default: ["model", "app"]
106
106
  - "model": Tool visible to and callable by the agent
107
- - "app": Tool callable by the app from this server only`),csp:Kn().optional(),permissions:Kn().optional()});C({mimeTypes:de(E()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});C({method:$("ui/download-file"),params:C({contents:de($e([pw,mw])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});C({method:$("ui/message"),params:C({role:$("user").describe('Message role, currently only "user" is supported.'),content:de(Co).describe("Message content blocks (text, image, etc.).")})});C({method:$("ui/notifications/sandbox-resource-ready"),params:C({html:E().describe("HTML content to load into the inner iframe."),sandbox:E().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Hf.optional().describe("CSP configuration from resource metadata."),permissions:Vf.optional().describe("Sandbox permissions from resource metadata.")})});var H$=C({method:$("ui/notifications/tool-result"),params:qa.describe("Standard MCP tool execution result.")}),kw=C({toolInfo:C({id:ko.optional().describe("JSON-RPC id of the tools/call request."),tool:Bf.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:A$.optional().describe("Current color theme preference."),styles:F$.optional().describe("Style configuration for theming the app."),displayMode:mi.optional().describe("How the UI is currently displayed."),availableDisplayModes:de(mi).optional().describe("Display modes the host supports."),containerDimensions:$e([C({height:we().describe("Fixed container height in pixels.")}),C({maxHeight:$e([we(),gr()]).optional().describe("Maximum container height in pixels.")})]).and($e([C({width:we().describe("Fixed container width in pixels.")}),C({maxWidth:$e([we(),gr()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
108
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:E().optional().describe("User's language and region preference in BCP 47 format."),timeZone:E().optional().describe("User's timezone in IANA format."),userAgent:E().optional().describe("Host application identifier."),platform:$e([$("web"),$("desktop"),$("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:C({touch:Pe().optional().describe("Whether the device supports touch input."),hover:Pe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:C({top:we().describe("Top safe area inset in pixels."),right:we().describe("Right safe area inset in pixels."),bottom:we().describe("Bottom safe area inset in pixels."),left:we().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),V$=C({method:$("ui/notifications/host-context-changed"),params:kw.describe("Partial context update containing only changed fields.")});C({method:$("ui/update-model-context"),params:C({content:de(Co).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Ce(E(),Re().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});C({method:$("ui/initialize"),params:C({appInfo:Ha.describe("App identification (name and version)."),appCapabilities:j$.describe("Features and capabilities this app provides."),protocolVersion:E().describe("Protocol version this app supports.")})});var q$=C({protocolVersion:E().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ha.describe("Host application identification and version."),hostCapabilities:G$.describe("Features and capabilities provided by the host."),hostContext:kw.describe("Rich context about the host environment.")}).passthrough(),W$={target:"draft-2020-12"};async function rp(e,t){let n=e["~standard"];if(n.jsonSchema)return n.jsonSchema[t](W$);if(n.vendor==="zod"){let{z:r}=await dk(()=>Promise.resolve().then(()=>O0),void 0,import.meta.url);return r.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function ip(e,t,n=""){let r=await e["~standard"].validate(t);if(r.issues){let i=r.issues.map(o=>{let s=o.path?.map(a=>typeof a=="object"?a.key:a).join(".");return s?`${s}: ${o.message}`:o.message}).join("; ");throw Error(n+i)}return r.value}function K$(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function J$(e){if(document.getElementById("__mcp-host-fonts"))return;let t=document.createElement("style");t.id="__mcp-host-fonts",t.textContent=e,document.head.appendChild(t)}class qf extends $${_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(t){if(this._initializedSent)return;let n=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:P$,toolinputpartial:D$,toolresult:H$,toolcancelled:O$,hostcontextchanged:V$};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!qf.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(t,n){n&&this._assertHandlerTiming(t),super.setEventHandler(t,n)}addEventListener(t,n){this._assertHandlerTiming(t),super.addEventListener(t,n)}onEventDispatch(t,n){t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...n})}constructor(t,n={},r={autoResize:!0}){super(r),this._appInfo=t,this._capabilities=n,this.options=r,r.allowUnsafeEval||Qe({jitless:!0}),this.setRequestHandler(Va,i=>(console.log("Received ping:",i.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=E$(this._capabilities,t)}registerTool(t,n,r){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let i=this,o=()=>{i._initializedSent&&i._capabilities.tools?.listChanged&&i.sendToolListChanged()},s=n.inputSchema!==void 0,a={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,o()},disable(){this.enabled=!1,o()},update(u){Object.assign(this,u),o()},remove(){i._registeredTools[t]===a&&(delete i._registeredTools[t],o())},handler:async(u,c)=>{if(!a.enabled)throw Error(`Tool ${t} is disabled`);let l;if(s){let d=a.inputSchema,f=d?await ip(d,u??{},`Invalid input for tool ${t}: `):u??{};l=await r(f,c)}else l=await r(c);return a.outputSchema&&!l.isError&&(l.structuredContent=await ip(a.outputSchema,l.structuredContent,`Invalid output for tool ${t}: `)),l}};return this._registeredTools[t]=a,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),o(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,n)=>{let r=this._registeredTools[t.name];if(!r)throw Error(`Tool ${t.name} not found`);return r.handler(t.arguments,n)},this.onlisttools=async(t,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,i])=>i.enabled).map(async([r,i])=>{let o={name:r,title:i.title,description:i.description,inputSchema:i.inputSchema?await rp(i.inputSchema,"input"):{type:"object",properties:{}}};return i.outputSchema&&(o.outputSchema=await rp(i.outputSchema,"output")),i.annotations&&(o.annotations=i.annotations),i._meta&&(o._meta=i._meta),o}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler(U$,(n,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n.params,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler(yw,(n,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler(gw,(n,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,r)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${t} registered`)}}assertNotificationCapability(t){}assertTaskCapability(t){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(t){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(t,n){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},qa,{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(t,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},hw,n)}async listServerResources(t,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},fw,n)}async createSamplingMessage(t,n){this._assertInitialized("createSamplingMessage");let r=t.tools?ww:bw;return await this.request({method:"sampling/createMessage",params:t},r,n)}sendMessage(t,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},z$,n)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},Af,n)}openLink(t,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},R$,n)}sendOpenLink=this.openLink;downloadFile(t,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},L$,n)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},Z$,n)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,n=0,r=0,i=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let s=document.documentElement,a=s.style.height;s.style.height="max-content";let u=Math.ceil(s.getBoundingClientRect().height);s.style.height=a;let c=Math.ceil(window.innerWidth);(c!==n||u!==r)&&(n=c,r=u,this.sendSizeChanged({width:c,height:u}))}))};i();let o=new ResizeObserver(i);return o.observe(document.documentElement),o.observe(document.body),()=>o.disconnect()}async connect(t=new _w(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(t);try{let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:T$}},q$,n);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}}const Y$="Chain Insights graph",X$="This graph is no longer available. Ask for it again.",op="data-chain-insights-view",Q$="This window cannot reach the local Chain Insights page. Open the link in your own browser for clicks that load more",ts=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Sw=e=>!ts(e)||!ts(e.result)?null:{arguments:ts(e.arguments)?e.arguments:null,result:e.result};function eT(e,t){const n=t.querySelector(`script[type="application/json"][${op}]`);if(!n||n.getAttribute(op)!==e)return null;try{return Sw(JSON.parse(n.textContent??""))}catch{return null}}const tT=new Set(["127.0.0.1","localhost","[::1]","::1"]);function nT(e){const t=new URLSearchParams(e.search).get("view");if(t&&t.trim())return t.trim();if(!tT.has(e.hostname))return null;const n=/^\/view\/([^/]+)\/?$/.exec(e.pathname);if(!n?.[1])return null;try{return decodeURIComponent(n[1])||null}catch{return null}}async function rT(e,t,n){const r=n?eT(e,n):null;if(r)return r;try{const i=await t(`/api/view/${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});return i.ok?Sw(await i.json()):null}catch{return null}}function iT(e,t){return{async callServerTool({name:n,arguments:r}){let i;try{i=await e(`/api/tools/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({arguments:r})})}catch{throw new Error(Q$)}let o=null;try{o=await i.json()}catch{o=null}if(ts(o)&&(Array.isArray(o.content)||"structuredContent"in o||"isError"in o))return o;throw new Error(i.ok?"the local Chain Insights page answered with no tool result":`the local Chain Insights page answered HTTP ${i.status}`)},async openLink({url:n}){return t(n,"_blank","noopener"),{}}}}const xw=new Map;function oT(e,t){xw.set(e,t)}function sp(e){return xw.get(e)??null}const sT=/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i;function aT(e){try{const t=e.createElement("canvas");if(typeof t.getContext!="function")return!1;const n={failIfMajorPerformanceCaveat:!0},r=t.getContext("webgl2",n)??t.getContext("webgl",n);if(!r)return!1;const i=r.getExtension?.("WEBGL_debug_renderer_info"),o=String(i?r.getParameter(i.UNMASKED_RENDERER_WEBGL):r.getParameter(r.RENDERER)??"");return sT.test(o)?(r.getExtension?.("WEBGL_lose_context")?.loseContext(),!1):(r.getExtension?.("WEBGL_lose_context")?.loseContext(),!0)}catch{return!1}}const uT="http://www.w3.org/2000/svg";let cT=0;function Fo(e){return Math.round(e*10)/10}function lT(e,t,n={}){const r=e.createElementNS(uT,t);for(const[i,o]of Object.entries(n))r.setAttribute(i,String(o));return r}function ap(e,t,n,r){const i=`cia-graph-svg-${++cT}`,o=e.ownerDocument,s=(M,H)=>lT(o,M,H),a=(M,H,Q)=>{const ie=s("text",{x:0,y:H,"text-anchor":"middle",class:Q,"pointer-events":"none"});return ie.textContent=M,ie},{width:u,height:c}=t.dimensions(),l=s("svg",{class:"cia-graph-svg",viewBox:`0 0 ${u} ${c}`,role:"group",tabindex:0,"aria-label":r.label??"Money-flow graph. Drag the background or use arrow keys to pan, plus and minus to zoom. Select an address or a link for details."}),d=s("defs"),f=s("pattern",{id:`${i}-dots`,width:24,height:24,patternUnits:"userSpaceOnUse"});f.append(s("circle",{class:"cia-graph-dot",cx:1,cy:1,r:1})),d.append(f);const h=s("rect",{class:"cia-graph-backdrop",width:"100%",height:"100%","data-canvas":""}),p=s("rect",{class:"cia-graph-dots",width:"100%",height:"100%",fill:`url(#${i}-dots)`,"data-canvas":""}),m=s("g",{"data-viewport":""}),y=s("g",{"data-edges":"",class:"cia-graph-edges"}),w=s("g",{"data-nodes":"",class:"cia-graph-nodes"});m.append(y,w),l.append(d,h,p,m),e.append(l);const g=new Map,b=new Map,v=new Map;let k=null;function S(){if(k)return k;const M=t.model(),H=t.positions(),Q=new Map;k=Q;const ie=M.nodes.length>tC,J=new Map(M.nodes.map(L=>[L.address,L])),I=ie?[]:VT(M,H,t.notes());for(const L of M.edges){const G=J.get(L.from),pe=J.get(L.to),se=G&&H[G.id],ne=pe&&H[pe.id];if(!G||!pe||!se||!ne){Q.set(L.id,null);continue}if(ie){Q.set(L.id,ec(se,ne,Zn(G,M.checked_address),Zn(pe,M.checked_address)));continue}const ke=I.filter(xe=>xe.id!==G.id&&xe.id!==pe.id);Q.set(L.id,nC(se,ne,Zn(G,M.checked_address),Zn(pe,M.checked_address),ke))}return Q}function _(M){let H=g.get(M);if(H)return H;H=`${i}-arrow-${g.size}`;const Q=s("marker",{id:H,viewBox:"0 0 10 10",refX:9,refY:5,markerWidth:6,markerHeight:6,orient:"auto-start-reverse",markerUnits:"strokeWidth"}),ie=s("path",{d:"M0 0L10 5L0 10Z",class:"cia-graph-arrowhead"});return ie.style.fill=M,Q.append(ie),d.append(Q),g.set(M,H),H}function N(){return[...t.model().nodes??[]].sort((M,H)=>String(M.id).localeCompare(String(H.id)))}function P(){k=null;const M=t.model();y.replaceChildren(),w.replaceChildren(),b.clear(),v.clear();const H=new Map(M.nodes.map(Q=>[Q.address,Q]));for(const Q of M.edges){const ie=H.get(Q.from);if(!ie||!H.get(Q.to))continue;const J=t.colorOf(ie),I=s("g",{class:"cia-graph-edge graph-edge",tabindex:0,role:"button","aria-label":oc(Q,t.now())});I.dataset.edgeId=Q.id,I.style.setProperty("--edge-tone",J);const L=iC(),G=s("path",{class:"cia-graph-edge-hit","stroke-width":L.hit.width,"pointer-events":"stroke"}),pe=s("path",{class:"cia-graph-edge-line","stroke-width":L.line.width,"marker-end":`url(#${_(J)})`,"pointer-events":"none"});I.append(G,pe);const se=M.edges.length<=zw?Pw(Q):"";let ne;if(se){pe.id=`${i}-edge-${v.size}`;const ke=s("textPath",{href:`#${pe.id}`,startOffset:"50%","text-anchor":"middle"});ke.textContent=se;const xe=s("text",{class:"cia-graph-edge-caption",dy:"-4","pointer-events":"none","aria-hidden":"true"});xe.append(ke),I.append(xe),ne=xe}I.addEventListener("keydown",ke=>{mp(ke.key)&&(ke.preventDefault(),n.selectEdge(Q.id,"keyboard"))}),I.addEventListener("pointerenter",ke=>n.showTooltip(ke,oc(Q,t.now()))),I.addEventListener("pointerleave",()=>n.hideTooltip()),y.append(I),v.set(Q.id,{group:I,hit:G,line:pe,...ne?{caption:ne}:{}})}for(const Q of N())w.append(z(Q));K(),re()}function z(M){const H=t.model(),Q=M.address===H.checked_address,ie=t.notes().get(M.id),J=Nn(M,H.checked_address,ie),I=J.radius,L=s("g",{class:"cia-graph-node graph-node",tabindex:0,role:"button","aria-label":ic(M),"aria-pressed":"false"});L.dataset.nodeId=M.id,Q&&(L.dataset.checked=""),L.style.setProperty("--node-tone",t.colorOf(M)),Q&&L.append(s("circle",{class:"cia-graph-node-ring",r:I+6})),L.append(s("circle",{class:"cia-graph-node-body",r:I})),L.append(s("circle",{class:"cia-graph-node-dot",r:J.dot}));for(const G of J.texts)L.append(a(G.text,G.y,`cia-graph-node-${G.kind}`));ie&&(L.dataset.state="refused");for(const G of t.flags().get(M.id)??[])L.setAttribute(`data-flag-${G}`,"");return L.addEventListener("keydown",G=>{mp(G.key)&&(G.preventDefault(),n.selectNode(M.id,"keyboard"))}),L.addEventListener("pointerenter",G=>n.showTooltip(G,ic(M))),L.addEventListener("pointerleave",()=>n.hideTooltip()),b.set(M.id,L),L}function j(){const M=t.transform();m.setAttribute("transform",`translate(${M.x} ${M.y}) scale(${M.scale})`)}function K(){j();const M=t.positions(),{width:H,height:Q}=t.dimensions();for(const[J,I]of b){const L=M[J]??{x:H/2,y:Q/2};I.setAttribute("transform",`translate(${Fo(L.x)} ${Fo(L.y)})`)}const ie=S();for(const J of t.model().edges){const I=v.get(J.id);if(!I)continue;const L=ie.get(J.id)??null;I.group.style.display=L?"":"none",L&&(I.hit.setAttribute("d",L.d),I.line.setAttribute("d",L.d),I.caption&&(I.caption.style.display=L.kind==="forward"||L.kind==="vertical"||L.kind==="straight"?"":"none"))}}function Y(M){const H=t.model(),Q=t.positions(),ie=Q[M],J=b.get(M);if(!ie||!J)return;J.setAttribute("transform",`translate(${Fo(ie.x)} ${Fo(ie.y)})`);const I=H.nodes.find(G=>G.id===M);if(!I)return;const L=new Map(H.nodes.map(G=>[G.address,G]));for(const G of H.edges){if(G.from!==I.address&&G.to!==I.address)continue;const pe=v.get(G.id),se=L.get(G.from),ne=L.get(G.to),ke=se&&Q[se.id],xe=ne&&Q[ne.id];if(!pe||!se||!ne||!ke||!xe)continue;const Ze=ec(ke,xe,Zn(se,H.checked_address),Zn(ne,H.checked_address));pe.group.style.display=Ze?"":"none",Ze&&(pe.hit.setAttribute("d",Ze.d),pe.line.setAttribute("d",Ze.d))}}function re(){const M=t.model(),H=t.selected(),Q=t.highlighted(),ie=H?.kind==="node"?M.nodes.find(J=>J.id===H.id)?.address??null:null;for(const J of M.edges){const I=v.get(J.id);if(!I)continue;const L=H?.kind==="edge"&&H.id===J.id,G=H?.kind==="edge"?L?qt.related:qt.faded:Iw(J,ie),pe=G===qt.faded;I.group.setAttribute("opacity",pe?String(G):"1"),I.line.setAttribute("stroke-opacity",pe?"1":String(G)),I.group.dataset.opacity=String(G),I.group.dataset.state=G===qt.rest?"rest":G===qt.related?"related":"faded",I.group.setAttribute("aria-pressed",String(L))}for(const[J,I]of b){const L=H?.kind==="node"&&H.id===J;I.classList.toggle("is-selected",L),I.classList.toggle("is-focused",Q===J),I.setAttribute("aria-pressed",String(L))}}function he(){let M=null;for(const H of S().values())H?.bounds&&(M=M??{...H.bounds},M.x1=Math.min(M.x1,H.bounds.x1),M.y1=Math.min(M.y1,H.bounds.y1),M.x2=Math.max(M.x2,H.bounds.x2),M.y2=Math.max(M.y2,H.bounds.y2));return M}return{kind:"svg",surface:l,build:P,geometry(){k=null,K()},moveNode:Y,endMove(){k=null,K()},camera:j,selection:re,flag(M,H,Q){b.get(M)?.toggleAttribute(`data-flag-${H}`,Q)},theme(){for(const M of t.model().nodes)b.get(M.id)?.style.setProperty("--node-tone",t.colorOf(M))},resize(M,H){l.setAttribute("viewBox",`0 0 ${M} ${H}`)},pick:()=>null,linkBounds:he,destroy(){l.remove()}}}const dT=.1,fT=2.5,hT=5,pT="chain-insights.flows.v1",Wf="cia-graph-model",mT=90,qt={rest:.6,related:.95,faded:.25},up={checked:24,other:19},gi=16,gT=[["Sanctioned","Sanctioned"],["Scam","Scam"],["Poisoned","Poisoned"],["OnMoneyTrail","On money trail"],["Mixer","Mixer"],["Bridge","Bridge"],["Exchange","Exchange"],["Victim","Victim"],["Targeted","Targeted"]],Br=["exchange","scam","sanctioned","victim","pool","other"],yT={exchange:"infrastructure",scam:"danger",sanctioned:"danger",victim:"target",pool:"trail",other:"neutral"},Ew={exchange:"Exchange",scam:"Scam",sanctioned:"Sanctioned",victim:"Victim",pool:"Pool",other:""};function Kf(e){return!!e&&e.schema===pT}function vT(e){return!!e&&e.kind===Wf}function Ke(e){return String(e??"").trim().toLowerCase()}function bT(e){const t=Ke(e);return Br.includes(t)?t:"other"}function vn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Xu(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function wT(e){const t=String(e??"").toUpperCase();return t==="IN"||t==="OUT"||t==="MIXED"||t==="CHECKED"?t:"OUT"}function At(e){return vT(e)?e:Kf(e)?_T(e):ST(e)}function _T(e){const t=Ke(e.center),n=new Map;for(const a of e.nodes??[]){const u=Ke(a?.address);u&&!n.has(u)&&n.set(u,a)}const r=[],i=new Set;for(const a of e.edges??[]){const u=Ke(a?.from),c=Ke(a?.to);if(!n.has(u)||!n.has(c)||u===c)continue;const l=`${u}->${c}`;i.has(l)||(i.add(l),r.push({id:l,from:u,to:c,source:"flows",amount_usd_sum:vn(a.usd),tx_count:vn(a.tx_count),first_seen_timestamp:vn(a.first_seen_ms),last_seen_timestamp:vn(a.last_seen_ms),...typeof a.link_kind=="string"&&a.link_kind?{link_kind:a.link_kind}:{}}))}const o=kT(t,[...n.keys()],r),s=[...n.entries()].map(([a,u])=>{const c=o.get(a)??{direction:"OUT",hop:2};return{id:a,address:a,direction:a===t?"CHECKED":c.direction,hop:a===t?0:c.hop,labels:Xu(u.labels),taxonomy:[],role:bT(u.role),total_in_usd:vn(u.total_in_usd),total_out_usd:vn(u.total_out_usd),degree_in:vn(u.degree_in),degree_out:vn(u.degree_out)}});return{kind:Wf,checked_address:t,network:e.network??null,nodes:s,edges:r,truncated:!!e.truncated,cursor:e.cursor??null}}function kT(e,t,n){const r=new Map,i=new Map,o=new Map,s=(d,f,h)=>d.set(f,[...d.get(f)??[],h]);for(const d of n)s(r,d.from,d.to),s(i,d.to,d.from),s(o,d.from,d.to),s(o,d.to,d.from);const a=d=>{const f=new Map([[e,0]]);for(let h=[e];h.length;){const p=[];for(const m of h)for(const y of d.get(m)??[])f.has(y)||(f.set(y,(f.get(m)??0)+1),p.push(y));h=p}return f},u=a(r),c=a(i),l=new Map;for(const d of t){if(d===e)continue;const f=u.get(d),h=c.get(d);if(f==null&&h==null)continue;const p=f!=null&&h!=null?f<h?"OUT":h<f?"IN":"MIXED":f!=null?"OUT":"IN";l.set(d,{direction:p,hop:Math.min(2,Math.min(f??1/0,h??1/0))})}for(let d=!0;d;){d=!1;for(const f of t){if(f===e||l.has(f))continue;const h=(o.get(f)??[]).find(m=>m!==e&&l.has(m));if(h==null)continue;const p=l.get(h);l.set(f,{direction:p.direction==="MIXED"?"OUT":p.direction,hop:2}),d=!0}}return l}function ST(e){const t=(e?.nodes??[]).map(r=>({...r,id:String(r.id??r.address),address:r.address,hop:Number(r.hop)||0,direction:r.address===e.checked_address?"CHECKED":wT(r.direction),labels:Xu(r.labels),taxonomy:Xu(r.taxonomy),role:null})),n=(e?.edges??[]).map(r=>({...r,id:String(r.id??`${r.from}->${r.to}`),amount_usd_sum:r.amount_usd_sum??null,tx_count:r.tx_count??null,first_seen_timestamp:r.first_seen_timestamp??null,last_seen_timestamp:r.last_seen_timestamp??null,source:"risk"}));return{kind:Wf,checked_address:e?.checked_address??"",network:null,nodes:t,edges:n,truncated:!1,cursor:null}}function xT(e,t,n){const r=At(t),i=kn(e,n??r.checked_address),o=e.nodes.find(d=>d.id===i),s=new Map(e.nodes.map(d=>[Ke(d.address),d])),a=[];for(const d of r.nodes){if(s.has(Ke(d.address)))continue;const f=!o||o.direction==="CHECKED"?d.direction==="CHECKED"?"OUT":d.direction:o.direction,h={...d,id:d.id,direction:f,hop:Math.min(2,(o?.hop??0)+1)};a.push(h),s.set(Ke(d.address),h)}const u=new Set(e.edges.map(d=>d.id)),c=new Set(e.edges.map(d=>`${Ke(d.from)}->${Ke(d.to)}`)),l=[...e.edges];for(const d of r.edges){const f=`${Ke(d.from)}->${Ke(d.to)}`;if(u.has(d.id)||c.has(f)||!s.has(Ke(d.from))||!s.has(Ke(d.to)))continue;const h=s.get(Ke(d.from)).address,p=s.get(Ke(d.to)).address;l.push({...d,from:h,to:p}),u.add(d.id),c.add(f)}return{model:{...e,nodes:[...e.nodes,...a],edges:l,truncated:e.truncated||r.truncated},added:a.map(d=>d.id)}}function kn(e,t){if(t==null)return null;const n=Ke(t);return e.nodes.find(i=>i.id===t||Ke(i.address)===n)?.id??null}function yi(e){return typeof e!="string"||e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Jf(e){return String(e??"").trim().replace(/\s+/g," ")}function ms(e){return Jf(e).replaceAll(" ","").toLowerCase()}function An(e){const t=[...e.taxonomy??[],...e.labels??[]],n=new Set,r=[];for(const i of t){const o=Jf(i),s=o.toLowerCase();!o||s==="address"||n.has(s)||(n.add(s),r.push(o))}return r}function Uo(e,t){const n=new Set(An(e).map(ms));return t.some(r=>n.has(ms(r)))}function ET(e){if(e.role&&Br.includes(e.role))return yT[e.role];if(Uo(e,["Sanctioned","Scam","Poisoned"]))return"danger";if(Uo(e,["Victim","Targeted"]))return"target";if(Uo(e,["OnMoneyTrail","Mixer"]))return"trail";if(Uo(e,["Exchange","Bridge","token contract"]))return"infrastructure";if(e.risk_score!=null){const t=String(e.risk_level).toLowerCase();if(t==="critical"||t==="high"||t==="medium"||t==="low")return t}return"neutral"}function We(e){return`var(--cia-graph-${e})`}const $T={semantic:{danger:{stroke:We("danger"),fill:We("node")},target:{stroke:We("target"),fill:We("node")},trail:{stroke:We("trail"),fill:We("node")},infrastructure:{stroke:We("infrastructure"),fill:We("node")},neutral:{stroke:We("neutral"),fill:We("node")}},risk:{CRITICAL:{stroke:We("critical"),fill:We("node")},HIGH:{stroke:We("high"),fill:We("node")},MEDIUM:{stroke:We("medium"),fill:We("node")},LOW:{stroke:We("low"),fill:We("node")}}};function TT(e,t=$T){const n=ET(e);return n==="critical"||n==="high"||n==="medium"||n==="low"?t.risk[n.toUpperCase()]??t.semantic.neutral:t.semantic[n]}function CT(e){return e.role&&Br.includes(e.role)?We(`role-${e.role}`):TT(e).stroke}function Ao(e){if(e.role&&e.role!=="other"&&Br.includes(e.role))return Ew[e.role];const t=An(e);for(const[r,i]of gT)if(t.some(o=>ms(o)===ms(r)))return i;return(Array.isArray(e.labels)?e.labels.map(Jf).filter(Boolean).sort((r,i)=>r.localeCompare(i)):[])[0]??""}function Qu(e){return Math.min(fT,Math.max(dT,e))}function Wa(e){return[...e.nodes??[]].sort((t,n)=>String(t.id).localeCompare(String(n.id)))}function $w(e,t=Wa(e)){return t.find(n=>n.address===e.checked_address)??t[0]}function cp(e,t){return e.address===t?43:e.hop>=2?25:30}function Zn(e,t){return e.address===t?up.checked:up.other}function Nn(e,t,n){const r=e.address===t,i=Zn(e,t),o=Ao(e),s=[];return o&&s.push({kind:"role",text:wC(o),y:i+17}),s.push({kind:"address",text:yi(e.address),y:i+(o?33:17)}),n&&s.push({kind:"note",text:n,y:i+(o?48:32)}),{radius:i,ring:r,dot:r?8:5,texts:s}}const AT={role:{size:13,advance:.68},address:{size:11,advance:.62},note:{size:11,advance:.6}},lu=2;function Yf(e){const t=e.radius+(e.ring?7:2),n=[{kind:"circle",box:{x1:-t,y1:-t,x2:t,y2:t}}];for(const r of e.texts){const i=AT[r.kind],o=[...r.text].length*i.size*i.advance/2+lu;n.push({kind:r.kind,box:{x1:-o,y1:r.y-i.size*.8-lu,x2:o,y2:r.y+i.size*.25+lu}})}return n}function Tw(e){return e.length?{x1:Math.min(...e.map(t=>t.x1)),y1:Math.min(...e.map(t=>t.y1)),x2:Math.max(...e.map(t=>t.x2)),y2:Math.max(...e.map(t=>t.y2))}:null}function gs(e){return Tw(Yf(e).map(t=>t.box))}const vi=(e,t)=>(e instanceof Map?e.get(t):e?.[t])??null;function IT(e,t,n){const r=At(e),i=[];for(const o of r.nodes){const s=t[o.id];if(s)for(const{kind:a,box:u}of Yf(Nn(o,r.checked_address,vi(n,o.id))))i.push({id:o.id,kind:a,x1:s.x+u.x1,y1:s.y+u.y1,x2:s.x+u.x2,y2:s.y+u.y2})}return i}function NT(e,t,n){return Tw(IT(e,t,n))}function RT(e,t){return e.x1<t.x2&&t.x1<e.x2&&e.y1<t.y2&&t.y1<e.y2}function LT(e){let t=0;for(const n of String(e))t=(t<<5)-t+n.charCodeAt(0)|0;return Math.abs(t)}function zT(e,t,n){const r=At(e),i={x:t/2,y:n/2},o={},s=Wa(r),a=$w(r,s);if(!a)return o;o[a.id]=i;const u=new Map;for(const l of s){if(l.id===a.id)continue;let d=l.direction==="IN"?-1:1;l.direction==="MIXED"&&(d=LT(l.id)%2?-1:1);const f=Math.min(2,Math.max(1,Number(l.hop)||1)),h=`${d}:${f}`;u.has(h)||u.set(h,[]),u.get(h).push(l)}const c=PT(r);for(const[l,d]of u){const[f,h]=l.split(":"),p=Number(f),m=Number(h),y=i.x+p*(m===1?t*.23:t*.43);d.sort((w,g)=>(c.get(g.address)??0)-(c.get(w.address)??0)||String(w.id).localeCompare(String(g.id))),Object.assign(o,DT(d,y,i.y,r.checked_address))}return o}function PT(e){const t=new Map;for(const n of e.edges){const r=Math.max(n.last_seen_timestamp??0,n.first_seen_timestamp??0);for(const i of[n.from,n.to])r>(t.get(i)??0)&&t.set(i,r)}return t}function DT(e,t,n,r,i=24){const o=e.map((u,c)=>({node:u,x:t,y:n+(c-(e.length-1)/2)*64})),s=u=>gs(Nn(u,r)),a=(u,c)=>Math.max(cp(u,r)+cp(c,r)+20,s(u).y2-s(c).y1+2);for(let u=0;u<i;u++){for(let d=1;d<o.length;d++){const f=o[d-1],h=o[d];!f||!h||(h.y=Math.max(h.y,f.y+a(f.node,h.node)))}for(let d=o.length-2;d>=0;d--){const f=o[d],h=o[d+1];!f||!h||(f.y=Math.min(f.y,h.y-a(f.node,h.node)))}const c=o[0],l=o[o.length-1];if(c&&l){const d=(c.y+l.y)/2,f=n-d;for(const h of o)h.y+=f}}return Object.fromEntries(o.map(u=>[u.node.id,{x:u.x,y:u.y}]))}function OT(e,t,n){const r=At(e),i={x:t/2,y:n/2},o={},s=Wa(r),a=$w(r,s);if(!a)return o;o[a.id]=i;const u=s.filter(c=>c.id!==a.id);return u.forEach((c,l)=>{const d=-Math.PI/2+l*Math.PI*2/Math.max(1,u.length),f=c.hop>=2?Math.min(t,n)*.39:Math.min(t,n)*.27;o[c.id]={x:i.x+Math.cos(d)*f,y:i.y+Math.sin(d)*f}}),o}function MT(e,t,n,r){const i=At(e),o=Wa(i).filter(u=>t[u.id]),s=o.find(u=>u.address===i.checked_address);for(let u=0;u<o.length;u++)for(let c=u+1;c<o.length;c++){const l=o[u],d=o[c],f=l&&t[l.id],h=d&&t[d.id];if(!f||!h)continue;const p=h.x-f.x||.1,m=h.y-f.y||.1,y=Math.max(1,Math.hypot(p,m)),w=Math.max(0,88-y)*.012;f.x-=p/y*w,f.y-=m/y*w,h.x+=p/y*w,h.y+=m/y*w}const a=new Map(o.map(u=>[u.address,u]));for(const u of i.edges){const c=a.get(u.from),l=a.get(u.to);if(!c||!l)continue;const d=t[c.id],f=t[l.id];if(!d||!f)continue;const h=f.x-d.x,p=f.y-d.y,m=Math.max(1,Math.hypot(h,p)),y=(m-155)*.003;c!==s&&(d.x+=h/m*y,d.y+=p/m*y),l!==s&&(f.x-=h/m*y,f.y-=p/m*y)}return s&&(t[s.id]={x:n/2,y:r/2}),t}function FT(e,t,n,r=mT){const i=At(e),o=OT(i,t,n);for(let a=0;a<r;a++)MT(i,o,t,n);const s=new Set(i.nodes.filter(a=>a.address!==i.checked_address).map(a=>a.id));return Cw(i,o,s)}function Go(e,t,n,r){return t==="tree"?zT(e,n,r):FT(e,n,r)}function Cw(e,t,n,r,i=22,o=60){const s=At(e),a=s.nodes.filter(c=>t[c.id]),u=new Map(a.map(c=>[c.id,gs(Nn(c,s.checked_address,vi(r,c.id)))]));for(let c=0;c<o;c++){let l=!1;for(let d=0;d<a.length;d++)for(let f=d+1;f<a.length;f++){const h=a[d],p=a[f];if(!n.has(h.id)&&!n.has(p.id))continue;const m=t[h.id],y=t[p.id],w=u.get(h.id),g=u.get(p.id),b=Math.min(m.x+w.x2,y.x+g.x2)-Math.max(m.x+w.x1,y.x+g.x1)+i,v=Math.min(m.y+w.y2,y.y+g.y2)-Math.max(m.y+w.y1,y.y+g.y1)+i;if(b<=0||v<=0)continue;l=!0;const k=b<v,S=k?y.x>=m.x?1:-1:y.y>=m.y?1:-1,_=(k?b:v)/2+.5,P=n.has(h.id)&&n.has(p.id)?_:_*2;n.has(h.id)&&(k?m.x-=S*P:m.y-=S*P),n.has(p.id)&&(k?y.x+=S*P:y.y+=S*P)}if(!l)break}return t}const UT=80;function GT(e,t,n,r,i={}){const o=i.steps??UT,s=At(e),a=t[n],u={...t};if(!a)return u;const c=new Map(s.nodes.map(_=>[_.id,_])),l=[...r].sort().filter(_=>!u[_]&&c.has(_));if(!l.length)return u;const d=c.get(n)?.address,f=new Set(s.edges.filter(_=>_.to===d).map(_=>_.from)),h=new Set(s.edges.filter(_=>_.from===d).map(_=>_.to)),p=_=>{const N=c.get(_).address;return f.has(N)&&!h.has(N)},m=l.filter(p),y=l.filter(_=>!p(_)),w=(_,N)=>{const P=Math.max(6,Math.ceil(Math.sqrt(_.length*1.4))),z=Math.ceil(_.length/P);_.forEach((j,K)=>{const Y=Math.floor(K/P),re=Math.min(P,_.length-Y*P),he=K-Y*P;u[j]={x:a.x+N*(150+Y*120),y:a.y+(he-(re-1)/2)*64+(z>1?Y%2*32:0)}})};w(m,-1),w(y,1);const g=s.nodes.filter(_=>t[_.id]&&!l.includes(_.id)).map(_=>({point:t[_.id],box:gs(Nn(_,s.checked_address,vi(i.notes,_.id)))})),b=(_,N)=>{if(!_.length)return;const P=_.map(z=>({id:z,box:gs(Nn(c.get(z),s.checked_address,vi(i.notes,z)))}));for(let z=0;z<12;z++){const j={x1:1/0,y1:1/0,x2:-1/0,y2:-1/0};for(const{id:Y,box:re}of P){const he=u[Y];j.x1=Math.min(j.x1,he.x+re.x1),j.x2=Math.max(j.x2,he.x+re.x2),j.y1=Math.min(j.y1,he.y+re.y1),j.y2=Math.max(j.y2,he.y+re.y2)}let K=0;for(const Y of g){if(Math.min(j.y2,Y.point.y+Y.box.y2)-Math.max(j.y1,Y.point.y+Y.box.y1)+12<=0)continue;const he=N<0?j.x2+24-(Y.point.x+Y.box.x1):Y.point.x+Y.box.x2+24-j.x1;he>K&&(K=he)}if(K<=0)break;for(const Y of _)u[Y].x+=N*K}},v=new Set(l),k=s.nodes.filter(_=>u[_.id]),S=new Map(k.map(_=>[_.address,_]));for(let _=0;_<o;_++){for(let N=0;N<k.length;N++)for(let P=N+1;P<k.length;P++){const z=k[N],j=k[P];if(!v.has(z.id)&&!v.has(j.id))continue;const K=u[z.id],Y=u[j.id],re=Y.x-K.x||.1,he=Y.y-K.y||.1,M=Math.max(1,Math.hypot(re,he)),H=Math.max(0,110-M)*.02;H&&(v.has(z.id)&&(K.x-=re/M*H,K.y-=he/M*H),v.has(j.id)&&(Y.x+=re/M*H,Y.y+=he/M*H))}for(const N of s.edges){const P=S.get(N.from),z=S.get(N.to);if(!P||!z)continue;const j=u[P.id],K=u[z.id],Y=K.x-j.x,re=K.y-j.y,he=Math.max(1,Math.hypot(Y,re)),M=(he-150)*.003;v.has(P.id)&&(j.x+=Y/he*M,j.y+=re/he*M),v.has(z.id)&&(K.x-=Y/he*M,K.y-=re/he*M)}}return Cw(s,u,v,i.notes),b(m,-1),b(y,1),u}function jT(e,t,n,r=gi){const i=Math.max(1,e.x2-e.x1),o=Math.max(1,e.y2-e.y1),s=Qu(Math.min((t-r*2)/i,(n-r*2)/o));return{x:t/2-(e.x1+e.x2)/2*s,y:n/2-(e.y1+e.y2)/2*s,scale:s}}function lp(e,t,n,r=gi){return Math.min((t-r*2)/Math.max(1,e.x2-e.x1),(n-r*2)/Math.max(1,e.y2-e.y1))}function ZT(e,t,n,r,i=4){const o=t.x-e.x,s=t.y-e.y,a=Math.hypot(o,s),u=n+i,c=r+i;if(!Number.isFinite(a)||a<=0||u+c>=a)return null;const l=o/a,d=s/a;return{x1:e.x+l*u,y1:e.y+d*u,x2:t.x-l*c,y2:t.y-d*c}}function En(e){return Math.round(e*100)/100}function du(e,t,n,r,i){const o=s=>`${En(s.x)},${En(s.y)}`;return{kind:e,start:t,end:i,controls:[n,r],d:`M${o(t)} C${o(n)} ${o(r)} ${o(i)}`}}function ec(e,t,n,r,i=4){const o=t.x-e.x,s=t.y-e.y,a=Math.hypot(o,s),u=n+r+i*2;if(!Number.isFinite(a)||a<=u)return null;if(o>=u){const f={x:e.x+n+i,y:e.y},h={x:t.x-r-i,y:t.y},p=h.x-f.x,m=Math.max(p*.45,Math.min(65,p));return du("forward",f,{x:f.x+m,y:f.y},{x:h.x-m,y:h.y},h)}if(o<=-u){const f={x:e.x,y:e.y-n-i},h={x:t.x,y:t.y-r-i},p=Math.max(100,Math.abs(o)*.2);return du("backward",f,{x:f.x+85,y:f.y-p},{x:h.x+85,y:h.y-p},h)}if(Math.abs(s)>u){const f=s>0?1:-1,h={x:e.x,y:e.y+f*(n+i)},p={x:t.x,y:t.y-f*(r+i)},m=Math.abs(p.y-h.y),y=Math.max(m*.45,Math.min(40,m));return du("vertical",h,{x:h.x,y:h.y+f*y},{x:p.x,y:p.y-f*y},p)}const c=ZT(e,t,n,r,i),l={x:c.x1,y:c.y1},d={x:c.x2,y:c.y2};return{kind:"straight",start:l,end:d,controls:null,d:`M${En(l.x)},${En(l.y)} L${En(d.x)},${En(d.y)}`}}const BT=6,fu=BT+3,Qt=14,dp=10,HT=3,fp=6;function VT(e,t,n){const r=At(e),i=[];for(const o of r.nodes){const s=t[o.id];if(s)for(const{kind:a,box:u}of Yf(Nn(o,r.checked_address,vi(n,o.id))))a==="circle"?i.push({id:o.id,kind:"circle",x:s.x,y:s.y,r:u.x2}):i.push({id:o.id,kind:"box",x1:s.x+u.x1,y1:s.y+u.y1,x2:s.x+u.x2,y2:s.y+u.y2})}return i}function qT(e,t){if(t.kind==="circle")return Math.hypot(e.x-t.x,e.y-t.y)-t.r;const n=Math.max(t.x1-e.x,0,e.x-t.x2),r=Math.max(t.y1-e.y,0,e.y-t.y2);return n||r?Math.hypot(n,r):-Math.min(e.x-t.x1,t.x2-e.x,e.y-t.y1,t.y2-e.y)}function WT(e,t){return e.kind==="circle"?{x1:e.x-e.r-t,y1:e.y-e.r-t,x2:e.x+e.r+t,y2:e.y+e.r+t}:{x1:e.x1-t,y1:e.y1-t,x2:e.x2+t,y2:e.y2+t}}function KT(e,t){const n=1-t;return{x:n*n*n*e[0].x+3*n*n*t*e[1].x+3*n*t*t*e[2].x+t*t*t*e[3].x,y:n*n*n*e[0].y+3*n*n*t*e[1].y+3*n*t*t*e[2].y+t*t*t*e[3].y}}function JT(e){return e.controls?[{kind:"C",points:[e.start,e.controls[0],e.controls[1],e.end]}]:[{kind:"L",points:[e.start,e.end]}]}function Aw(e){let t=0,n;for(const r of e)n&&(t+=Math.hypot(r.x-n.x,r.y-n.y)),n=r;return t}function YT(e,t){const n=[];for(const r of e){const i=Math.max(1,Math.ceil(Aw(r.points)/t));for(let o=0;o<=i;o++){const s=o/i;if(r.kind==="L"){const[a,u]=r.points;n.push({x:a.x+(u.x-a.x)*s,y:a.y+(u.y-a.y)*s})}else n.push(KT(r.points,s))}}return n}function hp(e,t,n,r){const i=e.flatMap(a=>a.points),o={x1:Math.min(...i.map(a=>a.x)),y1:Math.min(...i.map(a=>a.y)),x2:Math.max(...i.map(a=>a.x)),y2:Math.max(...i.map(a=>a.y))},s=[];if(n.forEach((a,u)=>{a.x1<=o.x2&&o.x1<=a.x2&&a.y1<=o.y2&&o.y1<=a.y2&&s.push(u)}),!s.length)return!0;for(const a of YT(e,HT))for(const u of s){const c=n[u],l=t[u];if(!(!c||!l)&&!(a.x<c.x1||a.x>c.x2||a.y<c.y1||a.y>c.y2)&&qT(a,l)<r)return!1}return!0}function XT(e){const t=e[0],n=e[e.length-1];if(!t||!n)return[];const r=[];for(let s=1;s<e.length;s++)r.push(Aw(e.slice(s-1,s+1)));const i=[];let o=t;for(let s=1;s<e.length-1;s++){const a=e[s-1],u=e[s],c=e[s+1],l=r[s-1],d=r[s];if(!a||!u||!c||l===void 0||d===void 0)continue;const f=l/(s-1===0?1:2),h=d/(s===r.length-1?1:2),p=Math.min(Qt,f,h),m={x:(u.x-a.x)/l,y:(u.y-a.y)/l},y={x:(c.x-u.x)/d,y:(c.y-u.y)/d},w={x:u.x-m.x*p,y:u.y-m.y*p},g={x:u.x+y.x*p,y:u.y+y.y*p};i.push({kind:"L",points:[o,w]}),i.push({kind:"C",points:[w,{x:w.x+m.x*p*.55,y:w.y+m.y*p*.55},{x:g.x-y.x*p*.55,y:g.y-y.y*p*.55},g]}),o=g}return i.push({kind:"L",points:[o,n]}),i.filter(s=>s.kind==="C"||Math.hypot(s.points[1].x-s.points[0].x,s.points[1].y-s.points[0].y)>.01)}function QT(e){const t=i=>`${En(i.x)},${En(i.y)}`,n=e[0];if(!n)return"";let r=`M${t(n.points[0])}`;for(const i of e)r+=i.kind==="L"?` L${t(i.points[1])}`:` C${t(i.points[1])} ${t(i.points[2])} ${t(i.points[3])}`;return r}function pp(e,t,n,r,i){const o=Math.min(e.y,n)-Qt,s=Math.max(e.y,n)+Qt,a=d=>(d-e.x)*t;let u=1/0;for(const d of i)if(d.y1<e.y&&e.y<d.y2){const f=t===1?d.x1:d.x2,h=t===1?d.x2:d.x1;a(h)>0&&(u=Math.min(u,Math.max(0,a(f))))}const c=i.filter(d=>d.y1<s&&o<d.y2).map(d=>[a(t===1?d.x1:d.x2),a(t===1?d.x2:d.x1)]).filter(([,d])=>d>r).sort((d,f)=>d[0]-f[0]);let l=r;for(const[d,f]of[...c,[1/0,1/0]]){if(d>l+1){const h=Math.min(d,u);if(h<=l+1)return null;const p=Number.isFinite(h)&&h-l<80?(l+h)/2:l+40;return e.x+t*p}if(l=Math.max(l,f),l>=u)return null}return null}function eC(e){const t=[];for(const n of e){const r=t[t.length-1];r&&Math.abs(r.x-n.x)<.01&&Math.abs(r.y-n.y)<.01||t.push(n)}return t.filter((n,r)=>{if(r===0||r===t.length-1)return!0;const i=t[r-1],o=t[r+1];return!i||!o?!0:!(Math.abs(i.x-n.x)<.01&&Math.abs(o.x-n.x)<.01||Math.abs(i.y-n.y)<.01&&Math.abs(o.y-n.y)<.01)})}const tC=120;function nC(e,t,n,r,i,o=4){const s=ec(e,t,n,r,o);if(!s||!i.length)return s;const a=i.map(f=>WT(f,fu));if(hp(JT(s),i,a,fu))return s;const u=new Set([e.y,t.y]),c=f=>Math.abs(f-e.y)<fp?e.y:Math.abs(f-t.y)<fp?t.y:f;for(const f of a)u.add(c(Math.round(f.y1)-Qt-1)),u.add(c(Math.round(f.y2)+Qt+1));const l=t.x>=e.x?1:-1,d=[[l,l],[l,-l],[-l,l],[-l,-l]];for(const[f,h]of d){const p={x:e.x+f*(n+o),y:e.y},m={x:t.x-h*(r+o),y:t.y},y=[];for(const w of u){const g=Math.abs(w-p.y)<.01?p.x:pp(p,f,w,Qt,a);if(g===null)continue;const b=Math.abs(w-m.y)<.01?m.x:pp(m,-h,w,Qt+dp,a);if(b===null||Math.abs(w-m.y)<.01&&(m.x-g)*h<Qt+dp||Math.abs(w-p.y)<.01&&(b-p.x)*f<Qt)continue;const v=eC([p,{x:g,y:p.y},{x:g,y:w},{x:b,y:w},{x:b,y:m.y},m]);if(!rC(v,a))continue;let k=(v.length-2)*Qt,S;for(const _ of v)S&&(k+=Math.abs(_.x-S.x)+Math.abs(_.y-S.y)),S=_;y.push({points:v,length:k})}y.sort((w,g)=>{const b=w.points[2]?.y,v=g.points[2]?.y;return w.length-g.length||(b===void 0||v===void 0?0:b-v)});for(const w of y){const g=XT(w.points);if(!hp(g,i,a,fu))continue;const b=w.points,v=b[0],k=b[b.length-1];if(!v||!k)continue;const S={x1:Math.min(...b.map(_=>_.x)),y1:Math.min(...b.map(_=>_.y)),x2:Math.max(...b.map(_=>_.x)),y2:Math.max(...b.map(_=>_.y))};return{kind:"routed",start:v,end:k,controls:null,d:QT(g),bounds:S}}}return s}function rC(e,t){let n;for(const r of e){if(n){const i={x1:Math.min(n.x,r.x),y1:Math.min(n.y,r.y),x2:Math.max(n.x,r.x),y2:Math.max(n.y,r.y)};for(const o of t)if(RT(i,o))return!1}n=r}return!0}function Iw(e,t){if(!t)return qt.rest;const n=Ke(t);return Ke(e.from)===n||Ke(e.to)===n?qt.related:qt.faded}function iC(){return{hit:{stroke:"transparent",width:16},line:{stroke:We("edge"),width:1.6},arrow:{fill:We("edge")}}}function oC(e,t,n){return e!=="gravity"&&e!=="tree"?null:{layout:e,id:t,pointerId:n}}function sC(e,t,n,r){return e!=="node"&&e!=="edge"&&e!=="canvas"||!Number.isFinite(r?.x)||!Number.isFinite(r?.y)?null:{kind:e,id:t??null,pointerId:n,start:{...r},moved:!1}}function aC(e,t,n,r=hT){if(!e||e.pointerId!==t)return e;const i=Math.hypot(n.x-e.start.x,n.y-e.start.y);return{...e,moved:e.moved||i>r}}function uC(e,t,n=!1){return!e||e.pointerId!==t||n||e.moved?null:e.kind==="node"?{type:"select-node",id:e.id}:e.kind==="edge"?{type:"select-edge",id:e.id}:e.kind==="canvas"?{type:"clear-selection"}:null}function mp(e){return e==="Enter"||e===" "}function cC(e,t){return{x:(e.x-t.x)/t.scale,y:(e.y-t.y)/t.scale}}function lC(e,t,n,r,i){return!t||t.pointerId!==n||!Object.hasOwn(e,t.id)?!1:(e[t.id]=cC(r,i),!0)}function dC(e,t){return e?.pointerId===t?null:e}function fC(e,t,n,r){const i=Math.min(t.width/n,t.height/r),o=t.left+(t.width-n*i)/2,s=t.top+(t.height-r*i)/2;return{x:(e.x-o)/i,y:(e.y-s)/i}}function hC(e,t,n){const r=new Map;let i=null,o=null,s=null;function a(h){if(h===e)return{kind:"canvas",id:null};const p=h;if(p?.closest?.("[data-canvas]"))return{kind:"canvas",id:null};const m=p?.closest?.("[data-node-id]");if(m)return{kind:"node",id:m.dataset.nodeId??null};const y=p?.closest?.("[data-edge-id]");return y?{kind:"edge",id:y.dataset.edgeId??null}:null}function u(h){if(h.pointerType==="mouse"&&h.button!==0)return;const p=n?n(h):a(h.target);if(!p)return;const m=t.point(h);if(r.set(h.pointerId,m),e.setPointerCapture(h.pointerId),p.kind!=="canvas"&&(h.preventDefault(),h.stopPropagation()),r.size===1){i=sC(p.kind,p.id,h.pointerId,{x:h.clientX,y:h.clientY}),o=p.kind==="canvas"?{point:m,transform:{...t.transform()}}:null;return}if(i&&(i={...i,moved:!0}),o=null,r.size===2){const[y,w]=[...r.values()];y&&w&&(s={distance:Math.hypot(w.x-y.x,w.y-y.y),scale:t.transform().scale},t.startPinch())}}function c(h){if(!r.has(h.pointerId))return;const p=t.point(h);if(r.set(h.pointerId,p),s){const[m,y]=[...r.values()];m&&y&&t.pinch(s,[m,y],h);return}if(i?.pointerId===h.pointerId){if(i=aC(i,h.pointerId,{x:h.clientX,y:h.clientY}),!i?.moved)return;if(i.kind==="node"){t.drag(i.id??"",h.pointerId,p,h);return}if(i.kind==="edge")return}o&&t.pan(o,p,h)}function l(h,p=!1){const m=uC(i,h.pointerId,p);m&&t.select(m),i?.pointerId===h.pointerId&&(i=null),t.endDrag(h.pointerId),r.delete(h.pointerId),r.size||(i=null,o=null,s=null),e.hasPointerCapture(h.pointerId)&&e.releasePointerCapture(h.pointerId)}const d=h=>l(h),f=h=>l(h,!0);return e.addEventListener("pointerdown",u,!0),e.addEventListener("pointermove",c),e.addEventListener("pointerup",d),e.addEventListener("pointercancel",f),()=>{e.removeEventListener("pointerdown",u,!0),e.removeEventListener("pointermove",c),e.removeEventListener("pointerup",d),e.removeEventListener("pointercancel",f)}}function pC(e,t,n){let r=!1;function i(o,s=!1){r=o,e.classList.toggle("graph-panel--expanded",o),n.classList.toggle("graph-expanded",o),t.classList.toggle("expand-control--expanded",o),t.setAttribute("aria-expanded",String(o)),t.setAttribute("aria-label",o?"Close expanded graph":"Expand graph"),t.setAttribute("title",o?"Close expanded graph":"Expand graph"),o?(e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true")):(e.removeAttribute("role"),e.removeAttribute("aria-modal"),s&&t.focus())}return{open(){i(!0)},close(o={}){i(!1,o.restoreFocus!==!1)},toggle(){i(!r,r)},isOpen(){return r}}}function Nw(e){const t=String(e??"").toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function tc(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e)}function nc(e){return e==null?"Unavailable":new Intl.NumberFormat("en-US").format(e)}function $n(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"Unavailable";const t=new Date(e<1e11?e*1e3:e);return!Number.isFinite(t.getTime())||t.getUTCFullYear()<2009||t.getUTCFullYear()>2100?"Unavailable":new Intl.DateTimeFormat("en-GB",{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(t)}function Rw(e,t=Date.now()){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"Unavailable";const n=Math.max(0,(t-(e<1e11?e*1e3:e))/1e3),r=[[31536e3,"year"],[2592e3,"month"],[86400,"day"],[3600,"hour"],[60,"minute"]];for(const[i,o]of r){const s=Math.floor(n/i);if(s>=1)return`${s} ${o}${s===1?"":"s"} ago`}return"just now"}function rc(e){if(e.amount_usd_sum==null||e.price_coverage_ratio===0)return"Unavailable";const t=e.price_coverage_ratio;return tc(e.amount_usd_sum)+(t!=null&&t>0&&t<1?" (priced portion)":"")}function mC(e){const t=[["Incoming amount (USD)",e.total_in_usd==null?"Unavailable":tc(e.total_in_usd)],["Outgoing amount (USD)",e.total_out_usd==null?"Unavailable":tc(e.total_out_usd)]];return e.role&&Br.includes(e.role)?[["Role",Ew[e.role]||"Other"],...t,["Senders",nc(e.degree_in)],["Receivers",nc(e.degree_out)],["Labels",An(e).join(", ")||"No labels"]]:[["Address risk",e.risk_score==null?"Not scored":`${Math.round(e.risk_score*100)} · ${Nw(e.risk_level)}`],["Confidence","Unavailable"],...t,["First activity (UTC)",$n(e.first_activity_timestamp)],["Last activity (UTC)",$n(e.last_activity_timestamp)],["Labels",An(e).join(", ")||"No labels"]]}function gC(e,t){if(e.source==="flows")return[["From",e.from||"Unavailable"],["To",e.to||"Unavailable"],["Value (USD)",rc(e)],["Transfers",nc(e.tx_count)],["First seen (UTC)",$n(e.first_seen_timestamp)],["Last seen (UTC)",$n(e.last_seen_timestamp)],["Since last seen",Rw(e.last_seen_timestamp,t)],...e.link_kind?[["Link kind",e.link_kind]]:[]];const n=e.price_coverage_ratio;return[["From",e.from||"Unavailable"],["To",e.to||"Unavailable"],["Value (USD)",rc(e)],["Price coverage",n==null?"Unavailable":new Intl.NumberFormat("en-GB",{style:"percent",maximumFractionDigits:1}).format(n)],["Transfers",e.tx_count==null?"Unavailable":String(e.tx_count)],["First seen (UTC)",$n(e.first_seen_timestamp)],["Last seen (UTC)",$n(e.last_seen_timestamp)],["First transaction",e.first_tx_id||"Unavailable"],["Last transaction",e.last_tx_id||"Unavailable"]]}function Lw(e){return typeof e!="string"||!/^0x[a-fA-F0-9]{64}$/.test(e)?null:`https://robinhoodchain.blockscout.com/tx/${e.toLowerCase()}`}function ic(e){const t=Ao(e);if(e.role)return`${e.address}. ${t||"Other"}.${An(e).length?` Labels: ${An(e).join(", ")}.`:""}`;const n=e.risk_score==null?"Not scored":`${Math.round(e.risk_score*100)} ${Nw(e.risk_level)} risk`,r=An(e).join(", ");return`${e.address}. ${n}.${r?` Labels: ${r}.`:""}`}const zw=80;function yC(e){const t=Math.abs(e);return t>=1e9?`$${(e/1e9).toFixed(1)}B`:t>=1e6?`$${(e/1e6).toFixed(1)}M`:t>=1e4?`$${Math.round(e/1e3)}K`:t>=100?`$${Math.round(e)}`:`$${e.toFixed(2)}`}function vC(e,t){const n=u=>new Date(u<1e12?u*1e3:u),r=e&&e>0?n(e):null,i=t&&t>0?n(t):r;if(!i)return"";const o=u=>u.getUTCDate(),s=u=>u.toLocaleString("en-US",{month:"short",timeZone:"UTC"}),a=u=>`${o(u)} ${s(u)} ${u.getUTCFullYear()}`;return!r||r.toISOString().slice(0,10)===i.toISOString().slice(0,10)?a(i):r.getUTCFullYear()!==i.getUTCFullYear()?`${a(r)} – ${a(i)}`:r.getUTCMonth()!==i.getUTCMonth()?`${o(r)} ${s(r)} – ${a(i)}`:`${o(r)} – ${a(i)}`}function Pw(e){const t=e.amount_usd_sum!=null&&e.price_coverage_ratio!==0?yC(e.amount_usd_sum):"",n=vC(e.first_seen_timestamp,e.last_seen_timestamp);return[t,n].filter(Boolean).join(" · ")}function oc(e,t){const n=`${e.from} to ${e.to}. Aggregate value ${rc(e)}. ${e.tx_count??0} ${e.tx_count===1?"transfer":"transfers"}.`;return e.source==="flows"&&e.last_seen_timestamp?`${n} Last seen ${Rw(e.last_seen_timestamp,t)}.`:n}function bC(e,t){return At(e).nodes.map(n=>{const r={id:n.address,label:An(n).join(", ")||Ao(n)};n.role&&(r.role=n.role);const i=t?.(n.address);return i&&(r.href=i),r})}function wC(e,t=22){return e.length>t?`${e.slice(0,t-1)}…`:e}function _C(e,t,n={}){const r=e.ownerDocument;let i=At(t),o=n.layout??(Kf(t)?"tree":"gravity");const s={width:e.clientWidth||n.width||820,height:e.clientHeight||n.height||430};let a=Go(i,o,s.width,s.height);const u=new Map,c=new Map;let l={x:0,y:0,scale:1},d=null,f=null,h=null;const p=n.now??(()=>Date.now()),m=T=>n.nodeStyle?.(T).stroke??CT(T);e.classList.add("cia-graph-engine"),e.closest(".cia-graph-surface")||e.classList.add("cia-graph-surface");const y={model:()=>i,positions:()=>a,transform:()=>l,notes:()=>u,flags:()=>c,selected:()=>d,highlighted:()=>f,colorOf:m,now:p,dimensions:()=>s},w={selectNode:(T,F)=>H(T,F),selectEdge:(T,F)=>Q(T,F),showTooltip:(T,F)=>G(T,F),hideTooltip:()=>pe(),lost:()=>Ee()};function g(T){const F=T==="webgl"?sp("webgl"):null;if(F)try{return F(e,y,w,{label:n.label})}catch{}return ap(e,y,w,{label:n.label})}const b=n.renderer??(sp("webgl")&&aT(r)?"webgl":"svg");let v=g(b);e.dataset.renderer=v.kind;const k=()=>{const T=NT(i,a,u);if(!T)return null;const F=v.linkBounds();return F&&(T.x1=Math.min(T.x1,F.x1),T.y1=Math.min(T.y1,F.y1),T.x2=Math.max(T.x2,F.x2),T.y2=Math.max(T.y2,F.y2)),T},S=()=>{const T=k();return T?jT(T,s.width,s.height,gi):{x:0,y:0,scale:1}};l=S();const _=r.createElement("div");_.className="graph-tooltip cia-graph-tooltip",_.hidden=!0,_.setAttribute("role","tooltip"),e.append(_);let N=0,P=!1,z=!1;function j(){if(N){P=!0;return}v.build()}function K(){if(N){z=!0;return}l=S(),Y()}function Y(){v.camera()}function re(T="program"){const F=bC(i,n.href),X=d?.kind==="node"?i.nodes.find(ye=>ye.id===d.id)??null:null,Se=d?.kind==="edge"?i.edges.find(ye=>ye.id===d.id)??null:null;if(X){const ye=i.edges.filter(lt=>lt.from===X.address||lt.to===X.address);return{kind:"node",id:X.id,selectedId:X.address,nodes:F,title:"Selected address",identity:X.address,values:mC(X),related:ye,node:X,edge:null,source:T}}return Se?{kind:"edge",id:Se.id,selectedId:null,nodes:F,title:"Selected aggregate flow",identity:`${Se.from} → ${Se.to}`,values:gC(Se,p()),related:[Se],node:null,edge:Se,source:T}:{kind:null,id:null,selectedId:null,nodes:F,title:"Nothing selected",identity:"",values:[],related:[],node:null,edge:null,source:T}}function he(T){const F=re(T);M(F),n.onSelect?.(F)}function M(T){const F=n.selectionRoot,X=F?.querySelector("[data-selection-title]"),Se=F?.querySelector("[data-selection-identity]"),ye=F?.querySelector("[data-selection-meta]");!X||!Se||!ye||(X.textContent=T.title,Se.textContent=T.identity,ye.replaceChildren(...T.values.map(([lt,_t])=>{const Yt=r.createElement("div");Yt.className="meta-item",_t!=="Unavailable"&&(["From","To","First transaction","Last transaction"].includes(lt)&&Yt.classList.add("meta-item--identity"),lt==="Incoming amount (USD)"&&Yt.classList.add("meta-item--incoming"),lt==="Outgoing amount (USD)"&&Yt.classList.add("meta-item--outgoing")),["From","To","First transaction","Last transaction","Labels"].includes(lt)&&Yt.classList.add("meta-item--wide");const er=r.createElement("span");er.textContent=lt;const Pn=r.createElement("strong"),nn=["First transaction","Last transaction"].includes(lt)?Lw(_t):null;if(nn&&n.openLink){const Zt=n.openLink,Xt=r.createElement("button");Xt.type="button",Xt.className="cia-graph-explorer-link",Xt.dataset.explorer=nn,Xt.textContent=_t,Xt.setAttribute("aria-label",`${lt}: ${_t} (opens the explorer)`),Xt.addEventListener("click",()=>Zt(nn)),Pn.append(Xt)}else if(nn){const Zt=r.createElement("a");Zt.href=nn,Zt.target="_blank",Zt.rel="noopener noreferrer",Zt.textContent=_t,Zt.setAttribute("aria-label",`${lt}: ${_t} (opens in new tab)`),Pn.append(Zt)}else Pn.textContent=_t;return Yt.append(er,Pn),Yt})))}function H(T,F="program"){d=T?{kind:"node",id:T}:null,v.selection(),he(F)}function Q(T,F="program"){d=T?{kind:"edge",id:T}:null,v.selection(),he(F)}function ie(T){if(T==null)return H(null);const F=kn(i,T);if(F)return H(F);if(i.edges.some(X=>X.id===T))return Q(T)}function J(){l=S(),Y()}function I(T,F={x:s.width/2,y:s.height/2}){const X=Qu(l.scale*(1+T)),Se=X/l.scale;l={x:F.x-(F.x-l.x)*Se,y:F.y-(F.y-l.y)*Se,scale:X},Y()}function L(T){o=T,n.controls?.querySelectorAll("[data-layout]").forEach(F=>{F.classList.toggle("active",F.dataset.layout===T),F.setAttribute("aria-pressed",String(F.dataset.layout===T))}),n.onLayoutChange?.(T),a=Go(i,o,s.width,s.height),v.geometry(),J()}function G(T,F){_.textContent=F,_.hidden=!1;const X=e.getBoundingClientRect();_.style.left=`${Math.min(X.width-330,Math.max(8,T.clientX-X.left+12))}px`,_.style.top=`${Math.max(8,T.clientY-X.top+12)}px`}function pe(){_.hidden=!0}function se(T){return fC({x:T.clientX,y:T.clientY},v.surface.getBoundingClientRect(),s.width,s.height)}const ne={point:se,transform:()=>l,select(T){T.type==="select-node"?H(T.id,"pointer"):T.type==="select-edge"?Q(T.id,"pointer"):H(null,"canvas")},drag(T,F,X){!h&&(h=oC(o,T,F),!h)||lC(a,h,F,X,l)&&(ke=!0,v.moveNode(h.id))},endDrag(T){const F=h?.pointerId===T&&ke;h=dC(h,T),F&&(ke=!1,v.endMove())},pan(T,F){l={x:T.transform.x+F.x-T.point.x,y:T.transform.y+F.y-T.point.y,scale:l.scale},Y()},startPinch(){h=null},pinch(T,[F,X]){const Se=Math.hypot(X.x-F.x,X.y-F.y),ye=Qu(T.scale*Se/Math.max(1,T.distance));I(ye/l.scale-1,{x:(F.x+X.x)/2,y:(F.y+X.y)/2})}};let ke=!1;const xe=T=>{T.preventDefault(),I(T.deltaY>0?-.12:.12,se(T))},Ze={ArrowLeft:[60,0],ArrowRight:[-60,0],ArrowUp:[0,60],ArrowDown:[0,-60]},U=T=>{if(T.target!==v.surface)return;const F=Ze[T.key];F?(T.preventDefault(),l={...l,x:l.x+F[0],y:l.y+F[1]},Y()):T.key==="+"||T.key==="="?I(.18):T.key==="-"?I(-.18):T.key==="0"&&J()};let Z=()=>{};function V(){const T=v.surface,F=X=>v.pick(se(X));Z=hC(T,ne,v.kind==="svg"?void 0:F),T.addEventListener("wheel",xe,{passive:!1}),T.addEventListener("keydown",U)}function ee(){Z(),v.surface.removeEventListener("wheel",xe),v.surface.removeEventListener("keydown",U)}V();function Ee(){v.kind!=="svg"&&(ee(),v.destroy(),v=ap(e,y,w,{label:n.label}),e.dataset.renderer=v.kind,e.append(_),V(),j())}const ce=n.controls?.querySelector("[data-expand]")??null,ge=n.panel&&ce?pC(n.panel,ce,r.body):null,Le=()=>{ge?.toggle(),n.onExpansionChange?.(ge?.isOpen()??!1),requestAnimationFrame(J)},le=n.panel??e,ze=T=>{if(T.key==="Tab"&&ge?.isOpen()&&n.panel){const F=Array.from(n.panel.querySelectorAll('button,a[href],[tabindex="0"],summary')).filter(ye=>ye.checkVisibility()),X=F[0],Se=F.at(-1);T.shiftKey&&r.activeElement===X?(T.preventDefault(),Se?.focus()):!T.shiftKey&&r.activeElement===Se&&(T.preventDefault(),X?.focus())}if(T.key==="Escape"){if(ge?.isOpen()){ge.close(),n.onExpansionChange?.(!1),requestAnimationFrame(J);return}H(null,"keyboard")}};le.addEventListener("keydown",ze);const rt=[],et=(T,F)=>{T&&(T.addEventListener("click",F),rt.push([T,F]))};n.controls?.querySelectorAll("[data-layout]").forEach(T=>et(T,()=>L(T.dataset.layout==="tree"?"tree":"gravity"))),et(n.controls?.querySelector("[data-zoom='in']"),()=>I(.18)),et(n.controls?.querySelector("[data-zoom='out']"),()=>I(-.18)),et(n.controls?.querySelector("[data-zoom='fit']"),J),ge&&et(ce,Le);const me=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{const T=e.clientWidth,F=e.clientHeight;!T||!F||T===s.width&&F===s.height||(s.width=T,s.height=F,v.resize(T,F),J())});me?.observe(e),j(),n.selected&&ie(n.selected);const Je={update(T){const F=a;i=At(T);const X=i.nodes.every(ye=>F[ye.id])?{}:Go(i,o,s.width,s.height);a=Object.fromEntries(i.nodes.map(ye=>[ye.id,F[ye.id]??X[ye.id]]).filter(([,ye])=>ye)),d&&!(d.kind==="node"?i.nodes.some(ye=>ye.id===d.id):i.edges.some(ye=>ye.id===d.id))&&(d=null),f&&!i.nodes.some(ye=>ye.id===f)&&(f=null);const Se=new Set(i.nodes.map(ye=>ye.id));for(const ye of[...c.keys()])Se.has(ye)||c.delete(ye);j(),K()},merge(T,F){const X=xT(i,T,F);i=X.model;const Se=kn(i,F??At(T).checked_address);return a=Se&&o==="gravity"?GT(i,a,Se,X.added,{notes:u}):Go(i,o,s.width,s.height),j(),X.added.length&&K(),X.added},batch(T){N++;try{T()}finally{N--,!N&&P&&(P=!1,v.build()),!N&&z&&(z=!1,l=S(),Y())}},setTheme(T){T&&r.documentElement.setAttribute("data-theme",T),v.theme()},select:ie,destroy(){me?.disconnect(),ee(),le.removeEventListener("keydown",ze);for(const[T,F]of rt)T.removeEventListener("click",F);ge?.close({restoreFocus:!1}),v.destroy(),_.remove(),e.classList.remove("cia-graph-engine"),delete e.dataset.renderer,delete e.ciaGraph},fit:J,zoom:T=>I(T),setLayout:L,markNode(T,F){const X=kn(i,T);X&&(F?u.set(X,F):u.delete(X),j())},patchNode(T,F){const X=kn(i,T),Se=X?i.nodes.find(ye=>ye.id===X):null;return Se?(Object.assign(Se,F),v.selection(),!0):!1},flagNode(T,F,X){const Se=kn(i,T);if(!Se)return;const ye=c.get(Se)??new Set;X?ye.add(F):ye.delete(F),ye.size?c.set(Se,ye):c.delete(Se),N?P=!0:v.flag(Se,F,X)},positions:()=>structuredClone(a),model:()=>i,contentBounds:()=>k(),transform:()=>({...l}),highlight(T){f=T==null?null:kn(i,T),v.selection()},renderer:()=>v.kind,clientPoint(T){const F=kn(i,T),X=F?a[F]:null;if(!X)return null;const Se=v.surface.getBoundingClientRect(),ye=Math.min(Se.width/s.width,Se.height/s.height)||1,lt=Se.left+(Se.width-s.width*ye)/2,_t=Se.top+(Se.height-s.height*ye)/2;return{x:lt+(X.x*l.scale+l.x)*ye,y:_t+(X.y*l.scale+l.y)*ye}}};return Object.defineProperty(e,"ciaGraph",{value:Je,configurable:!0}),Je}const Dw="chain-insights.flows.v1",Ka="chain-insights.result.v1",Ow=5e3,gp=6,kC=3,Mw=/^0x[0-9a-fA-F]{40}$/,SC=/^0x[0-9a-fA-F]{64}$/;function xC(e){return typeof e=="string"&&(Mw.test(e)||SC.test(e))}function bi(e){return typeof e=="string"&&Mw.test(e)}function sc(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ja(e){const t=e?.facts?.query?.results;return Array.isArray(t)?t.filter(sc):[]}function EC(e){const t=e?.facts;return typeof t?.subject?.network=="string"&&t.subject.network?t.subject.network:"robinhood"}function Jt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&/^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(e.trim())){const t=Number(e);return Number.isFinite(t)?t:null}return null}function Xf(e){return e<1e11?e*1e3:e}const Fw=/^\d{4}-\d{2}-\d{2}$/,$C=Date.UTC(2009,0,1),TC=Date.UTC(2100,0,1);function ns(e){return new Date(Xf(e)).toISOString().slice(0,10)}function ys(e){if(typeof e!="string"||!Fw.test(e))return!1;const t=Date.parse(`${e}T00:00:00Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e}const CC=new Set(["day","date","hour","week","month"]),AC=["_timestamp","_time","_at"];function yp(e){return CC.has(e)||AC.some(t=>e.endsWith(t))}function Uw(e){const t=[];for(const n of e)for(const r of Object.keys(n))t.includes(r)||t.push(r);return t}function IC(e){return Array.isArray(e)?e.some(bi):bi(e)}function NC(e){return e.some(t=>Object.values(t).some(IC))}function Gw(e){return e.length>0&&e.every(t=>bi(t.from_address)&&bi(t.to_address))}const RC=/^(\d{4})-(\d{2})$/,LC=/^(\d{4})-W(\d{2})$/,zC=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,PC=/(?:Z|[+-]\d{2}:?\d{2})$/i;function DC(e,t){const n=Date.UTC(e,0,4);return n-(new Date(n).getUTCDay()+6)%7*864e5+(t-1)*7*864e5}function vp(e){if(typeof e=="string"){const r=e.trim();if(Fw.test(r))return ys(r)?Date.parse(`${r}T00:00:00Z`):null;const i=RC.exec(r);if(i){const s=Number(i[2])-1;return s>=0&&s<12?Date.UTC(Number(i[1]),s,1):null}const o=LC.exec(r);if(o){const s=Number(o[2]);return s>=1&&s<=53?DC(Number(o[1]),s):null}if(zC.test(r)){const s=r.replace(" ","T"),a=Date.parse(PC.test(s)?s:`${s}Z`);return Number.isFinite(a)?a:null}}const t=Jt(e);if(t==null)return null;const n=Xf(t);return n>=$C&&n<TC?n:null}function Qf(e,t={}){if(e.length===0||NC(e))return null;const n=Uw(e),i=n.filter(yp).find(d=>e.some(f=>vp(f[d])!=null));if(!i)return null;const o=n.filter(d=>{if(yp(d))return!1;const f=e.map(h=>h[d]).filter(h=>h!=null);return f.length>0&&f.every(h=>Jt(h)!=null)});if(o.length===0)return null;const s=o.slice(0,gp),a=new Map;let u=0;for(const d of e){const f=vp(d[i]);if(f==null)continue;u++;const h=a.get(f)??{count:0,sums:s.map(()=>null)};h.count++,s.forEach((p,m)=>{const y=Jt(d[p]);y!=null&&(h.sums[m]=(h.sums[m]??0)+y)}),a.set(f,h)}const c=[...a.entries()].sort((d,f)=>d[0]-f[0]);return c.filter(([,d])=>d.sums.some(f=>f!=null)).length<(t.minPoints??kC)?null:{xColumn:i,times:c.map(([d])=>d),rowCounts:c.map(([,d])=>d.count),daily:c.every(([d])=>d%864e5===0),series:s.map((d,f)=>({column:d,values:c.map(([,h])=>h.sums[f]??null)})),omittedColumns:o.slice(gp),skippedRows:e.length-u,failures:[]}}function OC(e){if(!e)return"failed";const t=/^\s*([a-z][a-z0-9_]*)\s*:/.exec(e);if(t?.[1])return t[1];const n=e.trim().split(/\s+/).slice(0,4).join(" ");return n.length>40?`${n.slice(0,39)}…`:n||"failed"}const MC=e=>e==null||Jt(e)!=null;function jw(e){const t=Bw(e);if(t.length<3||!t.every(c=>ys(c.id))||new Set(t.map(c=>c.id)).size!==t.length)return null;const n=t.filter(c=>c.ok);if(n.length===0||!n.every(c=>c.rows.length===1))return null;const r=Object.keys(n[0].rows[0]),i=[...r].sort().join("\0");for(const c of n){const l=c.rows[0];if(Object.keys(l).sort().join("\0")!==i||!Object.values(l).every(MC))return null}if(r.length===0||r.includes("day"))return null;const o=[...t].sort((c,l)=>c.id.localeCompare(l.id)),s=o.map(c=>({day:c.id,...c.ok?c.rows[0]:Object.fromEntries(r.map(l=>[l,null]))})),a=o.filter(c=>!c.ok).map(c=>({day:c.id,time:Date.parse(`${c.id}T00:00:00Z`),code:OC(c.error)})),u=Qf(s,{minPoints:1});return u?{rows:s,columns:r,failures:a,model:{...u,failures:a}}:null}const FC=/\baddress\s*:\s*(["'])(0x[0-9a-fA-F]{40})\1/g,UC=/^\s*(<)?-(?:\[[^\]]*\])?-(>)?/,GC=/(<)?-(?:\[[^\]]*\])?-(>)?\s*$/;function bp(e,t){if(!e)return"none";const n=!!e[1],r=!!e[2];return n===r?null:t==="after"?r?"from":"to":r?"to":"from"}function Zw(e){if(typeof e!="string"||!e)return null;const t=[...e.matchAll(FC)];if(t.length===0||new Set(t.map(r=>r[2].toLowerCase())).size!==1)return null;let n=null;for(const r of t){const i=r.index??0,o=e.lastIndexOf("(",i),s=e.indexOf(")",i);if(o<0||s<0)return null;const a=[bp(GC.exec(e.slice(0,o)),"before"),bp(UC.exec(e.slice(s+1)),"after")];if(a.includes(null))return null;for(const u of a)if(u!=="none"){if(n&&n!==u)return null;n=u}}return n?{address:t[0][2],end:n}:null}function jC(e,t){if(e.length===0||Gw(e))return null;const n=Zw(t);if(!n)return null;const r=n.address.toLowerCase(),i=Uw(e).filter(s=>e.every(a=>bi(a[s]))&&!e.every(a=>String(a[s]).toLowerCase()===r));if(i.length!==1)return null;const o=i[0];return e.map(s=>n.end==="from"?{...s,from_address:n.address,to_address:s[o]}:{...s,from_address:s[o],to_address:n.address})}function ZC(e){return Gw(e)?"graph":Qf(e)?"chart":"table"}const BC=[["sanctioned","sanctioned"],["scam","scam"],["victim","victim"],["pool","pool"],["exchange","exchange"]];function wp(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim()):[]}function HC(e,t){if(t)return"exchange";const n=new Set(e.map(r=>r.replace(/\s+/g,"").toLowerCase()));for(const[r,i]of BC)if(n.has(r))return i;return"other"}const _p=(e,t)=>e==null?t:t==null?e:e+t;function VC(e,t="robinhood",n){const r=new Map;for(const h of e)for(const p of new Set([String(h.from_address).toLowerCase(),String(h.to_address).toLowerCase()]))r.set(p,(r.get(p)??0)+1);let i="",o=0;for(const[h,p]of r)p>o&&(i=h,o=p);const s=n?.toLowerCase();s&&r.has(s)&&(i=s);const a=new Map,u=new Map,c=(h,p,m)=>{const y=a.get(h)??{address:h,labels:[],exchange:!1};for(const w of p)y.labels.some(g=>g.toLowerCase()===w.toLowerCase())||y.labels.push(w);y.exchange=y.exchange||m,a.set(h,y)};i&&a.set(i,{address:i,labels:[],exchange:!1});let l=0;for(const h of e){const p=String(h.from_address).toLowerCase(),m=String(h.to_address).toLowerCase(),y=[p,m].filter((k,S,_)=>!a.has(k)&&_.indexOf(k)===S).length;if(a.size+y>Ow||(l++,c(p,wp(h.from_labels),h.from_is_exchange===!0),c(m,wp(h.to_labels),h.to_is_exchange===!0),p===m))continue;const w=`${p}->${m}`,g=u.get(w)??{from:p,to:m,usd:null,tx:null,first:null,last:null,kinds:[]};g.usd=_p(g.usd,Jt(h.amount_usd_sum)),g.tx=_p(g.tx,Jt(h.tx_count));const b=Jt(h.first_seen_timestamp),v=Jt(h.last_seen_timestamp);b!=null&&(g.first=g.first==null?b:Math.min(g.first,b)),v!=null&&(g.last=g.last==null?v:Math.max(g.last,v)),typeof h.link_kind=="string"&&h.link_kind&&!g.kinds.includes(h.link_kind)&&g.kinds.push(h.link_kind),u.set(w,g)}const d=[...a.values()].map(h=>({address:h.address,role:HC(h.labels,h.exchange),labels:h.labels})),f=[...u.values()].map(h=>({from:h.from,to:h.to,usd:h.usd,tx_count:h.tx,first_seen_ms:h.first,last_seen_ms:h.last,...h.kinds.length?{link_kind:h.kinds.join(", ")}:{}}));return{view:{schema:Dw,network:t,center:i,nodes:d,edges:f,truncated:!1},rowsTotal:e.length,rowsDrawn:l,rowsLeftOut:e.length-l,addresses:a.size}}function Bw(e){const t=e?.facts?.queries;return Array.isArray(t)?t.filter(sc).map((n,r)=>({id:typeof n.id=="string"&&n.id?n.id:`Query ${r+1}`,ok:n.ok!==!1&&n.error==null,error:typeof n.error=="string"&&n.error?n.error:null,rows:Array.isArray(n.results)?n.results.filter(sc):[],count:typeof n.count=="number"?n.count:null,truncated:n.truncated===!0,elapsedMs:typeof n.elapsed_ms=="number"?n.elapsed_ms:null,query:typeof n.query=="string"&&n.query?n.query:null})):[]}const kp=200;function Hr(e){return(e?.content??[]).filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
109
- `).trim()}function Kr(e){if(typeof e=="string")return e.trim()||null;if(!e||typeof e!="object"||Array.isArray(e))return null;const{code:t,message:n,detail:r,error:i}=e,o=[n,r,i].find(a=>typeof a=="string"&&a.trim()!=="")?.trim()??null,s=typeof t=="string"&&t.trim()?t.trim():null;return o?s&&!o.startsWith(s)?`${s}: ${o}`:o:s}function Hw(e){if(!e)return null;const t=e.structuredContent,n=Kr(t?.error)??Kr(t?.facts?.error)??Kr(t?.facts?.query?.error);if(!e.isError||n)return n;const r=Hr(e);if(r.startsWith("{"))try{const i=JSON.parse(r),o=Kr(i?.error)??Kr(i);if(o)return o}catch{}return r||"The tool answered with an error."}const qC=new Set(["usage_status","subscription_status","meta_usage_status","meta_subscription_status"]);function Vw(e){if(!e||Hw(e)!=null)return"text";const t=e.structuredContent;if(t?.schema===Dw)return"flows";if(t?.schema===Ka){if(t.tool==="graph_query")return ZC(Ja(t));if(t.tool==="graph_query_batch")return!Array.isArray(t.facts?.queries)||t.facts.queries.length===0?"text":jw(t)?"chart":"batch";if(typeof t.tool=="string"&&qC.has(t.tool))return"balance"}return"text"}function A(e,t,n={},...r){const i=e.createElement(t);for(const[o,s]of Object.entries(n))s==null||s===!1||(o==="class"?i.className=String(s):o==="text"?i.textContent=String(s):i.setAttribute(o,s===!0?"":String(s)));for(const o of r)o==null||o===!1||i.append(typeof o=="string"?e.createTextNode(o):o);return i}function WC(e,t){const n=A(e,"code",{class:"cv-addr",title:t,"data-full":t,text:yi(t)}),r=A(e,"button",{type:"button",class:"cv-copy","data-copy":t,"aria-label":`Copy ${t}`,title:"Copy the full value",text:"Copy"});return r.addEventListener("click",()=>{KC(e,t,n,r)}),A(e,"span",{class:"cv-addr-cell"},n,r)}async function KC(e,t,n,r){const i=e.defaultView?.navigator?.clipboard;try{if(i?.writeText)return await i.writeText(t),r&&(r.textContent="Copied"),"copied"}catch{}return n.textContent=t,n.classList.add("is-full"),e.getSelection?.()?.selectAllChildren(n),r&&(r.textContent="Selected"),"selected"}function JC(e,t){return/(timestamp|seen|_at|_ms|time)$/i.test(t)&&e>1e9?$n(e):/usd/i.test(t)?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e):new Intl.NumberFormat("en-US",{maximumFractionDigits:4}).format(e)}const YC=160,Sp=2e3;function XC(e,t=YC){const n=e.trim().split(/\r?\n/,1)[0]??"",r=n.search(/[.!?](?=\s|$)/),i=(r<0?n:n.slice(0,r+1)).trim();if(i.length<=t)return i;const o=i.slice(0,t-1),s=o.lastIndexOf(" ");return`${(s>t*.6?o.slice(0,s):o).trimEnd()}…`}function qw(e,t,n){const r=e.ownerDocument,i=n.full!=null&&n.full.length>Sp?`${n.full.slice(0,Sp-1)}…`:n.full,o=i!=null&&i!==t,s=A(r,"section",{class:`cia-graph-surface cv-notice cv-notice-${n.kind}`,"data-view":n.view,"data-notice":n.kind,role:n.kind==="refused"?"alert":"status",title:o?i:null},o?A(r,"details",{class:"cv-notice-more"},A(r,"summary",{class:"cv-notice-line",text:t}),A(r,"p",{class:"cv-notice-full",text:i})):A(r,"p",{class:"cv-notice-line",text:t}));return e.replaceChildren(s),s}function QC(e){const t=e?.facts?.query,n=Array.isArray(t?.results)?t.results.filter(o=>!!o&&typeof o=="object"&&!Array.isArray(o)):[],r=n.slice(0,kp),i=[];for(const o of r)for(const s of Object.keys(o))i.includes(s)||i.push(s);return{columns:i,rows:r,total:n.length,truncated:n.length>kp||t?.truncated===!0,elapsedMs:typeof t?.elapsed_ms=="number"?t.elapsed_ms:null}}function eA(e,t,n){return t==null?A(e,"span",{class:"cv-null","aria-label":"empty",text:"—"}):xC(t)?WC(e,t):typeof t=="number"?e.createTextNode(JC(t,n)):typeof t=="boolean"?e.createTextNode(t?"yes":"no"):Array.isArray(t)?e.createTextNode(t.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(", ")):typeof t=="object"?e.createTextNode(JSON.stringify(t)):e.createTextNode(String(t))}const tA={from_address:"From address",to_address:"To address",address:"Address",amount_usd_sum:"Value (USD)",amount_usd:"Value (USD)",usd:"Value (USD)",tx_count:"Transfers",first_seen_timestamp:"First seen (UTC)",last_seen_timestamp:"Last seen (UTC)",first_activity_timestamp:"First activity (UTC)",last_activity_timestamp:"Last activity (UTC)",block_timestamp:"Time (UTC)",block_date:"Day",block_height:"Block",tx_id:"Transaction",from_labels:"From labels",to_labels:"To labels",labels:"Labels",degree_in:"Senders",degree_out:"Receivers",total_in_usd:"Incoming (USD)",total_out_usd:"Outgoing (USD)",total_volume_usd:"Volume (USD)",asset_symbol:"Token",amount:"Amount"};function nA(e){const t=tA[e];if(t)return t;const n=e.replace(/_/g," ").trim();return n?n[0].toUpperCase()+n.slice(1):e}function xp(e,t,n={}){const r=e.ownerDocument,i=QC(t.structuredContent),o=i.rows.length;if(i.total===0)return qw(e,"No rows.",{kind:"empty",view:"table"}),i;const s=`${new Intl.NumberFormat("en-US").format(o)} ${o===1?"row":"rows"}${i.elapsedMs==null?"":` in ${i.elapsedMs} ms`}`,a=A(r,"table",{class:"cv-table"},A(r,"thead",{},A(r,"tr",{},...i.columns.map(u=>A(r,"th",{scope:"col",title:u,text:nA(u)})))),A(r,"tbody",{},...i.rows.map(u=>A(r,"tr",{},...i.columns.map(c=>A(r,"td",{},eA(r,u[c],c)))))));return e.replaceChildren(A(r,"section",{class:"cv-card cv-table-view","data-view":"table","aria-label":"Graph query result"},A(r,"header",{class:"cv-card-head"},A(r,"strong",{text:"Graph query result"}),A(r,"span",{class:"cv-muted",text:s}),n.toggle??null),i.truncated?A(r,"p",{class:"cv-note",role:"note","data-truncated":"",text:`Truncated: showing the first ${new Intl.NumberFormat("en-US").format(o)} of ${new Intl.NumberFormat("en-US").format(i.total)} rows. Narrow the query to see the rest.`}):null,i.columns.length?A(r,"div",{class:"cv-table-wrap"},a):null)),i}const Jr=(e,t=0)=>typeof e=="number"&&Number.isFinite(e)?e:t,jo=e=>typeof e=="string"&&e?e:null;function rA(e){const t=e?.facts??{};if(typeof t.wallet=="string"&&t.wallet)return{kind:"wallet",wallet:t.wallet,tier:String(t.tier??"anonymous"),allowanceUsd:Jr(t.allowance_usd),consumedUsd:Jr(t.consumed_usd),windowEnd:jo(t.window_end)};const n=t.usage;if(n&&typeof n=="object"){const r="daily_units_limit"in n||"daily_units_used"in n,i=jo(n.access_mode);return{kind:"free",unit:r?"units":"seconds",used:Jr(r?n.daily_units_used:n.daily_seconds_used),limit:Jr(r?n.daily_units_limit:n.daily_seconds_limit),remaining:Jr(r?n.remaining_units:n.remaining_seconds),resetAt:jo(n.reset_at),identifierKind:jo(n.identifier_kind),accessMode:i,noLimit:!r&&i==="public_free"&&n.daily_seconds_limit===0}}return{kind:"unknown"}}const Ep=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e),Zo=(e,t)=>`${new Intl.NumberFormat("en-US").format(e)} ${t==="units"?e===1?"unit":"units":e===1?"second":"seconds"}`;function hu(e){if(!e)return"No active window";const t=Date.parse(e);return Number.isFinite(t)?`${$n(t)} UTC`:e}function $p(e,t,n,r){const i=n>0?Math.min(1,t/n):0,o=A(e,"div",{class:"cv-meter",role:"meter","aria-label":r,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":Math.min(t,n)},A(e,"span"));return o.firstElementChild.style.width=`${Math.round(i*100)}%`,o}function pu(e,t){return A(e,"dl",{class:"cv-facts"},...t.flatMap(([n,r])=>[A(e,"dt",{text:n}),A(e,"dd",{text:r})]))}function iA(e,t){const n=e.ownerDocument,r=rA(t.structuredContent);let i,o,s;return r.kind==="wallet"?(o="Wallet allowance",s=`${yi(r.wallet)} · ${r.tier==="subscriber"?"Subscriber":"No active subscription"}`,i=[$p(n,r.consumedUsd,r.allowanceUsd,"Share of today's allowance used"),pu(n,[["Daily allowance",Ep(r.allowanceUsd)],["Used today",Ep(r.consumedUsd)],["Window ends",hu(r.windowEnd)]])]):r.kind==="free"?(o="Free tier",s=`No wallet · counted per ${r.identifierKind==="ip"||!r.identifierKind?"network address":r.identifierKind}`,i=r.noLimit?[A(n,"p",{class:"cv-balance-note","data-no-limit":"",text:"Free access, no daily limit"}),pu(n,[["Daily allowance","No daily limit"],["Used today",Zo(r.used,r.unit)],["Window ends",hu(r.resetAt)]])]:[$p(n,r.used,r.limit,"Share of today's free allowance used"),pu(n,[["Daily allowance",Zo(r.limit,r.unit)],["Used today",Zo(r.used,r.unit)],["Left today",Zo(r.remaining,r.unit)],["Window ends",hu(r.resetAt)]])]):(o="Usage",s="The server sent no allowance figures.",i=[A(n,"p",{class:"cv-muted",text:Hr(t)||"Nothing to show."})]),e.replaceChildren(A(n,"section",{class:"cv-card cv-balance-view","data-view":"balance","data-balance":r.kind,"aria-label":o},A(n,"header",{class:"cv-card-head"},A(n,"strong",{text:o}),A(n,"span",{class:"cv-muted",text:s})),...i)),r}function wi(e,t,n="No drawing for this answer."){const r=e.ownerDocument,i=Hw(t);if(i!=null){qw(e,XC(i),{kind:"refused",view:"text",full:i});return}const o=Hr(t);e.replaceChildren(A(r,"section",{class:"cv-card cv-text-view","data-view":"text"},A(r,"p",{text:n}),o?A(r,"p",{class:"cv-muted cv-text-body",text:o.length>600?`${o.slice(0,599)}…`:o}):null))}function eh(e,t="Loading the Chain Insights view"){const n=e.ownerDocument;e.replaceChildren(A(n,"section",{class:"cv-card cv-skeleton","data-view":"loading","aria-busy":"true","aria-label":t},A(n,"span",{class:"cv-sr",text:t}),A(n,"div",{class:"cv-skel-line cv-skel-title"}),A(n,"div",{class:"cv-skel-line cv-skel-sub"}),A(n,"div",{class:"cv-skel-block"})))}const oA="http://www.w3.org/2000/svg",ac=720,sA=320,aA=6,uA=420,Tp=4,cA=120,ri={left:70,right:18,top:6},uc=18,Ww=16,Kw=6,Jw=26,lA=170,dA=82,fA=28,hA=80,Bn=1e3,xn=60*Bn,ir=60*xn,en=24*ir,pA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Yw(e,t){if(/usd/i.test(e))return"usd";const n=t.filter(r=>r!=null);return n.length>0&&n.every(Number.isInteger)?"count":"number"}const mA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),gA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumSignificantDigits:2}),yA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:"compact",maximumFractionDigits:1}),_i=new Intl.NumberFormat("en-US",{maximumFractionDigits:0}),vA=new Intl.NumberFormat("en-US",{maximumFractionDigits:4}),Xw=new Intl.NumberFormat("en-US",{maximumSignificantDigits:3}),Qw=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:2}),bA=new Intl.NumberFormat("en-US",{maximumFractionDigits:6});function vs(e,t){if(e==null)return"—";const n=e!==0&&Math.abs(e)<.01;return t==="usd"?n?gA.format(e):mA.format(e):t==="count"?_i.format(e):n?Xw.format(e):vA.format(e)}function wA(e){return e!==0&&Math.abs(e)<.01?Xw.format(e):Math.abs(e)<1e3?bA.format(Math.round(e*100)/100):Qw.format(e)}function Cp(e,t){return t==="usd"?Math.abs(e)<1e3?vs(e,"usd"):yA.format(e):t==="count"?Math.abs(e)<1e3?_i.format(e):Qw.format(e):wA(e)}function _A(e,t){const n=new Date(e).toISOString();return t?`${n.slice(0,10)} (UTC day)`:`${n.slice(0,10)} ${n.slice(11,19)} UTC`}function e_(e){return e<=en?"time":e<=cA*en?"day":"month"}const kA=[Bn,2*Bn,5*Bn,10*Bn,15*Bn,30*Bn,xn,2*xn,5*xn,10*xn,15*xn,30*xn,ir,2*ir,3*ir,6*ir,12*ir,en],SA=[1,2,3,7,14,30,60].map(e=>e*en),xA=[1,2,3,6,12,24,60,120],Ap=4*en,EA={time:76,day:84,month:72},$A=e=>new Date(e).getUTCFullYear()*12+new Date(e).getUTCMonth(),mu=e=>Date.UTC(Math.floor(e/12),e%12,1);function TA(e,t,n){const r=t-e,i=e_(r);if(r<=0)return{unit:i,step:0,times:[e]};const o=Math.max(2,Math.floor(n));if(i==="month"){for(const s of xA){const a=[];let u=$A(e);for(mu(u)<e&&u++;mu(u)<=t;u++)u%s===0&&a.push(mu(u));if(a.length<=o&&a.length>0)return{unit:i,step:s,times:a}}return{unit:i,step:0,times:[e,t]}}for(const s of i==="time"?kA:SA){const a=s===7*en||s===14*en?Math.ceil((e-Ap)/s)*s+Ap:i==="day"?Math.ceil(e/en)*en:Math.ceil(e/s)*s,u=a>t?0:Math.floor((t-a)/s)+1;if(u>0&&u<=o)return{unit:i,step:s,times:Array.from({length:u},(c,l)=>a+l*s)}}return{unit:i,step:0,times:[e,t]}}function CA(e,t,n){const r=new Date(e),i=r.toISOString();return t==="month"?n>=12?i.slice(0,4):`${pA[r.getUTCMonth()]} ${r.getUTCFullYear()}`:t==="day"||e%en===0?i.slice(0,10):n>0&&n<xn?i.slice(11,19):i.slice(11,16)}function AA(e){return e.series.map(t=>{let n=0,r=null,i=null;return t.values.forEach((o,s)=>{o!=null&&(n+=o,(r==null||o>r)&&(r=o,i=e.times[s]??null))}),{column:t.column,kind:Yw(t.column,t.values),total:n,peak:r,peakTime:i}})}const Pt=e=>new Date(e).toISOString(),t_=(e,t)=>Pt(e).slice(0,10)===Pt(t).slice(0,10);function IA(e){const t=e.times[0],n=e.times[e.times.length-1];if(t==null||n==null)return"no points";if(e.daily)return t===n?`${Pt(t).slice(0,10)} UTC`:`${Pt(t).slice(0,10)} to ${Pt(n).slice(0,10)} UTC`;const r=i=>`${Pt(i).slice(0,10)} ${Pt(i).slice(11,16)}`;return t===n?`${r(t)} UTC`:t_(t,n)?`${r(t)} to ${Pt(n).slice(11,16)} UTC`:`${r(t)} to ${r(n)} UTC`}function NA(e,t=new Set){const n=e.times.map((u,c)=>e.series.some(l=>l.values[c]!=null)),r=n.filter(Boolean).length,i=e.rowCounts.reduce((u,c,l)=>u+(n[l]?c:0),0),o=[IA(e),`${_i.format(r)} ${r===1?"point":"points"}${i>r?` from ${_i.format(i)} transfers`:""}`],s=e.times[0]??0,a=e.times[e.times.length-1]??0;for(const u of AA(e)){if(t.has(u.column))continue;if(u.peak==null||u.peakTime==null){o.push(`${u.column}: no values`);continue}const c=e.daily?`on ${Pt(u.peakTime).slice(0,10)}`:t_(s,a)?`at ${Pt(u.peakTime).slice(11,19)}`:`at ${Pt(u.peakTime).slice(0,10)} ${Pt(u.peakTime).slice(11,16)}`;o.push(`${u.column}: total ${vs(u.total,u.kind)}, peak ${vs(u.peak,u.kind)} ${c}`)}return e.failures.length&&o.push(`no answer for ${e.failures.map(u=>`${u.day} (${u.code})`).join(", ")}`),o.join(" · ")}function RA(e,t){if(e.length===0)return-1;let n=0,r=e.length-1;for(;n<r;){const i=n+r>>1;(e[i]??0)<t?n=i+1:r=i}return n>0&&Math.abs(t-(e[n-1]??0))<=Math.abs((e[n]??0)-t)?n-1:n}function LA(e,t,n){const r=Math.min(t,n),i=Math.max(t,n);let o=-1,s=-1;return e.forEach((a,u)=>{a<r||a>i||(o<0&&(o=u),s=u)}),o>=0&&s-o>=1?{start:o,end:s}:null}function zA(e,t,n){const r=Math.max(0,t),i=Math.min(e.times.length-1,n)+1,o=e.times.slice(r,i),s=o[0]??0,a=o[o.length-1]??0;return{...e,times:o,rowCounts:e.rowCounts.slice(r,i),series:e.series.map(u=>({column:u.column,values:u.values.slice(r,i)})),failures:e.failures.filter(u=>u.time>=s&&u.time<=a)}}function PA(e,t,n){if(e.has(t)){const r=new Set(e);return r.delete(t),r}return n.filter(r=>!e.has(r)).length<=1?e:new Set([...e,t])}const n_=e=>`var(--cia-graph-series-${e%aA+1})`;function bs(e,t){const n=e.last-e.first,r=e.plotRight-e.plotLeft;return n>0?e.plotLeft+(t-e.first)/n*r:e.plotLeft+r/2}function gu(e,t){const n=e.plotRight-e.plotLeft,r=Math.min(e.plotRight,Math.max(e.plotLeft,t));return n>0?e.first+(r-e.plotLeft)/n*(e.last-e.first):e.first}function r_(e,t){return e.plotBottom-(t-e.min)/(e.max-e.min||1)*(e.plotBottom-e.plotTop)}function DA(e){if(e<=1)return lA;const t=Math.floor((uA-ri.top-Kw-Jw-(e-1)*Ww)/e)-uc;return Math.max(fA,Math.min(dA,t))}function Ip(e,t=ac,n=new Set){const r=ri.left,i=t-ri.right,o=e.times[0]??0,s=e.times[e.times.length-1]??o,a={plotLeft:r,plotRight:i,first:o,last:s},u=e.series.map((p,m)=>({series:p,index:m})).filter(({series:p})=>!n.has(p.column)),c=DA(u.length),l=u.map(({series:p,index:m},y)=>{const w=ri.top+y*(uc+c+Ww),g=w+uc,b=g+c,v=p.values.filter(j=>j!=null),k=Math.min(0,...v),S=Math.max(...v,k+1e-9),_={plotTop:g,plotBottom:b,min:k,max:S},N=[],P=[];let z=[];return p.values.forEach((j,K)=>{if(j==null){z.length&&P.push(z),z=[];return}const Y=e.times[K]??o,re={x:bs(a,Y),y:r_(_,j),time:Y,value:j,index:K};N.push(re),z.push(re)}),z.length&&P.push(z),{column:p.column,index:m,kind:Yw(p.column,p.values),color:n_(m),top:w,plotTop:g,plotBottom:b,min:k,max:S,runs:P,points:N}}),d=(l[l.length-1]?.plotBottom??ri.top)+Kw,f=e_(s-o),h=[];if(e.times.length){const p=TA(o,s,(i-r)/EA[f]);for(const m of p.times){const y=bs(a,m),w=y-r<34?"start":i-y<34?"end":"middle";h.push({x:y,label:CA(m,p.unit,p.step),anchor:w})}}return{width:t,height:d+Jw,plotLeft:r,plotRight:i,first:o,last:s,unit:f,lanes:l,ticks:h,axisY:d}}function it(e,t,n={}){const r=e.createElementNS(oA,t);for(const[i,o]of Object.entries(n))r.setAttribute(i,String(o));return r}const Bt=e=>Math.round(e*10)/10;let OA=0;const MA="Time series plot. Left and Right arrows read the points one by one, Home and End jump to the ends, Escape hides the read-out. Drag across the plot to zoom.";function FA(e,t,n={}){const r=e.ownerDocument,i=t.series.map(I=>I.column),o={start:0,end:t.times.length-1};let s=new Set,a=o,u=null,c=null,l=ac,d=t,f=Ip(t,l);const h=A(r,"span",{class:"cv-muted cv-chart-summary","data-chart-summary":""}),p=t.series.map((I,L)=>{const G=A(r,"span",{class:"cv-chart-key","aria-hidden":"true"});G.style.setProperty("--cv-key",n_(L));const pe=A(r,"button",{type:"button",class:"cv-chart-series","data-series":I.column,"aria-pressed":"true"},G,A(r,"span",{text:I.column}));return pe.addEventListener("click",()=>{const se=PA(s,I.column,i);se!==s&&(s=se,z())}),pe}),m=A(r,"div",{class:"cv-chart-legend",role:"group","aria-label":"Show or hide a series"},...p),y=A(r,"button",{type:"button",class:"cv-chart-reset","data-reset-zoom":"",hidden:!0,text:"Reset zoom"}),w=it(r,"svg",{class:"cv-chart-svg",role:"img",preserveAspectRatio:"xMidYMid meet"}),g=A(r,"div",{class:"cv-chart-readout",id:`cv-chart-readout-${++OA}`,"data-chart-readout":"",role:"status","aria-live":"polite",hidden:!0}),b=A(r,"div",{class:"cv-chart-plot",tabindex:0,role:"group","aria-label":MA,"aria-describedby":g.id},w),v=A(r,"div",{class:"cv-chart-body"},b,g),k=it(r,"rect",{class:"cv-chart-brush"}),S=it(r,"g",{class:"cv-chart-cross","aria-hidden":"true"}),_=[t.omittedColumns.length?`${t.omittedColumns.length} more number ${t.omittedColumns.length===1?"column is":"columns are"} only in the table: ${t.omittedColumns.join(", ")}.`:"",t.skippedRows?`${t.skippedRows} ${t.skippedRows===1?"row has":"rows have"} no usable ${t.xColumn} and ${t.skippedRows===1?"is":"are"} only in the table.`:""].filter(Boolean),N=A(r,"section",{class:"cv-chart cia-graph-surface","data-view":"chart","aria-label":`Time series by ${t.xColumn}`},A(r,"header",{class:"cv-flows-head"},A(r,"div",{class:"cv-title"},A(r,"strong",{text:"Time series"}),h)),_.length?A(r,"p",{class:"cv-note",role:"note","data-chart-note":"",text:_.join(" ")}):null,A(r,"div",{class:"cv-chart-bar"},m,y,n.toggle??null),v);e.replaceChildren(N);function P(){const I=[],L=f.lanes[0]?.plotTop??0,G=d.times.length>1?(f.plotRight-f.plotLeft)/(d.times.length-1):24,pe=Math.max(6,Math.min(24,G*.6));for(const ne of d.failures){const ke=bs(f,ne.time),xe=it(r,"rect",{class:"cv-chart-failure","data-failure":ne.day,x:Bt(ke-pe/2),y:L,width:Bt(pe),height:Math.max(0,f.axisY-L)});I.push(xe)}for(const ne of f.lanes){const ke=it(r,"g",{class:"cv-chart-lane","data-series":ne.column}),xe=it(r,"rect",{class:"cv-chart-swatch",x:f.plotLeft,y:ne.top+4,width:14,height:4,rx:2});xe.style.fill=ne.color;const Ze=it(r,"text",{class:"cv-chart-name",x:f.plotLeft+20,y:ne.top+11});Ze.textContent=ne.column,ke.append(xe,Ze,it(r,"line",{class:"cv-chart-grid",x1:f.plotLeft,x2:f.plotRight,y1:ne.plotTop,y2:ne.plotTop}),it(r,"line",{class:"cv-chart-base",x1:f.plotLeft,x2:f.plotRight,y1:ne.plotBottom,y2:ne.plotBottom}));const U=it(r,"text",{class:"cv-chart-tick",x:f.plotLeft-8,y:ne.plotTop+4,"text-anchor":"end"});U.textContent=Cp(ne.max,ne.kind);const Z=it(r,"text",{class:"cv-chart-tick",x:f.plotLeft-8,y:ne.plotBottom+4,"text-anchor":"end"});Z.textContent=Cp(ne.min,ne.kind),ke.append(U,Z);for(const V of ne.runs){if(V.length<2)continue;const ee=it(r,"polyline",{class:"cv-chart-line",points:V.map(Ee=>`${Bt(Ee.x)},${Bt(Ee.y)}`).join(" "),fill:"none"});ee.style.stroke=ne.color,ke.append(ee)}if(ne.points.length<=hA)for(const V of ne.points){const ee=it(r,"circle",{class:"cv-chart-dot",cx:Bt(V.x),cy:Bt(V.y),r:3,"data-index":a.start+V.index,"data-time":V.time});ee.style.fill=ne.color,ke.append(ee)}I.push(ke)}const se=it(r,"g",{class:"cv-chart-axis"});for(const ne of f.ticks){const ke=it(r,"text",{class:"cv-chart-tick",x:Bt(ne.x),y:f.axisY+14,"text-anchor":ne.anchor});ke.textContent=ne.label,se.append(ke)}return I.push(se),I}function z(){d=zA(t,a.start,a.end),f=Ip(d,l,s);const I=f.lanes.map(G=>G.column);w.setAttribute("viewBox",`0 0 ${f.width} ${f.height}`),w.setAttribute("aria-label",`Line chart of ${I.join(", ")} by ${t.xColumn}, ${d.times.length} ${d.times.length===1?"point":"points"}`),w.replaceChildren(k,...P(),S),h.textContent=NA(d,s);for(const G of p){const pe=!s.has(G.dataset.series??"");G.setAttribute("aria-pressed",String(pe)),pe&&I.length===1?(G.setAttribute("aria-disabled","true"),G.title="At least one series stays visible"):(G.removeAttribute("aria-disabled"),G.removeAttribute("title"))}const L=a.start!==o.start||a.end!==o.end;y.hidden=!L,N.dataset.zoomed=String(L),j(),K()}function j(){if(!c||Math.abs(c.to-c.from)<Tp){k.style.display="none";return}const I=f.lanes[0]?.plotTop??0,L=Math.max(f.plotLeft,Math.min(c.from,c.to)),G=Math.min(f.plotRight,Math.max(c.from,c.to));k.setAttribute("x",String(Bt(L))),k.setAttribute("width",String(Bt(Math.max(0,G-L)))),k.setAttribute("y",String(I)),k.setAttribute("height",String(Math.max(0,f.axisY-I))),k.style.display=""}function K(){if(S.replaceChildren(),u==null||u<a.start||u>a.end){u=null,S.style.display="none",g.hidden=!0,g.replaceChildren(),delete b.dataset.focus;return}const I=u-a.start,L=d.times[I]??f.first,G=Bt(bs(f,L)),pe=f.lanes[0]?.plotTop??0;S.append(it(r,"line",{class:"cv-chart-crossline",x1:G,x2:G,y1:pe,y2:f.axisY}));const se=[];for(const xe of f.lanes){const Ze=d.series[xe.index]?.values[I]??null;if(Ze!=null){const Z=it(r,"circle",{class:"cv-chart-focus",cx:G,cy:Bt(r_(xe,Ze)),r:4.5});Z.style.fill=xe.color,S.append(Z)}const U=A(r,"span",{class:"cv-chart-key","aria-hidden":"true"});U.style.setProperty("--cv-key",xe.color),se.push(A(r,"dt",{},U,xe.column),A(r,"dd",{"data-value":xe.column,text:vs(Ze,xe.kind)}))}S.style.display="",S.dataset.index=String(u),S.dataset.time=String(L),b.dataset.focus=String(u);const ne=d.failures.find(xe=>xe.time===L),ke=d.rowCounts[I]??1;g.replaceChildren(...[A(r,"time",{datetime:new Date(L).toISOString(),text:_A(L,d.daily)}),ne?A(r,"p",{class:"cv-chart-readout-note","data-failure":ne.code,text:`No answer: ${ne.code}`}):null,ke>1?A(r,"p",{class:"cv-chart-readout-note","data-rows":ke,text:`${_i.format(ke)} transfers`}):null,A(r,"dl",{},...se)].filter(xe=>xe!=null)),g.hidden=!1,Y(G,pe)}function Y(I,L){const G=w.getBoundingClientRect(),pe=v.getBoundingClientRect(),se=G.width>0?G.width/f.width:1,ne=G.left-pe.left+I*se,ke=I>(f.plotLeft+f.plotRight)/2;g.style.left=`${Math.round(ke?ne-12:ne+12)}px`,g.style.top=`${Math.round(G.top-pe.top+L*se)}px`,g.dataset.side=ke?"left":"right"}const re=I=>{const L=w.getBoundingClientRect();return L.width>0?(I-L.left)*f.width/L.width:Number.NaN},he=I=>a.start+RA(d.times,gu(f,I));b.addEventListener("pointermove",I=>{const L=re(I.clientX);Number.isFinite(L)&&(c&&(c.to=L,j()),u=he(L),K())}),b.addEventListener("pointerdown",I=>{if(I.button!==0)return;const L=re(I.clientX);if(Number.isFinite(L)){I.preventDefault(),b.focus({preventScroll:!0}),c={from:L,to:L,pointer:I.pointerId};try{b.setPointerCapture(I.pointerId)}catch{}}});const M=I=>{if(!c)return;const{from:L,to:G,pointer:pe}=c;c=null;try{b.releasePointerCapture(pe)}catch{}if(j(),!I||Math.abs(G-L)<Tp)return;const se=LA(t.times,gu(f,L),gu(f,G));!se||se.start===a.start&&se.end===a.end||(a=se,u=he(G),z())};b.addEventListener("pointerup",()=>M(!0)),b.addEventListener("pointercancel",()=>M(!1)),b.addEventListener("pointerleave",()=>{c||(u=null,K())}),b.addEventListener("keydown",I=>{let L;if(I.key==="ArrowRight")L=u==null?a.start:Math.min(a.end,u+1);else if(I.key==="ArrowLeft")L=u==null?a.end:Math.max(a.start,u-1);else if(I.key==="Home")L=a.start;else if(I.key==="End")L=a.end;else if(I.key==="Escape"){if(u==null&&!c)return;c&&M(!1),L=null}else return;I.preventDefault(),u=L,K()}),y.addEventListener("click",()=>{a=o,u=null,z(),b.focus({preventScroll:!0})});const H=()=>{const I=Math.round(b.clientWidth);return I>0?Math.max(sA,I):null},Q=()=>{const I=H();I==null||I===l||(l=I,z())};l=H()??ac,z();const ie=r.defaultView?.ResizeObserver,J=ie?new ie(()=>Q()):null;return J?.observe(b),{root:N,get layout(){return f},refit:Q,destroy(){J?.disconnect()}}}const UA="chain-insights.transfers.v1",GA="graph_expand",i_=25;function jA(e,t,n,r,i={}){const o=i.cursor??{day:r,skip:0};return{network:e,from:t,to:n,day:o.day,...o.skip?{skip:o.skip}:{},...i.firstDay?{first_day:i.firstDay}:{},limit:i.limit??i_}}function ZA(e,t){const n=typeof e.first_seen_timestamp=="number"&&e.first_seen_timestamp>0?ns(e.first_seen_timestamp):null,r=typeof e.last_seen_timestamp=="number"&&e.last_seen_timestamp>0?ns(e.last_seen_timestamp):ns(t);return{first:n,last:n&&r<n?n:r}}function BA(e){if(!e)return"no answer";const t=Hr(e);return e.isError?t||"the server refused the read":/query_timeout|topology_busy/.test(t)?t:o_(e.structuredContent)?null:t||"the answer held no transfers"}function o_(e){const t=e;if(!t||t.schema!==UA||!Array.isArray(t.transfers)||typeof t.from!="string"||typeof t.to!="string"||!ys(t.day))return null;const n=[];for(const o of t.transfers){if(!o||typeof o!="object")continue;const s=o;if(typeof s.tx_id!="string")continue;const a=Jt(s.block_timestamp);n.push({tx_id:s.tx_id,block_timestamp:a,amount:typeof s.amount=="string"?s.amount:typeof s.amount=="number"?String(s.amount):null,asset_symbol:typeof s.asset_symbol=="string"&&s.asset_symbol?s.asset_symbol:null,amount_usd:Jt(s.amount_usd)})}const r=t.next,i=r&&typeof r=="object"&&ys(r.day)?{day:r.day,skip:Math.max(0,Math.floor(Jt(r.skip)??0))}:null;return{network:typeof t.network=="string"?t.network:null,from:t.from,to:t.to,day:t.day,transfers:n,truncated:t.truncated===!0,next:i}}function HA(e){return[...e].sort((t,n)=>(n.block_timestamp??0)-(t.block_timestamp??0)||t.tx_id.localeCompare(n.tx_id))}function VA(e){if(e==null)return"—";const t=e.trim().match(/^(-?)(\d+)(?:\.(\d+))?$/);if(!t)return e;const[,n="",r="0",i=""]=t,o=i.replace(/0+$/,"");return`${n}${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}${o?`.${o}`:""}`}function qA(e){return e==null?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:e!==0&&Math.abs(e)<.01?6:2}).format(e)}function WA(e){return e==null?"—":`${new Date(Xf(e)).toISOString().slice(11,19)} UTC`}function yu(e){return new Intl.DateTimeFormat("en-GB",{dateStyle:"medium",timeZone:"UTC"}).format(new Date(`${e}T00:00:00Z`))}function KA(e,t){const n=new Map;for(const r of e){const i=r.block_timestamp==null?t:ns(r.block_timestamp);n.has(i)||n.set(i,[]),n.get(i).push(r)}return[...n.entries()].sort(([r],[i])=>i.localeCompare(r)).map(([r,i])=>({day:r,transfers:i}))}function JA(e,t){const n=t.now??Date.now,r=A(e,"strong",{"data-link-title":"",text:"Transfers"}),i=A(e,"button",{type:"button",class:"cv-button cv-icon","data-link-close":"","aria-label":"Close the transfers",text:"×"}),o=A(e,"p",{class:"cv-link-pair","data-link-pair":""}),s=A(e,"div",{class:"cv-link-body","data-link-body":"",role:"status","aria-live":"polite"}),a=A(e,"button",{type:"button",class:"cv-button","data-link-more":"",text:"More transfers"}),u=A(e,"section",{class:"cv-linkpanel cv-linkpanel-embedded","data-link-panel":"","aria-label":"Transfers of the selected link",hidden:!0},A(e,"header",{class:"cv-link-head"},r,null),o,s,a);let c=null,l=0;function d(){if(!c){u.hidden=!0;return}u.hidden=!1,o.replaceChildren(A(e,"code",{"data-link-from":"",text:c.from})," → ",A(e,"code",{"data-link-to":"",text:c.to}));const y=c.transfers.length;r.textContent=y?`Transfers · ${y} listed`:"Transfers",a.hidden=!c.next||c.status==="error",a.disabled=c.status==="loading",a.textContent=c.status==="loading"&&c.pages?"Loading…":"More transfers",a.setAttribute("aria-label",c.next?`More transfers: the ${i_} before ${yu(c.next.day)}`:"More transfers");const w=[];if(y)for(const g of KA(c.transfers,c.day))w.push(A(e,"p",{class:"cv-link-day","data-link-day":g.day,text:`${yu(g.day)} (UTC)`})),w.push(A(e,"ol",{class:"cv-transfers"},...g.transfers.map(b=>YA(e,b,t.host))));c.status==="loading"?w.push(A(e,"p",{class:"cv-muted","data-link-loading":"",text:y?"Loading older transfers…":`Loading the transfers from ${yu(c.day)} back…`})):c.status==="error"?w.push(A(e,"p",{class:"cv-link-error","data-link-error":"",role:"alert",text:c.error??"The transfers could not be read."})):y||w.push(A(e,"p",{class:"cv-muted","data-link-empty":"",text:"No transfers between these two addresses in the days read."})),c.status==="ready"&&c.truncated&&w.push(A(e,"p",{class:"cv-muted","data-link-truncated":"",text:"A day held more transfers than one read lists; its oldest are not shown."})),c.status==="ready"&&!c.next&&y&&w.push(A(e,"p",{class:"cv-muted","data-link-first":"",text:c.firstDay?"Every transfer back to the day the link was first seen is listed.":"No older transfers were found."})),s.replaceChildren(...w)}async function f(y){const w=++l,g=c;g.status="loading",g.error=null,d(),t.onLayout?.();let b=null;try{b=await t.host.callServerTool({name:GA,arguments:jA(t.network,g.from,g.to,g.day,{firstDay:g.firstDay,cursor:y})})}catch(k){b={isError:!0,content:[{type:"text",text:k instanceof Error?k.message:String(k)}]}}if(w!==l||c!==g)return g;const v=BA(b);if(v)g.status="error",g.error=v.length>300?`${v.slice(0,299)}…`:v;else{const k=o_(b.structuredContent),S=new Set(g.transfers.map(_=>_.tx_id+String(_.block_timestamp)));g.status="ready",g.transfers=[...g.transfers,...HA(k.transfers).filter(_=>!S.has(_.tx_id+String(_.block_timestamp)))],g.truncated=g.truncated||k.truncated,g.next=k.next,g.pages+=1}return d(),t.onLayout?.(),g}const h=()=>m.close(),p=()=>{m.more()};i.addEventListener("click",h),a.addEventListener("click",p);const m={element:u,open(y){const w=ZA(y,n());return c={from:y.from,to:y.to,day:w.last,firstDay:w.first,status:"loading",transfers:[],next:null,pages:0,truncated:!1,error:null},f(null)},async more(){return!c||c.status==="loading"||!c.next?null:f(c.next)},close(){l++,c=null,d(),t.onLayout?.()},state:()=>c?{...c,transfers:[...c.transfers]}:null,destroy(){l++,i.removeEventListener("click",h),a.removeEventListener("click",p)}};return m}function YA(e,t,n){const r=Lw(t.tx_id),i=n.openLink,o=r&&i?A(e,"button",{type:"button",class:"cia-graph-explorer-link","data-explorer":r,"aria-label":`Transaction ${t.tx_id} (opens the explorer)`,title:t.tx_id,text:yi(t.tx_id)}):A(e,"code",{title:t.tx_id,text:yi(t.tx_id)});return r&&i&&o.addEventListener("click",()=>{i.call(n,{url:r}).catch(()=>{})}),A(e,"li",{class:"cv-transfer","data-tx":t.tx_id},A(e,"span",{class:"cv-transfer-time",text:WA(t.block_timestamp)}),A(e,"span",{class:"cv-transfer-amount",text:`${VA(t.amount)}${t.asset_symbol?` ${t.asset_symbol}`:""}`}),A(e,"span",{class:"cv-transfer-usd",text:t.amount_usd==null?"— USD":qA(t.amount_usd)}),o)}const Np="graph_expand",Bo="too busy to expand",s_=640,XA=300,vu=.45,QA="Full screen shows the whole graph",e1="Open in browser",bu="The host did not open the link.",t1="If nothing opened, copy this link into your browser:",Rp=400,wu="expanded",a_=5e3,n1="Click an address for its details. Double-click it to load its senders and receivers, and again to fold them back. Click a link to list its transfers.",r1="chain-insights.address.v1";function i1(e,t){return{network:e,address:t,details:!0}}function o1(e){const t=e;if(!t||t.schema!==r1||typeof t.address!="string")return null;const n=i=>typeof i=="number"&&Number.isFinite(i)?i:null,r={address:t.address.toLowerCase(),total_in_usd:n(t.total_in_usd),total_out_usd:n(t.total_out_usd),degree_in:n(t.degree_in),degree_out:n(t.degree_out)};return Array.isArray(t.labels)&&(r.labels=t.labels.filter(i=>typeof i=="string")),typeof t.role=="string"&&Br.includes(t.role)&&(r.role=t.role),r}function s1(e){return e.total_in_usd==null&&e.total_out_usd==null&&e.degree_in==null&&e.degree_out==null}const cc=new Intl.NumberFormat("en-US");function Lp(e){const t=e.remaining;if(!t||typeof t!="object")return null;const n=Number(t.senders),r=Number(t.receivers);return!Number.isFinite(n)||!Number.isFinite(r)?null:{senders:Math.max(0,n),receivers:Math.max(0,r)}}function a1(e){if(!e||e.senders+e.receivers<=0)return null;const t=(n,r)=>`${cc.format(n)} more ${r}${n===1?"":"s"}`;return`${t(e.senders,"sender")}, ${t(e.receivers,"receiver")} not loaded`}function u1(e,t){return`Not loaded: ${cc.format(e)} ${e===1?"link":"links"} of ${t} would take the picture past ${cc.format(a_)} addresses. Fold another address to make room.`}const zp=e=>!!(e&&(e.truncated||e.remaining&&e.remaining.senders+e.remaining.receivers>0));let c1=0;const l1=[["scam","Scam"],["sanctioned","Sanctioned"],["exchange","Exchange"],["victim","Victim"],["pool","Pool"],["other","Other"]];function th(e){return typeof e=="string"&&/^http:\/\/(?:127\.0\.0\.1|localhost):\d+(?:[/?#]|$)/.test(e)}function d1(e){return!e.browser&&!!e.host.openLink&&th(e.viewUrl)}function f1(e,t,n){return{network:e,address:t,in_offset:n?.in_offset??0,out_offset:n?.out_offset??0}}function h1(e){const t=Hr(e);return e?e.isError?t||"the server refused the expansion":/query_timeout|topology_busy/.test(t)?t:Kf(e.structuredContent)?null:t||"the answer held no money flows":"no answer"}function p1(e,t,n,r=s_,i=XA){if(!e||t<=0)return{height:r,fits:!0};const o=Math.max(1,e.x2-e.x1),s=Math.max(1,e.y2-e.y1),a=Math.max(vu,Math.min(1,(t-gi*2)/o)),u=Math.ceil(n+s*a+gi*2),c=Math.min(r,Math.max(i,u));return lp(e,t,c-n)>=vu?{height:c,fits:!0}:{height:r,fits:lp(e,t,r-n)>=vu}}function m1(e){return/query_timeout|topology_busy|timed? ?out/i.test(e)}function Pp(e){const t=e.split(`
110
- `)[0].trim();return t.length>200?`${t.slice(0,199)}…`:t}function g1(e,t){return`investigator expanded ${e}: ${t} new addresses`}function y1(e,t){const n=e.nodes.find(r=>r.address.toLowerCase()===t.toLowerCase());return n&&Ao({role:n.role??null,labels:n.labels??[]})||"Other"}function u_(e,t,n){const r=e.ownerDocument,i=t.network??"robinhood",o=t.center.toLowerCase(),s=()=>new Map(t.cursor?[[o,{cursor:t.cursor,truncated:!!t.truncated,remaining:Lp(t)}]]:[]);let a=s();const u=new Set,c=new Set;let l=[];const d=new Set;let f=null,h=null;const p=n.now??Date.now,m=n.title??"Money flow graph",y=A(r,"p",{class:"cv-status",role:"status","aria-live":"polite",text:n1}),w=A(r,"ul",{class:"cv-roles","aria-label":"Address roles"}),g=A(r,"div",{class:"cv-canvas","data-graph":""}),b=A(r,"div",{class:"cv-detail","aria-label":"Selection"},A(r,"strong",{"data-selection-title":""}),A(r,"code",{"data-selection-identity":""}),A(r,"div",{class:"cv-detail-meta","data-selection-meta":""})),v=A(r,"strong",{"data-side-title":"",text:"Details"}),k=A(r,"button",{type:"button",class:"cv-button cv-icon","data-side-close":"","aria-label":"Close the details",text:"×"}),S=A(r,"button",{type:"button",class:"cv-button","data-toggle-expand":"",hidden:!0,text:"Expand"}),_=A(r,"button",{type:"button",class:"cv-button","data-more":"",hidden:!0,text:"More flows"}),N=A(r,"p",{class:"cv-remaining cv-muted","data-remaining":"",hidden:!0}),P=JA(r,{host:n.host,network:i,now:n.now,embedded:!0,onLayout:()=>X()}),z=A(r,"aside",{class:"cv-side","data-side-panel":"","aria-label":"Details of the selection",hidden:!0},A(r,"header",{class:"cv-side-head"},v,k),b,N,A(r,"div",{class:"cv-side-actions"},S,_),P.element),j=A(r,"button",{type:"button",class:"cv-button","data-fullscreen":"",hidden:!0,"aria-label":"Open full screen",text:"Full screen"}),K=A(r,"button",{type:"button",class:"cv-button","data-reset":"","aria-label":"Reset: fold every expansion back and draw the first answer again",title:"Fold every expansion back and draw the first answer again",text:"Reset"}),Y=A(r,"span",{class:"cv-hint","data-fullscreen-hint":"",hidden:!0,text:QA}),re=A(r,"button",{type:"button",class:"cv-button","data-open-browser":"",hidden:!d1(n),"aria-label":"Open the graph in your browser",title:"Open the graph in your browser",text:e1}),he=A(r,"div",{class:"cv-toggle",role:"group","aria-label":"Layout"},A(r,"button",{type:"button",class:"cv-toggle-button","data-layout":"gravity","aria-pressed":"true",title:"Linked addresses pull together; an expansion settles around the address you opened",text:"Gravity"}),A(r,"button",{type:"button",class:"cv-toggle-button","data-layout":"tree","aria-pressed":"false",title:"Senders left, receivers right, newest activity first",text:"Tree"})),M=A(r,"div",{class:"cv-actions"},he,A(r,"button",{type:"button",class:"cv-button cv-icon","data-zoom":"out","aria-label":"Zoom out",text:"−"}),A(r,"button",{type:"button",class:"cv-button cv-icon","data-zoom":"in","aria-label":"Zoom in",text:"+"}),A(r,"button",{type:"button",class:"cv-button","data-zoom":"fit","aria-label":"Fit the graph",text:"Fit"}),K,Y,j,re),H=A(r,"span",{class:"cv-muted","data-subtitle":""}),Q=`cv-addresses-${++c1}`,ie=A(r,"div",{class:"cv-visually-hidden",role:"listbox",tabindex:"0",id:Q,"data-address-list":"","aria-label":"Drawn addresses. Down and Up move, Enter shows the details, Shift+Enter expands or folds."});let J=[],I=-1;const L=A(r,"section",{class:"cv-flows cia-graph-surface","data-view":"flows","aria-label":`${m} of ${o}`},A(r,"header",{class:"cv-flows-head"},A(r,"div",{class:"cv-title"},A(r,"strong",{text:m}),H),n.toggle??null,M),w,n.note?A(r,"p",{class:"cv-note",role:"note","data-left-out":"",text:n.note}):null,A(r,"div",{class:"cv-body"},ie,g,z),y);e.replaceChildren(L);function G(){const D=me.model(),ae=D.truncated?" · more flows than shown":"";H.textContent=`${o} · ${y1(t,o)} · ${i} · ${D.nodes.length} addresses${ae}`;const ve=new Set(D.nodes.map(je=>je.role??"other")),Oe=l1.filter(([je])=>je!=="other"&&ve.has(je));w.hidden=Oe.length===0,w.replaceChildren(...Oe.map(([je,mt])=>{const Ve=A(r,"i",{"aria-hidden":"true"});return Ve.style.background=`var(--cia-graph-role-${je})`,A(r,"li",{"data-role":je},Ve,mt)})),pe()}function pe(){const D=me.model().nodes,ae=J[I]??null;J=D.map(Oe=>Oe.address.toLowerCase()),ie.replaceChildren(...D.map((Oe,je)=>A(r,"div",{role:"option",id:`${Q}-${je}`,"data-list-address":J[je],"aria-selected":"false",text:`${Oe.address} ${Ao({role:Oe.role??null,labels:Oe.labels??[]})||"Other"}`})));const ve=ae?J.indexOf(ae):-1;I=ve>=0?ve:J.length?Math.min(Math.max(I,-1),J.length-1):-1,se()}function se(){for(const ae of ie.children)ae.setAttribute("aria-selected",String(ae.id===`${Q}-${I}`));I>=0?ie.setAttribute("aria-activedescendant",`${Q}-${I}`):ie.removeAttribute("aria-activedescendant");const D=r.activeElement===ie;me.highlight(D?J[I]??null:null)}function ne(D){return D?me.model().nodes.find(ae=>ae.id===D)?.address.toLowerCase()??null:null}const ke=D=>{const ae=D.target,ve=D.key==="Enter"||D.key===" ",Oe=ae?.closest?.("[data-node-id]");if(ve&&D.shiftKey&&Oe){D.preventDefault();const je=ne(Oe.dataset.nodeId);je&&_t(je)}};g.addEventListener("keydown",ke,!0);function xe(D){J.length&&(I=Math.max(0,Math.min(J.length-1,D)),se())}const Ze=()=>{I<0&&J.length&&(I=0),se()},U=()=>me.highlight(null),Z=D=>{const ae=J[I];switch(D.key){case"ArrowDown":D.preventDefault(),xe(I+1);return;case"ArrowUp":D.preventDefault(),xe(I-1);return;case"Home":D.preventDefault(),xe(0);return;case"End":D.preventDefault(),xe(J.length-1);return;case"Escape":nu();return;case"Enter":case" ":if(D.preventDefault(),!ae)return;D.shiftKey?_t(ae):me.select(ae);return}};ie.addEventListener("focus",Ze),ie.addEventListener("blur",U),ie.addEventListener("keydown",Z);function V(){const D=h;if(!D){S.hidden=!0,_.hidden=!0,N.hidden=!0;return}const ae=d.has(D),ve=ae?a1(a.get(D)?.remaining??null):null;N.hidden=!ve,N.textContent=ve??"",S.hidden=!1,S.disabled=u.has(D)||c.has(D),S.textContent=u.has(D)?"Too busy to expand":ae?"Collapse":"Expand",S.setAttribute("aria-label",`${S.textContent} ${D}`),_.hidden=!(ae&&zp(a.get(D)))}function ee(D){const ae=z.hidden;z.hidden=D.kind==null,D.kind==="node"&&D.node?(h=D.node.address.toLowerCase(),v.textContent="Address details",P.close(),s1(D.node)&&ce(h)):(h=null,D.kind==="edge"?v.textContent="Link details":P.close()),V(),ae!==z.hidden&&X()}const Ee=new Set;async function ce(D){if(Ee.has(D))return;Ee.add(D);let ae=null;try{ae=await n.host.callServerTool({name:Np,arguments:i1(i,D)})}catch(mt){ae={isError:!0,content:[{type:"text",text:mt instanceof Error?mt.message:String(mt)}]}}const ve=ae&&!ae.isError?o1(ae.structuredContent):null;if(!ve){Ee.delete(D),y.textContent=`The totals of ${D} could not be read: ${Pp(ae&&Hr(ae)||"no answer")}.`;return}const{address:Oe,...je}=ve;me.patchNode(D,je)&&h===D&&me.select(D)}let ge=null;function Le(){ge&&clearTimeout(ge),ge=null}function le(D){const ae=D.source==="pointer"&&D.kind==="node"&&D.node,ve=D.source!=="program"&&D.kind==="edge"&&D.edge;if(Le(),ae){const Oe=D.node.address.toLowerCase(),je=p();f&&f.address===Oe&&je-f.at<=Rp?(f=null,nu(),_t(Oe)):(f={address:Oe,at:je},ge=setTimeout(()=>{ge=null,ee(D)},Rp));return}D.kind!=="node"&&(f=null),ee(D),ve&&P.open(D.edge)}const ze=n.height??s_,rt=`${m} of ${o}: senders on the left, receivers on the right. Select an address for its details; double-click it, or press Shift+Enter, to load its senders and receivers, and again to fold them back. Select a link to list its transfers.`;function et(){return _C(g,t,{layout:n.layout??"gravity",width:n.width??720,height:ze,now:n.now,controls:M,selectionRoot:b,onSelect:le,openLink:D=>{n.host.openLink?.({url:D}).catch(()=>{y.textContent=bu})},label:rt})}let me=et();G();let Je=n.displayMode??"inline",T=n.availableDisplayModes??[];const F=()=>!n.browser&&!!n.host.requestDisplayMode&&(T.length===0||T.includes("fullscreen"));function X(){if(Je==="fullscreen"){L.style.removeProperty("height"),Y.hidden=!0;return}const D=g.clientWidth||n.width||720,ae=Math.max(0,L.offsetHeight-g.offsetHeight)||140,{height:ve,fits:Oe}=p1(me.contentBounds(),D,ae);L.style.height=`${ve}px`,Y.hidden=Oe||!F(),L.dataset.fits=String(Oe),me.fit()}async function Se(D){try{await n.host.updateModelContext?.({content:[{type:"text",text:D}]})}catch{}}async function ye(D,ae=!1){const ve=D.toLowerCase();if(u.has(ve))return y.textContent=`${ve} is ${Bo}.`,{added:[],refused:Bo};if(c.has(ve))return{added:[],refused:null};const Oe=a.get(ve);if(Oe&&!zp(Oe))return y.textContent=`Every recent flow of ${ve} is drawn.`,{added:[],refused:null};c.add(ve),V(),y.textContent=`Loading the flows of ${ve}…`;let je=null;try{je=await n.host.callServerTool({name:Np,arguments:f1(i,ve,ae||Oe?Oe?.cursor:null)})}catch(xt){je={isError:!0,content:[{type:"text",text:xt instanceof Error?xt.message:String(xt)}]}}finally{c.delete(ve)}const mt=h1(je);if(mt)return m1(mt)?(u.add(ve),me.markNode(ve,Bo),y.textContent=`${ve} is ${Bo}. The drawing is kept.`):y.textContent=`${ve} could not be expanded: ${Pp(mt)}. The drawing is kept; try again.`,V(),{added:[],refused:mt};const Ve=je.structuredContent,ru=me.model(),Dn=new Set(ru.nodes.map(xt=>xt.address.toLowerCase())),iu=new Set;for(const xt of Ve.nodes)Dn.has(xt.address.toLowerCase())||iu.add(xt.address.toLowerCase());for(const xt of Ve.edges)for(const No of[xt.from,xt.to])Dn.has(No.toLowerCase())||iu.add(No.toLowerCase());if(Dn.size+iu.size>a_){const xt=new Set(ru.edges.map(On=>`${On.from.toLowerCase()}->${On.to.toLowerCase()}`)),No=new Set(Ve.edges.map(On=>`${On.from.toLowerCase()}->${On.to.toLowerCase()}`).filter(On=>!xt.has(On))).size,dh=u1(No,ve);return y.textContent=dh,V(),{added:[],refused:dh}}const Io=me.merge(Ve,ve);return l.push({address:ve,page:Ve}),d.add(ve),me.flagNode(ve,wu,!0),a.set(ve,{cursor:Ve.cursor??null,truncated:!!Ve.truncated,remaining:Lp(Ve)}),G(),X(),V(),y.textContent=`${Io.length} new ${Io.length===1?"address":"addresses"} linked to ${ve}. Double-click it again to fold them back.`,await Se(g1(ve,Io.length)),{added:Io,refused:null}}function lt(D){const ae=D.toLowerCase();if(!d.has(ae))return{removed:0};const ve=me.model().nodes.length;d.delete(ae),a.delete(ae);const Oe=l.filter(Ve=>Ve.address!==ae),je=[];me.batch(()=>{me.flagNode(ae,wu,!1),me.update(t);for(const Ve of Oe)me.model().nodes.some(Dn=>Dn.address.toLowerCase()===Ve.address)?(me.merge(Ve.page,Ve.address),je.push(Ve)):je.some(Dn=>Dn.address===Ve.address)||(me.flagNode(Ve.address,wu,!1),d.delete(Ve.address),a.delete(Ve.address))}),l=je;const mt=Math.max(0,ve-me.model().nodes.length);return h&&!me.model().nodes.some(Ve=>Ve.address.toLowerCase()===h)&&(z.hidden=!0,h=null),G(),X(),V(),y.textContent=`Folded ${ae} back: ${mt} ${mt===1?"address":"addresses"} removed.`,Se(`investigator collapsed ${ae}: ${mt} addresses removed`),{removed:mt}}async function _t(D){d.has(D)?lt(D):await ye(D)}function Yt(){Le(),me.destroy(),l=[],d.clear(),u.clear(),c.clear(),a=s(),Ee.clear(),f=null,h=null,P.close(),z.hidden=!0,me=et(),G(),X(),V(),y.textContent="The first answer again: every expansion folded back."}function er(D,ae){D&&(Je=D),ae&&(T=ae),L.dataset.displayMode=Je,j.hidden=!F(),j.textContent=Je==="fullscreen"?"Exit full screen":"Full screen",j.setAttribute("aria-label",Je==="fullscreen"?"Back to the inline view":"Open full screen"),X()}er(Je);const Pn=async()=>{const D=Je==="fullscreen"?"inline":"fullscreen";try{const ae=await n.host.requestDisplayMode?.({mode:D});er(ae?.mode??D)}catch{y.textContent="The host did not change the display mode."}},nn=(D,ae)=>{y.replaceChildren(A(r,"span",{text:`${D} `}),A(r,"code",{class:"cv-view-link","data-view-link":"",text:ae}))},Zt=async()=>{const D=n.viewUrl;if(!(!th(D)||!n.host.openLink)){nn(t1,D);try{(await n.host.openLink({url:D}))?.isError===!0&&nn(bu,D)}catch{nn(bu,D)}}},Xt=()=>Yt();function nu(){Le();const D=!z.hidden;me.select(null),P.close(),z.hidden=!0,h=null,V(),D&&X()}const uh=()=>nu(),ch=()=>{h&&_t(h)},lh=()=>{h&&ye(h,!0)};return j.addEventListener("click",Pn),re.addEventListener("click",Zt),K.addEventListener("click",Xt),k.addEventListener("click",uh),S.addEventListener("click",ch),_.addEventListener("click",lh),{root:L,get graph(){return me},expand:D=>ye(D),collapse:lt,reset:Yt,expanded:()=>[...d],setLayout:D=>me.setLayout(D),linkPanel:P,openLink(D,ae){const ve=me.model().edges.find(Oe=>Oe.from===D.toLowerCase()&&Oe.to===ae.toLowerCase());return ve?(me.select(ve.id),P.open(ve)):Promise.resolve(null)},setTheme(D){me.setTheme(D)},setDisplayMode:er,refit:X,destroy(){Le(),g.removeEventListener("keydown",ke,!0),ie.removeEventListener("focus",Ze),ie.removeEventListener("blur",U),ie.removeEventListener("keydown",Z),j.removeEventListener("click",Pn),re.removeEventListener("click",Zt),K.removeEventListener("click",Xt),k.removeEventListener("click",uh),S.removeEventListener("click",ch),_.removeEventListener("click",lh),P.destroy(),me.destroy()}}}function lc(e){return{kind:e,flows:()=>[],setTheme(){},setDisplayMode(){},refit(){},destroy(){}}}function v1(e,t){return{kind:e,flows:()=>{const n=t();return n?[n]:[]},setTheme(n){t()?.setTheme(n)},setDisplayMode(n,r){t()?.setDisplayMode(n,r)},refit(){t()?.refit()},destroy(){t()?.destroy()}}}const c_=e=>({host:e.host,availableDisplayModes:e.availableDisplayModes,displayMode:e.displayMode,now:e.now,width:e.width,height:e.height,viewUrl:e.browser?null:e.viewUrl??null,browser:e.browser===!0});function b1(e){return typeof e?.query=="string"&&e.query?e.query:null}function w1(e,t,n){const r=Array.isArray(e?.queries)?e.queries:[],i=s=>{const a=s?.query;return typeof a=="string"&&a?a:null},o=r.find(s=>s?.id===t);return i(o||r[n])}function _1(e,t){const n=e.structuredContent;if(!t||!n?.facts?.query)return e;const r=jC(Ja(n),t);return r?{...e,structuredContent:{...n,facts:{...n.facts,query:{...n.facts.query,results:r}}}}:e}function k1(e,t){if(e<=0)return null;const n=new Intl.NumberFormat("en-US");return`${n.format(e)} of ${n.format(t)} rows ${e===1?"is":"are"} not drawn: a graph holds at most ${n.format(Ow)} addresses. The table has the rows.`}function S1(e,t,n){const r=[];let i="picture";const o=s=>{for(const a of s.querySelectorAll("[data-show]"))a.setAttribute("aria-pressed",String(a.dataset.show===i))};return{make(){const s=A(e,"button",{type:"button",class:"cv-toggle-button","data-show":"picture",text:t}),a=A(e,"button",{type:"button",class:"cv-toggle-button","data-show":"table",text:"Table"});s.addEventListener("click",()=>n("picture")),a.addEventListener("click",()=>n("table"));const u=A(e,"div",{class:"cv-toggle",role:"group","aria-label":"Show the rows as"},s,a);return r.push(u),o(u),u},set(s){i=s,r.forEach(o)}}}function x1(e,t){const n=t?.facts?.subject;return{content:[],structuredContent:{schema:Ka,tool:"graph_query",facts:{...n?{subject:n}:{},query:{results:e,count:e.length,truncated:!1}}}}}function E1(e){const t=jw(e.structuredContent);if(t)return{model:t.model,table:x1(t.rows,e.structuredContent)};const n=Qf(Ja(e.structuredContent));return n?{model:n,table:e}:null}function l_(e,t,n,r=null){const i=e.ownerDocument,o=_1(t,r),s=Vw(o),a=s==="chart"?E1(o):null;if(s!=="graph"&&!a)return s==="table"?xp(e,o):wi(e,o),lc(s==="table"?"table":"text");const u=o.structuredContent,c=Ja(u),l=a?.table??t,d=A(i,"div",{class:"cv-face","data-face":"picture"}),f=A(i,"div",{class:"cv-face","data-face":"table",hidden:!0});e.replaceChildren(d,f);const h=S1(i,s==="graph"?"Graph":"Chart",g=>w(g));let p=null,m=null,y=-1;if(s==="graph"){const g=VC(c,EC(u),Zw(r)?.address);p=u_(d,g.view,{...c_(n),title:"Money flow graph",toggle:h.make(),note:k1(g.rowsLeftOut,g.rowsTotal)})}else m=FA(d,a.model,{toggle:h.make()});function w(g){if(d.hidden=g!=="picture",f.hidden=g!=="table",g==="table"){const b=p?.expanded().length?p.graph.model():null,v=b?b.nodes.length*100003+b.edges.length:0;y!==v&&(y=v,xp(f,b?$1(b,l):l,{toggle:h.make()}))}h.set(g),g==="picture"&&(p?.refit(),m?.refit())}return{kind:s,flows:()=>p?[p]:[],setTheme(g){p?.setTheme(g)},setDisplayMode(g,b){p?.setDisplayMode(g,b)},refit(){d.hidden||(p?.refit(),m?.refit())},destroy(){p?.destroy(),m?.destroy()}}}function $1(e,t){const n=new Map(e.nodes.map(o=>[o.address,o.labels??[]])),r=e.edges.map(o=>({from_address:o.from,to_address:o.to,amount_usd_sum:o.amount_usd_sum,tx_count:o.tx_count,first_seen_timestamp:o.first_seen_timestamp,last_seen_timestamp:o.last_seen_timestamp,from_labels:n.get(o.from)??[],to_labels:n.get(o.to)??[]})),i=t.structuredContent?.facts?.subject;return{content:[],structuredContent:{schema:Ka,tool:"graph_query",facts:{...i?{subject:i}:{},query:{results:r,count:r.length,truncated:!!e.truncated,elapsed_ms:null}}}}}function T1(e,t){if(!e.ok)return{isError:!0,content:[{type:"text",text:e.error??"The query failed."}]};const n=t?.facts?.subject;return{content:[],structuredContent:{schema:Ka,tool:"graph_query",facts:{...n?{subject:n}:{},query:{results:e.rows,count:e.count??e.rows.length,truncated:e.truncated,elapsed_ms:e.elapsedMs}}}}}function C1(e,t,n){const r=e.ownerDocument,i=Bw(t.structuredContent),o=i.map((p,m)=>A(r,"button",{type:"button",role:"tab",class:"cv-tab",id:`cv-tab-${m}`,"data-tab":p.id,"aria-controls":`cv-panel-${m}`,"aria-selected":"false",tabindex:-1,text:p.ok?p.id:`${p.id} (failed)`})),s=i.map((p,m)=>A(r,"div",{class:"cv-tabpanel",role:"tabpanel",id:`cv-panel-${m}`,"aria-labelledby":`cv-tab-${m}`,hidden:!0})),a=A(r,"div",{class:"cv-tabs",role:"tablist","aria-label":"Queries of the batch"},...o);e.replaceChildren(a,...s);const u=i.map(()=>null);let c=n.displayMode,l=n.availableDisplayModes,d=-1;const f=()=>e.style.setProperty("--cv-tabs-h",`${a.offsetHeight}px`);function h(p){const m=i[p],y=s[p];if(!m||!y)return;d=p,o.forEach((g,b)=>{g.setAttribute("aria-selected",String(b===p)),g.tabIndex=b===p?0:-1}),s.forEach((g,b)=>{g.hidden=b!==p});const w=u[p];if(w)w.refit();else{const g=m.query??w1(n.toolInput,m.id,p),b=l_(y,T1(m,t.structuredContent),{...n,displayMode:c,availableDisplayModes:l},g);u[p]=b,y.dataset.view=b.kind}f()}return o.forEach((p,m)=>{p.addEventListener("click",()=>h(m)),p.addEventListener("keydown",y=>{const w=o.length-1,g=y.key==="ArrowRight"?m===w?0:m+1:y.key==="ArrowLeft"?m===0?w:m-1:y.key==="Home"?0:y.key==="End"?w:null;g!=null&&(y.preventDefault(),h(g),o[g]?.focus())})}),h(0),{kind:"batch",flows:()=>u.flatMap(p=>p?.flows()??[]),setTheme(p){for(const m of u)m?.setTheme(p)},setDisplayMode(p,m){p&&(c=p),m&&(l=m);for(const y of u)y?.setDisplayMode(p,m);f()},refit(){d>=0&&u[d]?.refit()},destroy(){for(const p of u)p?.destroy()}}}function A1(e){const t=e?.structuredContent?.view_url;return th(t)?t:null}function d_(e,t,n){const r={...n,viewUrl:n.viewUrl??A1(t)},i=Vw(t);if(i==="flows"){const o=u_(e,t.structuredContent,c_(r));return v1("flows",()=>o)}return i==="graph"||i==="chart"||i==="table"?l_(e,t,r,b1(r.toolInput)):i==="batch"?C1(e,t,r):i==="balance"?(iA(e,t),lc("balance")):(wi(e,t),lc("text"))}function I1(e){return e==="light"||e==="dark"}function N1(e,t=()=>!1){return I1(e?.theme)?e.theme:t()?"dark":"light"}function _u(e,t){const n={...e??{},...t??{}};return(e?.styles||t?.styles)&&(n.styles={...e?.styles??{},...t?.styles??{},variables:{...e?.styles?.variables??{},...t?.styles?.variables??{}}}),n}function ws(e,t,n={}){const r=e.documentElement,i=N1(t,n.prefersDark);r.setAttribute("data-theme",i),r.style.colorScheme=i;const o=t?.styles?.variables;o&&n.applyVariables&&n.applyVariables(o,r);const s=t?.styles?.css?.fonts;return s&&n.applyFonts&&n.applyFonts(s),i}function R1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ho={exports:{}},Dp;function L1(){if(Dp)return Ho.exports;Dp=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(k,S,_){return Function.prototype.apply.call(k,S,_)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(k){return Object.getOwnPropertyNames(k).concat(Object.getOwnPropertySymbols(k))}:n=function(k){return Object.getOwnPropertyNames(k)};function r(v){console&&console.warn&&console.warn(v)}var i=Number.isNaN||function(k){return k!==k};function o(){o.init.call(this)}Ho.exports=o,Ho.exports.once=w,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(v){if(typeof v!="number"||v<0||i(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");s=v}}),o.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(k){if(typeof k!="number"||k<0||i(k))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+k+".");return this._maxListeners=k,this};function u(v){return v._maxListeners===void 0?o.defaultMaxListeners:v._maxListeners}o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(k){for(var S=[],_=1;_<arguments.length;_++)S.push(arguments[_]);var N=k==="error",P=this._events;if(P!==void 0)N=N&&P.error===void 0;else if(!N)return!1;if(N){var z;if(S.length>0&&(z=S[0]),z instanceof Error)throw z;var j=new Error("Unhandled error."+(z?" ("+z.message+")":""));throw j.context=z,j}var K=P[k];if(K===void 0)return!1;if(typeof K=="function")t(K,this,S);else for(var Y=K.length,re=p(K,Y),_=0;_<Y;++_)t(re[_],this,S);return!0};function c(v,k,S,_){var N,P,z;if(a(S),P=v._events,P===void 0?(P=v._events=Object.create(null),v._eventsCount=0):(P.newListener!==void 0&&(v.emit("newListener",k,S.listener?S.listener:S),P=v._events),z=P[k]),z===void 0)z=P[k]=S,++v._eventsCount;else if(typeof z=="function"?z=P[k]=_?[S,z]:[z,S]:_?z.unshift(S):z.push(S),N=u(v),N>0&&z.length>N&&!z.warned){z.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+z.length+" "+String(k)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=v,j.type=k,j.count=z.length,r(j)}return v}o.prototype.addListener=function(k,S){return c(this,k,S,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(k,S){return c(this,k,S,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(v,k,S){var _={fired:!1,wrapFn:void 0,target:v,type:k,listener:S},N=l.bind(_);return N.listener=S,_.wrapFn=N,N}o.prototype.once=function(k,S){return a(S),this.on(k,d(this,k,S)),this},o.prototype.prependOnceListener=function(k,S){return a(S),this.prependListener(k,d(this,k,S)),this},o.prototype.removeListener=function(k,S){var _,N,P,z,j;if(a(S),N=this._events,N===void 0)return this;if(_=N[k],_===void 0)return this;if(_===S||_.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete N[k],N.removeListener&&this.emit("removeListener",k,_.listener||S));else if(typeof _!="function"){for(P=-1,z=_.length-1;z>=0;z--)if(_[z]===S||_[z].listener===S){j=_[z].listener,P=z;break}if(P<0)return this;P===0?_.shift():m(_,P),_.length===1&&(N[k]=_[0]),N.removeListener!==void 0&&this.emit("removeListener",k,j||S)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(k){var S,_,N;if(_=this._events,_===void 0)return this;if(_.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_[k]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _[k]),this;if(arguments.length===0){var P=Object.keys(_),z;for(N=0;N<P.length;++N)z=P[N],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(S=_[k],typeof S=="function")this.removeListener(k,S);else if(S!==void 0)for(N=S.length-1;N>=0;N--)this.removeListener(k,S[N]);return this};function f(v,k,S){var _=v._events;if(_===void 0)return[];var N=_[k];return N===void 0?[]:typeof N=="function"?S?[N.listener||N]:[N]:S?y(N):p(N,N.length)}o.prototype.listeners=function(k){return f(this,k,!0)},o.prototype.rawListeners=function(k){return f(this,k,!1)},o.listenerCount=function(v,k){return typeof v.listenerCount=="function"?v.listenerCount(k):h.call(v,k)},o.prototype.listenerCount=h;function h(v){var k=this._events;if(k!==void 0){var S=k[v];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function p(v,k){for(var S=new Array(k),_=0;_<k;++_)S[_]=v[_];return S}function m(v,k){for(;k+1<v.length;k++)v[k]=v[k+1];v.pop()}function y(v){for(var k=new Array(v.length),S=0;S<k.length;++S)k[S]=v[S].listener||v[S];return k}function w(v,k){return new Promise(function(S,_){function N(z){v.removeListener(k,P),_(z)}function P(){typeof v.removeListener=="function"&&v.removeListener("error",N),S([].slice.call(arguments))}b(v,k,P,{once:!0}),k!=="error"&&g(v,N,{once:!0})})}function g(v,k,S){typeof v.on=="function"&&b(v,"error",k,S)}function b(v,k,S,_){if(typeof v.on=="function")_.once?v.once(k,S):v.on(k,S);else if(typeof v.addEventListener=="function")v.addEventListener(k,function N(P){_.once&&v.removeEventListener(k,N),S(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Ho.exports}var f_=L1();function z1(){const e=arguments[0];for(let t=1,n=arguments.length;t<n;t++)if(arguments[t])for(const r in arguments[t])e[r]=arguments[t][r];return e}let Ye=z1;typeof Object.assign=="function"&&(Ye=Object.assign);function Ot(e,t,n,r){const i=e._nodes.get(t);let o=null;return i&&(r==="mixed"?o=i.out&&i.out[n]||i.undirected&&i.undirected[n]:r==="directed"?o=i.out&&i.out[n]:o=i.undirected&&i.undirected[n]),o}function ot(e){return typeof e=="object"&&e!==null}function h_(e){let t;for(t in e)return!1;return!0}function Lt(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function Ht(e,t,n){const r={enumerable:!0,configurable:!0};typeof n=="function"?r.get=n:(r.value=n,r.writable=!1),Object.defineProperty(e,t,r)}function Op(e){return!(!ot(e)||e.attributes&&!Array.isArray(e.attributes))}function P1(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function un(){const e=arguments;let t=null,n=-1;return{[Symbol.iterator](){return this},next(){let r=null;do{if(t===null){if(n++,n>=e.length)return{done:!0};t=e[n][Symbol.iterator]()}if(r=t.next(),r.done){t=null;continue}break}while(!0);return r}}}function Vr(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}class nh extends Error{constructor(t){super(),this.name="GraphError",this.message=t}}class W extends nh{constructor(t){super(t),this.name="InvalidArgumentsGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W.prototype.constructor)}}class B extends nh{constructor(t){super(t),this.name="NotFoundGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,B.prototype.constructor)}}class ue extends nh{constructor(t){super(t),this.name="UsageGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ue.prototype.constructor)}}function p_(e,t){this.key=e,this.attributes=t,this.clear()}p_.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}};function m_(e,t){this.key=e,this.attributes=t,this.clear()}m_.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function g_(e,t){this.key=e,this.attributes=t,this.clear()}g_.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function qr(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}qr.prototype.attach=function(){let e="out",t="in";this.undirected&&(e=t="undirected");const n=this.source.key,r=this.target.key;this.source[e][r]=this,!(this.undirected&&n===r)&&(this.target[t][n]=this)};qr.prototype.attachMulti=function(){let e="out",t="in";const n=this.source.key,r=this.target.key;this.undirected&&(e=t="undirected");const i=this.source[e],o=i[r];if(typeof o>"u"){i[r]=this,this.undirected&&n===r||(this.target[t][n]=this);return}o.previous=this,this.next=o,i[r]=this,this.target[t][n]=this};qr.prototype.detach=function(){const e=this.source.key,t=this.target.key;let n="out",r="in";this.undirected&&(n=r="undirected"),delete this.source[n][t],delete this.target[r][e]};qr.prototype.detachMulti=function(){const e=this.source.key,t=this.target.key;let n="out",r="in";this.undirected&&(n=r="undirected"),this.previous===void 0?this.next===void 0?(delete this.source[n][t],delete this.target[r][e]):(this.next.previous=void 0,this.source[n][t]=this.next,this.target[r][e]=this.next):(this.previous.next=this.next,this.next!==void 0&&(this.next.previous=this.previous))};const y_=0,v_=1,D1=2,b_=3;function yn(e,t,n,r,i,o,s){let a,u,c,l;if(r=""+r,n===y_){if(a=e._nodes.get(r),!a)throw new B(`Graph.${t}: could not find the "${r}" node in the graph.`);c=i,l=o}else if(n===b_){if(i=""+i,u=e._edges.get(i),!u)throw new B(`Graph.${t}: could not find the "${i}" edge in the graph.`);const d=u.source.key,f=u.target.key;if(r===d)a=u.target;else if(r===f)a=u.source;else throw new B(`Graph.${t}: the "${r}" node is not attached to the "${i}" edge (${d}, ${f}).`);c=o,l=s}else{if(u=e._edges.get(r),!u)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`);n===v_?a=u.source:a=u.target,c=i,l=o}return[a,c,l]}function O1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return s.attributes[a]}}function M1(e,t,n){e.prototype[t]=function(r,i){const[o]=yn(this,t,n,r,i);return o.attributes}}function F1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return s.attributes.hasOwnProperty(a)}}function U1(e,t,n){e.prototype[t]=function(r,i,o,s){const[a,u,c]=yn(this,t,n,r,i,o,s);return a.attributes[u]=c,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:u}),this}}function G1(e,t,n){e.prototype[t]=function(r,i,o,s){const[a,u,c]=yn(this,t,n,r,i,o,s);if(typeof c!="function")throw new W(`Graph.${t}: updater should be a function.`);const l=a.attributes,d=c(l[u]);return l[u]=d,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:u}),this}}function j1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return delete s.attributes[a],this.emit("nodeAttributesUpdated",{key:s.key,type:"remove",attributes:s.attributes,name:a}),this}}function Z1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(!ot(a))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return s.attributes=a,this.emit("nodeAttributesUpdated",{key:s.key,type:"replace",attributes:s.attributes}),this}}function B1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(!ot(a))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return Ye(s.attributes,a),this.emit("nodeAttributesUpdated",{key:s.key,type:"merge",attributes:s.attributes,data:a}),this}}function H1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(typeof a!="function")throw new W(`Graph.${t}: provided updater is not a function.`);return s.attributes=a(s.attributes),this.emit("nodeAttributesUpdated",{key:s.key,type:"update",attributes:s.attributes}),this}}const V1=[{name:e=>`get${e}Attribute`,attacher:O1},{name:e=>`get${e}Attributes`,attacher:M1},{name:e=>`has${e}Attribute`,attacher:F1},{name:e=>`set${e}Attribute`,attacher:U1},{name:e=>`update${e}Attribute`,attacher:G1},{name:e=>`remove${e}Attribute`,attacher:j1},{name:e=>`replace${e}Attributes`,attacher:Z1},{name:e=>`merge${e}Attributes`,attacher:B1},{name:e=>`update${e}Attributes`,attacher:H1}];function q1(e){V1.forEach(function({name:t,attacher:n}){n(e,t("Node"),y_),n(e,t("Source"),v_),n(e,t("Target"),D1),n(e,t("Opposite"),b_)})}function W1(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return o.attributes[i]}}function K1(e,t,n){e.prototype[t]=function(r){let i;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+r,s=""+arguments[1];if(i=Ot(this,o,s,n),!i)throw new B(`Graph.${t}: could not find an edge for the given path ("${o}" - "${s}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,i=this._edges.get(r),!i)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return i.attributes}}function J1(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return o.attributes.hasOwnProperty(i)}}function Y1(e,t,n){e.prototype[t]=function(r,i,o){let s;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const a=""+r,u=""+i;if(i=arguments[2],o=arguments[3],s=Ot(this,a,u,n),!s)throw new B(`Graph.${t}: could not find an edge for the given path ("${a}" - "${u}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,s=this._edges.get(r),!s)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return s.attributes[i]=o,this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}function X1(e,t,n){e.prototype[t]=function(r,i,o){let s;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const a=""+r,u=""+i;if(i=arguments[2],o=arguments[3],s=Ot(this,a,u,n),!s)throw new B(`Graph.${t}: could not find an edge for the given path ("${a}" - "${u}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,s=this._edges.get(r),!s)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(typeof o!="function")throw new W(`Graph.${t}: updater should be a function.`);return s.attributes[i]=o(s.attributes[i]),this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}function Q1(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return delete o.attributes[i],this.emit("edgeAttributesUpdated",{key:o.key,type:"remove",attributes:o.attributes,name:i}),this}}function eI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(!ot(i))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return o.attributes=i,this.emit("edgeAttributesUpdated",{key:o.key,type:"replace",attributes:o.attributes}),this}}function tI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(!ot(i))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return Ye(o.attributes,i),this.emit("edgeAttributesUpdated",{key:o.key,type:"merge",attributes:o.attributes,data:i}),this}}function nI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new ue(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new ue(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new ue(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(typeof i!="function")throw new W(`Graph.${t}: provided updater is not a function.`);return o.attributes=i(o.attributes),this.emit("edgeAttributesUpdated",{key:o.key,type:"update",attributes:o.attributes}),this}}const rI=[{name:e=>`get${e}Attribute`,attacher:W1},{name:e=>`get${e}Attributes`,attacher:K1},{name:e=>`has${e}Attribute`,attacher:J1},{name:e=>`set${e}Attribute`,attacher:Y1},{name:e=>`update${e}Attribute`,attacher:X1},{name:e=>`remove${e}Attribute`,attacher:Q1},{name:e=>`replace${e}Attributes`,attacher:eI},{name:e=>`merge${e}Attributes`,attacher:tI},{name:e=>`update${e}Attributes`,attacher:nI}];function iI(e){rI.forEach(function({name:t,attacher:n}){n(e,t("Edge"),"mixed"),n(e,t("DirectedEdge"),"directed"),n(e,t("UndirectedEdge"),"undirected")})}const oI=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function sI(e,t,n,r){let i=!1;for(const o in t){if(o===r)continue;const s=t[o];if(i=n(s.key,s.attributes,s.source.key,s.target.key,s.source.attributes,s.target.attributes,s.undirected),e&&i)return s.key}}function aI(e,t,n,r){let i,o,s,a=!1;for(const u in t)if(u!==r){i=t[u];do{if(o=i.source,s=i.target,a=n(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected),e&&a)return i.key;i=i.next}while(i!==void 0)}}function ku(e,t){const n=Object.keys(e),r=n.length;let i,o=0;return{[Symbol.iterator](){return this},next(){do if(i)i=i.next;else{if(o>=r)return{done:!0};const s=n[o++];if(s===t){i=void 0;continue}i=e[s]}while(!i);return{done:!1,value:{edge:i.key,attributes:i.attributes,source:i.source.key,target:i.target.key,sourceAttributes:i.source.attributes,targetAttributes:i.target.attributes,undirected:i.undirected}}}}}function uI(e,t,n,r){const i=t[n];if(!i)return;const o=i.source,s=i.target;if(r(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected)&&e)return i.key}function cI(e,t,n,r){let i=t[n];if(!i)return;let o=!1;do{if(o=r(i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes,i.undirected),e&&o)return i.key;i=i.next}while(i!==void 0)}function Su(e,t){let n=e[t];if(n.next!==void 0)return{[Symbol.iterator](){return this},next(){if(!n)return{done:!0};const i={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:i}}};let r=!1;return{[Symbol.iterator](){return this},next(){return r===!0?{done:!0}:(r=!0,{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}})}}}function lI(e,t){if(e.size===0)return[];if(t==="mixed"||t===e.type)return Array.from(e._edges.keys());const n=t==="undirected"?e.undirectedSize:e.directedSize,r=new Array(n),i=t==="undirected",o=e._edges.values();let s=0,a,u;for(;a=o.next(),a.done!==!0;)u=a.value,u.undirected===i&&(r[s++]=u.key);return r}function w_(e,t,n,r){if(t.size===0)return;const i=n!=="mixed"&&n!==t.type,o=n==="undirected";let s,a,u=!1;const c=t._edges.values();for(;s=c.next(),s.done!==!0;){if(a=s.value,i&&a.undirected!==o)continue;const{key:l,attributes:d,source:f,target:h}=a;if(u=r(l,d,f.key,h.key,f.attributes,h.attributes,a.undirected),e&&u)return l}}function dI(e,t){if(e.size===0)return Vr();const n=t!=="mixed"&&t!==e.type,r=t==="undirected",i=e._edges.values();return{[Symbol.iterator](){return this},next(){let o,s;for(;;){if(o=i.next(),o.done)return o;if(s=o.value,!(n&&s.undirected!==r))break}return{value:{edge:s.key,attributes:s.attributes,source:s.source.key,target:s.target.key,sourceAttributes:s.source.attributes,targetAttributes:s.target.attributes,undirected:s.undirected},done:!1}}}}function rh(e,t,n,r,i,o){const s=t?aI:sI;let a;if(n!=="undirected"&&(r!=="out"&&(a=s(e,i.in,o),e&&a)||r!=="in"&&(a=s(e,i.out,o,r?void 0:i.key),e&&a))||n!=="directed"&&(a=s(e,i.undirected,o),e&&a))return a}function fI(e,t,n,r){const i=[];return rh(!1,e,t,n,r,function(o){i.push(o)}),i}function hI(e,t,n){let r=Vr();return e!=="undirected"&&(t!=="out"&&typeof n.in<"u"&&(r=un(r,ku(n.in))),t!=="in"&&typeof n.out<"u"&&(r=un(r,ku(n.out,t?void 0:n.key)))),e!=="directed"&&typeof n.undirected<"u"&&(r=un(r,ku(n.undirected))),r}function ih(e,t,n,r,i,o,s){const a=n?cI:uI;let u;if(t!=="undirected"&&(typeof i.in<"u"&&r!=="out"&&(u=a(e,i.in,o,s),e&&u)||typeof i.out<"u"&&r!=="in"&&(r||i.key!==o)&&(u=a(e,i.out,o,s),e&&u))||t!=="directed"&&typeof i.undirected<"u"&&(u=a(e,i.undirected,o,s),e&&u))return u}function pI(e,t,n,r,i){const o=[];return ih(!1,e,t,n,r,i,function(s){o.push(s)}),o}function mI(e,t,n,r){let i=Vr();return e!=="undirected"&&(typeof n.in<"u"&&t!=="out"&&r in n.in&&(i=un(i,Su(n.in,r))),typeof n.out<"u"&&t!=="in"&&r in n.out&&(t||n.key!==r)&&(i=un(i,Su(n.out,r)))),e!=="directed"&&typeof n.undirected<"u"&&r in n.undirected&&(i=un(i,Su(n.undirected,r))),i}function gI(e,t){const{name:n,type:r,direction:i}=t;e.prototype[n]=function(o,s){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return[];if(!arguments.length)return lI(this,r);if(arguments.length===1){o=""+o;const a=this._nodes.get(o);if(typeof a>"u")throw new B(`Graph.${n}: could not find the "${o}" node in the graph.`);return fI(this.multi,r==="mixed"?this.type:r,i,a)}if(arguments.length===2){o=""+o,s=""+s;const a=this._nodes.get(o);if(!a)throw new B(`Graph.${n}: could not find the "${o}" source node in the graph.`);if(!this._nodes.has(s))throw new B(`Graph.${n}: could not find the "${s}" target node in the graph.`);return pI(r,this.multi,i,a,s)}throw new W(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function yI(e,t){const{name:n,type:r,direction:i}=t,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(c,l,d){if(!(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)){if(arguments.length===1)return d=c,w_(!1,this,r,d);if(arguments.length===2){c=""+c,d=l;const f=this._nodes.get(c);if(typeof f>"u")throw new B(`Graph.${o}: could not find the "${c}" node in the graph.`);return rh(!1,this.multi,r==="mixed"?this.type:r,i,f,d)}if(arguments.length===3){c=""+c,l=""+l;const f=this._nodes.get(c);if(!f)throw new B(`Graph.${o}: could not find the "${c}" source node in the graph.`);if(!this._nodes.has(l))throw new B(`Graph.${o}: could not find the "${l}" target node in the graph.`);return ih(!1,r,this.multi,i,f,l,d)}throw new W(`Graph.${o}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)}};const s="map"+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(){const c=Array.prototype.slice.call(arguments),l=c.pop();let d;if(c.length===0){let f=0;r!=="directed"&&(f+=this.undirectedSize),r!=="undirected"&&(f+=this.directedSize),d=new Array(f);let h=0;c.push((p,m,y,w,g,b,v)=>{d[h++]=l(p,m,y,w,g,b,v)})}else d=[],c.push((f,h,p,m,y,w,g)=>{d.push(l(f,h,p,m,y,w,g))});return this[o].apply(this,c),d};const a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(){const c=Array.prototype.slice.call(arguments),l=c.pop(),d=[];return c.push((f,h,p,m,y,w,g)=>{l(f,h,p,m,y,w,g)&&d.push(f)}),this[o].apply(this,c),d};const u="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[u]=function(){let c=Array.prototype.slice.call(arguments);if(c.length<2||c.length>4)throw new W(`Graph.${u}: invalid number of arguments (expecting 2, 3 or 4 and got ${c.length}).`);if(typeof c[c.length-1]=="function"&&typeof c[c.length-2]!="function")throw new W(`Graph.${u}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let l,d;c.length===2?(l=c[0],d=c[1],c=[]):c.length===3?(l=c[1],d=c[2],c=[c[0]]):c.length===4&&(l=c[2],d=c[3],c=[c[0],c[1]]);let f=d;return c.push((h,p,m,y,w,g,b)=>{f=l(f,h,p,m,y,w,g,b)}),this[o].apply(this,c),f}}function vI(e,t){const{name:n,type:r,direction:i}=t,o="find"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(u,c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return!1;if(arguments.length===1)return l=u,w_(!0,this,r,l);if(arguments.length===2){u=""+u,l=c;const d=this._nodes.get(u);if(typeof d>"u")throw new B(`Graph.${o}: could not find the "${u}" node in the graph.`);return rh(!0,this.multi,r==="mixed"?this.type:r,i,d,l)}if(arguments.length===3){u=""+u,c=""+c;const d=this._nodes.get(u);if(!d)throw new B(`Graph.${o}: could not find the "${u}" source node in the graph.`);if(!this._nodes.has(c))throw new B(`Graph.${o}: could not find the "${c}" target node in the graph.`);return ih(!0,r,this.multi,i,d,c,l)}throw new W(`Graph.${o}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};const s="some"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(){const u=Array.prototype.slice.call(arguments),c=u.pop();return u.push((d,f,h,p,m,y,w)=>c(d,f,h,p,m,y,w)),!!this[o].apply(this,u)};const a="every"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(){const u=Array.prototype.slice.call(arguments),c=u.pop();return u.push((d,f,h,p,m,y,w)=>!c(d,f,h,p,m,y,w)),!this[o].apply(this,u)}}function bI(e,t){const{name:n,type:r,direction:i}=t,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(s,a){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return Vr();if(!arguments.length)return dI(this,r);if(arguments.length===1){s=""+s;const u=this._nodes.get(s);if(!u)throw new B(`Graph.${o}: could not find the "${s}" node in the graph.`);return hI(r,i,u)}if(arguments.length===2){s=""+s,a=""+a;const u=this._nodes.get(s);if(!u)throw new B(`Graph.${o}: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(a))throw new B(`Graph.${o}: could not find the "${a}" target node in the graph.`);return mI(r,i,u,a)}throw new W(`Graph.${o}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function wI(e){oI.forEach(t=>{gI(e,t),yI(e,t),vI(e,t),bI(e,t)})}const _I=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function Ya(){this.A=null,this.B=null}Ya.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)};Ya.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function Yr(e,t,n,r,i){for(const o in r){const s=r[o],a=s.source,u=s.target,c=a===n?u:a;if(t&&t.has(c.key))continue;const l=i(c.key,c.attributes);if(e&&l)return c.key}}function oh(e,t,n,r,i){if(t!=="mixed"){if(t==="undirected")return Yr(e,null,r,r.undirected,i);if(typeof n=="string")return Yr(e,null,r,r[n],i)}const o=new Ya;let s;if(t!=="undirected"){if(n!=="out"){if(s=Yr(e,null,r,r.in,i),e&&s)return s;o.wrap(r.in)}if(n!=="in"){if(s=Yr(e,o,r,r.out,i),e&&s)return s;o.wrap(r.out)}}if(t!=="directed"&&(s=Yr(e,o,r,r.undirected,i),e&&s))return s}function kI(e,t,n){if(e!=="mixed"){if(e==="undirected")return Object.keys(n.undirected);if(typeof t=="string")return Object.keys(n[t])}const r=[];return oh(!1,e,t,n,function(i){r.push(i)}),r}function Xr(e,t,n){const r=Object.keys(n),i=r.length;let o=0;return{[Symbol.iterator](){return this},next(){let s=null;do{if(o>=i)return e&&e.wrap(n),{done:!0};const a=n[r[o++]],u=a.source,c=a.target;if(s=u===t?c:u,e&&e.has(s.key)){s=null;continue}}while(s===null);return{done:!1,value:{neighbor:s.key,attributes:s.attributes}}}}}function SI(e,t,n){if(e!=="mixed"){if(e==="undirected")return Xr(null,n,n.undirected);if(typeof t=="string")return Xr(null,n,n[t])}let r=Vr();const i=new Ya;return e!=="undirected"&&(t!=="out"&&(r=un(r,Xr(i,n,n.in))),t!=="in"&&(r=un(r,Xr(i,n,n.out)))),e!=="directed"&&(r=un(r,Xr(i,n,n.undirected))),r}function xI(e,t){const{name:n,type:r,direction:i}=t;e.prototype[n]=function(o){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return[];o=""+o;const s=this._nodes.get(o);if(typeof s>"u")throw new B(`Graph.${n}: could not find the "${o}" node in the graph.`);return kI(r==="mixed"?this.type:r,i,s)}}function EI(e,t){const{name:n,type:r,direction:i}=t,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return;c=""+c;const d=this._nodes.get(c);if(typeof d>"u")throw new B(`Graph.${o}: could not find the "${c}" node in the graph.`);oh(!1,r==="mixed"?this.type:r,i,d,l)};const s="map"+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(c,l){const d=[];return this[o](c,(f,h)=>{d.push(l(f,h))}),d};const a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(c,l){const d=[];return this[o](c,(f,h)=>{l(f,h)&&d.push(f)}),d};const u="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[u]=function(c,l,d){if(arguments.length<3)throw new W(`Graph.${u}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let f=d;return this[o](c,(h,p)=>{f=l(f,h,p)}),f}}function $I(e,t){const{name:n,type:r,direction:i}=t,o=n[0].toUpperCase()+n.slice(1,-1),s="find"+o;e.prototype[s]=function(c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return;c=""+c;const d=this._nodes.get(c);if(typeof d>"u")throw new B(`Graph.${s}: could not find the "${c}" node in the graph.`);return oh(!0,r==="mixed"?this.type:r,i,d,l)};const a="some"+o;e.prototype[a]=function(c,l){return!!this[s](c,l)};const u="every"+o;e.prototype[u]=function(c,l){return!this[s](c,(f,h)=>!l(f,h))}}function TI(e,t){const{name:n,type:r,direction:i}=t,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(s){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return Vr();s=""+s;const a=this._nodes.get(s);if(typeof a>"u")throw new B(`Graph.${o}: could not find the "${s}" node in the graph.`);return SI(r==="mixed"?this.type:r,i,a)}}function CI(e){_I.forEach(t=>{xI(e,t),EI(e,t),$I(e,t),TI(e,t)})}function Vo(e,t,n,r,i){const o=r._nodes.values(),s=r.type;let a,u,c,l,d,f;for(;a=o.next(),a.done!==!0;){let h=!1;if(u=a.value,s!=="undirected"){l=u.out;for(c in l){d=l[c];do f=d.target,h=!0,i(u.key,f.key,u.attributes,f.attributes,d.key,d.attributes,d.undirected),d=d.next;while(d)}}if(s!=="directed"){l=u.undirected;for(c in l)if(!(t&&u.key>c)){d=l[c];do f=d.target,f.key!==c&&(f=d.source),h=!0,i(u.key,f.key,u.attributes,f.attributes,d.key,d.attributes,d.undirected),d=d.next;while(d)}}n&&!h&&i(u.key,null,u.attributes,null,null,null,null)}}function AI(e,t){const n={key:e};return h_(t.attributes)||(n.attributes=Ye({},t.attributes)),n}function II(e,t,n){const r={key:t,source:n.source.key,target:n.target.key};return h_(n.attributes)||(r.attributes=Ye({},n.attributes)),e==="mixed"&&n.undirected&&(r.undirected=!0),r}function NI(e){if(!ot(e))throw new W('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in e))throw new W("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!ot(e.attributes)||e.attributes===null))throw new W("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function RI(e){if(!ot(e))throw new W('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in e))throw new W("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new W("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!ot(e.attributes)||e.attributes===null))throw new W("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&typeof e.undirected!="boolean")throw new W("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}const LI=P1(),zI=new Set(["directed","undirected","mixed"]),Mp=new Set(["domain","_events","_eventsCount","_maxListeners"]),PI=[{name:e=>`${e}Edge`,generateKey:!0},{name:e=>`${e}DirectedEdge`,generateKey:!0,type:"directed"},{name:e=>`${e}UndirectedEdge`,generateKey:!0,type:"undirected"},{name:e=>`${e}EdgeWithKey`},{name:e=>`${e}DirectedEdgeWithKey`,type:"directed"},{name:e=>`${e}UndirectedEdgeWithKey`,type:"undirected"}],DI={allowSelfLoops:!0,multi:!1,type:"mixed"};function OI(e,t,n){if(n&&!ot(n))throw new W(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=""+t,n=n||{},e._nodes.has(t))throw new ue(`Graph.addNode: the "${t}" node already exist in the graph.`);const r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit("nodeAdded",{key:t,attributes:n}),r}function Fp(e,t,n){const r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit("nodeAdded",{key:t,attributes:n}),r}function __(e,t,n,r,i,o,s,a){if(!r&&e.type==="undirected")throw new ue(`Graph.${t}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);if(r&&e.type==="directed")throw new ue(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(a&&!ot(a))throw new W(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`);if(o=""+o,s=""+s,a=a||{},!e.allowSelfLoops&&o===s)throw new ue(`Graph.${t}: source & target are the same ("${o}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);const u=e._nodes.get(o),c=e._nodes.get(s);if(!u)throw new B(`Graph.${t}: source node "${o}" not found.`);if(!c)throw new B(`Graph.${t}: target node "${s}" not found.`);const l={key:null,undirected:r,source:o,target:s,attributes:a};if(n)i=e._edgeKeyGenerator();else if(i=""+i,e._edges.has(i))throw new ue(`Graph.${t}: the "${i}" edge already exists in the graph.`);if(!e.multi&&(r?typeof u.undirected[s]<"u":typeof u.out[s]<"u"))throw new ue(`Graph.${t}: an edge linking "${o}" to "${s}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);const d=new qr(r,i,u,c,a);e._edges.set(i,d);const f=o===s;return r?(u.undirectedDegree++,c.undirectedDegree++,f&&(u.undirectedLoops++,e._undirectedSelfLoopCount++)):(u.outDegree++,c.inDegree++,f&&(u.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),r?e._undirectedSize++:e._directedSize++,l.key=i,e.emit("edgeAdded",l),i}function MI(e,t,n,r,i,o,s,a,u){if(!r&&e.type==="undirected")throw new ue(`Graph.${t}: you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.`);if(r&&e.type==="directed")throw new ue(`Graph.${t}: you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.`);if(a){if(u){if(typeof a!="function")throw new W(`Graph.${t}: invalid updater function. Expecting a function but got "${a}"`)}else if(!ot(a))throw new W(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`)}o=""+o,s=""+s;let c;if(u&&(c=a,a=void 0),!e.allowSelfLoops&&o===s)throw new ue(`Graph.${t}: source & target are the same ("${o}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let l=e._nodes.get(o),d=e._nodes.get(s),f,h;if(!n&&(f=e._edges.get(i),f)){if((f.source.key!==o||f.target.key!==s)&&(!r||f.source.key!==s||f.target.key!==o))throw new ue(`Graph.${t}: inconsistency detected when attempting to merge the "${i}" edge with "${o}" source & "${s}" target vs. ("${f.source.key}", "${f.target.key}").`);h=f}if(!h&&!e.multi&&l&&(h=r?l.undirected[s]:l.out[s]),h){const g=[h.key,!1,!1,!1];if(u?!c:!a)return g;if(u){const b=h.attributes;h.attributes=c(b),e.emit("edgeAttributesUpdated",{type:"replace",key:h.key,attributes:h.attributes})}else Ye(h.attributes,a),e.emit("edgeAttributesUpdated",{type:"merge",key:h.key,attributes:h.attributes,data:a});return g}a=a||{},u&&c&&(a=c(a));const p={key:null,undirected:r,source:o,target:s,attributes:a};if(n)i=e._edgeKeyGenerator();else if(i=""+i,e._edges.has(i))throw new ue(`Graph.${t}: the "${i}" edge already exists in the graph.`);let m=!1,y=!1;l||(l=Fp(e,o,{}),m=!0,o===s&&(d=l,y=!0)),d||(d=Fp(e,s,{}),y=!0),f=new qr(r,i,l,d,a),e._edges.set(i,f);const w=o===s;return r?(l.undirectedDegree++,d.undirectedDegree++,w&&(l.undirectedLoops++,e._undirectedSelfLoopCount++)):(l.outDegree++,d.inDegree++,w&&(l.directedLoops++,e._directedSelfLoopCount++)),e.multi?f.attachMulti():f.attach(),r?e._undirectedSize++:e._directedSize++,p.key=i,e.emit("edgeAdded",p),[i,!0,m,y]}function tr(e,t){e._edges.delete(t.key);const{source:n,target:r,attributes:i}=t,o=t.undirected,s=n===r;o?(n.undirectedDegree--,r.undirectedDegree--,s&&(n.undirectedLoops--,e._undirectedSelfLoopCount--)):(n.outDegree--,r.inDegree--,s&&(n.directedLoops--,e._directedSelfLoopCount--)),e.multi?t.detachMulti():t.detach(),o?e._undirectedSize--:e._directedSize--,e.emit("edgeDropped",{key:t.key,attributes:i,source:n.key,target:r.key,undirected:o})}class Fe extends f_.EventEmitter{constructor(t){if(super(),t=Ye({},DI,t),typeof t.multi!="boolean")throw new W(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${t.multi}".`);if(!zI.has(t.type))throw new W(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${t.type}".`);if(typeof t.allowSelfLoops!="boolean")throw new W(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${t.allowSelfLoops}".`);const n=t.type==="mixed"?p_:t.type==="directed"?m_:g_;Lt(this,"NodeDataClass",n);const r="geid_"+LI()+"_";let i=0;const o=()=>{let s;do s=r+i++;while(this._edges.has(s));return s};Lt(this,"_attributes",{}),Lt(this,"_nodes",new Map),Lt(this,"_edges",new Map),Lt(this,"_directedSize",0),Lt(this,"_undirectedSize",0),Lt(this,"_directedSelfLoopCount",0),Lt(this,"_undirectedSelfLoopCount",0),Lt(this,"_edgeKeyGenerator",o),Lt(this,"_options",t),Mp.forEach(s=>Lt(this,s,this[s])),Ht(this,"order",()=>this._nodes.size),Ht(this,"size",()=>this._edges.size),Ht(this,"directedSize",()=>this._directedSize),Ht(this,"undirectedSize",()=>this._undirectedSize),Ht(this,"selfLoopCount",()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),Ht(this,"directedSelfLoopCount",()=>this._directedSelfLoopCount),Ht(this,"undirectedSelfLoopCount",()=>this._undirectedSelfLoopCount),Ht(this,"multi",this._options.multi),Ht(this,"type",this._options.type),Ht(this,"allowSelfLoops",this._options.allowSelfLoops),Ht(this,"implementation",()=>"graphology")}_resetInstanceCounters(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0}hasNode(t){return this._nodes.has(""+t)}hasDirectedEdge(t,n){if(this.type==="undirected")return!1;if(arguments.length===1){const r=""+t,i=this._edges.get(r);return!!i&&!i.undirected}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?r.out.hasOwnProperty(n):!1}throw new W(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasUndirectedEdge(t,n){if(this.type==="directed")return!1;if(arguments.length===1){const r=""+t,i=this._edges.get(r);return!!i&&i.undirected}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?r.undirected.hasOwnProperty(n):!1}throw new W(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasEdge(t,n){if(arguments.length===1){const r=""+t;return this._edges.has(r)}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?typeof r.out<"u"&&r.out.hasOwnProperty(n)||typeof r.undirected<"u"&&r.undirected.hasOwnProperty(n):!1}throw new W(`Graph.hasEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}directedEdge(t,n){if(this.type==="undirected")return;if(t=""+t,n=""+n,this.multi)throw new ue("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");const r=this._nodes.get(t);if(!r)throw new B(`Graph.directedEdge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.directedEdge: could not find the "${n}" target node in the graph.`);const i=r.out&&r.out[n]||void 0;if(i)return i.key}undirectedEdge(t,n){if(this.type==="directed")return;if(t=""+t,n=""+n,this.multi)throw new ue("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");const r=this._nodes.get(t);if(!r)throw new B(`Graph.undirectedEdge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.undirectedEdge: could not find the "${n}" target node in the graph.`);const i=r.undirected&&r.undirected[n]||void 0;if(i)return i.key}edge(t,n){if(this.multi)throw new ue("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.edge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.edge: could not find the "${n}" target node in the graph.`);const i=r.out&&r.out[n]||r.undirected&&r.undirected[n]||void 0;if(i)return i.key}areDirectedNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areDirectedNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.in||n in r.out}areOutNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areOutNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.out}areInNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areInNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.in}areUndirectedNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areUndirectedNeighbors: could not find the "${t}" node in the graph.`);return this.type==="directed"?!1:n in r.undirected}areNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&(n in r.in||n in r.out)||this.type!=="directed"&&n in r.undirected}areInboundNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areInboundNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&n in r.in||this.type!=="directed"&&n in r.undirected}areOutboundNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areOutboundNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&n in r.out||this.type!=="directed"&&n in r.undirected}inDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree}outDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.outDegree}directedDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.directedDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree}undirectedDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.undirectedDegree: could not find the "${t}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree}inboundDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inboundDegree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.inDegree),r}outboundDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outboundDegree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.outDegree),r}degree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.degree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.inDegree+n.outDegree),r}inDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree-n.directedLoops}outDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.outDegree-n.directedLoops}directedDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.directedDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree-n.directedLoops*2}undirectedDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.undirectedDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree-n.undirectedLoops*2}inboundDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inboundDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.inDegree,i+=n.directedLoops),r-i}outboundDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outboundDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.outDegree,i+=n.directedLoops),r-i}degreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.degreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.inDegree+n.outDegree,i+=n.directedLoops*2),r-i}source(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.source: could not find the "${t}" edge in the graph.`);return n.source.key}target(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.target: could not find the "${t}" edge in the graph.`);return n.target.key}extremities(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.extremities: could not find the "${t}" edge in the graph.`);return[n.source.key,n.target.key]}opposite(t,n){t=""+t,n=""+n;const r=this._edges.get(n);if(!r)throw new B(`Graph.opposite: could not find the "${n}" edge in the graph.`);const i=r.source.key,o=r.target.key;if(t===i)return o;if(t===o)return i;throw new B(`Graph.opposite: the "${t}" node is not attached to the "${n}" edge (${i}, ${o}).`)}hasExtremity(t,n){t=""+t,n=""+n;const r=this._edges.get(t);if(!r)throw new B(`Graph.hasExtremity: could not find the "${t}" edge in the graph.`);return r.source.key===n||r.target.key===n}isUndirected(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isUndirected: could not find the "${t}" edge in the graph.`);return n.undirected}isDirected(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isDirected: could not find the "${t}" edge in the graph.`);return!n.undirected}isSelfLoop(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isSelfLoop: could not find the "${t}" edge in the graph.`);return n.source===n.target}addNode(t,n){return OI(this,t,n).key}mergeNode(t,n){if(n&&!ot(n))throw new W(`Graph.mergeNode: invalid attributes. Expecting an object but got "${n}"`);t=""+t,n=n||{};let r=this._nodes.get(t);return r?(n&&(Ye(r.attributes,n),this.emit("nodeAttributesUpdated",{type:"merge",key:t,attributes:r.attributes,data:n})),[t,!1]):(r=new this.NodeDataClass(t,n),this._nodes.set(t,r),this.emit("nodeAdded",{key:t,attributes:n}),[t,!0])}updateNode(t,n){if(n&&typeof n!="function")throw new W(`Graph.updateNode: invalid updater function. Expecting a function but got "${n}"`);t=""+t;let r=this._nodes.get(t);if(r){if(n){const o=r.attributes;r.attributes=n(o),this.emit("nodeAttributesUpdated",{type:"replace",key:t,attributes:r.attributes})}return[t,!1]}const i=n?n({}):{};return r=new this.NodeDataClass(t,i),this._nodes.set(t,r),this.emit("nodeAdded",{key:t,attributes:i}),[t,!0]}dropNode(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.dropNode: could not find the "${t}" node in the graph.`);let r;if(this.type!=="undirected"){for(const i in n.out){r=n.out[i];do tr(this,r),r=r.next;while(r)}for(const i in n.in){r=n.in[i];do tr(this,r),r=r.next;while(r)}}if(this.type!=="directed")for(const i in n.undirected){r=n.undirected[i];do tr(this,r),r=r.next;while(r)}this._nodes.delete(t),this.emit("nodeDropped",{key:t,attributes:n.attributes})}dropEdge(t){let n;if(arguments.length>1){const r=""+arguments[0],i=""+arguments[1];if(n=Ot(this,r,i,this.type),!n)throw new B(`Graph.dropEdge: could not find the "${r}" -> "${i}" edge in the graph.`)}else if(t=""+t,n=this._edges.get(t),!n)throw new B(`Graph.dropEdge: could not find the "${t}" edge in the graph.`);return tr(this,n),this}dropDirectedEdge(t,n){if(arguments.length<2)throw new ue("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new ue("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");t=""+t,n=""+n;const r=Ot(this,t,n,"directed");if(!r)throw new B(`Graph.dropDirectedEdge: could not find a "${t}" -> "${n}" edge in the graph.`);return tr(this,r),this}dropUndirectedEdge(t,n){if(arguments.length<2)throw new ue("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new ue("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");const r=Ot(this,t,n,"undirected");if(!r)throw new B(`Graph.dropUndirectedEdge: could not find a "${t}" -> "${n}" edge in the graph.`);return tr(this,r),this}clear(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")}clearEdges(){const t=this._nodes.values();let n;for(;n=t.next(),n.done!==!0;)n.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")}getAttribute(t){return this._attributes[t]}getAttributes(){return this._attributes}hasAttribute(t){return this._attributes.hasOwnProperty(t)}setAttribute(t,n){return this._attributes[t]=n,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:t}),this}updateAttribute(t,n){if(typeof n!="function")throw new W("Graph.updateAttribute: updater should be a function.");const r=this._attributes[t];return this._attributes[t]=n(r),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:t}),this}removeAttribute(t){return delete this._attributes[t],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:t}),this}replaceAttributes(t){if(!ot(t))throw new W("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=t,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this}mergeAttributes(t){if(!ot(t))throw new W("Graph.mergeAttributes: provided attributes are not a plain object.");return Ye(this._attributes,t),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:t}),this}updateAttributes(t){if(typeof t!="function")throw new W("Graph.updateAttributes: provided updater is not a function.");return this._attributes=t(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this}updateEachNodeAttributes(t,n){if(typeof t!="function")throw new W("Graph.updateEachNodeAttributes: expecting an updater function.");if(n&&!Op(n))throw new W("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const r=this._nodes.values();let i,o;for(;i=r.next(),i.done!==!0;)o=i.value,o.attributes=t(o.key,o.attributes);this.emit("eachNodeAttributesUpdated",{hints:n||null})}updateEachEdgeAttributes(t,n){if(typeof t!="function")throw new W("Graph.updateEachEdgeAttributes: expecting an updater function.");if(n&&!Op(n))throw new W("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const r=this._edges.values();let i,o,s,a;for(;i=r.next(),i.done!==!0;)o=i.value,s=o.source,a=o.target,o.attributes=t(o.key,o.attributes,s.key,a.key,s.attributes,a.attributes,o.undirected);this.emit("eachEdgeAttributesUpdated",{hints:n||null})}forEachAdjacencyEntry(t){if(typeof t!="function")throw new W("Graph.forEachAdjacencyEntry: expecting a callback.");Vo(!1,!1,!1,this,t)}forEachAdjacencyEntryWithOrphans(t){if(typeof t!="function")throw new W("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");Vo(!1,!1,!0,this,t)}forEachAssymetricAdjacencyEntry(t){if(typeof t!="function")throw new W("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");Vo(!1,!0,!1,this,t)}forEachAssymetricAdjacencyEntryWithOrphans(t){if(typeof t!="function")throw new W("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");Vo(!1,!0,!0,this,t)}nodes(){return Array.from(this._nodes.keys())}forEachNode(t){if(typeof t!="function")throw new W("Graph.forEachNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)i=r.value,t(i.key,i.attributes)}findNode(t){if(typeof t!="function")throw new W("Graph.findNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,t(i.key,i.attributes))return i.key}mapNodes(t){if(typeof t!="function")throw new W("Graph.mapNode: expecting a callback.");const n=this._nodes.values();let r,i;const o=new Array(this.order);let s=0;for(;r=n.next(),r.done!==!0;)i=r.value,o[s++]=t(i.key,i.attributes);return o}someNode(t){if(typeof t!="function")throw new W("Graph.someNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,t(i.key,i.attributes))return!0;return!1}everyNode(t){if(typeof t!="function")throw new W("Graph.everyNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,!t(i.key,i.attributes))return!1;return!0}filterNodes(t){if(typeof t!="function")throw new W("Graph.filterNodes: expecting a callback.");const n=this._nodes.values();let r,i;const o=[];for(;r=n.next(),r.done!==!0;)i=r.value,t(i.key,i.attributes)&&o.push(i.key);return o}reduceNodes(t,n){if(typeof t!="function")throw new W("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new W("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");let r=n;const i=this._nodes.values();let o,s;for(;o=i.next(),o.done!==!0;)s=o.value,r=t(r,s.key,s.attributes);return r}nodeEntries(){const t=this._nodes.values();return{[Symbol.iterator](){return this},next(){const n=t.next();if(n.done)return n;const r=n.value;return{value:{node:r.key,attributes:r.attributes},done:!1}}}}export(){const t=new Array(this._nodes.size);let n=0;this._nodes.forEach((i,o)=>{t[n++]=AI(o,i)});const r=new Array(this._edges.size);return n=0,this._edges.forEach((i,o)=>{r[n++]=II(this.type,o,i)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:t,edges:r}}import(t,n=!1){if(t instanceof Fe)return t.forEachNode((u,c)=>{n?this.mergeNode(u,c):this.addNode(u,c)}),t.forEachEdge((u,c,l,d,f,h,p)=>{n?p?this.mergeUndirectedEdgeWithKey(u,l,d,c):this.mergeDirectedEdgeWithKey(u,l,d,c):p?this.addUndirectedEdgeWithKey(u,l,d,c):this.addDirectedEdgeWithKey(u,l,d,c)}),this;if(!ot(t))throw new W("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(t.attributes){if(!ot(t.attributes))throw new W("Graph.import: invalid attributes. Expecting a plain object.");n?this.mergeAttributes(t.attributes):this.replaceAttributes(t.attributes)}let r,i,o,s,a;if(t.nodes){if(o=t.nodes,!Array.isArray(o))throw new W("Graph.import: invalid nodes. Expecting an array.");for(r=0,i=o.length;r<i;r++){s=o[r],NI(s);const{key:u,attributes:c}=s;n?this.mergeNode(u,c):this.addNode(u,c)}}if(t.edges){let u=!1;if(this.type==="undirected"&&(u=!0),o=t.edges,!Array.isArray(o))throw new W("Graph.import: invalid edges. Expecting an array.");for(r=0,i=o.length;r<i;r++){a=o[r],RI(a);const{source:c,target:l,attributes:d,undirected:f=u}=a;let h;"key"in a?(h=n?f?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:f?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,h.call(this,a.key,c,l,d)):(h=n?f?this.mergeUndirectedEdge:this.mergeDirectedEdge:f?this.addUndirectedEdge:this.addDirectedEdge,h.call(this,c,l,d))}}return this}nullCopy(t){const n=new Fe(Ye({},this._options,t));return n.replaceAttributes(Ye({},this.getAttributes())),n}emptyCopy(t){const n=this.nullCopy(t);return this._nodes.forEach((r,i)=>{const o=Ye({},r.attributes);r=new n.NodeDataClass(i,o),n._nodes.set(i,r)}),n}copy(t){if(t=t||{},typeof t.type=="string"&&t.type!==this.type&&t.type!=="mixed")throw new ue(`Graph.copy: cannot create an incompatible copy from "${this.type}" type to "${t.type}" because this would mean losing information about the current graph.`);if(typeof t.multi=="boolean"&&t.multi!==this.multi&&t.multi!==!0)throw new ue("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if(typeof t.allowSelfLoops=="boolean"&&t.allowSelfLoops!==this.allowSelfLoops&&t.allowSelfLoops!==!0)throw new ue("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");const n=this.emptyCopy(t),r=this._edges.values();let i,o;for(;i=r.next(),i.done!==!0;)o=i.value,__(n,"copy",!1,o.undirected,o.key,o.source.key,o.target.key,Ye({},o.attributes));return n}toJSON(){return this.export()}toString(){return"[object Graph]"}inspect(){const t={};this._nodes.forEach((o,s)=>{t[s]=o.attributes});const n={},r={};this._edges.forEach((o,s)=>{const a=o.undirected?"--":"->";let u="",c=o.source.key,l=o.target.key,d;o.undirected&&c>l&&(d=c,c=l,l=d);const f=`(${c})${a}(${l})`;s.startsWith("geid_")?this.multi&&(typeof r[f]>"u"?r[f]=0:r[f]++,u+=`${r[f]}. `):u+=`[${s}]: `,u+=f,n[u]=o.attributes});const i={};for(const o in this)this.hasOwnProperty(o)&&!Mp.has(o)&&typeof this[o]!="function"&&typeof o!="symbol"&&(i[o]=this[o]);return i.attributes=this._attributes,i.nodes=t,i.edges=n,Lt(i,"constructor",this.constructor),i}}typeof Symbol<"u"&&(Fe.prototype[Symbol.for("nodejs.util.inspect.custom")]=Fe.prototype.inspect);PI.forEach(e=>{["add","merge","update"].forEach(t=>{const n=e.name(t),r=t==="add"?__:MI;e.generateKey?Fe.prototype[n]=function(i,o,s){return r(this,n,!0,(e.type||this.type)==="undirected",null,i,o,s,t==="update")}:Fe.prototype[n]=function(i,o,s,a){return r(this,n,!1,(e.type||this.type)==="undirected",i,o,s,a,t==="update")}})});q1(Fe);iI(Fe);wI(Fe);CI(Fe);class k_ extends Fe{constructor(t){const n=Ye({type:"directed"},t);if("multi"in n&&n.multi!==!1)throw new W("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="directed")throw new W('DirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class S_ extends Fe{constructor(t){const n=Ye({type:"undirected"},t);if("multi"in n&&n.multi!==!1)throw new W("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="undirected")throw new W('UndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class x_ extends Fe{constructor(t){const n=Ye({multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(n)}}class E_ extends Fe{constructor(t){const n=Ye({type:"directed",multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="directed")throw new W('MultiDirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class $_ extends Fe{constructor(t){const n=Ye({type:"undirected",multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="undirected")throw new W('MultiUndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}function Wr(e){e.from=function(t,n){const r=Ye({},t.options,n),i=new e(r);return i.import(t),i}}Wr(Fe);Wr(k_);Wr(S_);Wr(x_);Wr(E_);Wr($_);Fe.Graph=Fe;Fe.DirectedGraph=k_;Fe.UndirectedGraph=S_;Fe.MultiGraph=x_;Fe.MultiDirectedGraph=E_;Fe.MultiUndirectedGraph=$_;Fe.InvalidArgumentsGraphError=W;Fe.NotFoundGraphError=B;Fe.UsageGraphError=ue;function FI(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ui(e){var t=FI(e,"string");return typeof t=="symbol"?t:t+""}function ht(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Up(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,ui(r.key),r)}}function pt(e,t,n){return t&&Up(e.prototype,t),n&&Up(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function wr(e){return wr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},wr(e)}function T_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(T_=function(){return!!e})()}function UI(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function GI(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return UI(e)}function Gt(e,t,n){return t=wr(t),GI(e,T_()?Reflect.construct(t,n||[],wr(e).constructor):t.apply(e,n))}function dc(e,t){return dc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},dc(e,t)}function jt(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dc(e,t)}function jI(e){if(Array.isArray(e))return e}function ZI(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,a=[],u=!0,c=!1;try{if(o=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(l){c=!0,i=l}finally{try{if(!u&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function fc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function C_(e,t){if(e){if(typeof e=="string")return fc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?fc(e,t):void 0}}function BI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
111
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _r(e,t){return jI(e)||ZI(e,t)||C_(e,t)||BI()}var xu={black:"#000000",silver:"#C0C0C0",gray:"#808080",grey:"#808080",white:"#FFFFFF",maroon:"#800000",red:"#FF0000",purple:"#800080",fuchsia:"#FF00FF",green:"#008000",lime:"#00FF00",olive:"#808000",yellow:"#FFFF00",navy:"#000080",blue:"#0000FF",teal:"#008080",aqua:"#00FFFF",darkblue:"#00008B",mediumblue:"#0000CD",darkgreen:"#006400",darkcyan:"#008B8B",deepskyblue:"#00BFFF",darkturquoise:"#00CED1",mediumspringgreen:"#00FA9A",springgreen:"#00FF7F",cyan:"#00FFFF",midnightblue:"#191970",dodgerblue:"#1E90FF",lightseagreen:"#20B2AA",forestgreen:"#228B22",seagreen:"#2E8B57",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",limegreen:"#32CD32",mediumseagreen:"#3CB371",turquoise:"#40E0D0",royalblue:"#4169E1",steelblue:"#4682B4",darkslateblue:"#483D8B",mediumturquoise:"#48D1CC",indigo:"#4B0082",darkolivegreen:"#556B2F",cadetblue:"#5F9EA0",cornflowerblue:"#6495ED",rebeccapurple:"#663399",mediumaquamarine:"#66CDAA",dimgray:"#696969",dimgrey:"#696969",slateblue:"#6A5ACD",olivedrab:"#6B8E23",slategray:"#708090",slategrey:"#708090",lightslategray:"#778899",lightslategrey:"#778899",mediumslateblue:"#7B68EE",lawngreen:"#7CFC00",chartreuse:"#7FFF00",aquamarine:"#7FFFD4",skyblue:"#87CEEB",lightskyblue:"#87CEFA",blueviolet:"#8A2BE2",darkred:"#8B0000",darkmagenta:"#8B008B",saddlebrown:"#8B4513",darkseagreen:"#8FBC8F",lightgreen:"#90EE90",mediumpurple:"#9370DB",darkviolet:"#9400D3",palegreen:"#98FB98",darkorchid:"#9932CC",yellowgreen:"#9ACD32",sienna:"#A0522D",brown:"#A52A2A",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",lightblue:"#ADD8E6",greenyellow:"#ADFF2F",paleturquoise:"#AFEEEE",lightsteelblue:"#B0C4DE",powderblue:"#B0E0E6",firebrick:"#B22222",darkgoldenrod:"#B8860B",mediumorchid:"#BA55D3",rosybrown:"#BC8F8F",darkkhaki:"#BDB76B",mediumvioletred:"#C71585",indianred:"#CD5C5C",peru:"#CD853F",chocolate:"#D2691E",tan:"#D2B48C",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",thistle:"#D8BFD8",orchid:"#DA70D6",goldenrod:"#DAA520",palevioletred:"#DB7093",crimson:"#DC143C",gainsboro:"#DCDCDC",plum:"#DDA0DD",burlywood:"#DEB887",lightcyan:"#E0FFFF",lavender:"#E6E6FA",darksalmon:"#E9967A",violet:"#EE82EE",palegoldenrod:"#EEE8AA",lightcoral:"#F08080",khaki:"#F0E68C",aliceblue:"#F0F8FF",honeydew:"#F0FFF0",azure:"#F0FFFF",sandybrown:"#F4A460",wheat:"#F5DEB3",beige:"#F5F5DC",whitesmoke:"#F5F5F5",mintcream:"#F5FFFA",ghostwhite:"#F8F8FF",salmon:"#FA8072",antiquewhite:"#FAEBD7",linen:"#FAF0E6",lightgoldenrodyellow:"#FAFAD2",oldlace:"#FDF5E6",magenta:"#FF00FF",deeppink:"#FF1493",orangered:"#FF4500",tomato:"#FF6347",hotpink:"#FF69B4",coral:"#FF7F50",darkorange:"#FF8C00",lightsalmon:"#FFA07A",orange:"#FFA500",lightpink:"#FFB6C1",pink:"#FFC0CB",gold:"#FFD700",peachpuff:"#FFDAB9",navajowhite:"#FFDEAD",moccasin:"#FFE4B5",bisque:"#FFE4C4",mistyrose:"#FFE4E1",blanchedalmond:"#FFEBCD",papayawhip:"#FFEFD5",lavenderblush:"#FFF0F5",seashell:"#FFF5EE",cornsilk:"#FFF8DC",lemonchiffon:"#FFFACD",floralwhite:"#FFFAF0",snow:"#FFFAFA",lightyellow:"#FFFFE0",ivory:"#FFFFF0"},A_=new Int8Array(4),rs=new Int32Array(A_.buffer,0,1),I_=new Float32Array(A_.buffer,0,1),HI=/^\s*rgba?\s*\(/,VI=/^\s*rgba?\s*\(\s*([0-9]*)\s*,\s*([0-9]*)\s*,\s*([0-9]*)(?:\s*,\s*(.*)?)?\)\s*$/;function qI(e){var t=0,n=0,r=0,i=1;if(e[0]==="#")e.length===4?(t=parseInt(e.charAt(1)+e.charAt(1),16),n=parseInt(e.charAt(2)+e.charAt(2),16),r=parseInt(e.charAt(3)+e.charAt(3),16)):(t=parseInt(e.charAt(1)+e.charAt(2),16),n=parseInt(e.charAt(3)+e.charAt(4),16),r=parseInt(e.charAt(5)+e.charAt(6),16)),e.length===9&&(i=parseInt(e.charAt(7)+e.charAt(8),16)/255);else if(HI.test(e)){var o=e.match(VI);o&&(t=+o[1],n=+o[2],r=+o[3],o[4]&&(i=+o[4]))}return{r:t,g:n,b:r,a:i}}var ar={};for(var qo in xu)ar[qo]=zn(xu[qo]),ar[xu[qo]]=ar[qo];function N_(e,t,n,r,i){return rs[0]=r<<24|n<<16|t<<8|e,rs[0]=rs[0]&4278190079,I_[0]}function zn(e){if(e=e.toLowerCase(),typeof ar[e]<"u")return ar[e];var t=qI(e),n=t.r,r=t.g,i=t.b,o=t.a;o=o*255|0;var s=N_(n,r,i,o);return ar[e]=s,s}function WI(e,t){I_[0]=zn(e);var n=rs[0],r=n&255,i=n>>8&255,o=n>>16&255,s=n>>24&255;return[r,i,o,s]}var Eu={};function R_(e){if(typeof Eu[e]<"u")return Eu[e];var t=(e&16711680)>>>16,n=(e&65280)>>>8,r=e&255,i=255,o=N_(t,n,r,i);return Eu[e]=o,o}function Gp(e,t,n,r){return n+(t<<8)+(e<<16)}function jp(e,t,n,r,i,o){var s=Math.floor(n/o*i),a=Math.floor(e.drawingBufferHeight/o-r/o*i),u=new Uint8Array(4);e.bindFramebuffer(e.FRAMEBUFFER,t),e.readPixels(s,a,1,1,e.RGBA,e.UNSIGNED_BYTE,u);var c=_r(u,4),l=c[0],d=c[1],f=c[2],h=c[3];return[l,d,f,h]}function O(e,t,n){return(t=ui(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function te(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Zp(Object(n),!0).forEach(function(r){O(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Zp(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function KI(e,t){for(;!{}.hasOwnProperty.call(e,t)&&(e=wr(e))!==null;);return e}function hc(){return hc=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=KI(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},hc.apply(null,arguments)}function L_(e,t,n,r){var i=hc(wr(e.prototype),t,n);return typeof i=="function"?function(o){return i.apply(n,o)}:i}function JI(e){return e.normalized?1:e.size}function $u(e){var t=0;return e.forEach(function(n){return t+=JI(n)}),t}function z_(e,t,n){var r=e==="VERTEX"?t.VERTEX_SHADER:t.FRAGMENT_SHADER,i=t.createShader(r);if(i===null)throw new Error("loadShader: error while creating the shader");t.shaderSource(i,n),t.compileShader(i);var o=t.getShaderParameter(i,t.COMPILE_STATUS);if(!o){var s=t.getShaderInfoLog(i);throw t.deleteShader(i),new Error(`loadShader: error while compiling the shader:
107
+ - "app": Tool callable by the app from this server only`),csp:Jn().optional(),permissions:Jn().optional()});C({mimeTypes:le(E()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});C({method:$("ui/download-file"),params:C({contents:le(Ee([gw,yw])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});C({method:$("ui/message"),params:C({role:$("user").describe('Message role, currently only "user" is supported.'),content:le(Io).describe("Message content blocks (text, image, etc.).")})});C({method:$("ui/notifications/sandbox-resource-ready"),params:C({html:E().describe("HTML content to load into the inner iframe."),sandbox:E().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Hf.optional().describe("CSP configuration from resource metadata."),permissions:qf.optional().describe("Sandbox permissions from resource metadata.")})});var W$=C({method:$("ui/notifications/tool-result"),params:Ka.describe("Standard MCP tool execution result.")}),xw=C({toolInfo:C({id:xo.optional().describe("JSON-RPC id of the tools/call request."),tool:Vf.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:R$.optional().describe("Current color theme preference."),styles:j$.optional().describe("Style configuration for theming the app."),displayMode:yi.optional().describe("How the UI is currently displayed."),availableDisplayModes:le(yi).optional().describe("Display modes the host supports."),containerDimensions:Ee([C({height:ve().describe("Fixed container height in pixels.")}),C({maxHeight:Ee([ve(),yr()]).optional().describe("Maximum container height in pixels.")})]).and(Ee([C({width:ve().describe("Fixed container width in pixels.")}),C({maxWidth:Ee([ve(),yr()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
108
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:E().optional().describe("User's language and region preference in BCP 47 format."),timeZone:E().optional().describe("User's timezone in IANA format."),userAgent:E().optional().describe("Host application identifier."),platform:Ee([$("web"),$("desktop"),$("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:C({touch:Pe().optional().describe("Whether the device supports touch input."),hover:Pe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:C({top:ve().describe("Top safe area inset in pixels."),right:ve().describe("Right safe area inset in pixels."),bottom:ve().describe("Bottom safe area inset in pixels."),left:ve().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),K$=C({method:$("ui/notifications/host-context-changed"),params:xw.describe("Partial context update containing only changed fields.")});C({method:$("ui/update-model-context"),params:C({content:le(Io).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Te(E(),Ne().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});C({method:$("ui/initialize"),params:C({appInfo:qa.describe("App identification (name and version)."),appCapabilities:V$.describe("Features and capabilities this app provides."),protocolVersion:E().describe("Protocol version this app supports.")})});var J$=C({protocolVersion:E().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:qa.describe("Host application identification and version."),hostCapabilities:B$.describe("Features and capabilities provided by the host."),hostContext:xw.describe("Rich context about the host environment.")}).passthrough(),Y$={target:"draft-2020-12"};async function op(e,t){let n=e["~standard"];if(n.jsonSchema)return n.jsonSchema[t](Y$);if(n.vendor==="zod"){let{z:r}=await pk(()=>Promise.resolve().then(()=>Ux),void 0,import.meta.url);return r.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function sp(e,t,n=""){let r=await e["~standard"].validate(t);if(r.issues){let i=r.issues.map(o=>{let s=o.path?.map(a=>typeof a=="object"?a.key:a).join(".");return s?`${s}: ${o.message}`:o.message}).join("; ");throw Error(n+i)}return r.value}function X$(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Q$(e){if(document.getElementById("__mcp-host-fonts"))return;let t=document.createElement("style");t.id="__mcp-host-fonts",t.textContent=e,document.head.appendChild(t)}class Wf extends A${_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(t){if(this._initializedSent)return;let n=`[ext-apps] App.${t}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(n);console.warn(`${n}. This will throw in a future release.`)}eventSchemas={toolinput:M$,toolinputpartial:F$,toolresult:W$,toolcancelled:U$,hostcontextchanged:K$};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(t){if(!Wf.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(t,n){n&&this._assertHandlerTiming(t),super.setEventHandler(t,n)}addEventListener(t,n){this._assertHandlerTiming(t),super.addEventListener(t,n)}onEventDispatch(t,n){t==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...n})}constructor(t,n={},r={autoResize:!0}){super(r),this._appInfo=t,this._capabilities=n,this.options=r,r.allowUnsafeEval||Qe({jitless:!0}),this.setRequestHandler(Wa,i=>(console.log("Received ping:",i.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=C$(this._capabilities,t)}registerTool(t,n,r){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let i=this,o=()=>{i._initializedSent&&i._capabilities.tools?.listChanged&&i.sendToolListChanged()},s=n.inputSchema!==void 0,a={title:n.title,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,annotations:n.annotations,_meta:n._meta,enabled:!0,enable(){this.enabled=!0,o()},disable(){this.enabled=!1,o()},update(u){Object.assign(this,u),o()},remove(){i._registeredTools[t]===a&&(delete i._registeredTools[t],o())},handler:async(u,c)=>{if(!a.enabled)throw Error(`Tool ${t} is disabled`);let l;if(s){let d=a.inputSchema,f=d?await sp(d,u??{},`Invalid input for tool ${t}: `):u??{};l=await r(f,c)}else l=await r(c);return a.outputSchema&&!l.isError&&(l.structuredContent=await sp(a.outputSchema,l.structuredContent,`Invalid output for tool ${t}: `)),l}};return this._registeredTools[t]=a,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),o(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(t,n)=>{let r=this._registeredTools[t.name];if(!r)throw Error(`Tool ${t.name} not found`);return r.handler(t.arguments,n)},this.onlisttools=async(t,n)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([r,i])=>i.enabled).map(async([r,i])=>{let o={name:r,title:i.title,description:i.description,inputSchema:i.inputSchema?await op(i.inputSchema,"input"):{type:"object",properties:{}}};return i.outputSchema&&(o.outputSchema=await op(i.outputSchema,"output")),i.annotations&&(o.annotations=i.annotations),i._meta&&(o._meta=i._meta),o}))}))}async sendToolListChanged(t={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:t})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(t){this.setEventHandler("toolinput",t)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(t){this.setEventHandler("toolinputpartial",t)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(t){this.setEventHandler("toolresult",t)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(t){this.setEventHandler("toolcancelled",t)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(t){this.setEventHandler("hostcontextchanged",t)}_onteardown;get onteardown(){return this._onteardown}set onteardown(t){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,t),this._onteardown=t,this.replaceRequestHandler(Z$,(n,r)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(n.params,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler(bw,(n,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(n.params,r)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(t){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,t),this._onlisttools=t,this.replaceRequestHandler(vw,(n,r)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(n.params,r)})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${t})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${t} registered`)}}assertNotificationCapability(t){}assertTaskCapability(t){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(t){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(t,n){if(this._assertInitialized("callServerTool"),typeof t=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${t}"). Did you mean: callServerTool({ name: "${t}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:t},Ka,{onprogress:()=>{},resetTimeoutOnProgress:!0,...n})}async readServerResource(t,n){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:t},mw,n)}async listServerResources(t,n){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:t},pw,n)}async createSamplingMessage(t,n){this._assertInitialized("createSamplingMessage");let r=t.tools?kw:_w;return await this.request({method:"sampling/createMessage",params:t},r,n)}sendMessage(t,n){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:t},O$,n)}sendLog(t){return this.notification({method:"notifications/message",params:t})}updateModelContext(t,n){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:t},If,n)}openLink(t,n){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:t},P$,n)}sendOpenLink=this.openLink;downloadFile(t,n){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:t},D$,n)}requestTeardown(t={}){return this.notification({method:"ui/notifications/request-teardown",params:t})}requestDisplayMode(t,n){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:t},H$,n)}sendSizeChanged(t){return this.notification({method:"ui/notifications/size-changed",params:t})}setupSizeChangedNotifications(){let t=!1,n=0,r=0,i=()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1;let s=document.documentElement,a=s.style.height;s.style.height="max-content";let u=Math.ceil(s.getBoundingClientRect().height);s.style.height=a;let c=Math.ceil(window.innerWidth);(c!==n||u!==r)&&(n=c,r=u,this.sendSizeChanged({width:c,height:u}))}))};i();let o=new ResizeObserver(i);return o.observe(document.documentElement),o.observe(document.body),()=>o.disconnect()}async connect(t=new Sw(window.parent,window.parent),n){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(t);try{let r=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:I$}},J$,n);if(r===void 0)throw Error(`Server sent invalid initialize result: ${r}`);this._hostCapabilities=r.hostCapabilities,this._hostInfo=r.hostInfo,this._hostContext=r.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(r){throw this.close(),r}}}const eT="Chain Insights graph",tT="This graph is no longer available. Ask for it again.",ap="data-chain-insights-view",nT="This window cannot reach the local Chain Insights page. Open the link in your own browser for clicks that load more",rs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ew=e=>!rs(e)||!rs(e.result)?null:{arguments:rs(e.arguments)?e.arguments:null,result:e.result};function rT(e,t){const n=t.querySelector(`script[type="application/json"][${ap}]`);if(!n||n.getAttribute(ap)!==e)return null;try{return Ew(JSON.parse(n.textContent??""))}catch{return null}}const iT=new Set(["127.0.0.1","localhost","[::1]","::1"]);function oT(e){const t=new URLSearchParams(e.search).get("view");if(t&&t.trim())return t.trim();if(!iT.has(e.hostname))return null;const n=/^\/view\/([^/]+)\/?$/.exec(e.pathname);if(!n?.[1])return null;try{return decodeURIComponent(n[1])||null}catch{return null}}async function sT(e,t,n){const r=n?rT(e,n):null;if(r)return r;try{const i=await t(`/api/view/${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});return i.ok?Ew(await i.json()):null}catch{return null}}function aT(e,t){return{async callServerTool({name:n,arguments:r}){let i;try{i=await e(`/api/tools/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({arguments:r})})}catch{throw new Error(nT)}let o=null;try{o=await i.json()}catch{o=null}if(rs(o)&&(Array.isArray(o.content)||"structuredContent"in o||"isError"in o))return o;throw new Error(i.ok?"the local Chain Insights page answered with no tool result":`the local Chain Insights page answered HTTP ${i.status}`)},async openLink({url:n}){return t(n,"_blank","noopener"),{}}}}const $w=new Map;function uT(e,t){$w.set(e,t)}function up(e){return $w.get(e)??null}const cT=/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i;function lT(e){try{const t=e.createElement("canvas");if(typeof t.getContext!="function")return!1;const n={failIfMajorPerformanceCaveat:!0},r=t.getContext("webgl2",n)??t.getContext("webgl",n);if(!r)return!1;const i=r.getExtension?.("WEBGL_debug_renderer_info"),o=String(i?r.getParameter(i.UNMASKED_RENDERER_WEBGL):r.getParameter(r.RENDERER)??"");return cT.test(o)?(r.getExtension?.("WEBGL_lose_context")?.loseContext(),!1):(r.getExtension?.("WEBGL_lose_context")?.loseContext(),!0)}catch{return!1}}const dT="http://www.w3.org/2000/svg";let fT=0;function Go(e){return Math.round(e*10)/10}function hT(e,t,n={}){const r=e.createElementNS(dT,t);for(const[i,o]of Object.entries(n))r.setAttribute(i,String(o));return r}function cp(e,t,n,r){const i=`cia-graph-svg-${++fT}`,o=e.ownerDocument,s=(G,q)=>hT(o,G,q),a=(G,q,Y)=>{const ne=s("text",{x:0,y:q,"text-anchor":"middle",class:Y,"pointer-events":"none"});return ne.textContent=G,ne},{width:u,height:c}=t.dimensions(),l=s("svg",{class:"cia-graph-svg",viewBox:`0 0 ${u} ${c}`,role:"group",tabindex:0,"aria-label":r.label??"Money-flow graph. Drag the background or use arrow keys to pan, plus and minus to zoom. Select an address or a link for details."}),d=s("defs"),f=s("pattern",{id:`${i}-dots`,width:24,height:24,patternUnits:"userSpaceOnUse"});f.append(s("circle",{class:"cia-graph-dot",cx:1,cy:1,r:1})),d.append(f);const h=s("rect",{class:"cia-graph-backdrop",width:"100%",height:"100%","data-canvas":""}),p=s("rect",{class:"cia-graph-dots",width:"100%",height:"100%",fill:`url(#${i}-dots)`,"data-canvas":""}),m=s("g",{"data-viewport":""}),y=s("g",{"data-edges":"",class:"cia-graph-edges"}),_=s("g",{"data-nodes":"",class:"cia-graph-nodes"});m.append(y,_),l.append(d,h,p,m),e.append(l);const g=new Map,b=new Map,v=new Map;let w=null;function k(){if(w)return w;const G=t.model(),q=t.positions(),Y=new Map;w=Y;const ne=G.nodes.length>iC,K=new Map(G.nodes.map(L=>[L.address,L])),I=ne?[]:KT(G,q,t.notes());for(const L of G.edges){const U=K.get(L.from),fe=K.get(L.to),ie=U&&q[U.id],te=fe&&q[fe.id];if(!U||!fe||!ie||!te){Y.set(L.id,null);continue}if(ne){Y.set(L.id,tc(ie,te,Bn(U,G.checked_address),Bn(fe,G.checked_address)));continue}const _e=I.filter(Se=>Se.id!==U.id&&Se.id!==fe.id);Y.set(L.id,oC(ie,te,Bn(U,G.checked_address),Bn(fe,G.checked_address),_e))}return Y}function x(G){let q=g.get(G);if(q)return q;q=`${i}-arrow-${g.size}`;const Y=s("marker",{id:q,viewBox:"0 0 10 10",refX:9,refY:5,markerWidth:6,markerHeight:6,orient:"auto-start-reverse",markerUnits:"strokeWidth"}),ne=s("path",{d:"M0 0L10 5L0 10Z",class:"cia-graph-arrowhead"});return ne.style.fill=G,Y.append(ne),d.append(Y),g.set(G,q),q}function N(){return[...t.model().nodes??[]].sort((G,q)=>String(G.id).localeCompare(String(q.id)))}function z(){w=null;const G=t.model();y.replaceChildren(),_.replaceChildren(),b.clear(),v.clear();const q=new Map(G.nodes.map(Y=>[Y.address,Y]));for(const Y of G.edges){const ne=q.get(Y.from);if(!ne||!q.get(Y.to))continue;const K=t.colorOf(ne),I=s("g",{class:"cia-graph-edge graph-edge",tabindex:0,role:"button","aria-label":sc(Y,t.now())});I.dataset.edgeId=Y.id,I.style.setProperty("--edge-tone",K);const L=aC(),U=s("path",{class:"cia-graph-edge-hit","stroke-width":L.hit.width,"pointer-events":"stroke"}),fe=s("path",{class:"cia-graph-edge-line","stroke-width":L.line.width,"marker-end":`url(#${x(K)})`,"pointer-events":"none"});I.append(U,fe);const ie=G.edges.length<=Ow?Mw(Y):"";let te;if(ie){fe.id=`${i}-edge-${v.size}`;const _e=s("textPath",{href:`#${fe.id}`,startOffset:"50%","text-anchor":"middle"});_e.textContent=ie;const Se=s("text",{class:"cia-graph-edge-caption",dy:"-4","pointer-events":"none","aria-hidden":"true"});Se.append(_e),I.append(Se),te=Se}I.addEventListener("keydown",_e=>{yp(_e.key)&&(_e.preventDefault(),n.selectEdge(Y.id,"keyboard"))}),I.addEventListener("pointerenter",_e=>n.showTooltip(_e,sc(Y,t.now()))),I.addEventListener("pointerleave",()=>n.hideTooltip()),y.append(I),v.set(Y.id,{group:I,hit:U,line:fe,...te?{caption:te}:{}})}for(const Y of N())_.append(O(Y));ee(),we()}function O(G){const q=t.model(),Y=G.address===q.checked_address,ne=t.notes().get(G.id),K=Rn(G,q.checked_address,ne),I=K.radius,L=s("g",{class:"cia-graph-node graph-node",tabindex:0,role:"button","aria-label":oc(G),"aria-pressed":"false"});L.dataset.nodeId=G.id,Y&&(L.dataset.checked=""),L.style.setProperty("--node-tone",t.colorOf(G)),Y&&L.append(s("circle",{class:"cia-graph-node-ring",r:I+6})),L.append(s("circle",{class:"cia-graph-node-body",r:I})),L.append(s("circle",{class:"cia-graph-node-dot",r:K.dot}));for(const U of K.texts)L.append(a(U.text,U.y,`cia-graph-node-${U.kind}`));ne&&(L.dataset.state="refused");for(const U of t.flags().get(G.id)??[])L.setAttribute(`data-flag-${U}`,"");return L.addEventListener("keydown",U=>{yp(U.key)&&(U.preventDefault(),n.selectNode(G.id,"keyboard"))}),L.addEventListener("pointerenter",U=>n.showTooltip(U,oc(G))),L.addEventListener("pointerleave",()=>n.hideTooltip()),b.set(G.id,L),L}function Z(){const G=t.transform();m.setAttribute("transform",`translate(${G.x} ${G.y}) scale(${G.scale})`)}function ee(){Z();const G=t.positions(),{width:q,height:Y}=t.dimensions();for(const[K,I]of b){const L=G[K]??{x:q/2,y:Y/2};I.setAttribute("transform",`translate(${Go(L.x)} ${Go(L.y)})`)}const ne=k();for(const K of t.model().edges){const I=v.get(K.id);if(!I)continue;const L=ne.get(K.id)??null;I.group.style.display=L?"":"none",L&&(I.hit.setAttribute("d",L.d),I.line.setAttribute("d",L.d),I.caption&&(I.caption.style.display=L.kind==="forward"||L.kind==="vertical"||L.kind==="straight"?"":"none"))}}function ae(G){const q=t.model(),Y=t.positions(),ne=Y[G],K=b.get(G);if(!ne||!K)return;K.setAttribute("transform",`translate(${Go(ne.x)} ${Go(ne.y)})`);const I=q.nodes.find(U=>U.id===G);if(!I)return;const L=new Map(q.nodes.map(U=>[U.address,U]));for(const U of q.edges){if(U.from!==I.address&&U.to!==I.address)continue;const fe=v.get(U.id),ie=L.get(U.from),te=L.get(U.to),_e=ie&&Y[ie.id],Se=te&&Y[te.id];if(!fe||!ie||!te||!_e||!Se)continue;const Ze=tc(_e,Se,Bn(ie,q.checked_address),Bn(te,q.checked_address));fe.group.style.display=Ze?"":"none",Ze&&(fe.hit.setAttribute("d",Ze.d),fe.line.setAttribute("d",Ze.d))}}function we(){const G=t.model(),q=t.selected(),Y=t.highlighted(),ne=q?.kind==="node"?G.nodes.find(K=>K.id===q.id)?.address??null:null;for(const K of G.edges){const I=v.get(K.id);if(!I)continue;const L=q?.kind==="edge"&&q.id===K.id,U=q?.kind==="edge"?L?qt.related:qt.faded:Lw(K,ne),fe=U===qt.faded;I.group.setAttribute("opacity",fe?String(U):"1"),I.line.setAttribute("stroke-opacity",fe?"1":String(U)),I.group.dataset.opacity=String(U),I.group.dataset.state=U===qt.rest?"rest":U===qt.related?"related":"faded",I.group.setAttribute("aria-pressed",String(L))}for(const[K,I]of b){const L=q?.kind==="node"&&q.id===K;I.classList.toggle("is-selected",L),I.classList.toggle("is-focused",Y===K),I.setAttribute("aria-pressed",String(L))}}function Re(){let G=null;for(const q of k().values())q?.bounds&&(G=G??{...q.bounds},G.x1=Math.min(G.x1,q.bounds.x1),G.y1=Math.min(G.y1,q.bounds.y1),G.x2=Math.max(G.x2,q.bounds.x2),G.y2=Math.max(G.y2,q.bounds.y2));return G}return{kind:"svg",surface:l,build:z,geometry(){w=null,ee()},moveNode:ae,endMove(){w=null,ee()},camera:Z,selection:we,flag(G,q,Y){b.get(G)?.toggleAttribute(`data-flag-${q}`,Y)},theme(){for(const G of t.model().nodes)b.get(G.id)?.style.setProperty("--node-tone",t.colorOf(G))},resize(G,q){l.setAttribute("viewBox",`0 0 ${G} ${q}`)},pick:()=>null,linkBounds:Re,destroy(){l.remove()}}}const pT=.1,mT=2.5,gT=5,yT="chain-insights.flows.v1",Kf="cia-graph-model",vT=300,qt={rest:.6,related:.95,faded:.25},lp={checked:24,other:19},vi=16,bT=[["Sanctioned","Sanctioned"],["Scam","Scam"],["Poisoned","Poisoned"],["OnMoneyTrail","On money trail"],["Mixer","Mixer"],["Bridge","Bridge"],["Exchange","Exchange"],["Victim","Victim"],["Targeted","Targeted"]],Hr=["exchange","scam","sanctioned","victim","pool","other"],wT={exchange:"infrastructure",scam:"danger",sanctioned:"danger",victim:"target",pool:"trail",other:"neutral"},Tw={exchange:"Exchange",scam:"Scam",sanctioned:"Sanctioned",victim:"Victim",pool:"Pool",other:""};function Jf(e){return!!e&&e.schema===yT}function _T(e){return!!e&&e.kind===Kf}function Ke(e){return String(e??"").trim().toLowerCase()}function kT(e){const t=Ke(e);return Hr.includes(t)?t:"other"}function vn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Qu(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function ST(e){const t=String(e??"").toUpperCase();return t==="IN"||t==="OUT"||t==="MIXED"||t==="CHECKED"?t:"OUT"}function Dt(e){return _T(e)?e:Jf(e)?xT(e):$T(e)}function xT(e){const t=Ke(e.center),n=new Map;for(const a of e.nodes??[]){const u=Ke(a?.address);u&&!n.has(u)&&n.set(u,a)}const r=[],i=new Set;for(const a of e.edges??[]){const u=Ke(a?.from),c=Ke(a?.to);if(!n.has(u)||!n.has(c)||u===c)continue;const l=`${u}->${c}`;i.has(l)||(i.add(l),r.push({id:l,from:u,to:c,source:"flows",amount_usd_sum:vn(a.usd),tx_count:vn(a.tx_count),first_seen_timestamp:vn(a.first_seen_ms),last_seen_timestamp:vn(a.last_seen_ms),...typeof a.link_kind=="string"&&a.link_kind?{link_kind:a.link_kind}:{}}))}const o=ET(t,[...n.keys()],r),s=[...n.entries()].map(([a,u])=>{const c=o.get(a)??{direction:"OUT",hop:2};return{id:a,address:a,direction:a===t?"CHECKED":c.direction,hop:a===t?0:c.hop,labels:Qu(u.labels),taxonomy:[],role:kT(u.role),total_in_usd:vn(u.total_in_usd),total_out_usd:vn(u.total_out_usd),degree_in:vn(u.degree_in),degree_out:vn(u.degree_out)}});return{kind:Kf,checked_address:t,network:e.network??null,nodes:s,edges:r,truncated:!!e.truncated,cursor:e.cursor??null}}function ET(e,t,n){const r=new Map,i=new Map,o=new Map,s=(d,f,h)=>d.set(f,[...d.get(f)??[],h]);for(const d of n)s(r,d.from,d.to),s(i,d.to,d.from),s(o,d.from,d.to),s(o,d.to,d.from);const a=d=>{const f=new Map([[e,0]]);for(let h=[e];h.length;){const p=[];for(const m of h)for(const y of d.get(m)??[])f.has(y)||(f.set(y,(f.get(m)??0)+1),p.push(y));h=p}return f},u=a(r),c=a(i),l=new Map;for(const d of t){if(d===e)continue;const f=u.get(d),h=c.get(d);if(f==null&&h==null)continue;const p=f!=null&&h!=null?f<h?"OUT":h<f?"IN":"MIXED":f!=null?"OUT":"IN";l.set(d,{direction:p,hop:Math.min(2,Math.min(f??1/0,h??1/0))})}for(let d=!0;d;){d=!1;for(const f of t){if(f===e||l.has(f))continue;const h=(o.get(f)??[]).find(m=>m!==e&&l.has(m));if(h==null)continue;const p=l.get(h);l.set(f,{direction:p.direction==="MIXED"?"OUT":p.direction,hop:2}),d=!0}}return l}function $T(e){const t=(e?.nodes??[]).map(r=>({...r,id:String(r.id??r.address),address:r.address,hop:Number(r.hop)||0,direction:r.address===e.checked_address?"CHECKED":ST(r.direction),labels:Qu(r.labels),taxonomy:Qu(r.taxonomy),role:null})),n=(e?.edges??[]).map(r=>({...r,id:String(r.id??`${r.from}->${r.to}`),amount_usd_sum:r.amount_usd_sum??null,tx_count:r.tx_count??null,first_seen_timestamp:r.first_seen_timestamp??null,last_seen_timestamp:r.last_seen_timestamp??null,source:"risk"}));return{kind:Kf,checked_address:e?.checked_address??"",network:null,nodes:t,edges:n,truncated:!1,cursor:null}}function TT(e,t,n){const r=Dt(t),i=kn(e,n??r.checked_address),o=e.nodes.find(d=>d.id===i),s=new Map(e.nodes.map(d=>[Ke(d.address),d])),a=[];for(const d of r.nodes){if(s.has(Ke(d.address)))continue;const f=!o||o.direction==="CHECKED"?d.direction==="CHECKED"?"OUT":d.direction:o.direction,h={...d,id:d.id,direction:f,hop:Math.min(2,(o?.hop??0)+1)};a.push(h),s.set(Ke(d.address),h)}const u=new Set(e.edges.map(d=>d.id)),c=new Set(e.edges.map(d=>`${Ke(d.from)}->${Ke(d.to)}`)),l=[...e.edges];for(const d of r.edges){const f=`${Ke(d.from)}->${Ke(d.to)}`;if(u.has(d.id)||c.has(f)||!s.has(Ke(d.from))||!s.has(Ke(d.to)))continue;const h=s.get(Ke(d.from)).address,p=s.get(Ke(d.to)).address;l.push({...d,from:h,to:p}),u.add(d.id),c.add(f)}return{model:{...e,nodes:[...e.nodes,...a],edges:l,truncated:e.truncated||r.truncated},added:a.map(d=>d.id)}}function kn(e,t){if(t==null)return null;const n=Ke(t);return e.nodes.find(i=>i.id===t||Ke(i.address)===n)?.id??null}function bi(e){return typeof e!="string"||e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Yf(e){return String(e??"").trim().replace(/\s+/g," ")}function ys(e){return Yf(e).replaceAll(" ","").toLowerCase()}function In(e){const t=[...e.taxonomy??[],...e.labels??[]],n=new Set,r=[];for(const i of t){const o=Yf(i),s=o.toLowerCase();!o||s==="address"||n.has(s)||(n.add(s),r.push(o))}return r}function jo(e,t){const n=new Set(In(e).map(ys));return t.some(r=>n.has(ys(r)))}function CT(e){if(e.role&&Hr.includes(e.role))return wT[e.role];if(jo(e,["Sanctioned","Scam","Poisoned"]))return"danger";if(jo(e,["Victim","Targeted"]))return"target";if(jo(e,["OnMoneyTrail","Mixer"]))return"trail";if(jo(e,["Exchange","Bridge","token contract"]))return"infrastructure";if(e.risk_score!=null){const t=String(e.risk_level).toLowerCase();if(t==="critical"||t==="high"||t==="medium"||t==="low")return t}return"neutral"}function We(e){return`var(--cia-graph-${e})`}const AT={semantic:{danger:{stroke:We("danger"),fill:We("node")},target:{stroke:We("target"),fill:We("node")},trail:{stroke:We("trail"),fill:We("node")},infrastructure:{stroke:We("infrastructure"),fill:We("node")},neutral:{stroke:We("neutral"),fill:We("node")}},risk:{CRITICAL:{stroke:We("critical"),fill:We("node")},HIGH:{stroke:We("high"),fill:We("node")},MEDIUM:{stroke:We("medium"),fill:We("node")},LOW:{stroke:We("low"),fill:We("node")}}};function IT(e,t=AT){const n=CT(e);return n==="critical"||n==="high"||n==="medium"||n==="low"?t.risk[n.toUpperCase()]??t.semantic.neutral:t.semantic[n]}function NT(e){return e.role&&Hr.includes(e.role)?We(`role-${e.role}`):IT(e).stroke}function No(e){if(e.role&&e.role!=="other"&&Hr.includes(e.role))return Tw[e.role];const t=In(e);for(const[r,i]of bT)if(t.some(o=>ys(o)===ys(r)))return i;return(Array.isArray(e.labels)?e.labels.map(Yf).filter(Boolean).sort((r,i)=>r.localeCompare(i)):[])[0]??""}function ec(e){return Math.min(mT,Math.max(pT,e))}function Xf(e){return[...e.nodes??[]].sort((t,n)=>String(t.id).localeCompare(String(n.id)))}function Cw(e,t=Xf(e)){return t.find(n=>n.address===e.checked_address)??t[0]}function dp(e,t){return e.address===t?43:e.hop>=2?25:30}function Bn(e,t){return e.address===t?lp.checked:lp.other}function Rn(e,t,n){const r=e.address===t,i=Bn(e,t),o=No(e),s=[];return o&&s.push({kind:"role",text:SC(o),y:i+17}),s.push({kind:"address",text:bi(e.address),y:i+(o?33:17)}),n&&s.push({kind:"note",text:n,y:i+(o?48:32)}),{radius:i,ring:r,dot:r?8:5,texts:s}}const RT={role:{size:13,advance:.68},address:{size:11,advance:.62},note:{size:11,advance:.6}},du=2;function Qf(e){const t=e.radius+(e.ring?7:2),n=[{kind:"circle",box:{x1:-t,y1:-t,x2:t,y2:t}}];for(const r of e.texts){const i=RT[r.kind],o=[...r.text].length*i.size*i.advance/2+du;n.push({kind:r.kind,box:{x1:-o,y1:r.y-i.size*.8-du,x2:o,y2:r.y+i.size*.25+du}})}return n}function Aw(e){return e.length?{x1:Math.min(...e.map(t=>t.x1)),y1:Math.min(...e.map(t=>t.y1)),x2:Math.max(...e.map(t=>t.x2)),y2:Math.max(...e.map(t=>t.y2))}:null}function vs(e){return Aw(Qf(e).map(t=>t.box))}const wi=(e,t)=>(e instanceof Map?e.get(t):e?.[t])??null;function LT(e,t,n){const r=Dt(e),i=[];for(const o of r.nodes){const s=t[o.id];if(s)for(const{kind:a,box:u}of Qf(Rn(o,r.checked_address,wi(n,o.id))))i.push({id:o.id,kind:a,x1:s.x+u.x1,y1:s.y+u.y1,x2:s.x+u.x2,y2:s.y+u.y2})}return i}function zT(e,t,n){return Aw(LT(e,t,n))}function PT(e,t){return e.x1<t.x2&&t.x1<e.x2&&e.y1<t.y2&&t.y1<e.y2}function DT(e){let t=0;for(const n of String(e))t=(t<<5)-t+n.charCodeAt(0)|0;return Math.abs(t)}function OT(e,t,n){const r=Dt(e),i={x:t/2,y:n/2},o={},s=Xf(r),a=Cw(r,s);if(!a)return o;o[a.id]=i;const u=new Map;for(const l of s){if(l.id===a.id)continue;let d=l.direction==="IN"?-1:1;l.direction==="MIXED"&&(d=DT(l.id)%2?-1:1);const f=Math.min(2,Math.max(1,Number(l.hop)||1)),h=`${d}:${f}`;u.has(h)||u.set(h,[]),u.get(h).push(l)}const c=MT(r);for(const[l,d]of u){const[f,h]=l.split(":"),p=Number(f),m=Number(h),y=i.x+p*(m===1?t*.23:t*.43);d.sort((_,g)=>(c.get(g.address)??0)-(c.get(_.address)??0)||String(_.id).localeCompare(String(g.id))),Object.assign(o,FT(d,y,i.y,r.checked_address))}return o}function MT(e){const t=new Map;for(const n of e.edges){const r=Math.max(n.last_seen_timestamp??0,n.first_seen_timestamp??0);for(const i of[n.from,n.to])r>(t.get(i)??0)&&t.set(i,r)}return t}function FT(e,t,n,r,i=24){const o=e.map((u,c)=>({node:u,x:t,y:n+(c-(e.length-1)/2)*64})),s=u=>vs(Rn(u,r)),a=(u,c)=>Math.max(dp(u,r)+dp(c,r)+20,s(u).y2-s(c).y1+2);for(let u=0;u<i;u++){for(let d=1;d<o.length;d++){const f=o[d-1],h=o[d];!f||!h||(h.y=Math.max(h.y,f.y+a(f.node,h.node)))}for(let d=o.length-2;d>=0;d--){const f=o[d],h=o[d+1];!f||!h||(f.y=Math.min(f.y,h.y-a(f.node,h.node)))}const c=o[0],l=o[o.length-1];if(c&&l){const d=(c.y+l.y)/2,f=n-d;for(const h of o)h.y+=f}}return Object.fromEntries(o.map(u=>[u.node.id,{x:u.x,y:u.y}]))}function UT(e,t,n){const r=Dt(e),i={x:t/2,y:n/2},o={},s=Xf(r),a=Cw(r,s);if(!a)return o;o[a.id]=i;const u=s.filter(c=>c.id!==a.id);return u.forEach((c,l)=>{const d=-Math.PI/2+l*Math.PI*2/Math.max(1,u.length)+(_r(c.id)-.5)*.3,f=(c.hop>=2?Math.min(t,n)*.39:Math.min(t,n)*.27)*(.85+_r(c.id+"/r")*.3);o[c.id]={x:i.x+Math.cos(d)*f,y:i.y+Math.sin(d)*f}}),o}function _r(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0)%10007/10007}const Sn={link:150,repel:50,reach:300,spring:.06,centre:.02};function GT(e,t,n,r,i){const o=e.nodes.filter(l=>t[l.id]),s=new Map(o.map(l=>[l.id,{x:0,y:0}])),a=o.filter(l=>n.has(l.id)),u=new Map(a.map((l,d)=>[l.id,d]));for(let l=0;l<a.length;l++){const d=a[l],f=t[d.id],h=s.get(d.id);for(const p of o){if(p===d)continue;const m=u.get(p.id);if(m!==void 0&&m<l)continue;const y=t[p.id];let _=y.x-f.x,g=y.y-f.y;!_&&!g&&(_=_r(d.id+p.id)-.5,g=_r(p.id+d.id)-.5);const b=Math.max(8,Math.hypot(_,g));if(b>=Sn.reach)continue;const v=Sn.repel*Sn.repel/b*(1-b/Sn.reach),w=_/b*v,k=g/b*v;if(h.x-=w,h.y-=k,m!==void 0){const x=s.get(p.id);x.x+=w,x.y+=k}}}const c=new Map(o.map(l=>[l.address,l]));for(const l of e.edges){const d=c.get(l.from),f=c.get(l.to);if(!d||!f||d===f)continue;const h=t[d.id],p=t[f.id],m=p.x-h.x,y=p.y-h.y,_=Math.max(1,Math.hypot(m,y)),g=(_-Sn.link)*Sn.spring,b=m/_*g,v=y/_*g,w=s.get(d.id);w.x+=b,w.y+=v;const k=s.get(f.id);k.x-=b,k.y-=v}for(const l of o){if(!n.has(l.id))continue;const d=t[l.id],f=s.get(l.id),h=Sn.centre/Math.max(1,l.hop);f.x+=(r.x-d.x)*h,f.y+=(r.y-d.y)*h;const p=Math.hypot(f.x,f.y),m=30*i,y=p>m?m/p:1;d.x+=f.x*y*Math.min(1,i*4),d.y+=f.y*y*Math.min(1,i*4)}}function Iw(e,t,n,r,i){const o=e.nodes.filter(c=>t[c.id]).length,s=Math.max(1,n.size*o);i=Math.min(i,Math.max(60,Math.floor(4e7/s)));const a=i>1?Math.pow(.01,1/(i-1)):1;let u=1;for(let c=0;c<i;c++)GT(e,t,n,r,u),u*=a;return t}function jT(e,t,n,r=vT){const i=Dt(e),o=UT(i,t,n),s=i.nodes.find(u=>u.address===i.checked_address),a=new Set(i.nodes.filter(u=>u!==s).map(u=>u.id));return Iw(i,o,a,{x:t/2,y:n/2},r),s&&(o[s.id]={x:t/2,y:n/2}),Nw(i,o,a)}function Zo(e,t,n,r){return t==="tree"?OT(e,n,r):jT(e,n,r)}function Nw(e,t,n,r,i=22,o=60){const s=Dt(e),a=s.nodes.filter(d=>t[d.id]),u=new Map(a.map(d=>[d.id,vs(Rn(d,s.checked_address,wi(r,d.id)))])),c=a.filter(d=>n.has(d.id)),l=new Map(c.map((d,f)=>[d.id,f]));for(let d=0;d<o;d++){let f=!1;for(let h=0;h<c.length;h++)for(const p of a){const m=c[h];if(p===m)continue;const y=l.get(p.id);if(y!==void 0&&y<h)continue;const _=t[m.id],g=t[p.id],b=u.get(m.id),v=u.get(p.id),w=Math.min(_.x+b.x2,g.x+v.x2)-Math.max(_.x+b.x1,g.x+v.x1)+i,k=Math.min(_.y+b.y2,g.y+v.y2)-Math.max(_.y+b.y1,g.y+v.y1)+i;if(w<=0||k<=0)continue;f=!0;const x=w<k,N=x?g.x>=_.x?1:-1:g.y>=_.y?1:-1,z=(x?w:k)/2+.5,Z=n.has(m.id)&&n.has(p.id)?z:z*2;n.has(m.id)&&(x?_.x-=N*Z:_.y-=N*Z),n.has(p.id)&&(x?g.x+=N*Z:g.y+=N*Z)}if(!f)break}return t}const ZT=300;function BT(e,t,n,r,i={}){const o=i.steps??ZT,s=Dt(e),a=t[n],u={...t};if(!a)return u;const c=new Map(s.nodes.map(w=>[w.id,w])),l=[...r].sort().filter(w=>!u[w]&&c.has(w));if(!l.length)return u;const d=c.get(n)?.address,f=new Set(s.edges.filter(w=>w.to===d).map(w=>w.from)),h=new Set(s.edges.filter(w=>w.from===d).map(w=>w.to)),p=w=>{const k=c.get(w).address;return f.has(k)&&!h.has(k)},m=l.filter(p),y=l.filter(w=>!p(w)),_=(w,k)=>{w.forEach((N,z)=>{const O=Math.floor(z/10),Z=Math.min(10,w.length-O*10),ee=z-O*10,ae=Math.PI*.8,we=(Z===1?0:-ae/2+ee*ae/(Z-1))+(_r(N)-.5)*.2,Re=(Sn.link+O*110)*(.9+_r(N+"/r")*.2);u[N]={x:a.x+k*Math.cos(we)*Re,y:a.y+Math.sin(we)*Re}})};_(m,-1),_(y,1);const g=s.nodes.filter(w=>t[w.id]&&!l.includes(w.id)).map(w=>({point:t[w.id],box:vs(Rn(w,s.checked_address,wi(i.notes,w.id)))})),b=(w,k)=>{if(!w.length)return;const x=w.map(N=>({id:N,box:vs(Rn(c.get(N),s.checked_address,wi(i.notes,N)))}));for(let N=0;N<12;N++){const z={x1:1/0,y1:1/0,x2:-1/0,y2:-1/0};for(const{id:Z,box:ee}of x){const ae=u[Z];z.x1=Math.min(z.x1,ae.x+ee.x1),z.x2=Math.max(z.x2,ae.x+ee.x2),z.y1=Math.min(z.y1,ae.y+ee.y1),z.y2=Math.max(z.y2,ae.y+ee.y2)}let O=0;for(const Z of g){if(Math.min(z.y2,Z.point.y+Z.box.y2)-Math.max(z.y1,Z.point.y+Z.box.y1)+12<=0)continue;const ae=k<0?z.x2+24-(Z.point.x+Z.box.x1):Z.point.x+Z.box.x2+24-z.x1;ae>O&&(O=ae)}if(O<=0)break;for(const Z of w)u[Z].x+=k*O}},v=new Set(l);return Iw(s,u,v,{x:a.x,y:a.y},o),Nw(s,u,v,i.notes),b(m,-1),b(y,1),u}function VT(e,t,n,r=vi){const i=Math.max(1,e.x2-e.x1),o=Math.max(1,e.y2-e.y1),s=ec(Math.min((t-r*2)/i,(n-r*2)/o));return{x:t/2-(e.x1+e.x2)/2*s,y:n/2-(e.y1+e.y2)/2*s,scale:s}}function fp(e,t,n,r=vi){return Math.min((t-r*2)/Math.max(1,e.x2-e.x1),(n-r*2)/Math.max(1,e.y2-e.y1))}function HT(e,t,n,r,i=4){const o=t.x-e.x,s=t.y-e.y,a=Math.hypot(o,s),u=n+i,c=r+i;if(!Number.isFinite(a)||a<=0||u+c>=a)return null;const l=o/a,d=s/a;return{x1:e.x+l*u,y1:e.y+d*u,x2:t.x-l*c,y2:t.y-d*c}}function $n(e){return Math.round(e*100)/100}function fu(e,t,n,r,i){const o=s=>`${$n(s.x)},${$n(s.y)}`;return{kind:e,start:t,end:i,controls:[n,r],d:`M${o(t)} C${o(n)} ${o(r)} ${o(i)}`}}function tc(e,t,n,r,i=4){const o=t.x-e.x,s=t.y-e.y,a=Math.hypot(o,s),u=n+r+i*2;if(!Number.isFinite(a)||a<=u)return null;if(o>=u){const f={x:e.x+n+i,y:e.y},h={x:t.x-r-i,y:t.y},p=h.x-f.x,m=Math.max(p*.45,Math.min(65,p));return fu("forward",f,{x:f.x+m,y:f.y},{x:h.x-m,y:h.y},h)}if(o<=-u){const f={x:e.x,y:e.y-n-i},h={x:t.x,y:t.y-r-i},p=Math.max(100,Math.abs(o)*.2);return fu("backward",f,{x:f.x+85,y:f.y-p},{x:h.x+85,y:h.y-p},h)}if(Math.abs(s)>u){const f=s>0?1:-1,h={x:e.x,y:e.y+f*(n+i)},p={x:t.x,y:t.y-f*(r+i)},m=Math.abs(p.y-h.y),y=Math.max(m*.45,Math.min(40,m));return fu("vertical",h,{x:h.x,y:h.y+f*y},{x:p.x,y:p.y-f*y},p)}const c=HT(e,t,n,r,i),l={x:c.x1,y:c.y1},d={x:c.x2,y:c.y2};return{kind:"straight",start:l,end:d,controls:null,d:`M${$n(l.x)},${$n(l.y)} L${$n(d.x)},${$n(d.y)}`}}const qT=6,hu=qT+3,Qt=14,hp=10,WT=3,pp=6;function KT(e,t,n){const r=Dt(e),i=[];for(const o of r.nodes){const s=t[o.id];if(s)for(const{kind:a,box:u}of Qf(Rn(o,r.checked_address,wi(n,o.id))))a==="circle"?i.push({id:o.id,kind:"circle",x:s.x,y:s.y,r:u.x2}):i.push({id:o.id,kind:"box",x1:s.x+u.x1,y1:s.y+u.y1,x2:s.x+u.x2,y2:s.y+u.y2})}return i}function JT(e,t){if(t.kind==="circle")return Math.hypot(e.x-t.x,e.y-t.y)-t.r;const n=Math.max(t.x1-e.x,0,e.x-t.x2),r=Math.max(t.y1-e.y,0,e.y-t.y2);return n||r?Math.hypot(n,r):-Math.min(e.x-t.x1,t.x2-e.x,e.y-t.y1,t.y2-e.y)}function YT(e,t){return e.kind==="circle"?{x1:e.x-e.r-t,y1:e.y-e.r-t,x2:e.x+e.r+t,y2:e.y+e.r+t}:{x1:e.x1-t,y1:e.y1-t,x2:e.x2+t,y2:e.y2+t}}function XT(e,t){const n=1-t;return{x:n*n*n*e[0].x+3*n*n*t*e[1].x+3*n*t*t*e[2].x+t*t*t*e[3].x,y:n*n*n*e[0].y+3*n*n*t*e[1].y+3*n*t*t*e[2].y+t*t*t*e[3].y}}function QT(e){return e.controls?[{kind:"C",points:[e.start,e.controls[0],e.controls[1],e.end]}]:[{kind:"L",points:[e.start,e.end]}]}function Rw(e){let t=0,n;for(const r of e)n&&(t+=Math.hypot(r.x-n.x,r.y-n.y)),n=r;return t}function eC(e,t){const n=[];for(const r of e){const i=Math.max(1,Math.ceil(Rw(r.points)/t));for(let o=0;o<=i;o++){const s=o/i;if(r.kind==="L"){const[a,u]=r.points;n.push({x:a.x+(u.x-a.x)*s,y:a.y+(u.y-a.y)*s})}else n.push(XT(r.points,s))}}return n}function mp(e,t,n,r){const i=e.flatMap(a=>a.points),o={x1:Math.min(...i.map(a=>a.x)),y1:Math.min(...i.map(a=>a.y)),x2:Math.max(...i.map(a=>a.x)),y2:Math.max(...i.map(a=>a.y))},s=[];if(n.forEach((a,u)=>{a.x1<=o.x2&&o.x1<=a.x2&&a.y1<=o.y2&&o.y1<=a.y2&&s.push(u)}),!s.length)return!0;for(const a of eC(e,WT))for(const u of s){const c=n[u],l=t[u];if(!(!c||!l)&&!(a.x<c.x1||a.x>c.x2||a.y<c.y1||a.y>c.y2)&&JT(a,l)<r)return!1}return!0}function tC(e){const t=e[0],n=e[e.length-1];if(!t||!n)return[];const r=[];for(let s=1;s<e.length;s++)r.push(Rw(e.slice(s-1,s+1)));const i=[];let o=t;for(let s=1;s<e.length-1;s++){const a=e[s-1],u=e[s],c=e[s+1],l=r[s-1],d=r[s];if(!a||!u||!c||l===void 0||d===void 0)continue;const f=l/(s-1===0?1:2),h=d/(s===r.length-1?1:2),p=Math.min(Qt,f,h),m={x:(u.x-a.x)/l,y:(u.y-a.y)/l},y={x:(c.x-u.x)/d,y:(c.y-u.y)/d},_={x:u.x-m.x*p,y:u.y-m.y*p},g={x:u.x+y.x*p,y:u.y+y.y*p};i.push({kind:"L",points:[o,_]}),i.push({kind:"C",points:[_,{x:_.x+m.x*p*.55,y:_.y+m.y*p*.55},{x:g.x-y.x*p*.55,y:g.y-y.y*p*.55},g]}),o=g}return i.push({kind:"L",points:[o,n]}),i.filter(s=>s.kind==="C"||Math.hypot(s.points[1].x-s.points[0].x,s.points[1].y-s.points[0].y)>.01)}function nC(e){const t=i=>`${$n(i.x)},${$n(i.y)}`,n=e[0];if(!n)return"";let r=`M${t(n.points[0])}`;for(const i of e)r+=i.kind==="L"?` L${t(i.points[1])}`:` C${t(i.points[1])} ${t(i.points[2])} ${t(i.points[3])}`;return r}function gp(e,t,n,r,i){const o=Math.min(e.y,n)-Qt,s=Math.max(e.y,n)+Qt,a=d=>(d-e.x)*t;let u=1/0;for(const d of i)if(d.y1<e.y&&e.y<d.y2){const f=t===1?d.x1:d.x2,h=t===1?d.x2:d.x1;a(h)>0&&(u=Math.min(u,Math.max(0,a(f))))}const c=i.filter(d=>d.y1<s&&o<d.y2).map(d=>[a(t===1?d.x1:d.x2),a(t===1?d.x2:d.x1)]).filter(([,d])=>d>r).sort((d,f)=>d[0]-f[0]);let l=r;for(const[d,f]of[...c,[1/0,1/0]]){if(d>l+1){const h=Math.min(d,u);if(h<=l+1)return null;const p=Number.isFinite(h)&&h-l<80?(l+h)/2:l+40;return e.x+t*p}if(l=Math.max(l,f),l>=u)return null}return null}function rC(e){const t=[];for(const n of e){const r=t[t.length-1];r&&Math.abs(r.x-n.x)<.01&&Math.abs(r.y-n.y)<.01||t.push(n)}return t.filter((n,r)=>{if(r===0||r===t.length-1)return!0;const i=t[r-1],o=t[r+1];return!i||!o?!0:!(Math.abs(i.x-n.x)<.01&&Math.abs(o.x-n.x)<.01||Math.abs(i.y-n.y)<.01&&Math.abs(o.y-n.y)<.01)})}const iC=120;function oC(e,t,n,r,i,o=4){const s=tc(e,t,n,r,o);if(!s||!i.length)return s;const a=i.map(f=>YT(f,hu));if(mp(QT(s),i,a,hu))return s;const u=new Set([e.y,t.y]),c=f=>Math.abs(f-e.y)<pp?e.y:Math.abs(f-t.y)<pp?t.y:f;for(const f of a)u.add(c(Math.round(f.y1)-Qt-1)),u.add(c(Math.round(f.y2)+Qt+1));const l=t.x>=e.x?1:-1,d=[[l,l],[l,-l],[-l,l],[-l,-l]];for(const[f,h]of d){const p={x:e.x+f*(n+o),y:e.y},m={x:t.x-h*(r+o),y:t.y},y=[];for(const _ of u){const g=Math.abs(_-p.y)<.01?p.x:gp(p,f,_,Qt,a);if(g===null)continue;const b=Math.abs(_-m.y)<.01?m.x:gp(m,-h,_,Qt+hp,a);if(b===null||Math.abs(_-m.y)<.01&&(m.x-g)*h<Qt+hp||Math.abs(_-p.y)<.01&&(b-p.x)*f<Qt)continue;const v=rC([p,{x:g,y:p.y},{x:g,y:_},{x:b,y:_},{x:b,y:m.y},m]);if(!sC(v,a))continue;let w=(v.length-2)*Qt,k;for(const x of v)k&&(w+=Math.abs(x.x-k.x)+Math.abs(x.y-k.y)),k=x;y.push({points:v,length:w})}y.sort((_,g)=>{const b=_.points[2]?.y,v=g.points[2]?.y;return _.length-g.length||(b===void 0||v===void 0?0:b-v)});for(const _ of y){const g=tC(_.points);if(!mp(g,i,a,hu))continue;const b=_.points,v=b[0],w=b[b.length-1];if(!v||!w)continue;const k={x1:Math.min(...b.map(x=>x.x)),y1:Math.min(...b.map(x=>x.y)),x2:Math.max(...b.map(x=>x.x)),y2:Math.max(...b.map(x=>x.y))};return{kind:"routed",start:v,end:w,controls:null,d:nC(g),bounds:k}}}return s}function sC(e,t){let n;for(const r of e){if(n){const i={x1:Math.min(n.x,r.x),y1:Math.min(n.y,r.y),x2:Math.max(n.x,r.x),y2:Math.max(n.y,r.y)};for(const o of t)if(PT(i,o))return!1}n=r}return!0}function Lw(e,t){if(!t)return qt.rest;const n=Ke(t);return Ke(e.from)===n||Ke(e.to)===n?qt.related:qt.faded}function aC(){return{hit:{stroke:"transparent",width:16},line:{stroke:We("edge"),width:1.6},arrow:{fill:We("edge")}}}function uC(e,t,n){return e!=="gravity"&&e!=="tree"?null:{layout:e,id:t,pointerId:n}}function cC(e,t,n,r){return e!=="node"&&e!=="edge"&&e!=="canvas"||!Number.isFinite(r?.x)||!Number.isFinite(r?.y)?null:{kind:e,id:t??null,pointerId:n,start:{...r},moved:!1}}function lC(e,t,n,r=gT){if(!e||e.pointerId!==t)return e;const i=Math.hypot(n.x-e.start.x,n.y-e.start.y);return{...e,moved:e.moved||i>r}}function dC(e,t,n=!1){return!e||e.pointerId!==t||n||e.moved?null:e.kind==="node"?{type:"select-node",id:e.id}:e.kind==="edge"?{type:"select-edge",id:e.id}:e.kind==="canvas"?{type:"clear-selection"}:null}function yp(e){return e==="Enter"||e===" "}function fC(e,t){return{x:(e.x-t.x)/t.scale,y:(e.y-t.y)/t.scale}}function hC(e,t,n,r,i){return!t||t.pointerId!==n||!Object.hasOwn(e,t.id)?!1:(e[t.id]=fC(r,i),!0)}function pC(e,t){return e?.pointerId===t?null:e}function mC(e,t,n,r){const i=Math.min(t.width/n,t.height/r),o=t.left+(t.width-n*i)/2,s=t.top+(t.height-r*i)/2;return{x:(e.x-o)/i,y:(e.y-s)/i}}function gC(e,t,n){const r=new Map;let i=null,o=null,s=null;function a(h){if(h===e)return{kind:"canvas",id:null};const p=h;if(p?.closest?.("[data-canvas]"))return{kind:"canvas",id:null};const m=p?.closest?.("[data-node-id]");if(m)return{kind:"node",id:m.dataset.nodeId??null};const y=p?.closest?.("[data-edge-id]");return y?{kind:"edge",id:y.dataset.edgeId??null}:null}function u(h){if(h.pointerType==="mouse"&&h.button!==0)return;const p=n?n(h):a(h.target);if(!p)return;const m=t.point(h);if(r.set(h.pointerId,m),e.setPointerCapture(h.pointerId),p.kind!=="canvas"&&(h.preventDefault(),h.stopPropagation()),r.size===1){i=cC(p.kind,p.id,h.pointerId,{x:h.clientX,y:h.clientY}),o=p.kind==="canvas"?{point:m,transform:{...t.transform()}}:null;return}if(i&&(i={...i,moved:!0}),o=null,r.size===2){const[y,_]=[...r.values()];y&&_&&(s={distance:Math.hypot(_.x-y.x,_.y-y.y),scale:t.transform().scale},t.startPinch())}}function c(h){if(!r.has(h.pointerId))return;const p=t.point(h);if(r.set(h.pointerId,p),s){const[m,y]=[...r.values()];m&&y&&t.pinch(s,[m,y],h);return}if(i?.pointerId===h.pointerId){if(i=lC(i,h.pointerId,{x:h.clientX,y:h.clientY}),!i?.moved)return;if(i.kind==="node"){t.drag(i.id??"",h.pointerId,p,h);return}if(i.kind==="edge")return}o&&t.pan(o,p,h)}function l(h,p=!1){const m=dC(i,h.pointerId,p);m&&t.select(m),i?.pointerId===h.pointerId&&(i=null),t.endDrag(h.pointerId),r.delete(h.pointerId),r.size||(i=null,o=null,s=null),e.hasPointerCapture(h.pointerId)&&e.releasePointerCapture(h.pointerId)}const d=h=>l(h),f=h=>l(h,!0);return e.addEventListener("pointerdown",u,!0),e.addEventListener("pointermove",c),e.addEventListener("pointerup",d),e.addEventListener("pointercancel",f),()=>{e.removeEventListener("pointerdown",u,!0),e.removeEventListener("pointermove",c),e.removeEventListener("pointerup",d),e.removeEventListener("pointercancel",f)}}function yC(e,t,n){let r=!1;function i(o,s=!1){r=o,e.classList.toggle("graph-panel--expanded",o),n.classList.toggle("graph-expanded",o),t.classList.toggle("expand-control--expanded",o),t.setAttribute("aria-expanded",String(o)),t.setAttribute("aria-label",o?"Close expanded graph":"Expand graph"),t.setAttribute("title",o?"Close expanded graph":"Expand graph"),o?(e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true")):(e.removeAttribute("role"),e.removeAttribute("aria-modal"),s&&t.focus())}return{open(){i(!0)},close(o={}){i(!1,o.restoreFocus!==!1)},toggle(){i(!r,r)},isOpen(){return r}}}function zw(e){const t=String(e??"").toLowerCase();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function nc(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e)}function rc(e){return e==null?"Unavailable":new Intl.NumberFormat("en-US").format(e)}function Tn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"Unavailable";const t=new Date(e<1e11?e*1e3:e);return!Number.isFinite(t.getTime())||t.getUTCFullYear()<2009||t.getUTCFullYear()>2100?"Unavailable":new Intl.DateTimeFormat("en-GB",{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(t)}function Pw(e,t=Date.now()){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"Unavailable";const n=Math.max(0,(t-(e<1e11?e*1e3:e))/1e3),r=[[31536e3,"year"],[2592e3,"month"],[86400,"day"],[3600,"hour"],[60,"minute"]];for(const[i,o]of r){const s=Math.floor(n/i);if(s>=1)return`${s} ${o}${s===1?"":"s"} ago`}return"just now"}function ic(e){if(e.amount_usd_sum==null||e.price_coverage_ratio===0)return"Unavailable";const t=e.price_coverage_ratio;return nc(e.amount_usd_sum)+(t!=null&&t>0&&t<1?" (priced portion)":"")}function vC(e){const t=[["Incoming amount (USD)",e.total_in_usd==null?"Unavailable":nc(e.total_in_usd)],["Outgoing amount (USD)",e.total_out_usd==null?"Unavailable":nc(e.total_out_usd)]];return e.role&&Hr.includes(e.role)?[["Role",Tw[e.role]||"Other"],...t,["Senders",rc(e.degree_in)],["Receivers",rc(e.degree_out)],["Labels",In(e).join(", ")||"No labels"]]:[["Address risk",e.risk_score==null?"Not scored":`${Math.round(e.risk_score*100)} · ${zw(e.risk_level)}`],["Confidence","Unavailable"],...t,["First activity (UTC)",Tn(e.first_activity_timestamp)],["Last activity (UTC)",Tn(e.last_activity_timestamp)],["Labels",In(e).join(", ")||"No labels"]]}function bC(e,t){if(e.source==="flows")return[["From",e.from||"Unavailable"],["To",e.to||"Unavailable"],["Value (USD)",ic(e)],["Transfers",rc(e.tx_count)],["First seen (UTC)",Tn(e.first_seen_timestamp)],["Last seen (UTC)",Tn(e.last_seen_timestamp)],["Since last seen",Pw(e.last_seen_timestamp,t)],...e.link_kind?[["Link kind",e.link_kind]]:[]];const n=e.price_coverage_ratio;return[["From",e.from||"Unavailable"],["To",e.to||"Unavailable"],["Value (USD)",ic(e)],["Price coverage",n==null?"Unavailable":new Intl.NumberFormat("en-GB",{style:"percent",maximumFractionDigits:1}).format(n)],["Transfers",e.tx_count==null?"Unavailable":String(e.tx_count)],["First seen (UTC)",Tn(e.first_seen_timestamp)],["Last seen (UTC)",Tn(e.last_seen_timestamp)],["First transaction",e.first_tx_id||"Unavailable"],["Last transaction",e.last_tx_id||"Unavailable"]]}function Dw(e){return typeof e!="string"||!/^0x[a-fA-F0-9]{64}$/.test(e)?null:`https://robinhoodchain.blockscout.com/tx/${e.toLowerCase()}`}function oc(e){const t=No(e);if(e.role)return`${e.address}. ${t||"Other"}.${In(e).length?` Labels: ${In(e).join(", ")}.`:""}`;const n=e.risk_score==null?"Not scored":`${Math.round(e.risk_score*100)} ${zw(e.risk_level)} risk`,r=In(e).join(", ");return`${e.address}. ${n}.${r?` Labels: ${r}.`:""}`}const Ow=80;function wC(e){const t=Math.abs(e);return t>=1e9?`$${(e/1e9).toFixed(1)}B`:t>=1e6?`$${(e/1e6).toFixed(1)}M`:t>=1e4?`$${Math.round(e/1e3)}K`:t>=100?`$${Math.round(e)}`:`$${e.toFixed(2)}`}function _C(e,t){const n=u=>new Date(u<1e12?u*1e3:u),r=e&&e>0?n(e):null,i=t&&t>0?n(t):r;if(!i)return"";const o=u=>u.getUTCDate(),s=u=>u.toLocaleString("en-US",{month:"short",timeZone:"UTC"}),a=u=>`${o(u)} ${s(u)} ${u.getUTCFullYear()}`;return!r||r.toISOString().slice(0,10)===i.toISOString().slice(0,10)?a(i):r.getUTCFullYear()!==i.getUTCFullYear()?`${a(r)} – ${a(i)}`:r.getUTCMonth()!==i.getUTCMonth()?`${o(r)} ${s(r)} – ${a(i)}`:`${o(r)} – ${a(i)}`}function Mw(e){const t=e.amount_usd_sum!=null&&e.price_coverage_ratio!==0?wC(e.amount_usd_sum):"",n=_C(e.first_seen_timestamp,e.last_seen_timestamp);return[t,n].filter(Boolean).join(" · ")}function sc(e,t){const n=`${e.from} to ${e.to}. Aggregate value ${ic(e)}. ${e.tx_count??0} ${e.tx_count===1?"transfer":"transfers"}.`;return e.source==="flows"&&e.last_seen_timestamp?`${n} Last seen ${Pw(e.last_seen_timestamp,t)}.`:n}function kC(e,t){return Dt(e).nodes.map(n=>{const r={id:n.address,label:In(n).join(", ")||No(n)};n.role&&(r.role=n.role);const i=t?.(n.address);return i&&(r.href=i),r})}function SC(e,t=22){return e.length>t?`${e.slice(0,t-1)}…`:e}function xC(e,t,n={}){const r=e.ownerDocument;let i=Dt(t),o=n.layout??(Jf(t)?"tree":"gravity");const s={width:e.clientWidth||n.width||820,height:e.clientHeight||n.height||430};let a=Zo(i,o,s.width,s.height);const u=new Map,c=new Map;let l={x:0,y:0,scale:1},d=null,f=null,h=null;const p=n.now??(()=>Date.now()),m=T=>n.nodeStyle?.(T).stroke??NT(T);e.classList.add("cia-graph-engine"),e.closest(".cia-graph-surface")||e.classList.add("cia-graph-surface");const y={model:()=>i,positions:()=>a,transform:()=>l,notes:()=>u,flags:()=>c,selected:()=>d,highlighted:()=>f,colorOf:m,now:p,dimensions:()=>s},_={selectNode:(T,M)=>q(T,M),selectEdge:(T,M)=>Y(T,M),showTooltip:(T,M)=>U(T,M),hideTooltip:()=>fe(),lost:()=>xe()};function g(T){const M=T==="webgl"?up("webgl"):null;if(M)try{return M(e,y,_,{label:n.label})}catch{}return cp(e,y,_,{label:n.label})}const b=n.renderer??(up("webgl")&&lT(r)?"webgl":"svg");let v=g(b);e.dataset.renderer=v.kind;const w=()=>{const T=zT(i,a,u);if(!T)return null;const M=v.linkBounds();return M&&(T.x1=Math.min(T.x1,M.x1),T.y1=Math.min(T.y1,M.y1),T.x2=Math.max(T.x2,M.x2),T.y2=Math.max(T.y2,M.y2)),T},k=()=>{const T=w();return T?VT(T,s.width,s.height,vi):{x:0,y:0,scale:1}};l=k();const x=r.createElement("div");x.className="graph-tooltip cia-graph-tooltip",x.hidden=!0,x.setAttribute("role","tooltip"),e.append(x);let N=0,z=!1,O=!1;function Z(){if(N){z=!0;return}v.build()}function ee(){if(N){O=!0;return}l=k(),ae()}function ae(){v.camera()}function we(T="program"){const M=kC(i,n.href),J=d?.kind==="node"?i.nodes.find(me=>me.id===d.id)??null:null,ke=d?.kind==="edge"?i.edges.find(me=>me.id===d.id)??null:null;if(J){const me=i.edges.filter(lt=>lt.from===J.address||lt.to===J.address);return{kind:"node",id:J.id,selectedId:J.address,nodes:M,title:"Selected address",identity:J.address,values:vC(J),related:me,node:J,edge:null,source:T}}return ke?{kind:"edge",id:ke.id,selectedId:null,nodes:M,title:"Selected aggregate flow",identity:`${ke.from} → ${ke.to}`,values:bC(ke,p()),related:[ke],node:null,edge:ke,source:T}:{kind:null,id:null,selectedId:null,nodes:M,title:"Nothing selected",identity:"",values:[],related:[],node:null,edge:null,source:T}}function Re(T){const M=we(T);G(M),n.onSelect?.(M)}function G(T){const M=n.selectionRoot,J=M?.querySelector("[data-selection-title]"),ke=M?.querySelector("[data-selection-identity]"),me=M?.querySelector("[data-selection-meta]");!J||!ke||!me||(J.textContent=T.title,ke.textContent=T.identity,me.replaceChildren(...T.values.map(([lt,_t])=>{const Yt=r.createElement("div");Yt.className="meta-item",_t!=="Unavailable"&&(["From","To","First transaction","Last transaction"].includes(lt)&&Yt.classList.add("meta-item--identity"),lt==="Incoming amount (USD)"&&Yt.classList.add("meta-item--incoming"),lt==="Outgoing amount (USD)"&&Yt.classList.add("meta-item--outgoing")),["From","To","First transaction","Last transaction","Labels"].includes(lt)&&Yt.classList.add("meta-item--wide");const tr=r.createElement("span");tr.textContent=lt;const Dn=r.createElement("strong"),nn=["First transaction","Last transaction"].includes(lt)?Dw(_t):null;if(nn&&n.openLink){const Zt=n.openLink,Xt=r.createElement("button");Xt.type="button",Xt.className="cia-graph-explorer-link",Xt.dataset.explorer=nn,Xt.textContent=_t,Xt.setAttribute("aria-label",`${lt}: ${_t} (opens the explorer)`),Xt.addEventListener("click",()=>Zt(nn)),Dn.append(Xt)}else if(nn){const Zt=r.createElement("a");Zt.href=nn,Zt.target="_blank",Zt.rel="noopener noreferrer",Zt.textContent=_t,Zt.setAttribute("aria-label",`${lt}: ${_t} (opens in new tab)`),Dn.append(Zt)}else Dn.textContent=_t;return Yt.append(tr,Dn),Yt})))}function q(T,M="program"){d=T?{kind:"node",id:T}:null,v.selection(),Re(M)}function Y(T,M="program"){d=T?{kind:"edge",id:T}:null,v.selection(),Re(M)}function ne(T){if(T==null)return q(null);const M=kn(i,T);if(M)return q(M);if(i.edges.some(J=>J.id===T))return Y(T)}function K(){l=k(),ae()}function I(T,M={x:s.width/2,y:s.height/2}){const J=ec(l.scale*(1+T)),ke=J/l.scale;l={x:M.x-(M.x-l.x)*ke,y:M.y-(M.y-l.y)*ke,scale:J},ae()}function L(T){o=T,n.controls?.querySelectorAll("[data-layout]").forEach(M=>{M.classList.toggle("active",M.dataset.layout===T),M.setAttribute("aria-pressed",String(M.dataset.layout===T))}),n.onLayoutChange?.(T),a=Zo(i,o,s.width,s.height),v.geometry(),K()}function U(T,M){x.textContent=M,x.hidden=!1;const J=e.getBoundingClientRect();x.style.left=`${Math.min(J.width-330,Math.max(8,T.clientX-J.left+12))}px`,x.style.top=`${Math.max(8,T.clientY-J.top+12)}px`}function fe(){x.hidden=!0}function ie(T){return mC({x:T.clientX,y:T.clientY},v.surface.getBoundingClientRect(),s.width,s.height)}const te={point:ie,transform:()=>l,select(T){T.type==="select-node"?q(T.id,"pointer"):T.type==="select-edge"?Y(T.id,"pointer"):q(null,"canvas")},drag(T,M,J){!h&&(h=uC(o,T,M),!h)||hC(a,h,M,J,l)&&(_e=!0,v.moveNode(h.id))},endDrag(T){const M=h?.pointerId===T&&_e;h=pC(h,T),M&&(_e=!1,v.endMove())},pan(T,M){l={x:T.transform.x+M.x-T.point.x,y:T.transform.y+M.y-T.point.y,scale:l.scale},ae()},startPinch(){h=null},pinch(T,[M,J]){const ke=Math.hypot(J.x-M.x,J.y-M.y),me=ec(T.scale*ke/Math.max(1,T.distance));I(me/l.scale-1,{x:(M.x+J.x)/2,y:(M.y+J.y)/2})}};let _e=!1;const Se=T=>{T.preventDefault(),I(T.deltaY>0?-.12:.12,ie(T))},Ze={ArrowLeft:[60,0],ArrowRight:[-60,0],ArrowUp:[0,60],ArrowDown:[0,-60]},F=T=>{if(T.target!==v.surface)return;const M=Ze[T.key];M?(T.preventDefault(),l={...l,x:l.x+M[0],y:l.y+M[1]},ae()):T.key==="+"||T.key==="="?I(.18):T.key==="-"?I(-.18):T.key==="0"&&K()};let j=()=>{};function V(){const T=v.surface,M=J=>v.pick(ie(J));j=gC(T,te,v.kind==="svg"?void 0:M),T.addEventListener("wheel",Se,{passive:!1}),T.addEventListener("keydown",F)}function X(){j(),v.surface.removeEventListener("wheel",Se),v.surface.removeEventListener("keydown",F)}V();function xe(){v.kind!=="svg"&&(X(),v.destroy(),v=cp(e,y,_,{label:n.label}),e.dataset.renderer=v.kind,e.append(x),V(),Z())}const ue=n.controls?.querySelector("[data-expand]")??null,pe=n.panel&&ue?yC(n.panel,ue,r.body):null,Le=()=>{pe?.toggle(),n.onExpansionChange?.(pe?.isOpen()??!1),requestAnimationFrame(K)},ce=n.panel??e,ze=T=>{if(T.key==="Tab"&&pe?.isOpen()&&n.panel){const M=Array.from(n.panel.querySelectorAll('button,a[href],[tabindex="0"],summary')).filter(me=>me.checkVisibility()),J=M[0],ke=M.at(-1);T.shiftKey&&r.activeElement===J?(T.preventDefault(),ke?.focus()):!T.shiftKey&&r.activeElement===ke&&(T.preventDefault(),J?.focus())}if(T.key==="Escape"){if(pe?.isOpen()){pe.close(),n.onExpansionChange?.(!1),requestAnimationFrame(K);return}q(null,"keyboard")}};ce.addEventListener("keydown",ze);const rt=[],et=(T,M)=>{T&&(T.addEventListener("click",M),rt.push([T,M]))};n.controls?.querySelectorAll("[data-layout]").forEach(T=>et(T,()=>L(T.dataset.layout==="tree"?"tree":"gravity"))),et(n.controls?.querySelector("[data-zoom='in']"),()=>I(.18)),et(n.controls?.querySelector("[data-zoom='out']"),()=>I(-.18)),et(n.controls?.querySelector("[data-zoom='fit']"),K),pe&&et(ue,Le);const he=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{const T=e.clientWidth,M=e.clientHeight;!T||!M||T===s.width&&M===s.height||(s.width=T,s.height=M,v.resize(T,M),K())});he?.observe(e),Z(),n.selected&&ne(n.selected);const Je={update(T){const M=a;i=Dt(T);const J=i.nodes.every(me=>M[me.id])?{}:Zo(i,o,s.width,s.height);a=Object.fromEntries(i.nodes.map(me=>[me.id,M[me.id]??J[me.id]]).filter(([,me])=>me)),d&&!(d.kind==="node"?i.nodes.some(me=>me.id===d.id):i.edges.some(me=>me.id===d.id))&&(d=null),f&&!i.nodes.some(me=>me.id===f)&&(f=null);const ke=new Set(i.nodes.map(me=>me.id));for(const me of[...c.keys()])ke.has(me)||c.delete(me);Z(),ee()},merge(T,M){const J=TT(i,T,M);i=J.model;const ke=kn(i,M??Dt(T).checked_address);return a=ke&&o==="gravity"?BT(i,a,ke,J.added,{notes:u}):Zo(i,o,s.width,s.height),Z(),J.added.length&&ee(),J.added},batch(T){N++;try{T()}finally{N--,!N&&z&&(z=!1,v.build()),!N&&O&&(O=!1,l=k(),ae())}},setTheme(T){T&&r.documentElement.setAttribute("data-theme",T),v.theme()},select:ne,destroy(){he?.disconnect(),X(),ce.removeEventListener("keydown",ze);for(const[T,M]of rt)T.removeEventListener("click",M);pe?.close({restoreFocus:!1}),v.destroy(),x.remove(),e.classList.remove("cia-graph-engine"),delete e.dataset.renderer,delete e.ciaGraph},fit:K,zoom:T=>I(T),setLayout:L,markNode(T,M){const J=kn(i,T);J&&(M?u.set(J,M):u.delete(J),Z())},patchNode(T,M){const J=kn(i,T),ke=J?i.nodes.find(me=>me.id===J):null;return ke?(Object.assign(ke,M),v.selection(),!0):!1},flagNode(T,M,J){const ke=kn(i,T);if(!ke)return;const me=c.get(ke)??new Set;J?me.add(M):me.delete(M),me.size?c.set(ke,me):c.delete(ke),N?z=!0:v.flag(ke,M,J)},positions:()=>structuredClone(a),model:()=>i,contentBounds:()=>w(),transform:()=>({...l}),highlight(T){f=T==null?null:kn(i,T),v.selection()},renderer:()=>v.kind,clientPoint(T){const M=kn(i,T),J=M?a[M]:null;if(!J)return null;const ke=v.surface.getBoundingClientRect(),me=Math.min(ke.width/s.width,ke.height/s.height)||1,lt=ke.left+(ke.width-s.width*me)/2,_t=ke.top+(ke.height-s.height*me)/2;return{x:lt+(J.x*l.scale+l.x)*me,y:_t+(J.y*l.scale+l.y)*me}}};return Object.defineProperty(e,"ciaGraph",{value:Je,configurable:!0}),Je}const Fw="chain-insights.flows.v1",Ja="chain-insights.result.v1",Uw=5e3,vp=6,EC=3,Gw=/^0x[0-9a-fA-F]{40}$/,$C=/^0x[0-9a-fA-F]{64}$/;function TC(e){return typeof e=="string"&&(Gw.test(e)||$C.test(e))}function _i(e){return typeof e=="string"&&Gw.test(e)}function ac(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ya(e){const t=e?.facts?.query?.results;return Array.isArray(t)?t.filter(ac):[]}function CC(e){const t=e?.facts;return typeof t?.subject?.network=="string"&&t.subject.network?t.subject.network:"robinhood"}function Jt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&/^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(e.trim())){const t=Number(e);return Number.isFinite(t)?t:null}return null}function eh(e){return e<1e11?e*1e3:e}const jw=/^\d{4}-\d{2}-\d{2}$/,AC=Date.UTC(2009,0,1),IC=Date.UTC(2100,0,1);function is(e){return new Date(eh(e)).toISOString().slice(0,10)}function bs(e){if(typeof e!="string"||!jw.test(e))return!1;const t=Date.parse(`${e}T00:00:00Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e}const NC=new Set(["day","date","hour","week","month"]),RC=["_timestamp","_time","_at"];function bp(e){return NC.has(e)||RC.some(t=>e.endsWith(t))}function Zw(e){const t=[];for(const n of e)for(const r of Object.keys(n))t.includes(r)||t.push(r);return t}function LC(e){return Array.isArray(e)?e.some(_i):_i(e)}function zC(e){return e.some(t=>Object.values(t).some(LC))}function Bw(e){return e.length>0&&e.every(t=>_i(t.from_address)&&_i(t.to_address))}const PC=/^(\d{4})-(\d{2})$/,DC=/^(\d{4})-W(\d{2})$/,OC=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,MC=/(?:Z|[+-]\d{2}:?\d{2})$/i;function FC(e,t){const n=Date.UTC(e,0,4);return n-(new Date(n).getUTCDay()+6)%7*864e5+(t-1)*7*864e5}function wp(e){if(typeof e=="string"){const r=e.trim();if(jw.test(r))return bs(r)?Date.parse(`${r}T00:00:00Z`):null;const i=PC.exec(r);if(i){const s=Number(i[2])-1;return s>=0&&s<12?Date.UTC(Number(i[1]),s,1):null}const o=DC.exec(r);if(o){const s=Number(o[2]);return s>=1&&s<=53?FC(Number(o[1]),s):null}if(OC.test(r)){const s=r.replace(" ","T"),a=Date.parse(MC.test(s)?s:`${s}Z`);return Number.isFinite(a)?a:null}}const t=Jt(e);if(t==null)return null;const n=eh(t);return n>=AC&&n<IC?n:null}function th(e,t={}){if(e.length===0||zC(e))return null;const n=Zw(e),i=n.filter(bp).find(d=>e.some(f=>wp(f[d])!=null));if(!i)return null;const o=n.filter(d=>{if(bp(d))return!1;const f=e.map(h=>h[d]).filter(h=>h!=null);return f.length>0&&f.every(h=>Jt(h)!=null)});if(o.length===0)return null;const s=o.slice(0,vp),a=new Map;let u=0;for(const d of e){const f=wp(d[i]);if(f==null)continue;u++;const h=a.get(f)??{count:0,sums:s.map(()=>null)};h.count++,s.forEach((p,m)=>{const y=Jt(d[p]);y!=null&&(h.sums[m]=(h.sums[m]??0)+y)}),a.set(f,h)}const c=[...a.entries()].sort((d,f)=>d[0]-f[0]);return c.filter(([,d])=>d.sums.some(f=>f!=null)).length<(t.minPoints??EC)?null:{xColumn:i,times:c.map(([d])=>d),rowCounts:c.map(([,d])=>d.count),daily:c.every(([d])=>d%864e5===0),series:s.map((d,f)=>({column:d,values:c.map(([,h])=>h.sums[f]??null)})),omittedColumns:o.slice(vp),skippedRows:e.length-u,failures:[]}}function UC(e){if(!e)return"failed";const t=/^\s*([a-z][a-z0-9_]*)\s*:/.exec(e);if(t?.[1])return t[1];const n=e.trim().split(/\s+/).slice(0,4).join(" ");return n.length>40?`${n.slice(0,39)}…`:n||"failed"}const GC=e=>e==null||Jt(e)!=null;function Vw(e){const t=qw(e);if(t.length<3||!t.every(c=>bs(c.id))||new Set(t.map(c=>c.id)).size!==t.length)return null;const n=t.filter(c=>c.ok);if(n.length===0||!n.every(c=>c.rows.length===1))return null;const r=Object.keys(n[0].rows[0]),i=[...r].sort().join("\0");for(const c of n){const l=c.rows[0];if(Object.keys(l).sort().join("\0")!==i||!Object.values(l).every(GC))return null}if(r.length===0||r.includes("day"))return null;const o=[...t].sort((c,l)=>c.id.localeCompare(l.id)),s=o.map(c=>({day:c.id,...c.ok?c.rows[0]:Object.fromEntries(r.map(l=>[l,null]))})),a=o.filter(c=>!c.ok).map(c=>({day:c.id,time:Date.parse(`${c.id}T00:00:00Z`),code:UC(c.error)})),u=th(s,{minPoints:1});return u?{rows:s,columns:r,failures:a,model:{...u,failures:a}}:null}const jC=/\baddress\s*:\s*(["'])(0x[0-9a-fA-F]{40})\1/g,ZC=/^\s*(<)?-(?:\[[^\]]*\])?-(>)?/,BC=/(<)?-(?:\[[^\]]*\])?-(>)?\s*$/;function _p(e,t){if(!e)return"none";const n=!!e[1],r=!!e[2];return n===r?null:t==="after"?r?"from":"to":r?"to":"from"}function Hw(e){if(typeof e!="string"||!e)return null;const t=[...e.matchAll(jC)];if(t.length===0||new Set(t.map(r=>r[2].toLowerCase())).size!==1)return null;let n=null;for(const r of t){const i=r.index??0,o=e.lastIndexOf("(",i),s=e.indexOf(")",i);if(o<0||s<0)return null;const a=[_p(BC.exec(e.slice(0,o)),"before"),_p(ZC.exec(e.slice(s+1)),"after")];if(a.includes(null))return null;for(const u of a)if(u!=="none"){if(n&&n!==u)return null;n=u}}return n?{address:t[0][2],end:n}:null}function VC(e,t){if(e.length===0||Bw(e))return null;const n=Hw(t);if(!n)return null;const r=n.address.toLowerCase(),i=Zw(e).filter(s=>e.every(a=>_i(a[s]))&&!e.every(a=>String(a[s]).toLowerCase()===r));if(i.length!==1)return null;const o=i[0];return e.map(s=>n.end==="from"?{...s,from_address:n.address,to_address:s[o]}:{...s,from_address:s[o],to_address:n.address})}function HC(e){return Bw(e)?"graph":th(e)?"chart":"table"}const qC=[["sanctioned","sanctioned"],["scam","scam"],["victim","victim"],["pool","pool"],["exchange","exchange"]];function kp(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim()):[]}function WC(e,t){if(t)return"exchange";const n=new Set(e.map(r=>r.replace(/\s+/g,"").toLowerCase()));for(const[r,i]of qC)if(n.has(r))return i;return"other"}const Sp=(e,t)=>e==null?t:t==null?e:e+t;function KC(e,t="robinhood",n){const r=new Map;for(const h of e)for(const p of new Set([String(h.from_address).toLowerCase(),String(h.to_address).toLowerCase()]))r.set(p,(r.get(p)??0)+1);let i="",o=0;for(const[h,p]of r)p>o&&(i=h,o=p);const s=n?.toLowerCase();s&&r.has(s)&&(i=s);const a=new Map,u=new Map,c=(h,p,m)=>{const y=a.get(h)??{address:h,labels:[],exchange:!1};for(const _ of p)y.labels.some(g=>g.toLowerCase()===_.toLowerCase())||y.labels.push(_);y.exchange=y.exchange||m,a.set(h,y)};i&&a.set(i,{address:i,labels:[],exchange:!1});let l=0;for(const h of e){const p=String(h.from_address).toLowerCase(),m=String(h.to_address).toLowerCase(),y=[p,m].filter((w,k,x)=>!a.has(w)&&x.indexOf(w)===k).length;if(a.size+y>Uw||(l++,c(p,kp(h.from_labels),h.from_is_exchange===!0),c(m,kp(h.to_labels),h.to_is_exchange===!0),p===m))continue;const _=`${p}->${m}`,g=u.get(_)??{from:p,to:m,usd:null,tx:null,first:null,last:null,kinds:[]};g.usd=Sp(g.usd,Jt(h.amount_usd_sum)),g.tx=Sp(g.tx,Jt(h.tx_count));const b=Jt(h.first_seen_timestamp),v=Jt(h.last_seen_timestamp);b!=null&&(g.first=g.first==null?b:Math.min(g.first,b)),v!=null&&(g.last=g.last==null?v:Math.max(g.last,v)),typeof h.link_kind=="string"&&h.link_kind&&!g.kinds.includes(h.link_kind)&&g.kinds.push(h.link_kind),u.set(_,g)}const d=[...a.values()].map(h=>({address:h.address,role:WC(h.labels,h.exchange),labels:h.labels})),f=[...u.values()].map(h=>({from:h.from,to:h.to,usd:h.usd,tx_count:h.tx,first_seen_ms:h.first,last_seen_ms:h.last,...h.kinds.length?{link_kind:h.kinds.join(", ")}:{}}));return{view:{schema:Fw,network:t,center:i,nodes:d,edges:f,truncated:!1},rowsTotal:e.length,rowsDrawn:l,rowsLeftOut:e.length-l,addresses:a.size}}function qw(e){const t=e?.facts?.queries;return Array.isArray(t)?t.filter(ac).map((n,r)=>({id:typeof n.id=="string"&&n.id?n.id:`Query ${r+1}`,ok:n.ok!==!1&&n.error==null,error:typeof n.error=="string"&&n.error?n.error:null,rows:Array.isArray(n.results)?n.results.filter(ac):[],count:typeof n.count=="number"?n.count:null,truncated:n.truncated===!0,elapsedMs:typeof n.elapsed_ms=="number"?n.elapsed_ms:null,query:typeof n.query=="string"&&n.query?n.query:null})):[]}const xp=200;function qr(e){return(e?.content??[]).filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
109
+ `).trim()}function Yr(e){if(typeof e=="string")return e.trim()||null;if(!e||typeof e!="object"||Array.isArray(e))return null;const{code:t,message:n,detail:r,error:i}=e,o=[n,r,i].find(a=>typeof a=="string"&&a.trim()!=="")?.trim()??null,s=typeof t=="string"&&t.trim()?t.trim():null;return o?s&&!o.startsWith(s)?`${s}: ${o}`:o:s}function Ww(e){if(!e)return null;const t=e.structuredContent,n=Yr(t?.error)??Yr(t?.facts?.error)??Yr(t?.facts?.query?.error);if(!e.isError||n)return n;const r=qr(e);if(r.startsWith("{"))try{const i=JSON.parse(r),o=Yr(i?.error)??Yr(i);if(o)return o}catch{}return r||"The tool answered with an error."}const JC=new Set(["usage_status","subscription_status","meta_usage_status","meta_subscription_status"]);function Kw(e){if(!e||Ww(e)!=null)return"text";const t=e.structuredContent;if(t?.schema===Fw)return"flows";if(t?.schema===Ja){if(t.tool==="graph_query")return HC(Ya(t));if(t.tool==="graph_query_batch")return!Array.isArray(t.facts?.queries)||t.facts.queries.length===0?"text":Vw(t)?"chart":"batch";if(typeof t.tool=="string"&&JC.has(t.tool))return"balance"}return"text"}function A(e,t,n={},...r){const i=e.createElement(t);for(const[o,s]of Object.entries(n))s==null||s===!1||(o==="class"?i.className=String(s):o==="text"?i.textContent=String(s):i.setAttribute(o,s===!0?"":String(s)));for(const o of r)o==null||o===!1||i.append(typeof o=="string"?e.createTextNode(o):o);return i}function YC(e,t){const n=A(e,"code",{class:"cv-addr",title:t,"data-full":t,text:bi(t)}),r=A(e,"button",{type:"button",class:"cv-copy","data-copy":t,"aria-label":`Copy ${t}`,title:"Copy the full value",text:"Copy"});return r.addEventListener("click",()=>{XC(e,t,n,r)}),A(e,"span",{class:"cv-addr-cell"},n,r)}async function XC(e,t,n,r){const i=e.defaultView?.navigator?.clipboard;try{if(i?.writeText)return await i.writeText(t),r&&(r.textContent="Copied"),"copied"}catch{}return n.textContent=t,n.classList.add("is-full"),e.getSelection?.()?.selectAllChildren(n),r&&(r.textContent="Selected"),"selected"}function QC(e,t){return/(timestamp|seen|_at|_ms|time)$/i.test(t)&&e>1e9?Tn(e):/usd/i.test(t)?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e):new Intl.NumberFormat("en-US",{maximumFractionDigits:4}).format(e)}const eA=160,Ep=2e3;function tA(e,t=eA){const n=e.trim().split(/\r?\n/,1)[0]??"",r=n.search(/[.!?](?=\s|$)/),i=(r<0?n:n.slice(0,r+1)).trim();if(i.length<=t)return i;const o=i.slice(0,t-1),s=o.lastIndexOf(" ");return`${(s>t*.6?o.slice(0,s):o).trimEnd()}…`}function Jw(e,t,n){const r=e.ownerDocument,i=n.full!=null&&n.full.length>Ep?`${n.full.slice(0,Ep-1)}…`:n.full,o=i!=null&&i!==t,s=A(r,"section",{class:`cia-graph-surface cv-notice cv-notice-${n.kind}`,"data-view":n.view,"data-notice":n.kind,role:n.kind==="refused"?"alert":"status",title:o?i:null},o?A(r,"details",{class:"cv-notice-more"},A(r,"summary",{class:"cv-notice-line",text:t}),A(r,"p",{class:"cv-notice-full",text:i})):A(r,"p",{class:"cv-notice-line",text:t}));return e.replaceChildren(s),s}function nA(e){const t=e?.facts?.query,n=Array.isArray(t?.results)?t.results.filter(o=>!!o&&typeof o=="object"&&!Array.isArray(o)):[],r=n.slice(0,xp),i=[];for(const o of r)for(const s of Object.keys(o))i.includes(s)||i.push(s);return{columns:i,rows:r,total:n.length,truncated:n.length>xp||t?.truncated===!0,elapsedMs:typeof t?.elapsed_ms=="number"?t.elapsed_ms:null}}function rA(e,t,n){return t==null?A(e,"span",{class:"cv-null","aria-label":"empty",text:"—"}):TC(t)?YC(e,t):typeof t=="number"?e.createTextNode(QC(t,n)):typeof t=="boolean"?e.createTextNode(t?"yes":"no"):Array.isArray(t)?e.createTextNode(t.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(", ")):typeof t=="object"?e.createTextNode(JSON.stringify(t)):e.createTextNode(String(t))}const iA={from_address:"From address",to_address:"To address",address:"Address",amount_usd_sum:"Value (USD)",amount_usd:"Value (USD)",usd:"Value (USD)",tx_count:"Transfers",first_seen_timestamp:"First seen (UTC)",last_seen_timestamp:"Last seen (UTC)",first_activity_timestamp:"First activity (UTC)",last_activity_timestamp:"Last activity (UTC)",block_timestamp:"Time (UTC)",block_date:"Day",block_height:"Block",tx_id:"Transaction",from_labels:"From labels",to_labels:"To labels",labels:"Labels",degree_in:"Senders",degree_out:"Receivers",total_in_usd:"Incoming (USD)",total_out_usd:"Outgoing (USD)",total_volume_usd:"Volume (USD)",asset_symbol:"Token",amount:"Amount"};function oA(e){const t=iA[e];if(t)return t;const n=e.replace(/_/g," ").trim();return n?n[0].toUpperCase()+n.slice(1):e}function $p(e,t,n={}){const r=e.ownerDocument,i=nA(t.structuredContent),o=i.rows.length;if(i.total===0)return Jw(e,"No rows.",{kind:"empty",view:"table"}),i;const s=`${new Intl.NumberFormat("en-US").format(o)} ${o===1?"row":"rows"}${i.elapsedMs==null?"":` in ${i.elapsedMs} ms`}`,a=A(r,"table",{class:"cv-table"},A(r,"thead",{},A(r,"tr",{},...i.columns.map(u=>A(r,"th",{scope:"col",title:u,text:oA(u)})))),A(r,"tbody",{},...i.rows.map(u=>A(r,"tr",{},...i.columns.map(c=>A(r,"td",{},rA(r,u[c],c)))))));return e.replaceChildren(A(r,"section",{class:"cv-card cv-table-view","data-view":"table","aria-label":"Graph query result"},A(r,"header",{class:"cv-card-head"},A(r,"strong",{text:"Graph query result"}),A(r,"span",{class:"cv-muted",text:s}),n.toggle??null),i.truncated?A(r,"p",{class:"cv-note",role:"note","data-truncated":"",text:`Truncated: showing the first ${new Intl.NumberFormat("en-US").format(o)} of ${new Intl.NumberFormat("en-US").format(i.total)} rows. Narrow the query to see the rest.`}):null,i.columns.length?A(r,"div",{class:"cv-table-wrap"},a):null)),i}const Xr=(e,t=0)=>typeof e=="number"&&Number.isFinite(e)?e:t,Bo=e=>typeof e=="string"&&e?e:null;function sA(e){const t=e?.facts??{};if(typeof t.wallet=="string"&&t.wallet)return{kind:"wallet",wallet:t.wallet,tier:String(t.tier??"anonymous"),allowanceUsd:Xr(t.allowance_usd),consumedUsd:Xr(t.consumed_usd),windowEnd:Bo(t.window_end)};const n=t.usage;if(n&&typeof n=="object"){const r="daily_units_limit"in n||"daily_units_used"in n,i=Bo(n.access_mode);return{kind:"free",unit:r?"units":"seconds",used:Xr(r?n.daily_units_used:n.daily_seconds_used),limit:Xr(r?n.daily_units_limit:n.daily_seconds_limit),remaining:Xr(r?n.remaining_units:n.remaining_seconds),resetAt:Bo(n.reset_at),identifierKind:Bo(n.identifier_kind),accessMode:i,noLimit:!r&&i==="public_free"&&n.daily_seconds_limit===0}}return{kind:"unknown"}}const Tp=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:2}).format(e),Vo=(e,t)=>`${new Intl.NumberFormat("en-US").format(e)} ${t==="units"?e===1?"unit":"units":e===1?"second":"seconds"}`;function pu(e){if(!e)return"No active window";const t=Date.parse(e);return Number.isFinite(t)?`${Tn(t)} UTC`:e}function Cp(e,t,n,r){const i=n>0?Math.min(1,t/n):0,o=A(e,"div",{class:"cv-meter",role:"meter","aria-label":r,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":Math.min(t,n)},A(e,"span"));return o.firstElementChild.style.width=`${Math.round(i*100)}%`,o}function mu(e,t){return A(e,"dl",{class:"cv-facts"},...t.flatMap(([n,r])=>[A(e,"dt",{text:n}),A(e,"dd",{text:r})]))}function aA(e,t){const n=e.ownerDocument,r=sA(t.structuredContent);let i,o,s;return r.kind==="wallet"?(o="Wallet allowance",s=`${bi(r.wallet)} · ${r.tier==="subscriber"?"Subscriber":"No active subscription"}`,i=[Cp(n,r.consumedUsd,r.allowanceUsd,"Share of today's allowance used"),mu(n,[["Daily allowance",Tp(r.allowanceUsd)],["Used today",Tp(r.consumedUsd)],["Window ends",pu(r.windowEnd)]])]):r.kind==="free"?(o="Free tier",s=`No wallet · counted per ${r.identifierKind==="ip"||!r.identifierKind?"network address":r.identifierKind}`,i=r.noLimit?[A(n,"p",{class:"cv-balance-note","data-no-limit":"",text:"Free access, no daily limit"}),mu(n,[["Daily allowance","No daily limit"],["Used today",Vo(r.used,r.unit)],["Window ends",pu(r.resetAt)]])]:[Cp(n,r.used,r.limit,"Share of today's free allowance used"),mu(n,[["Daily allowance",Vo(r.limit,r.unit)],["Used today",Vo(r.used,r.unit)],["Left today",Vo(r.remaining,r.unit)],["Window ends",pu(r.resetAt)]])]):(o="Usage",s="The server sent no allowance figures.",i=[A(n,"p",{class:"cv-muted",text:qr(t)||"Nothing to show."})]),e.replaceChildren(A(n,"section",{class:"cv-card cv-balance-view","data-view":"balance","data-balance":r.kind,"aria-label":o},A(n,"header",{class:"cv-card-head"},A(n,"strong",{text:o}),A(n,"span",{class:"cv-muted",text:s})),...i)),r}function ki(e,t,n="No drawing for this answer."){const r=e.ownerDocument,i=Ww(t);if(i!=null){Jw(e,tA(i),{kind:"refused",view:"text",full:i});return}const o=qr(t);e.replaceChildren(A(r,"section",{class:"cv-card cv-text-view","data-view":"text"},A(r,"p",{text:n}),o?A(r,"p",{class:"cv-muted cv-text-body",text:o.length>600?`${o.slice(0,599)}…`:o}):null))}function nh(e,t="Loading the Chain Insights view"){const n=e.ownerDocument;e.replaceChildren(A(n,"section",{class:"cv-card cv-skeleton","data-view":"loading","aria-busy":"true","aria-label":t},A(n,"span",{class:"cv-sr",text:t}),A(n,"div",{class:"cv-skel-line cv-skel-title"}),A(n,"div",{class:"cv-skel-line cv-skel-sub"}),A(n,"div",{class:"cv-skel-block"})))}const uA="http://www.w3.org/2000/svg",uc=720,cA=320,lA=6,dA=420,Ap=4,fA=120,oi={left:70,right:18,top:6},cc=18,Yw=16,Xw=6,Qw=26,hA=170,pA=82,mA=28,gA=80,Vn=1e3,En=60*Vn,or=60*En,en=24*or,yA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function e_(e,t){if(/usd/i.test(e))return"usd";const n=t.filter(r=>r!=null);return n.length>0&&n.every(Number.isInteger)?"count":"number"}const vA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),bA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumSignificantDigits:2}),wA=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",notation:"compact",maximumFractionDigits:1}),Si=new Intl.NumberFormat("en-US",{maximumFractionDigits:0}),_A=new Intl.NumberFormat("en-US",{maximumFractionDigits:4}),t_=new Intl.NumberFormat("en-US",{maximumSignificantDigits:3}),n_=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:2}),kA=new Intl.NumberFormat("en-US",{maximumFractionDigits:6});function ws(e,t){if(e==null)return"—";const n=e!==0&&Math.abs(e)<.01;return t==="usd"?n?bA.format(e):vA.format(e):t==="count"?Si.format(e):n?t_.format(e):_A.format(e)}function SA(e){return e!==0&&Math.abs(e)<.01?t_.format(e):Math.abs(e)<1e3?kA.format(Math.round(e*100)/100):n_.format(e)}function Ip(e,t){return t==="usd"?Math.abs(e)<1e3?ws(e,"usd"):wA.format(e):t==="count"?Math.abs(e)<1e3?Si.format(e):n_.format(e):SA(e)}function xA(e,t){const n=new Date(e).toISOString();return t?`${n.slice(0,10)} (UTC day)`:`${n.slice(0,10)} ${n.slice(11,19)} UTC`}function r_(e){return e<=en?"time":e<=fA*en?"day":"month"}const EA=[Vn,2*Vn,5*Vn,10*Vn,15*Vn,30*Vn,En,2*En,5*En,10*En,15*En,30*En,or,2*or,3*or,6*or,12*or,en],$A=[1,2,3,7,14,30,60].map(e=>e*en),TA=[1,2,3,6,12,24,60,120],Np=4*en,CA={time:76,day:84,month:72},AA=e=>new Date(e).getUTCFullYear()*12+new Date(e).getUTCMonth(),gu=e=>Date.UTC(Math.floor(e/12),e%12,1);function IA(e,t,n){const r=t-e,i=r_(r);if(r<=0)return{unit:i,step:0,times:[e]};const o=Math.max(2,Math.floor(n));if(i==="month"){for(const s of TA){const a=[];let u=AA(e);for(gu(u)<e&&u++;gu(u)<=t;u++)u%s===0&&a.push(gu(u));if(a.length<=o&&a.length>0)return{unit:i,step:s,times:a}}return{unit:i,step:0,times:[e,t]}}for(const s of i==="time"?EA:$A){const a=s===7*en||s===14*en?Math.ceil((e-Np)/s)*s+Np:i==="day"?Math.ceil(e/en)*en:Math.ceil(e/s)*s,u=a>t?0:Math.floor((t-a)/s)+1;if(u>0&&u<=o)return{unit:i,step:s,times:Array.from({length:u},(c,l)=>a+l*s)}}return{unit:i,step:0,times:[e,t]}}function NA(e,t,n){const r=new Date(e),i=r.toISOString();return t==="month"?n>=12?i.slice(0,4):`${yA[r.getUTCMonth()]} ${r.getUTCFullYear()}`:t==="day"||e%en===0?i.slice(0,10):n>0&&n<En?i.slice(11,19):i.slice(11,16)}function RA(e){return e.series.map(t=>{let n=0,r=null,i=null;return t.values.forEach((o,s)=>{o!=null&&(n+=o,(r==null||o>r)&&(r=o,i=e.times[s]??null))}),{column:t.column,kind:e_(t.column,t.values),total:n,peak:r,peakTime:i}})}const zt=e=>new Date(e).toISOString(),i_=(e,t)=>zt(e).slice(0,10)===zt(t).slice(0,10);function LA(e){const t=e.times[0],n=e.times[e.times.length-1];if(t==null||n==null)return"no points";if(e.daily)return t===n?`${zt(t).slice(0,10)} UTC`:`${zt(t).slice(0,10)} to ${zt(n).slice(0,10)} UTC`;const r=i=>`${zt(i).slice(0,10)} ${zt(i).slice(11,16)}`;return t===n?`${r(t)} UTC`:i_(t,n)?`${r(t)} to ${zt(n).slice(11,16)} UTC`:`${r(t)} to ${r(n)} UTC`}function zA(e,t=new Set){const n=e.times.map((u,c)=>e.series.some(l=>l.values[c]!=null)),r=n.filter(Boolean).length,i=e.rowCounts.reduce((u,c,l)=>u+(n[l]?c:0),0),o=[LA(e),`${Si.format(r)} ${r===1?"point":"points"}${i>r?` from ${Si.format(i)} transfers`:""}`],s=e.times[0]??0,a=e.times[e.times.length-1]??0;for(const u of RA(e)){if(t.has(u.column))continue;if(u.peak==null||u.peakTime==null){o.push(`${u.column}: no values`);continue}const c=e.daily?`on ${zt(u.peakTime).slice(0,10)}`:i_(s,a)?`at ${zt(u.peakTime).slice(11,19)}`:`at ${zt(u.peakTime).slice(0,10)} ${zt(u.peakTime).slice(11,16)}`;o.push(`${u.column}: total ${ws(u.total,u.kind)}, peak ${ws(u.peak,u.kind)} ${c}`)}return e.failures.length&&o.push(`no answer for ${e.failures.map(u=>`${u.day} (${u.code})`).join(", ")}`),o.join(" · ")}function PA(e,t){if(e.length===0)return-1;let n=0,r=e.length-1;for(;n<r;){const i=n+r>>1;(e[i]??0)<t?n=i+1:r=i}return n>0&&Math.abs(t-(e[n-1]??0))<=Math.abs((e[n]??0)-t)?n-1:n}function DA(e,t,n){const r=Math.min(t,n),i=Math.max(t,n);let o=-1,s=-1;return e.forEach((a,u)=>{a<r||a>i||(o<0&&(o=u),s=u)}),o>=0&&s-o>=1?{start:o,end:s}:null}function OA(e,t,n){const r=Math.max(0,t),i=Math.min(e.times.length-1,n)+1,o=e.times.slice(r,i),s=o[0]??0,a=o[o.length-1]??0;return{...e,times:o,rowCounts:e.rowCounts.slice(r,i),series:e.series.map(u=>({column:u.column,values:u.values.slice(r,i)})),failures:e.failures.filter(u=>u.time>=s&&u.time<=a)}}function MA(e,t,n){if(e.has(t)){const r=new Set(e);return r.delete(t),r}return n.filter(r=>!e.has(r)).length<=1?e:new Set([...e,t])}const o_=e=>`var(--cia-graph-series-${e%lA+1})`;function _s(e,t){const n=e.last-e.first,r=e.plotRight-e.plotLeft;return n>0?e.plotLeft+(t-e.first)/n*r:e.plotLeft+r/2}function yu(e,t){const n=e.plotRight-e.plotLeft,r=Math.min(e.plotRight,Math.max(e.plotLeft,t));return n>0?e.first+(r-e.plotLeft)/n*(e.last-e.first):e.first}function s_(e,t){return e.plotBottom-(t-e.min)/(e.max-e.min||1)*(e.plotBottom-e.plotTop)}function FA(e){if(e<=1)return hA;const t=Math.floor((dA-oi.top-Xw-Qw-(e-1)*Yw)/e)-cc;return Math.max(mA,Math.min(pA,t))}function Rp(e,t=uc,n=new Set){const r=oi.left,i=t-oi.right,o=e.times[0]??0,s=e.times[e.times.length-1]??o,a={plotLeft:r,plotRight:i,first:o,last:s},u=e.series.map((p,m)=>({series:p,index:m})).filter(({series:p})=>!n.has(p.column)),c=FA(u.length),l=u.map(({series:p,index:m},y)=>{const _=oi.top+y*(cc+c+Yw),g=_+cc,b=g+c,v=p.values.filter(Z=>Z!=null),w=Math.min(0,...v),k=Math.max(...v,w+1e-9),x={plotTop:g,plotBottom:b,min:w,max:k},N=[],z=[];let O=[];return p.values.forEach((Z,ee)=>{if(Z==null){O.length&&z.push(O),O=[];return}const ae=e.times[ee]??o,we={x:_s(a,ae),y:s_(x,Z),time:ae,value:Z,index:ee};N.push(we),O.push(we)}),O.length&&z.push(O),{column:p.column,index:m,kind:e_(p.column,p.values),color:o_(m),top:_,plotTop:g,plotBottom:b,min:w,max:k,runs:z,points:N}}),d=(l[l.length-1]?.plotBottom??oi.top)+Xw,f=r_(s-o),h=[];if(e.times.length){const p=IA(o,s,(i-r)/CA[f]);for(const m of p.times){const y=_s(a,m),_=y-r<34?"start":i-y<34?"end":"middle";h.push({x:y,label:NA(m,p.unit,p.step),anchor:_})}}return{width:t,height:d+Qw,plotLeft:r,plotRight:i,first:o,last:s,unit:f,lanes:l,ticks:h,axisY:d}}function it(e,t,n={}){const r=e.createElementNS(uA,t);for(const[i,o]of Object.entries(n))r.setAttribute(i,String(o));return r}const Bt=e=>Math.round(e*10)/10;let UA=0;const GA="Time series plot. Left and Right arrows read the points one by one, Home and End jump to the ends, Escape hides the read-out. Drag across the plot to zoom.";function jA(e,t,n={}){const r=e.ownerDocument,i=t.series.map(I=>I.column),o={start:0,end:t.times.length-1};let s=new Set,a=o,u=null,c=null,l=uc,d=t,f=Rp(t,l);const h=A(r,"span",{class:"cv-muted cv-chart-summary","data-chart-summary":""}),p=t.series.map((I,L)=>{const U=A(r,"span",{class:"cv-chart-key","aria-hidden":"true"});U.style.setProperty("--cv-key",o_(L));const fe=A(r,"button",{type:"button",class:"cv-chart-series","data-series":I.column,"aria-pressed":"true"},U,A(r,"span",{text:I.column}));return fe.addEventListener("click",()=>{const ie=MA(s,I.column,i);ie!==s&&(s=ie,O())}),fe}),m=A(r,"div",{class:"cv-chart-legend",role:"group","aria-label":"Show or hide a series"},...p),y=A(r,"button",{type:"button",class:"cv-chart-reset","data-reset-zoom":"",hidden:!0,text:"Reset zoom"}),_=it(r,"svg",{class:"cv-chart-svg",role:"img",preserveAspectRatio:"xMidYMid meet"}),g=A(r,"div",{class:"cv-chart-readout",id:`cv-chart-readout-${++UA}`,"data-chart-readout":"",role:"status","aria-live":"polite",hidden:!0}),b=A(r,"div",{class:"cv-chart-plot",tabindex:0,role:"group","aria-label":GA,"aria-describedby":g.id},_),v=A(r,"div",{class:"cv-chart-body"},b,g),w=it(r,"rect",{class:"cv-chart-brush"}),k=it(r,"g",{class:"cv-chart-cross","aria-hidden":"true"}),x=[t.omittedColumns.length?`${t.omittedColumns.length} more number ${t.omittedColumns.length===1?"column is":"columns are"} only in the table: ${t.omittedColumns.join(", ")}.`:"",t.skippedRows?`${t.skippedRows} ${t.skippedRows===1?"row has":"rows have"} no usable ${t.xColumn} and ${t.skippedRows===1?"is":"are"} only in the table.`:""].filter(Boolean),N=A(r,"section",{class:"cv-chart cia-graph-surface","data-view":"chart","aria-label":`Time series by ${t.xColumn}`},A(r,"header",{class:"cv-flows-head"},A(r,"div",{class:"cv-title"},A(r,"strong",{text:"Time series"}),h)),x.length?A(r,"p",{class:"cv-note",role:"note","data-chart-note":"",text:x.join(" ")}):null,A(r,"div",{class:"cv-chart-bar"},m,y,n.toggle??null),v);e.replaceChildren(N);function z(){const I=[],L=f.lanes[0]?.plotTop??0,U=d.times.length>1?(f.plotRight-f.plotLeft)/(d.times.length-1):24,fe=Math.max(6,Math.min(24,U*.6));for(const te of d.failures){const _e=_s(f,te.time),Se=it(r,"rect",{class:"cv-chart-failure","data-failure":te.day,x:Bt(_e-fe/2),y:L,width:Bt(fe),height:Math.max(0,f.axisY-L)});I.push(Se)}for(const te of f.lanes){const _e=it(r,"g",{class:"cv-chart-lane","data-series":te.column}),Se=it(r,"rect",{class:"cv-chart-swatch",x:f.plotLeft,y:te.top+4,width:14,height:4,rx:2});Se.style.fill=te.color;const Ze=it(r,"text",{class:"cv-chart-name",x:f.plotLeft+20,y:te.top+11});Ze.textContent=te.column,_e.append(Se,Ze,it(r,"line",{class:"cv-chart-grid",x1:f.plotLeft,x2:f.plotRight,y1:te.plotTop,y2:te.plotTop}),it(r,"line",{class:"cv-chart-base",x1:f.plotLeft,x2:f.plotRight,y1:te.plotBottom,y2:te.plotBottom}));const F=it(r,"text",{class:"cv-chart-tick",x:f.plotLeft-8,y:te.plotTop+4,"text-anchor":"end"});F.textContent=Ip(te.max,te.kind);const j=it(r,"text",{class:"cv-chart-tick",x:f.plotLeft-8,y:te.plotBottom+4,"text-anchor":"end"});j.textContent=Ip(te.min,te.kind),_e.append(F,j);for(const V of te.runs){if(V.length<2)continue;const X=it(r,"polyline",{class:"cv-chart-line",points:V.map(xe=>`${Bt(xe.x)},${Bt(xe.y)}`).join(" "),fill:"none"});X.style.stroke=te.color,_e.append(X)}if(te.points.length<=gA)for(const V of te.points){const X=it(r,"circle",{class:"cv-chart-dot",cx:Bt(V.x),cy:Bt(V.y),r:3,"data-index":a.start+V.index,"data-time":V.time});X.style.fill=te.color,_e.append(X)}I.push(_e)}const ie=it(r,"g",{class:"cv-chart-axis"});for(const te of f.ticks){const _e=it(r,"text",{class:"cv-chart-tick",x:Bt(te.x),y:f.axisY+14,"text-anchor":te.anchor});_e.textContent=te.label,ie.append(_e)}return I.push(ie),I}function O(){d=OA(t,a.start,a.end),f=Rp(d,l,s);const I=f.lanes.map(U=>U.column);_.setAttribute("viewBox",`0 0 ${f.width} ${f.height}`),_.setAttribute("aria-label",`Line chart of ${I.join(", ")} by ${t.xColumn}, ${d.times.length} ${d.times.length===1?"point":"points"}`),_.replaceChildren(w,...z(),k),h.textContent=zA(d,s);for(const U of p){const fe=!s.has(U.dataset.series??"");U.setAttribute("aria-pressed",String(fe)),fe&&I.length===1?(U.setAttribute("aria-disabled","true"),U.title="At least one series stays visible"):(U.removeAttribute("aria-disabled"),U.removeAttribute("title"))}const L=a.start!==o.start||a.end!==o.end;y.hidden=!L,N.dataset.zoomed=String(L),Z(),ee()}function Z(){if(!c||Math.abs(c.to-c.from)<Ap){w.style.display="none";return}const I=f.lanes[0]?.plotTop??0,L=Math.max(f.plotLeft,Math.min(c.from,c.to)),U=Math.min(f.plotRight,Math.max(c.from,c.to));w.setAttribute("x",String(Bt(L))),w.setAttribute("width",String(Bt(Math.max(0,U-L)))),w.setAttribute("y",String(I)),w.setAttribute("height",String(Math.max(0,f.axisY-I))),w.style.display=""}function ee(){if(k.replaceChildren(),u==null||u<a.start||u>a.end){u=null,k.style.display="none",g.hidden=!0,g.replaceChildren(),delete b.dataset.focus;return}const I=u-a.start,L=d.times[I]??f.first,U=Bt(_s(f,L)),fe=f.lanes[0]?.plotTop??0;k.append(it(r,"line",{class:"cv-chart-crossline",x1:U,x2:U,y1:fe,y2:f.axisY}));const ie=[];for(const Se of f.lanes){const Ze=d.series[Se.index]?.values[I]??null;if(Ze!=null){const j=it(r,"circle",{class:"cv-chart-focus",cx:U,cy:Bt(s_(Se,Ze)),r:4.5});j.style.fill=Se.color,k.append(j)}const F=A(r,"span",{class:"cv-chart-key","aria-hidden":"true"});F.style.setProperty("--cv-key",Se.color),ie.push(A(r,"dt",{},F,Se.column),A(r,"dd",{"data-value":Se.column,text:ws(Ze,Se.kind)}))}k.style.display="",k.dataset.index=String(u),k.dataset.time=String(L),b.dataset.focus=String(u);const te=d.failures.find(Se=>Se.time===L),_e=d.rowCounts[I]??1;g.replaceChildren(...[A(r,"time",{datetime:new Date(L).toISOString(),text:xA(L,d.daily)}),te?A(r,"p",{class:"cv-chart-readout-note","data-failure":te.code,text:`No answer: ${te.code}`}):null,_e>1?A(r,"p",{class:"cv-chart-readout-note","data-rows":_e,text:`${Si.format(_e)} transfers`}):null,A(r,"dl",{},...ie)].filter(Se=>Se!=null)),g.hidden=!1,ae(U,fe)}function ae(I,L){const U=_.getBoundingClientRect(),fe=v.getBoundingClientRect(),ie=U.width>0?U.width/f.width:1,te=U.left-fe.left+I*ie,_e=I>(f.plotLeft+f.plotRight)/2;g.style.left=`${Math.round(_e?te-12:te+12)}px`,g.style.top=`${Math.round(U.top-fe.top+L*ie)}px`,g.dataset.side=_e?"left":"right"}const we=I=>{const L=_.getBoundingClientRect();return L.width>0?(I-L.left)*f.width/L.width:Number.NaN},Re=I=>a.start+PA(d.times,yu(f,I));b.addEventListener("pointermove",I=>{const L=we(I.clientX);Number.isFinite(L)&&(c&&(c.to=L,Z()),u=Re(L),ee())}),b.addEventListener("pointerdown",I=>{if(I.button!==0)return;const L=we(I.clientX);if(Number.isFinite(L)){I.preventDefault(),b.focus({preventScroll:!0}),c={from:L,to:L,pointer:I.pointerId};try{b.setPointerCapture(I.pointerId)}catch{}}});const G=I=>{if(!c)return;const{from:L,to:U,pointer:fe}=c;c=null;try{b.releasePointerCapture(fe)}catch{}if(Z(),!I||Math.abs(U-L)<Ap)return;const ie=DA(t.times,yu(f,L),yu(f,U));!ie||ie.start===a.start&&ie.end===a.end||(a=ie,u=Re(U),O())};b.addEventListener("pointerup",()=>G(!0)),b.addEventListener("pointercancel",()=>G(!1)),b.addEventListener("pointerleave",()=>{c||(u=null,ee())}),b.addEventListener("keydown",I=>{let L;if(I.key==="ArrowRight")L=u==null?a.start:Math.min(a.end,u+1);else if(I.key==="ArrowLeft")L=u==null?a.end:Math.max(a.start,u-1);else if(I.key==="Home")L=a.start;else if(I.key==="End")L=a.end;else if(I.key==="Escape"){if(u==null&&!c)return;c&&G(!1),L=null}else return;I.preventDefault(),u=L,ee()}),y.addEventListener("click",()=>{a=o,u=null,O(),b.focus({preventScroll:!0})});const q=()=>{const I=Math.round(b.clientWidth);return I>0?Math.max(cA,I):null},Y=()=>{const I=q();I==null||I===l||(l=I,O())};l=q()??uc,O();const ne=r.defaultView?.ResizeObserver,K=ne?new ne(()=>Y()):null;return K?.observe(b),{root:N,get layout(){return f},refit:Y,destroy(){K?.disconnect()}}}const ZA="chain-insights.transfers.v1",BA="graph_expand",a_=25;function VA(e,t,n,r,i={}){const o=i.cursor??{day:r,skip:0};return{network:e,from:t,to:n,day:o.day,...o.skip?{skip:o.skip}:{},...i.firstDay?{first_day:i.firstDay}:{},limit:i.limit??a_}}function HA(e,t){const n=typeof e.first_seen_timestamp=="number"&&e.first_seen_timestamp>0?is(e.first_seen_timestamp):null,r=typeof e.last_seen_timestamp=="number"&&e.last_seen_timestamp>0?is(e.last_seen_timestamp):is(t);return{first:n,last:n&&r<n?n:r}}function qA(e){if(!e)return"no answer";const t=qr(e);return e.isError?t||"the server refused the read":/query_timeout|topology_busy/.test(t)?t:u_(e.structuredContent)?null:t||"the answer held no transfers"}function u_(e){const t=e;if(!t||t.schema!==ZA||!Array.isArray(t.transfers)||typeof t.from!="string"||typeof t.to!="string"||!bs(t.day))return null;const n=[];for(const o of t.transfers){if(!o||typeof o!="object")continue;const s=o;if(typeof s.tx_id!="string")continue;const a=Jt(s.block_timestamp);n.push({tx_id:s.tx_id,block_timestamp:a,amount:typeof s.amount=="string"?s.amount:typeof s.amount=="number"?String(s.amount):null,asset_symbol:typeof s.asset_symbol=="string"&&s.asset_symbol?s.asset_symbol:null,amount_usd:Jt(s.amount_usd)})}const r=t.next,i=r&&typeof r=="object"&&bs(r.day)?{day:r.day,skip:Math.max(0,Math.floor(Jt(r.skip)??0))}:null;return{network:typeof t.network=="string"?t.network:null,from:t.from,to:t.to,day:t.day,transfers:n,truncated:t.truncated===!0,next:i}}function WA(e){return[...e].sort((t,n)=>(n.block_timestamp??0)-(t.block_timestamp??0)||t.tx_id.localeCompare(n.tx_id))}function KA(e){if(e==null)return"—";const t=e.trim().match(/^(-?)(\d+)(?:\.(\d+))?$/);if(!t)return e;const[,n="",r="0",i=""]=t,o=i.replace(/0+$/,"");return`${n}${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}${o?`.${o}`:""}`}function JA(e){return e==null?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:e!==0&&Math.abs(e)<.01?6:2}).format(e)}function YA(e){return e==null?"—":`${new Date(eh(e)).toISOString().slice(11,19)} UTC`}function vu(e){return new Intl.DateTimeFormat("en-GB",{dateStyle:"medium",timeZone:"UTC"}).format(new Date(`${e}T00:00:00Z`))}function XA(e,t){const n=new Map;for(const r of e){const i=r.block_timestamp==null?t:is(r.block_timestamp);n.has(i)||n.set(i,[]),n.get(i).push(r)}return[...n.entries()].sort(([r],[i])=>i.localeCompare(r)).map(([r,i])=>({day:r,transfers:i}))}function QA(e,t){const n=t.now??Date.now,r=A(e,"strong",{"data-link-title":"",text:"Transfers"}),i=A(e,"button",{type:"button",class:"cv-button cv-icon","data-link-close":"","aria-label":"Close the transfers",text:"×"}),o=A(e,"p",{class:"cv-link-pair","data-link-pair":""}),s=A(e,"div",{class:"cv-link-body","data-link-body":"",role:"status","aria-live":"polite"}),a=A(e,"button",{type:"button",class:"cv-button","data-link-more":"",text:"More transfers"}),u=A(e,"section",{class:"cv-linkpanel cv-linkpanel-embedded","data-link-panel":"","aria-label":"Transfers of the selected link",hidden:!0},A(e,"header",{class:"cv-link-head"},r,null),o,s,a);let c=null,l=0;function d(){if(!c){u.hidden=!0;return}u.hidden=!1,o.replaceChildren(A(e,"code",{"data-link-from":"",text:c.from})," → ",A(e,"code",{"data-link-to":"",text:c.to}));const y=c.transfers.length;r.textContent=y?`Transfers · ${y} listed`:"Transfers",a.hidden=!c.next||c.status==="error",a.disabled=c.status==="loading",a.textContent=c.status==="loading"&&c.pages?"Loading…":"More transfers",a.setAttribute("aria-label",c.next?`More transfers: the ${a_} before ${vu(c.next.day)}`:"More transfers");const _=[];if(y)for(const g of XA(c.transfers,c.day))_.push(A(e,"p",{class:"cv-link-day","data-link-day":g.day,text:`${vu(g.day)} (UTC)`})),_.push(A(e,"ol",{class:"cv-transfers"},...g.transfers.map(b=>e1(e,b,t.host))));c.status==="loading"?_.push(A(e,"p",{class:"cv-muted","data-link-loading":"",text:y?"Loading older transfers…":`Loading the transfers from ${vu(c.day)} back…`})):c.status==="error"?_.push(A(e,"p",{class:"cv-link-error","data-link-error":"",role:"alert",text:c.error??"The transfers could not be read."})):y||_.push(A(e,"p",{class:"cv-muted","data-link-empty":"",text:"No transfers between these two addresses in the days read."})),c.status==="ready"&&c.truncated&&_.push(A(e,"p",{class:"cv-muted","data-link-truncated":"",text:"A day held more transfers than one read lists; its oldest are not shown."})),c.status==="ready"&&!c.next&&y&&_.push(A(e,"p",{class:"cv-muted","data-link-first":"",text:c.firstDay?"Every transfer back to the day the link was first seen is listed.":"No older transfers were found."})),s.replaceChildren(..._)}async function f(y){const _=++l,g=c;g.status="loading",g.error=null,d(),t.onLayout?.();let b=null;try{b=await t.host.callServerTool({name:BA,arguments:VA(t.network,g.from,g.to,g.day,{firstDay:g.firstDay,cursor:y})})}catch(w){b={isError:!0,content:[{type:"text",text:w instanceof Error?w.message:String(w)}]}}if(_!==l||c!==g)return g;const v=qA(b);if(v)g.status="error",g.error=v.length>300?`${v.slice(0,299)}…`:v;else{const w=u_(b.structuredContent),k=new Set(g.transfers.map(x=>x.tx_id+String(x.block_timestamp)));g.status="ready",g.transfers=[...g.transfers,...WA(w.transfers).filter(x=>!k.has(x.tx_id+String(x.block_timestamp)))],g.truncated=g.truncated||w.truncated,g.next=w.next,g.pages+=1}return d(),t.onLayout?.(),g}const h=()=>m.close(),p=()=>{m.more()};i.addEventListener("click",h),a.addEventListener("click",p);const m={element:u,open(y){const _=HA(y,n());return c={from:y.from,to:y.to,day:_.last,firstDay:_.first,status:"loading",transfers:[],next:null,pages:0,truncated:!1,error:null},f(null)},async more(){return!c||c.status==="loading"||!c.next?null:f(c.next)},close(){l++,c=null,d(),t.onLayout?.()},state:()=>c?{...c,transfers:[...c.transfers]}:null,destroy(){l++,i.removeEventListener("click",h),a.removeEventListener("click",p)}};return m}function e1(e,t,n){const r=Dw(t.tx_id),i=n.openLink,o=r&&i?A(e,"button",{type:"button",class:"cia-graph-explorer-link","data-explorer":r,"aria-label":`Transaction ${t.tx_id} (opens the explorer)`,title:t.tx_id,text:bi(t.tx_id)}):A(e,"code",{title:t.tx_id,text:bi(t.tx_id)});return r&&i&&o.addEventListener("click",()=>{i.call(n,{url:r}).catch(()=>{})}),A(e,"li",{class:"cv-transfer","data-tx":t.tx_id},A(e,"span",{class:"cv-transfer-time",text:YA(t.block_timestamp)}),A(e,"span",{class:"cv-transfer-amount",text:`${KA(t.amount)}${t.asset_symbol?` ${t.asset_symbol}`:""}`}),A(e,"span",{class:"cv-transfer-usd",text:t.amount_usd==null?"— USD":JA(t.amount_usd)}),o)}const Lp="graph_expand",Ho="too busy to expand",c_=640,t1=300,bu=.45,n1="Full screen shows the whole graph",r1="Open in browser",wu="The host did not open the link.",i1="If nothing opened, copy this link into your browser:",zp=400,_u="expanded",l_=5e3,o1="Click an address for its details. Double-click it to load its senders and receivers, and again to fold them back. Click a link to list its transfers.",s1="chain-insights.address.v1";function a1(e,t){return{network:e,address:t,details:!0}}function u1(e){const t=e;if(!t||t.schema!==s1||typeof t.address!="string")return null;const n=i=>typeof i=="number"&&Number.isFinite(i)?i:null,r={address:t.address.toLowerCase(),total_in_usd:n(t.total_in_usd),total_out_usd:n(t.total_out_usd),degree_in:n(t.degree_in),degree_out:n(t.degree_out)};return Array.isArray(t.labels)&&(r.labels=t.labels.filter(i=>typeof i=="string")),typeof t.role=="string"&&Hr.includes(t.role)&&(r.role=t.role),r}function c1(e){return e.total_in_usd==null&&e.total_out_usd==null&&e.degree_in==null&&e.degree_out==null}const lc=new Intl.NumberFormat("en-US");function Pp(e){const t=e.remaining;if(!t||typeof t!="object")return null;const n=Number(t.senders),r=Number(t.receivers);return!Number.isFinite(n)||!Number.isFinite(r)?null:{senders:Math.max(0,n),receivers:Math.max(0,r)}}function l1(e){if(!e||e.senders+e.receivers<=0)return null;const t=(n,r)=>`${lc.format(n)} more ${r}${n===1?"":"s"}`;return`${t(e.senders,"sender")}, ${t(e.receivers,"receiver")} not loaded`}function d1(e,t){return`Not loaded: ${lc.format(e)} ${e===1?"link":"links"} of ${t} would take the picture past ${lc.format(l_)} addresses. Fold another address to make room.`}const Dp=e=>!!(e&&(e.truncated||e.remaining&&e.remaining.senders+e.remaining.receivers>0));let f1=0;const h1=[["scam","Scam"],["sanctioned","Sanctioned"],["exchange","Exchange"],["victim","Victim"],["pool","Pool"],["other","Other"]];function rh(e){return typeof e=="string"&&/^http:\/\/(?:127\.0\.0\.1|localhost):\d+(?:[/?#]|$)/.test(e)}function p1(e){return!e.browser&&!!e.host.openLink&&rh(e.viewUrl)}function m1(e,t,n){return{network:e,address:t,in_offset:n?.in_offset??0,out_offset:n?.out_offset??0}}function g1(e){const t=qr(e);return e?e.isError?t||"the server refused the expansion":/query_timeout|topology_busy/.test(t)?t:Jf(e.structuredContent)?null:t||"the answer held no money flows":"no answer"}function y1(e,t,n,r=c_,i=t1){if(!e||t<=0)return{height:r,fits:!0};const o=Math.max(1,e.x2-e.x1),s=Math.max(1,e.y2-e.y1),a=Math.max(bu,Math.min(1,(t-vi*2)/o)),u=Math.ceil(n+s*a+vi*2),c=Math.min(r,Math.max(i,u));return fp(e,t,c-n)>=bu?{height:c,fits:!0}:{height:r,fits:fp(e,t,r-n)>=bu}}function v1(e){return/query_timeout|topology_busy|timed? ?out/i.test(e)}function Op(e){const t=e.split(`
110
+ `)[0].trim();return t.length>200?`${t.slice(0,199)}…`:t}function b1(e,t){return`investigator expanded ${e}: ${t} new addresses`}function w1(e,t){const n=e.nodes.find(r=>r.address.toLowerCase()===t.toLowerCase());return n&&No({role:n.role??null,labels:n.labels??[]})||"Other"}function d_(e,t,n){const r=e.ownerDocument,i=t.network??"robinhood",o=t.center.toLowerCase(),s=()=>new Map(t.cursor?[[o,{cursor:t.cursor,truncated:!!t.truncated,remaining:Pp(t)}]]:[]);let a=s();const u=new Set,c=new Set;let l=[];const d=new Set;let f=null,h=null;const p=n.now??Date.now,m=n.title??"Money flow graph",y=A(r,"p",{class:"cv-status",role:"status","aria-live":"polite",text:o1}),_=A(r,"ul",{class:"cv-roles","aria-label":"Address roles"}),g=A(r,"div",{class:"cv-canvas","data-graph":""}),b=A(r,"div",{class:"cv-detail","aria-label":"Selection"},A(r,"strong",{"data-selection-title":""}),A(r,"code",{"data-selection-identity":""}),A(r,"div",{class:"cv-detail-meta","data-selection-meta":""})),v=A(r,"strong",{"data-side-title":"",text:"Details"}),w=A(r,"button",{type:"button",class:"cv-button cv-icon","data-side-close":"","aria-label":"Close the details",text:"×"}),k=A(r,"button",{type:"button",class:"cv-button","data-toggle-expand":"",hidden:!0,text:"Expand"}),x=A(r,"button",{type:"button",class:"cv-button","data-more":"",hidden:!0,text:"More flows"}),N=A(r,"p",{class:"cv-remaining cv-muted","data-remaining":"",hidden:!0}),z=QA(r,{host:n.host,network:i,now:n.now,embedded:!0,onLayout:()=>J()}),O=A(r,"aside",{class:"cv-side","data-side-panel":"","aria-label":"Details of the selection",hidden:!0},A(r,"header",{class:"cv-side-head"},v,w),b,N,A(r,"div",{class:"cv-side-actions"},k,x),z.element),Z=A(r,"button",{type:"button",class:"cv-button","data-fullscreen":"",hidden:!0,"aria-label":"Open full screen",text:"Full screen"}),ee=A(r,"button",{type:"button",class:"cv-button","data-reset":"","aria-label":"Reset: fold every expansion back and draw the first answer again",title:"Fold every expansion back and draw the first answer again",text:"Reset"}),ae=A(r,"span",{class:"cv-hint","data-fullscreen-hint":"",hidden:!0,text:n1}),we=A(r,"button",{type:"button",class:"cv-button","data-open-browser":"",hidden:!p1(n),"aria-label":"Open the graph in your browser",title:"Open the graph in your browser",text:r1}),Re=A(r,"div",{class:"cv-toggle",role:"group","aria-label":"Layout"},A(r,"button",{type:"button",class:"cv-toggle-button","data-layout":"gravity","aria-pressed":"true",title:"Linked addresses pull together; an expansion settles around the address you opened",text:"Gravity"}),A(r,"button",{type:"button",class:"cv-toggle-button","data-layout":"tree","aria-pressed":"false",title:"Senders left, receivers right, newest activity first",text:"Tree"})),G=A(r,"div",{class:"cv-actions"},Re,A(r,"button",{type:"button",class:"cv-button cv-icon","data-zoom":"out","aria-label":"Zoom out",text:"−"}),A(r,"button",{type:"button",class:"cv-button cv-icon","data-zoom":"in","aria-label":"Zoom in",text:"+"}),A(r,"button",{type:"button",class:"cv-button","data-zoom":"fit","aria-label":"Fit the graph",text:"Fit"}),ee,ae,Z,we),q=A(r,"span",{class:"cv-muted","data-subtitle":""}),Y=`cv-addresses-${++f1}`,ne=A(r,"div",{class:"cv-visually-hidden",role:"listbox",tabindex:"0",id:Y,"data-address-list":"","aria-label":"Drawn addresses. Down and Up move, Enter shows the details, Shift+Enter expands or folds."});let K=[],I=-1;const L=A(r,"section",{class:"cv-flows cia-graph-surface","data-view":"flows","aria-label":`${m} of ${o}`},A(r,"header",{class:"cv-flows-head"},A(r,"div",{class:"cv-title"},A(r,"strong",{text:m}),q),n.toggle??null,G),_,n.note?A(r,"p",{class:"cv-note",role:"note","data-left-out":"",text:n.note}):null,A(r,"div",{class:"cv-body"},ne,g,O),y);e.replaceChildren(L);function U(){const P=he.model(),oe=P.truncated?" · more flows than shown":"";q.textContent=`${o} · ${w1(t,o)} · ${i} · ${P.nodes.length} addresses${oe}`;const ge=new Set(P.nodes.map(je=>je.role??"other")),Oe=h1.filter(([je])=>je!=="other"&&ge.has(je));_.hidden=Oe.length===0,_.replaceChildren(...Oe.map(([je,mt])=>{const He=A(r,"i",{"aria-hidden":"true"});return He.style.background=`var(--cia-graph-role-${je})`,A(r,"li",{"data-role":je},He,mt)})),fe()}function fe(){const P=he.model().nodes,oe=K[I]??null;K=P.map(Oe=>Oe.address.toLowerCase()),ne.replaceChildren(...P.map((Oe,je)=>A(r,"div",{role:"option",id:`${Y}-${je}`,"data-list-address":K[je],"aria-selected":"false",text:`${Oe.address} ${No({role:Oe.role??null,labels:Oe.labels??[]})||"Other"}`})));const ge=oe?K.indexOf(oe):-1;I=ge>=0?ge:K.length?Math.min(Math.max(I,-1),K.length-1):-1,ie()}function ie(){for(const oe of ne.children)oe.setAttribute("aria-selected",String(oe.id===`${Y}-${I}`));I>=0?ne.setAttribute("aria-activedescendant",`${Y}-${I}`):ne.removeAttribute("aria-activedescendant");const P=r.activeElement===ne;he.highlight(P?K[I]??null:null)}function te(P){return P?he.model().nodes.find(oe=>oe.id===P)?.address.toLowerCase()??null:null}const _e=P=>{const oe=P.target,ge=P.key==="Enter"||P.key===" ",Oe=oe?.closest?.("[data-node-id]");if(ge&&P.shiftKey&&Oe){P.preventDefault();const je=te(Oe.dataset.nodeId);je&&_t(je)}};g.addEventListener("keydown",_e,!0);function Se(P){K.length&&(I=Math.max(0,Math.min(K.length-1,P)),ie())}const Ze=()=>{I<0&&K.length&&(I=0),ie()},F=()=>he.highlight(null),j=P=>{const oe=K[I];switch(P.key){case"ArrowDown":P.preventDefault(),Se(I+1);return;case"ArrowUp":P.preventDefault(),Se(I-1);return;case"Home":P.preventDefault(),Se(0);return;case"End":P.preventDefault(),Se(K.length-1);return;case"Escape":ru();return;case"Enter":case" ":if(P.preventDefault(),!oe)return;P.shiftKey?_t(oe):he.select(oe);return}};ne.addEventListener("focus",Ze),ne.addEventListener("blur",F),ne.addEventListener("keydown",j);function V(){const P=h;if(!P){k.hidden=!0,x.hidden=!0,N.hidden=!0;return}const oe=d.has(P),ge=oe?l1(a.get(P)?.remaining??null):null;N.hidden=!ge,N.textContent=ge??"",k.hidden=!1,k.disabled=u.has(P)||c.has(P),k.textContent=u.has(P)?"Too busy to expand":oe?"Collapse":"Expand",k.setAttribute("aria-label",`${k.textContent} ${P}`),x.hidden=!(oe&&Dp(a.get(P)))}function X(P){const oe=O.hidden;O.hidden=P.kind==null,P.kind==="node"&&P.node?(h=P.node.address.toLowerCase(),v.textContent="Address details",z.close(),c1(P.node)&&ue(h)):(h=null,P.kind==="edge"?v.textContent="Link details":z.close()),V(),oe!==O.hidden&&J()}const xe=new Set;async function ue(P){if(xe.has(P))return;xe.add(P);let oe=null;try{oe=await n.host.callServerTool({name:Lp,arguments:a1(i,P)})}catch(mt){oe={isError:!0,content:[{type:"text",text:mt instanceof Error?mt.message:String(mt)}]}}const ge=oe&&!oe.isError?u1(oe.structuredContent):null;if(!ge){xe.delete(P),y.textContent=`The totals of ${P} could not be read: ${Op(oe&&qr(oe)||"no answer")}.`;return}const{address:Oe,...je}=ge;he.patchNode(P,je)&&h===P&&he.select(P)}let pe=null;function Le(){pe&&clearTimeout(pe),pe=null}function ce(P){const oe=P.source==="pointer"&&P.kind==="node"&&P.node,ge=P.source!=="program"&&P.kind==="edge"&&P.edge;if(Le(),oe){const Oe=P.node.address.toLowerCase(),je=p();f&&f.address===Oe&&je-f.at<=zp?(f=null,ru(),_t(Oe)):(f={address:Oe,at:je},pe=setTimeout(()=>{pe=null,X(P)},zp));return}P.kind!=="node"&&(f=null),X(P),ge&&z.open(P.edge)}const ze=n.height??c_,rt=`${m} of ${o}: senders on the left, receivers on the right. Select an address for its details; double-click it, or press Shift+Enter, to load its senders and receivers, and again to fold them back. Select a link to list its transfers.`;function et(){return xC(g,t,{layout:n.layout??"gravity",width:n.width??720,height:ze,now:n.now,controls:G,selectionRoot:b,onSelect:ce,openLink:P=>{n.host.openLink?.({url:P}).catch(()=>{y.textContent=wu})},label:rt})}let he=et();U();let Je=n.displayMode??"inline",T=n.availableDisplayModes??[];const M=()=>!n.browser&&!!n.host.requestDisplayMode&&(T.length===0||T.includes("fullscreen"));function J(){if(Je==="fullscreen"){L.style.removeProperty("height"),ae.hidden=!0;return}const P=g.clientWidth||n.width||720,oe=Math.max(0,L.offsetHeight-g.offsetHeight)||140,{height:ge,fits:Oe}=y1(he.contentBounds(),P,oe);L.style.height=`${ge}px`,ae.hidden=Oe||!M(),L.dataset.fits=String(Oe),he.fit()}async function ke(P){try{await n.host.updateModelContext?.({content:[{type:"text",text:P}]})}catch{}}async function me(P,oe=!1){const ge=P.toLowerCase();if(u.has(ge))return y.textContent=`${ge} is ${Ho}.`,{added:[],refused:Ho};if(c.has(ge))return{added:[],refused:null};const Oe=a.get(ge);if(Oe&&!Dp(Oe))return y.textContent=`Every recent flow of ${ge} is drawn.`,{added:[],refused:null};c.add(ge),V(),y.textContent=`Loading the flows of ${ge}…`;let je=null;try{je=await n.host.callServerTool({name:Lp,arguments:m1(i,ge,oe||Oe?Oe?.cursor:null)})}catch(xt){je={isError:!0,content:[{type:"text",text:xt instanceof Error?xt.message:String(xt)}]}}finally{c.delete(ge)}const mt=g1(je);if(mt)return v1(mt)?(u.add(ge),he.markNode(ge,Ho),y.textContent=`${ge} is ${Ho}. The drawing is kept.`):y.textContent=`${ge} could not be expanded: ${Op(mt)}. The drawing is kept; try again.`,V(),{added:[],refused:mt};const He=je.structuredContent,iu=he.model(),On=new Set(iu.nodes.map(xt=>xt.address.toLowerCase())),ou=new Set;for(const xt of He.nodes)On.has(xt.address.toLowerCase())||ou.add(xt.address.toLowerCase());for(const xt of He.edges)for(const Lo of[xt.from,xt.to])On.has(Lo.toLowerCase())||ou.add(Lo.toLowerCase());if(On.size+ou.size>l_){const xt=new Set(iu.edges.map(Mn=>`${Mn.from.toLowerCase()}->${Mn.to.toLowerCase()}`)),Lo=new Set(He.edges.map(Mn=>`${Mn.from.toLowerCase()}->${Mn.to.toLowerCase()}`).filter(Mn=>!xt.has(Mn))).size,hh=d1(Lo,ge);return y.textContent=hh,V(),{added:[],refused:hh}}const Ro=he.merge(He,ge);return l.push({address:ge,page:He}),d.add(ge),he.flagNode(ge,_u,!0),a.set(ge,{cursor:He.cursor??null,truncated:!!He.truncated,remaining:Pp(He)}),U(),J(),V(),y.textContent=`${Ro.length} new ${Ro.length===1?"address":"addresses"} linked to ${ge}. Double-click it again to fold them back.`,await ke(b1(ge,Ro.length)),{added:Ro,refused:null}}function lt(P){const oe=P.toLowerCase();if(!d.has(oe))return{removed:0};const ge=he.model().nodes.length;d.delete(oe),a.delete(oe);const Oe=l.filter(He=>He.address!==oe),je=[];he.batch(()=>{he.flagNode(oe,_u,!1),he.update(t);for(const He of Oe)he.model().nodes.some(On=>On.address.toLowerCase()===He.address)?(he.merge(He.page,He.address),je.push(He)):je.some(On=>On.address===He.address)||(he.flagNode(He.address,_u,!1),d.delete(He.address),a.delete(He.address))}),l=je;const mt=Math.max(0,ge-he.model().nodes.length);return h&&!he.model().nodes.some(He=>He.address.toLowerCase()===h)&&(O.hidden=!0,h=null),U(),J(),V(),y.textContent=`Folded ${oe} back: ${mt} ${mt===1?"address":"addresses"} removed.`,ke(`investigator collapsed ${oe}: ${mt} addresses removed`),{removed:mt}}async function _t(P){d.has(P)?lt(P):await me(P)}function Yt(){Le(),he.destroy(),l=[],d.clear(),u.clear(),c.clear(),a=s(),xe.clear(),f=null,h=null,z.close(),O.hidden=!0,he=et(),U(),J(),V(),y.textContent="The first answer again: every expansion folded back."}function tr(P,oe){P&&(Je=P),oe&&(T=oe),L.dataset.displayMode=Je,Z.hidden=!M(),Z.textContent=Je==="fullscreen"?"Exit full screen":"Full screen",Z.setAttribute("aria-label",Je==="fullscreen"?"Back to the inline view":"Open full screen"),J()}tr(Je);const Dn=async()=>{const P=Je==="fullscreen"?"inline":"fullscreen";try{const oe=await n.host.requestDisplayMode?.({mode:P});tr(oe?.mode??P)}catch{y.textContent="The host did not change the display mode."}},nn=(P,oe)=>{y.replaceChildren(A(r,"span",{text:`${P} `}),A(r,"code",{class:"cv-view-link","data-view-link":"",text:oe}))},Zt=async()=>{const P=n.viewUrl;if(!(!rh(P)||!n.host.openLink)){nn(i1,P);try{(await n.host.openLink({url:P}))?.isError===!0&&nn(wu,P)}catch{nn(wu,P)}}},Xt=()=>Yt();function ru(){Le();const P=!O.hidden;he.select(null),z.close(),O.hidden=!0,h=null,V(),P&&J()}const lh=()=>ru(),dh=()=>{h&&_t(h)},fh=()=>{h&&me(h,!0)};return Z.addEventListener("click",Dn),we.addEventListener("click",Zt),ee.addEventListener("click",Xt),w.addEventListener("click",lh),k.addEventListener("click",dh),x.addEventListener("click",fh),{root:L,get graph(){return he},expand:P=>me(P),collapse:lt,reset:Yt,expanded:()=>[...d],setLayout:P=>he.setLayout(P),linkPanel:z,openLink(P,oe){const ge=he.model().edges.find(Oe=>Oe.from===P.toLowerCase()&&Oe.to===oe.toLowerCase());return ge?(he.select(ge.id),z.open(ge)):Promise.resolve(null)},setTheme(P){he.setTheme(P)},setDisplayMode:tr,refit:J,destroy(){Le(),g.removeEventListener("keydown",_e,!0),ne.removeEventListener("focus",Ze),ne.removeEventListener("blur",F),ne.removeEventListener("keydown",j),Z.removeEventListener("click",Dn),we.removeEventListener("click",Zt),ee.removeEventListener("click",Xt),w.removeEventListener("click",lh),k.removeEventListener("click",dh),x.removeEventListener("click",fh),z.destroy(),he.destroy()}}}function dc(e){return{kind:e,flows:()=>[],setTheme(){},setDisplayMode(){},refit(){},destroy(){}}}function _1(e,t){return{kind:e,flows:()=>{const n=t();return n?[n]:[]},setTheme(n){t()?.setTheme(n)},setDisplayMode(n,r){t()?.setDisplayMode(n,r)},refit(){t()?.refit()},destroy(){t()?.destroy()}}}const f_=e=>({host:e.host,availableDisplayModes:e.availableDisplayModes,displayMode:e.displayMode,now:e.now,width:e.width,height:e.height,viewUrl:e.browser?null:e.viewUrl??null,browser:e.browser===!0});function k1(e){return typeof e?.query=="string"&&e.query?e.query:null}function S1(e,t,n){const r=Array.isArray(e?.queries)?e.queries:[],i=s=>{const a=s?.query;return typeof a=="string"&&a?a:null},o=r.find(s=>s?.id===t);return i(o||r[n])}function x1(e,t){const n=e.structuredContent;if(!t||!n?.facts?.query)return e;const r=VC(Ya(n),t);return r?{...e,structuredContent:{...n,facts:{...n.facts,query:{...n.facts.query,results:r}}}}:e}function E1(e,t){if(e<=0)return null;const n=new Intl.NumberFormat("en-US");return`${n.format(e)} of ${n.format(t)} rows ${e===1?"is":"are"} not drawn: a graph holds at most ${n.format(Uw)} addresses. The table has the rows.`}function $1(e,t,n){const r=[];let i="picture";const o=s=>{for(const a of s.querySelectorAll("[data-show]"))a.setAttribute("aria-pressed",String(a.dataset.show===i))};return{make(){const s=A(e,"button",{type:"button",class:"cv-toggle-button","data-show":"picture",text:t}),a=A(e,"button",{type:"button",class:"cv-toggle-button","data-show":"table",text:"Table"});s.addEventListener("click",()=>n("picture")),a.addEventListener("click",()=>n("table"));const u=A(e,"div",{class:"cv-toggle",role:"group","aria-label":"Show the rows as"},s,a);return r.push(u),o(u),u},set(s){i=s,r.forEach(o)}}}function T1(e,t){const n=t?.facts?.subject;return{content:[],structuredContent:{schema:Ja,tool:"graph_query",facts:{...n?{subject:n}:{},query:{results:e,count:e.length,truncated:!1}}}}}function C1(e){const t=Vw(e.structuredContent);if(t)return{model:t.model,table:T1(t.rows,e.structuredContent)};const n=th(Ya(e.structuredContent));return n?{model:n,table:e}:null}function h_(e,t,n,r=null){const i=e.ownerDocument,o=x1(t,r),s=Kw(o),a=s==="chart"?C1(o):null;if(s!=="graph"&&!a)return s==="table"?$p(e,o):ki(e,o),dc(s==="table"?"table":"text");const u=o.structuredContent,c=Ya(u),l=a?.table??t,d=A(i,"div",{class:"cv-face","data-face":"picture"}),f=A(i,"div",{class:"cv-face","data-face":"table",hidden:!0});e.replaceChildren(d,f);const h=$1(i,s==="graph"?"Graph":"Chart",g=>_(g));let p=null,m=null,y=-1;if(s==="graph"){const g=KC(c,CC(u),Hw(r)?.address);p=d_(d,g.view,{...f_(n),title:"Money flow graph",toggle:h.make(),note:E1(g.rowsLeftOut,g.rowsTotal)})}else m=jA(d,a.model,{toggle:h.make()});function _(g){if(d.hidden=g!=="picture",f.hidden=g!=="table",g==="table"){const b=p?.expanded().length?p.graph.model():null,v=b?b.nodes.length*100003+b.edges.length:0;y!==v&&(y=v,$p(f,b?A1(b,l):l,{toggle:h.make()}))}h.set(g),g==="picture"&&(p?.refit(),m?.refit())}return{kind:s,flows:()=>p?[p]:[],setTheme(g){p?.setTheme(g)},setDisplayMode(g,b){p?.setDisplayMode(g,b)},refit(){d.hidden||(p?.refit(),m?.refit())},destroy(){p?.destroy(),m?.destroy()}}}function A1(e,t){const n=new Map(e.nodes.map(o=>[o.address,o.labels??[]])),r=e.edges.map(o=>({from_address:o.from,to_address:o.to,amount_usd_sum:o.amount_usd_sum,tx_count:o.tx_count,first_seen_timestamp:o.first_seen_timestamp,last_seen_timestamp:o.last_seen_timestamp,from_labels:n.get(o.from)??[],to_labels:n.get(o.to)??[]})),i=t.structuredContent?.facts?.subject;return{content:[],structuredContent:{schema:Ja,tool:"graph_query",facts:{...i?{subject:i}:{},query:{results:r,count:r.length,truncated:!!e.truncated,elapsed_ms:null}}}}}function I1(e,t){if(!e.ok)return{isError:!0,content:[{type:"text",text:e.error??"The query failed."}]};const n=t?.facts?.subject;return{content:[],structuredContent:{schema:Ja,tool:"graph_query",facts:{...n?{subject:n}:{},query:{results:e.rows,count:e.count??e.rows.length,truncated:e.truncated,elapsed_ms:e.elapsedMs}}}}}function N1(e,t,n){const r=e.ownerDocument,i=qw(t.structuredContent),o=i.map((p,m)=>A(r,"button",{type:"button",role:"tab",class:"cv-tab",id:`cv-tab-${m}`,"data-tab":p.id,"aria-controls":`cv-panel-${m}`,"aria-selected":"false",tabindex:-1,text:p.ok?p.id:`${p.id} (failed)`})),s=i.map((p,m)=>A(r,"div",{class:"cv-tabpanel",role:"tabpanel",id:`cv-panel-${m}`,"aria-labelledby":`cv-tab-${m}`,hidden:!0})),a=A(r,"div",{class:"cv-tabs",role:"tablist","aria-label":"Queries of the batch"},...o);e.replaceChildren(a,...s);const u=i.map(()=>null);let c=n.displayMode,l=n.availableDisplayModes,d=-1;const f=()=>e.style.setProperty("--cv-tabs-h",`${a.offsetHeight}px`);function h(p){const m=i[p],y=s[p];if(!m||!y)return;d=p,o.forEach((g,b)=>{g.setAttribute("aria-selected",String(b===p)),g.tabIndex=b===p?0:-1}),s.forEach((g,b)=>{g.hidden=b!==p});const _=u[p];if(_)_.refit();else{const g=m.query??S1(n.toolInput,m.id,p),b=h_(y,I1(m,t.structuredContent),{...n,displayMode:c,availableDisplayModes:l},g);u[p]=b,y.dataset.view=b.kind}f()}return o.forEach((p,m)=>{p.addEventListener("click",()=>h(m)),p.addEventListener("keydown",y=>{const _=o.length-1,g=y.key==="ArrowRight"?m===_?0:m+1:y.key==="ArrowLeft"?m===0?_:m-1:y.key==="Home"?0:y.key==="End"?_:null;g!=null&&(y.preventDefault(),h(g),o[g]?.focus())})}),h(0),{kind:"batch",flows:()=>u.flatMap(p=>p?.flows()??[]),setTheme(p){for(const m of u)m?.setTheme(p)},setDisplayMode(p,m){p&&(c=p),m&&(l=m);for(const y of u)y?.setDisplayMode(p,m);f()},refit(){d>=0&&u[d]?.refit()},destroy(){for(const p of u)p?.destroy()}}}function R1(e){const t=e?.structuredContent?.view_url;return rh(t)?t:null}function p_(e,t,n){const r={...n,viewUrl:n.viewUrl??R1(t)},i=Kw(t);if(i==="flows"){const o=d_(e,t.structuredContent,f_(r));return _1("flows",()=>o)}return i==="graph"||i==="chart"||i==="table"?h_(e,t,r,k1(r.toolInput)):i==="batch"?N1(e,t,r):i==="balance"?(aA(e,t),dc("balance")):(ki(e,t),dc("text"))}function L1(e){return e==="light"||e==="dark"}function z1(e,t=()=>!1){return L1(e?.theme)?e.theme:t()?"dark":"light"}function ku(e,t){const n={...e??{},...t??{}};return(e?.styles||t?.styles)&&(n.styles={...e?.styles??{},...t?.styles??{},variables:{...e?.styles?.variables??{},...t?.styles?.variables??{}}}),n}function ks(e,t,n={}){const r=e.documentElement,i=z1(t,n.prefersDark);r.setAttribute("data-theme",i),r.style.colorScheme=i;const o=t?.styles?.variables;o&&n.applyVariables&&n.applyVariables(o,r);const s=t?.styles?.css?.fonts;return s&&n.applyFonts&&n.applyFonts(s),i}function P1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qo={exports:{}},Mp;function D1(){if(Mp)return qo.exports;Mp=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(w,k,x){return Function.prototype.apply.call(w,k,x)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(w){return Object.getOwnPropertyNames(w).concat(Object.getOwnPropertySymbols(w))}:n=function(w){return Object.getOwnPropertyNames(w)};function r(v){console&&console.warn&&console.warn(v)}var i=Number.isNaN||function(w){return w!==w};function o(){o.init.call(this)}qo.exports=o,qo.exports.once=_,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(v){if(typeof v!="number"||v<0||i(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");s=v}}),o.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(w){if(typeof w!="number"||w<0||i(w))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+w+".");return this._maxListeners=w,this};function u(v){return v._maxListeners===void 0?o.defaultMaxListeners:v._maxListeners}o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(w){for(var k=[],x=1;x<arguments.length;x++)k.push(arguments[x]);var N=w==="error",z=this._events;if(z!==void 0)N=N&&z.error===void 0;else if(!N)return!1;if(N){var O;if(k.length>0&&(O=k[0]),O instanceof Error)throw O;var Z=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw Z.context=O,Z}var ee=z[w];if(ee===void 0)return!1;if(typeof ee=="function")t(ee,this,k);else for(var ae=ee.length,we=p(ee,ae),x=0;x<ae;++x)t(we[x],this,k);return!0};function c(v,w,k,x){var N,z,O;if(a(k),z=v._events,z===void 0?(z=v._events=Object.create(null),v._eventsCount=0):(z.newListener!==void 0&&(v.emit("newListener",w,k.listener?k.listener:k),z=v._events),O=z[w]),O===void 0)O=z[w]=k,++v._eventsCount;else if(typeof O=="function"?O=z[w]=x?[k,O]:[O,k]:x?O.unshift(k):O.push(k),N=u(v),N>0&&O.length>N&&!O.warned){O.warned=!0;var Z=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(w)+" listeners added. Use emitter.setMaxListeners() to increase limit");Z.name="MaxListenersExceededWarning",Z.emitter=v,Z.type=w,Z.count=O.length,r(Z)}return v}o.prototype.addListener=function(w,k){return c(this,w,k,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(w,k){return c(this,w,k,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(v,w,k){var x={fired:!1,wrapFn:void 0,target:v,type:w,listener:k},N=l.bind(x);return N.listener=k,x.wrapFn=N,N}o.prototype.once=function(w,k){return a(k),this.on(w,d(this,w,k)),this},o.prototype.prependOnceListener=function(w,k){return a(k),this.prependListener(w,d(this,w,k)),this},o.prototype.removeListener=function(w,k){var x,N,z,O,Z;if(a(k),N=this._events,N===void 0)return this;if(x=N[w],x===void 0)return this;if(x===k||x.listener===k)--this._eventsCount===0?this._events=Object.create(null):(delete N[w],N.removeListener&&this.emit("removeListener",w,x.listener||k));else if(typeof x!="function"){for(z=-1,O=x.length-1;O>=0;O--)if(x[O]===k||x[O].listener===k){Z=x[O].listener,z=O;break}if(z<0)return this;z===0?x.shift():m(x,z),x.length===1&&(N[w]=x[0]),N.removeListener!==void 0&&this.emit("removeListener",w,Z||k)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(w){var k,x,N;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[w]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[w]),this;if(arguments.length===0){var z=Object.keys(x),O;for(N=0;N<z.length;++N)O=z[N],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(k=x[w],typeof k=="function")this.removeListener(w,k);else if(k!==void 0)for(N=k.length-1;N>=0;N--)this.removeListener(w,k[N]);return this};function f(v,w,k){var x=v._events;if(x===void 0)return[];var N=x[w];return N===void 0?[]:typeof N=="function"?k?[N.listener||N]:[N]:k?y(N):p(N,N.length)}o.prototype.listeners=function(w){return f(this,w,!0)},o.prototype.rawListeners=function(w){return f(this,w,!1)},o.listenerCount=function(v,w){return typeof v.listenerCount=="function"?v.listenerCount(w):h.call(v,w)},o.prototype.listenerCount=h;function h(v){var w=this._events;if(w!==void 0){var k=w[v];if(typeof k=="function")return 1;if(k!==void 0)return k.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function p(v,w){for(var k=new Array(w),x=0;x<w;++x)k[x]=v[x];return k}function m(v,w){for(;w+1<v.length;w++)v[w]=v[w+1];v.pop()}function y(v){for(var w=new Array(v.length),k=0;k<w.length;++k)w[k]=v[k].listener||v[k];return w}function _(v,w){return new Promise(function(k,x){function N(O){v.removeListener(w,z),x(O)}function z(){typeof v.removeListener=="function"&&v.removeListener("error",N),k([].slice.call(arguments))}b(v,w,z,{once:!0}),w!=="error"&&g(v,N,{once:!0})})}function g(v,w,k){typeof v.on=="function"&&b(v,"error",w,k)}function b(v,w,k,x){if(typeof v.on=="function")x.once?v.once(w,k):v.on(w,k);else if(typeof v.addEventListener=="function")v.addEventListener(w,function N(z){x.once&&v.removeEventListener(w,N),k(z)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return qo.exports}var m_=D1();function O1(){const e=arguments[0];for(let t=1,n=arguments.length;t<n;t++)if(arguments[t])for(const r in arguments[t])e[r]=arguments[t][r];return e}let Ye=O1;typeof Object.assign=="function"&&(Ye=Object.assign);function Ot(e,t,n,r){const i=e._nodes.get(t);let o=null;return i&&(r==="mixed"?o=i.out&&i.out[n]||i.undirected&&i.undirected[n]:r==="directed"?o=i.out&&i.out[n]:o=i.undirected&&i.undirected[n]),o}function ot(e){return typeof e=="object"&&e!==null}function g_(e){let t;for(t in e)return!1;return!0}function Rt(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function Vt(e,t,n){const r={enumerable:!0,configurable:!0};typeof n=="function"?r.get=n:(r.value=n,r.writable=!1),Object.defineProperty(e,t,r)}function Fp(e){return!(!ot(e)||e.attributes&&!Array.isArray(e.attributes))}function M1(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function un(){const e=arguments;let t=null,n=-1;return{[Symbol.iterator](){return this},next(){let r=null;do{if(t===null){if(n++,n>=e.length)return{done:!0};t=e[n][Symbol.iterator]()}if(r=t.next(),r.done){t=null;continue}break}while(!0);return r}}}function Wr(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}class ih extends Error{constructor(t){super(),this.name="GraphError",this.message=t}}class W extends ih{constructor(t){super(t),this.name="InvalidArgumentsGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W.prototype.constructor)}}class B extends ih{constructor(t){super(t),this.name="NotFoundGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,B.prototype.constructor)}}class se extends ih{constructor(t){super(t),this.name="UsageGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,se.prototype.constructor)}}function y_(e,t){this.key=e,this.attributes=t,this.clear()}y_.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}};function v_(e,t){this.key=e,this.attributes=t,this.clear()}v_.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function b_(e,t){this.key=e,this.attributes=t,this.clear()}b_.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function Kr(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}Kr.prototype.attach=function(){let e="out",t="in";this.undirected&&(e=t="undirected");const n=this.source.key,r=this.target.key;this.source[e][r]=this,!(this.undirected&&n===r)&&(this.target[t][n]=this)};Kr.prototype.attachMulti=function(){let e="out",t="in";const n=this.source.key,r=this.target.key;this.undirected&&(e=t="undirected");const i=this.source[e],o=i[r];if(typeof o>"u"){i[r]=this,this.undirected&&n===r||(this.target[t][n]=this);return}o.previous=this,this.next=o,i[r]=this,this.target[t][n]=this};Kr.prototype.detach=function(){const e=this.source.key,t=this.target.key;let n="out",r="in";this.undirected&&(n=r="undirected"),delete this.source[n][t],delete this.target[r][e]};Kr.prototype.detachMulti=function(){const e=this.source.key,t=this.target.key;let n="out",r="in";this.undirected&&(n=r="undirected"),this.previous===void 0?this.next===void 0?(delete this.source[n][t],delete this.target[r][e]):(this.next.previous=void 0,this.source[n][t]=this.next,this.target[r][e]=this.next):(this.previous.next=this.next,this.next!==void 0&&(this.next.previous=this.previous))};const w_=0,__=1,F1=2,k_=3;function yn(e,t,n,r,i,o,s){let a,u,c,l;if(r=""+r,n===w_){if(a=e._nodes.get(r),!a)throw new B(`Graph.${t}: could not find the "${r}" node in the graph.`);c=i,l=o}else if(n===k_){if(i=""+i,u=e._edges.get(i),!u)throw new B(`Graph.${t}: could not find the "${i}" edge in the graph.`);const d=u.source.key,f=u.target.key;if(r===d)a=u.target;else if(r===f)a=u.source;else throw new B(`Graph.${t}: the "${r}" node is not attached to the "${i}" edge (${d}, ${f}).`);c=o,l=s}else{if(u=e._edges.get(r),!u)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`);n===__?a=u.source:a=u.target,c=i,l=o}return[a,c,l]}function U1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return s.attributes[a]}}function G1(e,t,n){e.prototype[t]=function(r,i){const[o]=yn(this,t,n,r,i);return o.attributes}}function j1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return s.attributes.hasOwnProperty(a)}}function Z1(e,t,n){e.prototype[t]=function(r,i,o,s){const[a,u,c]=yn(this,t,n,r,i,o,s);return a.attributes[u]=c,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:u}),this}}function B1(e,t,n){e.prototype[t]=function(r,i,o,s){const[a,u,c]=yn(this,t,n,r,i,o,s);if(typeof c!="function")throw new W(`Graph.${t}: updater should be a function.`);const l=a.attributes,d=c(l[u]);return l[u]=d,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:u}),this}}function V1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);return delete s.attributes[a],this.emit("nodeAttributesUpdated",{key:s.key,type:"remove",attributes:s.attributes,name:a}),this}}function H1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(!ot(a))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return s.attributes=a,this.emit("nodeAttributesUpdated",{key:s.key,type:"replace",attributes:s.attributes}),this}}function q1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(!ot(a))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return Ye(s.attributes,a),this.emit("nodeAttributesUpdated",{key:s.key,type:"merge",attributes:s.attributes,data:a}),this}}function W1(e,t,n){e.prototype[t]=function(r,i,o){const[s,a]=yn(this,t,n,r,i,o);if(typeof a!="function")throw new W(`Graph.${t}: provided updater is not a function.`);return s.attributes=a(s.attributes),this.emit("nodeAttributesUpdated",{key:s.key,type:"update",attributes:s.attributes}),this}}const K1=[{name:e=>`get${e}Attribute`,attacher:U1},{name:e=>`get${e}Attributes`,attacher:G1},{name:e=>`has${e}Attribute`,attacher:j1},{name:e=>`set${e}Attribute`,attacher:Z1},{name:e=>`update${e}Attribute`,attacher:B1},{name:e=>`remove${e}Attribute`,attacher:V1},{name:e=>`replace${e}Attributes`,attacher:H1},{name:e=>`merge${e}Attributes`,attacher:q1},{name:e=>`update${e}Attributes`,attacher:W1}];function J1(e){K1.forEach(function({name:t,attacher:n}){n(e,t("Node"),w_),n(e,t("Source"),__),n(e,t("Target"),F1),n(e,t("Opposite"),k_)})}function Y1(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return o.attributes[i]}}function X1(e,t,n){e.prototype[t]=function(r){let i;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+r,s=""+arguments[1];if(i=Ot(this,o,s,n),!i)throw new B(`Graph.${t}: could not find an edge for the given path ("${o}" - "${s}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,i=this._edges.get(r),!i)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return i.attributes}}function Q1(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return o.attributes.hasOwnProperty(i)}}function eI(e,t,n){e.prototype[t]=function(r,i,o){let s;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const a=""+r,u=""+i;if(i=arguments[2],o=arguments[3],s=Ot(this,a,u,n),!s)throw new B(`Graph.${t}: could not find an edge for the given path ("${a}" - "${u}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,s=this._edges.get(r),!s)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return s.attributes[i]=o,this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}function tI(e,t,n){e.prototype[t]=function(r,i,o){let s;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const a=""+r,u=""+i;if(i=arguments[2],o=arguments[3],s=Ot(this,a,u,n),!s)throw new B(`Graph.${t}: could not find an edge for the given path ("${a}" - "${u}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,s=this._edges.get(r),!s)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(typeof o!="function")throw new W(`Graph.${t}: updater should be a function.`);return s.attributes[i]=o(s.attributes[i]),this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}function nI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}return delete o.attributes[i],this.emit("edgeAttributesUpdated",{key:o.key,type:"remove",attributes:o.attributes,name:i}),this}}function rI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(!ot(i))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return o.attributes=i,this.emit("edgeAttributesUpdated",{key:o.key,type:"replace",attributes:o.attributes}),this}}function iI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(!ot(i))throw new W(`Graph.${t}: provided attributes are not a plain object.`);return Ye(o.attributes,i),this.emit("edgeAttributesUpdated",{key:o.key,type:"merge",attributes:o.attributes,data:i}),this}}function oI(e,t,n){e.prototype[t]=function(r,i){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new se(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new se(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const s=""+r,a=""+i;if(i=arguments[2],o=Ot(this,s,a,n),!o)throw new B(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(n!=="mixed")throw new se(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(r=""+r,o=this._edges.get(r),!o)throw new B(`Graph.${t}: could not find the "${r}" edge in the graph.`)}if(typeof i!="function")throw new W(`Graph.${t}: provided updater is not a function.`);return o.attributes=i(o.attributes),this.emit("edgeAttributesUpdated",{key:o.key,type:"update",attributes:o.attributes}),this}}const sI=[{name:e=>`get${e}Attribute`,attacher:Y1},{name:e=>`get${e}Attributes`,attacher:X1},{name:e=>`has${e}Attribute`,attacher:Q1},{name:e=>`set${e}Attribute`,attacher:eI},{name:e=>`update${e}Attribute`,attacher:tI},{name:e=>`remove${e}Attribute`,attacher:nI},{name:e=>`replace${e}Attributes`,attacher:rI},{name:e=>`merge${e}Attributes`,attacher:iI},{name:e=>`update${e}Attributes`,attacher:oI}];function aI(e){sI.forEach(function({name:t,attacher:n}){n(e,t("Edge"),"mixed"),n(e,t("DirectedEdge"),"directed"),n(e,t("UndirectedEdge"),"undirected")})}const uI=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function cI(e,t,n,r){let i=!1;for(const o in t){if(o===r)continue;const s=t[o];if(i=n(s.key,s.attributes,s.source.key,s.target.key,s.source.attributes,s.target.attributes,s.undirected),e&&i)return s.key}}function lI(e,t,n,r){let i,o,s,a=!1;for(const u in t)if(u!==r){i=t[u];do{if(o=i.source,s=i.target,a=n(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected),e&&a)return i.key;i=i.next}while(i!==void 0)}}function Su(e,t){const n=Object.keys(e),r=n.length;let i,o=0;return{[Symbol.iterator](){return this},next(){do if(i)i=i.next;else{if(o>=r)return{done:!0};const s=n[o++];if(s===t){i=void 0;continue}i=e[s]}while(!i);return{done:!1,value:{edge:i.key,attributes:i.attributes,source:i.source.key,target:i.target.key,sourceAttributes:i.source.attributes,targetAttributes:i.target.attributes,undirected:i.undirected}}}}}function dI(e,t,n,r){const i=t[n];if(!i)return;const o=i.source,s=i.target;if(r(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected)&&e)return i.key}function fI(e,t,n,r){let i=t[n];if(!i)return;let o=!1;do{if(o=r(i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes,i.undirected),e&&o)return i.key;i=i.next}while(i!==void 0)}function xu(e,t){let n=e[t];if(n.next!==void 0)return{[Symbol.iterator](){return this},next(){if(!n)return{done:!0};const i={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:i}}};let r=!1;return{[Symbol.iterator](){return this},next(){return r===!0?{done:!0}:(r=!0,{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}})}}}function hI(e,t){if(e.size===0)return[];if(t==="mixed"||t===e.type)return Array.from(e._edges.keys());const n=t==="undirected"?e.undirectedSize:e.directedSize,r=new Array(n),i=t==="undirected",o=e._edges.values();let s=0,a,u;for(;a=o.next(),a.done!==!0;)u=a.value,u.undirected===i&&(r[s++]=u.key);return r}function S_(e,t,n,r){if(t.size===0)return;const i=n!=="mixed"&&n!==t.type,o=n==="undirected";let s,a,u=!1;const c=t._edges.values();for(;s=c.next(),s.done!==!0;){if(a=s.value,i&&a.undirected!==o)continue;const{key:l,attributes:d,source:f,target:h}=a;if(u=r(l,d,f.key,h.key,f.attributes,h.attributes,a.undirected),e&&u)return l}}function pI(e,t){if(e.size===0)return Wr();const n=t!=="mixed"&&t!==e.type,r=t==="undirected",i=e._edges.values();return{[Symbol.iterator](){return this},next(){let o,s;for(;;){if(o=i.next(),o.done)return o;if(s=o.value,!(n&&s.undirected!==r))break}return{value:{edge:s.key,attributes:s.attributes,source:s.source.key,target:s.target.key,sourceAttributes:s.source.attributes,targetAttributes:s.target.attributes,undirected:s.undirected},done:!1}}}}function oh(e,t,n,r,i,o){const s=t?lI:cI;let a;if(n!=="undirected"&&(r!=="out"&&(a=s(e,i.in,o),e&&a)||r!=="in"&&(a=s(e,i.out,o,r?void 0:i.key),e&&a))||n!=="directed"&&(a=s(e,i.undirected,o),e&&a))return a}function mI(e,t,n,r){const i=[];return oh(!1,e,t,n,r,function(o){i.push(o)}),i}function gI(e,t,n){let r=Wr();return e!=="undirected"&&(t!=="out"&&typeof n.in<"u"&&(r=un(r,Su(n.in))),t!=="in"&&typeof n.out<"u"&&(r=un(r,Su(n.out,t?void 0:n.key)))),e!=="directed"&&typeof n.undirected<"u"&&(r=un(r,Su(n.undirected))),r}function sh(e,t,n,r,i,o,s){const a=n?fI:dI;let u;if(t!=="undirected"&&(typeof i.in<"u"&&r!=="out"&&(u=a(e,i.in,o,s),e&&u)||typeof i.out<"u"&&r!=="in"&&(r||i.key!==o)&&(u=a(e,i.out,o,s),e&&u))||t!=="directed"&&typeof i.undirected<"u"&&(u=a(e,i.undirected,o,s),e&&u))return u}function yI(e,t,n,r,i){const o=[];return sh(!1,e,t,n,r,i,function(s){o.push(s)}),o}function vI(e,t,n,r){let i=Wr();return e!=="undirected"&&(typeof n.in<"u"&&t!=="out"&&r in n.in&&(i=un(i,xu(n.in,r))),typeof n.out<"u"&&t!=="in"&&r in n.out&&(t||n.key!==r)&&(i=un(i,xu(n.out,r)))),e!=="directed"&&typeof n.undirected<"u"&&r in n.undirected&&(i=un(i,xu(n.undirected,r))),i}function bI(e,t){const{name:n,type:r,direction:i}=t;e.prototype[n]=function(o,s){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return[];if(!arguments.length)return hI(this,r);if(arguments.length===1){o=""+o;const a=this._nodes.get(o);if(typeof a>"u")throw new B(`Graph.${n}: could not find the "${o}" node in the graph.`);return mI(this.multi,r==="mixed"?this.type:r,i,a)}if(arguments.length===2){o=""+o,s=""+s;const a=this._nodes.get(o);if(!a)throw new B(`Graph.${n}: could not find the "${o}" source node in the graph.`);if(!this._nodes.has(s))throw new B(`Graph.${n}: could not find the "${s}" target node in the graph.`);return yI(r,this.multi,i,a,s)}throw new W(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function wI(e,t){const{name:n,type:r,direction:i}=t,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(c,l,d){if(!(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)){if(arguments.length===1)return d=c,S_(!1,this,r,d);if(arguments.length===2){c=""+c,d=l;const f=this._nodes.get(c);if(typeof f>"u")throw new B(`Graph.${o}: could not find the "${c}" node in the graph.`);return oh(!1,this.multi,r==="mixed"?this.type:r,i,f,d)}if(arguments.length===3){c=""+c,l=""+l;const f=this._nodes.get(c);if(!f)throw new B(`Graph.${o}: could not find the "${c}" source node in the graph.`);if(!this._nodes.has(l))throw new B(`Graph.${o}: could not find the "${l}" target node in the graph.`);return sh(!1,r,this.multi,i,f,l,d)}throw new W(`Graph.${o}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)}};const s="map"+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(){const c=Array.prototype.slice.call(arguments),l=c.pop();let d;if(c.length===0){let f=0;r!=="directed"&&(f+=this.undirectedSize),r!=="undirected"&&(f+=this.directedSize),d=new Array(f);let h=0;c.push((p,m,y,_,g,b,v)=>{d[h++]=l(p,m,y,_,g,b,v)})}else d=[],c.push((f,h,p,m,y,_,g)=>{d.push(l(f,h,p,m,y,_,g))});return this[o].apply(this,c),d};const a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(){const c=Array.prototype.slice.call(arguments),l=c.pop(),d=[];return c.push((f,h,p,m,y,_,g)=>{l(f,h,p,m,y,_,g)&&d.push(f)}),this[o].apply(this,c),d};const u="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[u]=function(){let c=Array.prototype.slice.call(arguments);if(c.length<2||c.length>4)throw new W(`Graph.${u}: invalid number of arguments (expecting 2, 3 or 4 and got ${c.length}).`);if(typeof c[c.length-1]=="function"&&typeof c[c.length-2]!="function")throw new W(`Graph.${u}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let l,d;c.length===2?(l=c[0],d=c[1],c=[]):c.length===3?(l=c[1],d=c[2],c=[c[0]]):c.length===4&&(l=c[2],d=c[3],c=[c[0],c[1]]);let f=d;return c.push((h,p,m,y,_,g,b)=>{f=l(f,h,p,m,y,_,g,b)}),this[o].apply(this,c),f}}function _I(e,t){const{name:n,type:r,direction:i}=t,o="find"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(u,c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return!1;if(arguments.length===1)return l=u,S_(!0,this,r,l);if(arguments.length===2){u=""+u,l=c;const d=this._nodes.get(u);if(typeof d>"u")throw new B(`Graph.${o}: could not find the "${u}" node in the graph.`);return oh(!0,this.multi,r==="mixed"?this.type:r,i,d,l)}if(arguments.length===3){u=""+u,c=""+c;const d=this._nodes.get(u);if(!d)throw new B(`Graph.${o}: could not find the "${u}" source node in the graph.`);if(!this._nodes.has(c))throw new B(`Graph.${o}: could not find the "${c}" target node in the graph.`);return sh(!0,r,this.multi,i,d,c,l)}throw new W(`Graph.${o}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};const s="some"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(){const u=Array.prototype.slice.call(arguments),c=u.pop();return u.push((d,f,h,p,m,y,_)=>c(d,f,h,p,m,y,_)),!!this[o].apply(this,u)};const a="every"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(){const u=Array.prototype.slice.call(arguments),c=u.pop();return u.push((d,f,h,p,m,y,_)=>!c(d,f,h,p,m,y,_)),!this[o].apply(this,u)}}function kI(e,t){const{name:n,type:r,direction:i}=t,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(s,a){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return Wr();if(!arguments.length)return pI(this,r);if(arguments.length===1){s=""+s;const u=this._nodes.get(s);if(!u)throw new B(`Graph.${o}: could not find the "${s}" node in the graph.`);return gI(r,i,u)}if(arguments.length===2){s=""+s,a=""+a;const u=this._nodes.get(s);if(!u)throw new B(`Graph.${o}: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(a))throw new B(`Graph.${o}: could not find the "${a}" target node in the graph.`);return vI(r,i,u,a)}throw new W(`Graph.${o}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function SI(e){uI.forEach(t=>{bI(e,t),wI(e,t),_I(e,t),kI(e,t)})}const xI=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function Xa(){this.A=null,this.B=null}Xa.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)};Xa.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function Qr(e,t,n,r,i){for(const o in r){const s=r[o],a=s.source,u=s.target,c=a===n?u:a;if(t&&t.has(c.key))continue;const l=i(c.key,c.attributes);if(e&&l)return c.key}}function ah(e,t,n,r,i){if(t!=="mixed"){if(t==="undirected")return Qr(e,null,r,r.undirected,i);if(typeof n=="string")return Qr(e,null,r,r[n],i)}const o=new Xa;let s;if(t!=="undirected"){if(n!=="out"){if(s=Qr(e,null,r,r.in,i),e&&s)return s;o.wrap(r.in)}if(n!=="in"){if(s=Qr(e,o,r,r.out,i),e&&s)return s;o.wrap(r.out)}}if(t!=="directed"&&(s=Qr(e,o,r,r.undirected,i),e&&s))return s}function EI(e,t,n){if(e!=="mixed"){if(e==="undirected")return Object.keys(n.undirected);if(typeof t=="string")return Object.keys(n[t])}const r=[];return ah(!1,e,t,n,function(i){r.push(i)}),r}function ei(e,t,n){const r=Object.keys(n),i=r.length;let o=0;return{[Symbol.iterator](){return this},next(){let s=null;do{if(o>=i)return e&&e.wrap(n),{done:!0};const a=n[r[o++]],u=a.source,c=a.target;if(s=u===t?c:u,e&&e.has(s.key)){s=null;continue}}while(s===null);return{done:!1,value:{neighbor:s.key,attributes:s.attributes}}}}}function $I(e,t,n){if(e!=="mixed"){if(e==="undirected")return ei(null,n,n.undirected);if(typeof t=="string")return ei(null,n,n[t])}let r=Wr();const i=new Xa;return e!=="undirected"&&(t!=="out"&&(r=un(r,ei(i,n,n.in))),t!=="in"&&(r=un(r,ei(i,n,n.out)))),e!=="directed"&&(r=un(r,ei(i,n,n.undirected))),r}function TI(e,t){const{name:n,type:r,direction:i}=t;e.prototype[n]=function(o){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return[];o=""+o;const s=this._nodes.get(o);if(typeof s>"u")throw new B(`Graph.${n}: could not find the "${o}" node in the graph.`);return EI(r==="mixed"?this.type:r,i,s)}}function CI(e,t){const{name:n,type:r,direction:i}=t,o="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return;c=""+c;const d=this._nodes.get(c);if(typeof d>"u")throw new B(`Graph.${o}: could not find the "${c}" node in the graph.`);ah(!1,r==="mixed"?this.type:r,i,d,l)};const s="map"+n[0].toUpperCase()+n.slice(1);e.prototype[s]=function(c,l){const d=[];return this[o](c,(f,h)=>{d.push(l(f,h))}),d};const a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(c,l){const d=[];return this[o](c,(f,h)=>{l(f,h)&&d.push(f)}),d};const u="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[u]=function(c,l,d){if(arguments.length<3)throw new W(`Graph.${u}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let f=d;return this[o](c,(h,p)=>{f=l(f,h,p)}),f}}function AI(e,t){const{name:n,type:r,direction:i}=t,o=n[0].toUpperCase()+n.slice(1,-1),s="find"+o;e.prototype[s]=function(c,l){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return;c=""+c;const d=this._nodes.get(c);if(typeof d>"u")throw new B(`Graph.${s}: could not find the "${c}" node in the graph.`);return ah(!0,r==="mixed"?this.type:r,i,d,l)};const a="some"+o;e.prototype[a]=function(c,l){return!!this[s](c,l)};const u="every"+o;e.prototype[u]=function(c,l){return!this[s](c,(f,h)=>!l(f,h))}}function II(e,t){const{name:n,type:r,direction:i}=t,o=n.slice(0,-1)+"Entries";e.prototype[o]=function(s){if(r!=="mixed"&&this.type!=="mixed"&&r!==this.type)return Wr();s=""+s;const a=this._nodes.get(s);if(typeof a>"u")throw new B(`Graph.${o}: could not find the "${s}" node in the graph.`);return $I(r==="mixed"?this.type:r,i,a)}}function NI(e){xI.forEach(t=>{TI(e,t),CI(e,t),AI(e,t),II(e,t)})}function Wo(e,t,n,r,i){const o=r._nodes.values(),s=r.type;let a,u,c,l,d,f;for(;a=o.next(),a.done!==!0;){let h=!1;if(u=a.value,s!=="undirected"){l=u.out;for(c in l){d=l[c];do f=d.target,h=!0,i(u.key,f.key,u.attributes,f.attributes,d.key,d.attributes,d.undirected),d=d.next;while(d)}}if(s!=="directed"){l=u.undirected;for(c in l)if(!(t&&u.key>c)){d=l[c];do f=d.target,f.key!==c&&(f=d.source),h=!0,i(u.key,f.key,u.attributes,f.attributes,d.key,d.attributes,d.undirected),d=d.next;while(d)}}n&&!h&&i(u.key,null,u.attributes,null,null,null,null)}}function RI(e,t){const n={key:e};return g_(t.attributes)||(n.attributes=Ye({},t.attributes)),n}function LI(e,t,n){const r={key:t,source:n.source.key,target:n.target.key};return g_(n.attributes)||(r.attributes=Ye({},n.attributes)),e==="mixed"&&n.undirected&&(r.undirected=!0),r}function zI(e){if(!ot(e))throw new W('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in e))throw new W("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!ot(e.attributes)||e.attributes===null))throw new W("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function PI(e){if(!ot(e))throw new W('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in e))throw new W("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new W("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!ot(e.attributes)||e.attributes===null))throw new W("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&typeof e.undirected!="boolean")throw new W("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}const DI=M1(),OI=new Set(["directed","undirected","mixed"]),Up=new Set(["domain","_events","_eventsCount","_maxListeners"]),MI=[{name:e=>`${e}Edge`,generateKey:!0},{name:e=>`${e}DirectedEdge`,generateKey:!0,type:"directed"},{name:e=>`${e}UndirectedEdge`,generateKey:!0,type:"undirected"},{name:e=>`${e}EdgeWithKey`},{name:e=>`${e}DirectedEdgeWithKey`,type:"directed"},{name:e=>`${e}UndirectedEdgeWithKey`,type:"undirected"}],FI={allowSelfLoops:!0,multi:!1,type:"mixed"};function UI(e,t,n){if(n&&!ot(n))throw new W(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=""+t,n=n||{},e._nodes.has(t))throw new se(`Graph.addNode: the "${t}" node already exist in the graph.`);const r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit("nodeAdded",{key:t,attributes:n}),r}function Gp(e,t,n){const r=new e.NodeDataClass(t,n);return e._nodes.set(t,r),e.emit("nodeAdded",{key:t,attributes:n}),r}function x_(e,t,n,r,i,o,s,a){if(!r&&e.type==="undirected")throw new se(`Graph.${t}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);if(r&&e.type==="directed")throw new se(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(a&&!ot(a))throw new W(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`);if(o=""+o,s=""+s,a=a||{},!e.allowSelfLoops&&o===s)throw new se(`Graph.${t}: source & target are the same ("${o}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);const u=e._nodes.get(o),c=e._nodes.get(s);if(!u)throw new B(`Graph.${t}: source node "${o}" not found.`);if(!c)throw new B(`Graph.${t}: target node "${s}" not found.`);const l={key:null,undirected:r,source:o,target:s,attributes:a};if(n)i=e._edgeKeyGenerator();else if(i=""+i,e._edges.has(i))throw new se(`Graph.${t}: the "${i}" edge already exists in the graph.`);if(!e.multi&&(r?typeof u.undirected[s]<"u":typeof u.out[s]<"u"))throw new se(`Graph.${t}: an edge linking "${o}" to "${s}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);const d=new Kr(r,i,u,c,a);e._edges.set(i,d);const f=o===s;return r?(u.undirectedDegree++,c.undirectedDegree++,f&&(u.undirectedLoops++,e._undirectedSelfLoopCount++)):(u.outDegree++,c.inDegree++,f&&(u.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),r?e._undirectedSize++:e._directedSize++,l.key=i,e.emit("edgeAdded",l),i}function GI(e,t,n,r,i,o,s,a,u){if(!r&&e.type==="undirected")throw new se(`Graph.${t}: you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.`);if(r&&e.type==="directed")throw new se(`Graph.${t}: you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.`);if(a){if(u){if(typeof a!="function")throw new W(`Graph.${t}: invalid updater function. Expecting a function but got "${a}"`)}else if(!ot(a))throw new W(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`)}o=""+o,s=""+s;let c;if(u&&(c=a,a=void 0),!e.allowSelfLoops&&o===s)throw new se(`Graph.${t}: source & target are the same ("${o}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let l=e._nodes.get(o),d=e._nodes.get(s),f,h;if(!n&&(f=e._edges.get(i),f)){if((f.source.key!==o||f.target.key!==s)&&(!r||f.source.key!==s||f.target.key!==o))throw new se(`Graph.${t}: inconsistency detected when attempting to merge the "${i}" edge with "${o}" source & "${s}" target vs. ("${f.source.key}", "${f.target.key}").`);h=f}if(!h&&!e.multi&&l&&(h=r?l.undirected[s]:l.out[s]),h){const g=[h.key,!1,!1,!1];if(u?!c:!a)return g;if(u){const b=h.attributes;h.attributes=c(b),e.emit("edgeAttributesUpdated",{type:"replace",key:h.key,attributes:h.attributes})}else Ye(h.attributes,a),e.emit("edgeAttributesUpdated",{type:"merge",key:h.key,attributes:h.attributes,data:a});return g}a=a||{},u&&c&&(a=c(a));const p={key:null,undirected:r,source:o,target:s,attributes:a};if(n)i=e._edgeKeyGenerator();else if(i=""+i,e._edges.has(i))throw new se(`Graph.${t}: the "${i}" edge already exists in the graph.`);let m=!1,y=!1;l||(l=Gp(e,o,{}),m=!0,o===s&&(d=l,y=!0)),d||(d=Gp(e,s,{}),y=!0),f=new Kr(r,i,l,d,a),e._edges.set(i,f);const _=o===s;return r?(l.undirectedDegree++,d.undirectedDegree++,_&&(l.undirectedLoops++,e._undirectedSelfLoopCount++)):(l.outDegree++,d.inDegree++,_&&(l.directedLoops++,e._directedSelfLoopCount++)),e.multi?f.attachMulti():f.attach(),r?e._undirectedSize++:e._directedSize++,p.key=i,e.emit("edgeAdded",p),[i,!0,m,y]}function nr(e,t){e._edges.delete(t.key);const{source:n,target:r,attributes:i}=t,o=t.undirected,s=n===r;o?(n.undirectedDegree--,r.undirectedDegree--,s&&(n.undirectedLoops--,e._undirectedSelfLoopCount--)):(n.outDegree--,r.inDegree--,s&&(n.directedLoops--,e._directedSelfLoopCount--)),e.multi?t.detachMulti():t.detach(),o?e._undirectedSize--:e._directedSize--,e.emit("edgeDropped",{key:t.key,attributes:i,source:n.key,target:r.key,undirected:o})}class Fe extends m_.EventEmitter{constructor(t){if(super(),t=Ye({},FI,t),typeof t.multi!="boolean")throw new W(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${t.multi}".`);if(!OI.has(t.type))throw new W(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${t.type}".`);if(typeof t.allowSelfLoops!="boolean")throw new W(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${t.allowSelfLoops}".`);const n=t.type==="mixed"?y_:t.type==="directed"?v_:b_;Rt(this,"NodeDataClass",n);const r="geid_"+DI()+"_";let i=0;const o=()=>{let s;do s=r+i++;while(this._edges.has(s));return s};Rt(this,"_attributes",{}),Rt(this,"_nodes",new Map),Rt(this,"_edges",new Map),Rt(this,"_directedSize",0),Rt(this,"_undirectedSize",0),Rt(this,"_directedSelfLoopCount",0),Rt(this,"_undirectedSelfLoopCount",0),Rt(this,"_edgeKeyGenerator",o),Rt(this,"_options",t),Up.forEach(s=>Rt(this,s,this[s])),Vt(this,"order",()=>this._nodes.size),Vt(this,"size",()=>this._edges.size),Vt(this,"directedSize",()=>this._directedSize),Vt(this,"undirectedSize",()=>this._undirectedSize),Vt(this,"selfLoopCount",()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),Vt(this,"directedSelfLoopCount",()=>this._directedSelfLoopCount),Vt(this,"undirectedSelfLoopCount",()=>this._undirectedSelfLoopCount),Vt(this,"multi",this._options.multi),Vt(this,"type",this._options.type),Vt(this,"allowSelfLoops",this._options.allowSelfLoops),Vt(this,"implementation",()=>"graphology")}_resetInstanceCounters(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0}hasNode(t){return this._nodes.has(""+t)}hasDirectedEdge(t,n){if(this.type==="undirected")return!1;if(arguments.length===1){const r=""+t,i=this._edges.get(r);return!!i&&!i.undirected}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?r.out.hasOwnProperty(n):!1}throw new W(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasUndirectedEdge(t,n){if(this.type==="directed")return!1;if(arguments.length===1){const r=""+t,i=this._edges.get(r);return!!i&&i.undirected}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?r.undirected.hasOwnProperty(n):!1}throw new W(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasEdge(t,n){if(arguments.length===1){const r=""+t;return this._edges.has(r)}else if(arguments.length===2){t=""+t,n=""+n;const r=this._nodes.get(t);return r?typeof r.out<"u"&&r.out.hasOwnProperty(n)||typeof r.undirected<"u"&&r.undirected.hasOwnProperty(n):!1}throw new W(`Graph.hasEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}directedEdge(t,n){if(this.type==="undirected")return;if(t=""+t,n=""+n,this.multi)throw new se("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");const r=this._nodes.get(t);if(!r)throw new B(`Graph.directedEdge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.directedEdge: could not find the "${n}" target node in the graph.`);const i=r.out&&r.out[n]||void 0;if(i)return i.key}undirectedEdge(t,n){if(this.type==="directed")return;if(t=""+t,n=""+n,this.multi)throw new se("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");const r=this._nodes.get(t);if(!r)throw new B(`Graph.undirectedEdge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.undirectedEdge: could not find the "${n}" target node in the graph.`);const i=r.undirected&&r.undirected[n]||void 0;if(i)return i.key}edge(t,n){if(this.multi)throw new se("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.edge: could not find the "${t}" source node in the graph.`);if(!this._nodes.has(n))throw new B(`Graph.edge: could not find the "${n}" target node in the graph.`);const i=r.out&&r.out[n]||r.undirected&&r.undirected[n]||void 0;if(i)return i.key}areDirectedNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areDirectedNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.in||n in r.out}areOutNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areOutNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.out}areInNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areInNeighbors: could not find the "${t}" node in the graph.`);return this.type==="undirected"?!1:n in r.in}areUndirectedNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areUndirectedNeighbors: could not find the "${t}" node in the graph.`);return this.type==="directed"?!1:n in r.undirected}areNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&(n in r.in||n in r.out)||this.type!=="directed"&&n in r.undirected}areInboundNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areInboundNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&n in r.in||this.type!=="directed"&&n in r.undirected}areOutboundNeighbors(t,n){t=""+t,n=""+n;const r=this._nodes.get(t);if(!r)throw new B(`Graph.areOutboundNeighbors: could not find the "${t}" node in the graph.`);return this.type!=="undirected"&&n in r.out||this.type!=="directed"&&n in r.undirected}inDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree}outDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.outDegree}directedDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.directedDegree: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree}undirectedDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.undirectedDegree: could not find the "${t}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree}inboundDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inboundDegree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.inDegree),r}outboundDegree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outboundDegree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.outDegree),r}degree(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.degree: could not find the "${t}" node in the graph.`);let r=0;return this.type!=="directed"&&(r+=n.undirectedDegree),this.type!=="undirected"&&(r+=n.inDegree+n.outDegree),r}inDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree-n.directedLoops}outDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.outDegree-n.directedLoops}directedDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.directedDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree-n.directedLoops*2}undirectedDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.undirectedDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree-n.undirectedLoops*2}inboundDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.inboundDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.inDegree,i+=n.directedLoops),r-i}outboundDegreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.outboundDegreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.outDegree,i+=n.directedLoops),r-i}degreeWithoutSelfLoops(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.degreeWithoutSelfLoops: could not find the "${t}" node in the graph.`);let r=0,i=0;return this.type!=="directed"&&(r+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(r+=n.inDegree+n.outDegree,i+=n.directedLoops*2),r-i}source(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.source: could not find the "${t}" edge in the graph.`);return n.source.key}target(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.target: could not find the "${t}" edge in the graph.`);return n.target.key}extremities(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.extremities: could not find the "${t}" edge in the graph.`);return[n.source.key,n.target.key]}opposite(t,n){t=""+t,n=""+n;const r=this._edges.get(n);if(!r)throw new B(`Graph.opposite: could not find the "${n}" edge in the graph.`);const i=r.source.key,o=r.target.key;if(t===i)return o;if(t===o)return i;throw new B(`Graph.opposite: the "${t}" node is not attached to the "${n}" edge (${i}, ${o}).`)}hasExtremity(t,n){t=""+t,n=""+n;const r=this._edges.get(t);if(!r)throw new B(`Graph.hasExtremity: could not find the "${t}" edge in the graph.`);return r.source.key===n||r.target.key===n}isUndirected(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isUndirected: could not find the "${t}" edge in the graph.`);return n.undirected}isDirected(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isDirected: could not find the "${t}" edge in the graph.`);return!n.undirected}isSelfLoop(t){t=""+t;const n=this._edges.get(t);if(!n)throw new B(`Graph.isSelfLoop: could not find the "${t}" edge in the graph.`);return n.source===n.target}addNode(t,n){return UI(this,t,n).key}mergeNode(t,n){if(n&&!ot(n))throw new W(`Graph.mergeNode: invalid attributes. Expecting an object but got "${n}"`);t=""+t,n=n||{};let r=this._nodes.get(t);return r?(n&&(Ye(r.attributes,n),this.emit("nodeAttributesUpdated",{type:"merge",key:t,attributes:r.attributes,data:n})),[t,!1]):(r=new this.NodeDataClass(t,n),this._nodes.set(t,r),this.emit("nodeAdded",{key:t,attributes:n}),[t,!0])}updateNode(t,n){if(n&&typeof n!="function")throw new W(`Graph.updateNode: invalid updater function. Expecting a function but got "${n}"`);t=""+t;let r=this._nodes.get(t);if(r){if(n){const o=r.attributes;r.attributes=n(o),this.emit("nodeAttributesUpdated",{type:"replace",key:t,attributes:r.attributes})}return[t,!1]}const i=n?n({}):{};return r=new this.NodeDataClass(t,i),this._nodes.set(t,r),this.emit("nodeAdded",{key:t,attributes:i}),[t,!0]}dropNode(t){t=""+t;const n=this._nodes.get(t);if(!n)throw new B(`Graph.dropNode: could not find the "${t}" node in the graph.`);let r;if(this.type!=="undirected"){for(const i in n.out){r=n.out[i];do nr(this,r),r=r.next;while(r)}for(const i in n.in){r=n.in[i];do nr(this,r),r=r.next;while(r)}}if(this.type!=="directed")for(const i in n.undirected){r=n.undirected[i];do nr(this,r),r=r.next;while(r)}this._nodes.delete(t),this.emit("nodeDropped",{key:t,attributes:n.attributes})}dropEdge(t){let n;if(arguments.length>1){const r=""+arguments[0],i=""+arguments[1];if(n=Ot(this,r,i,this.type),!n)throw new B(`Graph.dropEdge: could not find the "${r}" -> "${i}" edge in the graph.`)}else if(t=""+t,n=this._edges.get(t),!n)throw new B(`Graph.dropEdge: could not find the "${t}" edge in the graph.`);return nr(this,n),this}dropDirectedEdge(t,n){if(arguments.length<2)throw new se("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new se("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");t=""+t,n=""+n;const r=Ot(this,t,n,"directed");if(!r)throw new B(`Graph.dropDirectedEdge: could not find a "${t}" -> "${n}" edge in the graph.`);return nr(this,r),this}dropUndirectedEdge(t,n){if(arguments.length<2)throw new se("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new se("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");const r=Ot(this,t,n,"undirected");if(!r)throw new B(`Graph.dropUndirectedEdge: could not find a "${t}" -> "${n}" edge in the graph.`);return nr(this,r),this}clear(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")}clearEdges(){const t=this._nodes.values();let n;for(;n=t.next(),n.done!==!0;)n.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")}getAttribute(t){return this._attributes[t]}getAttributes(){return this._attributes}hasAttribute(t){return this._attributes.hasOwnProperty(t)}setAttribute(t,n){return this._attributes[t]=n,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:t}),this}updateAttribute(t,n){if(typeof n!="function")throw new W("Graph.updateAttribute: updater should be a function.");const r=this._attributes[t];return this._attributes[t]=n(r),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:t}),this}removeAttribute(t){return delete this._attributes[t],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:t}),this}replaceAttributes(t){if(!ot(t))throw new W("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=t,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this}mergeAttributes(t){if(!ot(t))throw new W("Graph.mergeAttributes: provided attributes are not a plain object.");return Ye(this._attributes,t),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:t}),this}updateAttributes(t){if(typeof t!="function")throw new W("Graph.updateAttributes: provided updater is not a function.");return this._attributes=t(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this}updateEachNodeAttributes(t,n){if(typeof t!="function")throw new W("Graph.updateEachNodeAttributes: expecting an updater function.");if(n&&!Fp(n))throw new W("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const r=this._nodes.values();let i,o;for(;i=r.next(),i.done!==!0;)o=i.value,o.attributes=t(o.key,o.attributes);this.emit("eachNodeAttributesUpdated",{hints:n||null})}updateEachEdgeAttributes(t,n){if(typeof t!="function")throw new W("Graph.updateEachEdgeAttributes: expecting an updater function.");if(n&&!Fp(n))throw new W("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const r=this._edges.values();let i,o,s,a;for(;i=r.next(),i.done!==!0;)o=i.value,s=o.source,a=o.target,o.attributes=t(o.key,o.attributes,s.key,a.key,s.attributes,a.attributes,o.undirected);this.emit("eachEdgeAttributesUpdated",{hints:n||null})}forEachAdjacencyEntry(t){if(typeof t!="function")throw new W("Graph.forEachAdjacencyEntry: expecting a callback.");Wo(!1,!1,!1,this,t)}forEachAdjacencyEntryWithOrphans(t){if(typeof t!="function")throw new W("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");Wo(!1,!1,!0,this,t)}forEachAssymetricAdjacencyEntry(t){if(typeof t!="function")throw new W("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");Wo(!1,!0,!1,this,t)}forEachAssymetricAdjacencyEntryWithOrphans(t){if(typeof t!="function")throw new W("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");Wo(!1,!0,!0,this,t)}nodes(){return Array.from(this._nodes.keys())}forEachNode(t){if(typeof t!="function")throw new W("Graph.forEachNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)i=r.value,t(i.key,i.attributes)}findNode(t){if(typeof t!="function")throw new W("Graph.findNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,t(i.key,i.attributes))return i.key}mapNodes(t){if(typeof t!="function")throw new W("Graph.mapNode: expecting a callback.");const n=this._nodes.values();let r,i;const o=new Array(this.order);let s=0;for(;r=n.next(),r.done!==!0;)i=r.value,o[s++]=t(i.key,i.attributes);return o}someNode(t){if(typeof t!="function")throw new W("Graph.someNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,t(i.key,i.attributes))return!0;return!1}everyNode(t){if(typeof t!="function")throw new W("Graph.everyNode: expecting a callback.");const n=this._nodes.values();let r,i;for(;r=n.next(),r.done!==!0;)if(i=r.value,!t(i.key,i.attributes))return!1;return!0}filterNodes(t){if(typeof t!="function")throw new W("Graph.filterNodes: expecting a callback.");const n=this._nodes.values();let r,i;const o=[];for(;r=n.next(),r.done!==!0;)i=r.value,t(i.key,i.attributes)&&o.push(i.key);return o}reduceNodes(t,n){if(typeof t!="function")throw new W("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new W("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");let r=n;const i=this._nodes.values();let o,s;for(;o=i.next(),o.done!==!0;)s=o.value,r=t(r,s.key,s.attributes);return r}nodeEntries(){const t=this._nodes.values();return{[Symbol.iterator](){return this},next(){const n=t.next();if(n.done)return n;const r=n.value;return{value:{node:r.key,attributes:r.attributes},done:!1}}}}export(){const t=new Array(this._nodes.size);let n=0;this._nodes.forEach((i,o)=>{t[n++]=RI(o,i)});const r=new Array(this._edges.size);return n=0,this._edges.forEach((i,o)=>{r[n++]=LI(this.type,o,i)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:t,edges:r}}import(t,n=!1){if(t instanceof Fe)return t.forEachNode((u,c)=>{n?this.mergeNode(u,c):this.addNode(u,c)}),t.forEachEdge((u,c,l,d,f,h,p)=>{n?p?this.mergeUndirectedEdgeWithKey(u,l,d,c):this.mergeDirectedEdgeWithKey(u,l,d,c):p?this.addUndirectedEdgeWithKey(u,l,d,c):this.addDirectedEdgeWithKey(u,l,d,c)}),this;if(!ot(t))throw new W("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(t.attributes){if(!ot(t.attributes))throw new W("Graph.import: invalid attributes. Expecting a plain object.");n?this.mergeAttributes(t.attributes):this.replaceAttributes(t.attributes)}let r,i,o,s,a;if(t.nodes){if(o=t.nodes,!Array.isArray(o))throw new W("Graph.import: invalid nodes. Expecting an array.");for(r=0,i=o.length;r<i;r++){s=o[r],zI(s);const{key:u,attributes:c}=s;n?this.mergeNode(u,c):this.addNode(u,c)}}if(t.edges){let u=!1;if(this.type==="undirected"&&(u=!0),o=t.edges,!Array.isArray(o))throw new W("Graph.import: invalid edges. Expecting an array.");for(r=0,i=o.length;r<i;r++){a=o[r],PI(a);const{source:c,target:l,attributes:d,undirected:f=u}=a;let h;"key"in a?(h=n?f?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:f?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,h.call(this,a.key,c,l,d)):(h=n?f?this.mergeUndirectedEdge:this.mergeDirectedEdge:f?this.addUndirectedEdge:this.addDirectedEdge,h.call(this,c,l,d))}}return this}nullCopy(t){const n=new Fe(Ye({},this._options,t));return n.replaceAttributes(Ye({},this.getAttributes())),n}emptyCopy(t){const n=this.nullCopy(t);return this._nodes.forEach((r,i)=>{const o=Ye({},r.attributes);r=new n.NodeDataClass(i,o),n._nodes.set(i,r)}),n}copy(t){if(t=t||{},typeof t.type=="string"&&t.type!==this.type&&t.type!=="mixed")throw new se(`Graph.copy: cannot create an incompatible copy from "${this.type}" type to "${t.type}" because this would mean losing information about the current graph.`);if(typeof t.multi=="boolean"&&t.multi!==this.multi&&t.multi!==!0)throw new se("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if(typeof t.allowSelfLoops=="boolean"&&t.allowSelfLoops!==this.allowSelfLoops&&t.allowSelfLoops!==!0)throw new se("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");const n=this.emptyCopy(t),r=this._edges.values();let i,o;for(;i=r.next(),i.done!==!0;)o=i.value,x_(n,"copy",!1,o.undirected,o.key,o.source.key,o.target.key,Ye({},o.attributes));return n}toJSON(){return this.export()}toString(){return"[object Graph]"}inspect(){const t={};this._nodes.forEach((o,s)=>{t[s]=o.attributes});const n={},r={};this._edges.forEach((o,s)=>{const a=o.undirected?"--":"->";let u="",c=o.source.key,l=o.target.key,d;o.undirected&&c>l&&(d=c,c=l,l=d);const f=`(${c})${a}(${l})`;s.startsWith("geid_")?this.multi&&(typeof r[f]>"u"?r[f]=0:r[f]++,u+=`${r[f]}. `):u+=`[${s}]: `,u+=f,n[u]=o.attributes});const i={};for(const o in this)this.hasOwnProperty(o)&&!Up.has(o)&&typeof this[o]!="function"&&typeof o!="symbol"&&(i[o]=this[o]);return i.attributes=this._attributes,i.nodes=t,i.edges=n,Rt(i,"constructor",this.constructor),i}}typeof Symbol<"u"&&(Fe.prototype[Symbol.for("nodejs.util.inspect.custom")]=Fe.prototype.inspect);MI.forEach(e=>{["add","merge","update"].forEach(t=>{const n=e.name(t),r=t==="add"?x_:GI;e.generateKey?Fe.prototype[n]=function(i,o,s){return r(this,n,!0,(e.type||this.type)==="undirected",null,i,o,s,t==="update")}:Fe.prototype[n]=function(i,o,s,a){return r(this,n,!1,(e.type||this.type)==="undirected",i,o,s,a,t==="update")}})});J1(Fe);aI(Fe);SI(Fe);NI(Fe);class E_ extends Fe{constructor(t){const n=Ye({type:"directed"},t);if("multi"in n&&n.multi!==!1)throw new W("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="directed")throw new W('DirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class $_ extends Fe{constructor(t){const n=Ye({type:"undirected"},t);if("multi"in n&&n.multi!==!1)throw new W("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="undirected")throw new W('UndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class T_ extends Fe{constructor(t){const n=Ye({multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(n)}}class C_ extends Fe{constructor(t){const n=Ye({type:"directed",multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="directed")throw new W('MultiDirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class A_ extends Fe{constructor(t){const n=Ye({type:"undirected",multi:!0},t);if("multi"in n&&n.multi!==!0)throw new W("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="undirected")throw new W('MultiUndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}function Jr(e){e.from=function(t,n){const r=Ye({},t.options,n),i=new e(r);return i.import(t),i}}Jr(Fe);Jr(E_);Jr($_);Jr(T_);Jr(C_);Jr(A_);Fe.Graph=Fe;Fe.DirectedGraph=E_;Fe.UndirectedGraph=$_;Fe.MultiGraph=T_;Fe.MultiDirectedGraph=C_;Fe.MultiUndirectedGraph=A_;Fe.InvalidArgumentsGraphError=W;Fe.NotFoundGraphError=B;Fe.UsageGraphError=se;function jI(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function li(e){var t=jI(e,"string");return typeof t=="symbol"?t:t+""}function ht(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function jp(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,li(r.key),r)}}function pt(e,t,n){return t&&jp(e.prototype,t),n&&jp(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function kr(e){return kr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},kr(e)}function I_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(I_=function(){return!!e})()}function ZI(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function BI(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ZI(e)}function Gt(e,t,n){return t=kr(t),BI(e,I_()?Reflect.construct(t,n||[],kr(e).constructor):t.apply(e,n))}function fc(e,t){return fc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},fc(e,t)}function jt(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fc(e,t)}function VI(e){if(Array.isArray(e))return e}function HI(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,a=[],u=!0,c=!1;try{if(o=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(l){c=!0,i=l}finally{try{if(!u&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function hc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function N_(e,t){if(e){if(typeof e=="string")return hc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?hc(e,t):void 0}}function qI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
111
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Sr(e,t){return VI(e)||HI(e,t)||N_(e,t)||qI()}var Eu={black:"#000000",silver:"#C0C0C0",gray:"#808080",grey:"#808080",white:"#FFFFFF",maroon:"#800000",red:"#FF0000",purple:"#800080",fuchsia:"#FF00FF",green:"#008000",lime:"#00FF00",olive:"#808000",yellow:"#FFFF00",navy:"#000080",blue:"#0000FF",teal:"#008080",aqua:"#00FFFF",darkblue:"#00008B",mediumblue:"#0000CD",darkgreen:"#006400",darkcyan:"#008B8B",deepskyblue:"#00BFFF",darkturquoise:"#00CED1",mediumspringgreen:"#00FA9A",springgreen:"#00FF7F",cyan:"#00FFFF",midnightblue:"#191970",dodgerblue:"#1E90FF",lightseagreen:"#20B2AA",forestgreen:"#228B22",seagreen:"#2E8B57",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",limegreen:"#32CD32",mediumseagreen:"#3CB371",turquoise:"#40E0D0",royalblue:"#4169E1",steelblue:"#4682B4",darkslateblue:"#483D8B",mediumturquoise:"#48D1CC",indigo:"#4B0082",darkolivegreen:"#556B2F",cadetblue:"#5F9EA0",cornflowerblue:"#6495ED",rebeccapurple:"#663399",mediumaquamarine:"#66CDAA",dimgray:"#696969",dimgrey:"#696969",slateblue:"#6A5ACD",olivedrab:"#6B8E23",slategray:"#708090",slategrey:"#708090",lightslategray:"#778899",lightslategrey:"#778899",mediumslateblue:"#7B68EE",lawngreen:"#7CFC00",chartreuse:"#7FFF00",aquamarine:"#7FFFD4",skyblue:"#87CEEB",lightskyblue:"#87CEFA",blueviolet:"#8A2BE2",darkred:"#8B0000",darkmagenta:"#8B008B",saddlebrown:"#8B4513",darkseagreen:"#8FBC8F",lightgreen:"#90EE90",mediumpurple:"#9370DB",darkviolet:"#9400D3",palegreen:"#98FB98",darkorchid:"#9932CC",yellowgreen:"#9ACD32",sienna:"#A0522D",brown:"#A52A2A",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",lightblue:"#ADD8E6",greenyellow:"#ADFF2F",paleturquoise:"#AFEEEE",lightsteelblue:"#B0C4DE",powderblue:"#B0E0E6",firebrick:"#B22222",darkgoldenrod:"#B8860B",mediumorchid:"#BA55D3",rosybrown:"#BC8F8F",darkkhaki:"#BDB76B",mediumvioletred:"#C71585",indianred:"#CD5C5C",peru:"#CD853F",chocolate:"#D2691E",tan:"#D2B48C",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",thistle:"#D8BFD8",orchid:"#DA70D6",goldenrod:"#DAA520",palevioletred:"#DB7093",crimson:"#DC143C",gainsboro:"#DCDCDC",plum:"#DDA0DD",burlywood:"#DEB887",lightcyan:"#E0FFFF",lavender:"#E6E6FA",darksalmon:"#E9967A",violet:"#EE82EE",palegoldenrod:"#EEE8AA",lightcoral:"#F08080",khaki:"#F0E68C",aliceblue:"#F0F8FF",honeydew:"#F0FFF0",azure:"#F0FFFF",sandybrown:"#F4A460",wheat:"#F5DEB3",beige:"#F5F5DC",whitesmoke:"#F5F5F5",mintcream:"#F5FFFA",ghostwhite:"#F8F8FF",salmon:"#FA8072",antiquewhite:"#FAEBD7",linen:"#FAF0E6",lightgoldenrodyellow:"#FAFAD2",oldlace:"#FDF5E6",magenta:"#FF00FF",deeppink:"#FF1493",orangered:"#FF4500",tomato:"#FF6347",hotpink:"#FF69B4",coral:"#FF7F50",darkorange:"#FF8C00",lightsalmon:"#FFA07A",orange:"#FFA500",lightpink:"#FFB6C1",pink:"#FFC0CB",gold:"#FFD700",peachpuff:"#FFDAB9",navajowhite:"#FFDEAD",moccasin:"#FFE4B5",bisque:"#FFE4C4",mistyrose:"#FFE4E1",blanchedalmond:"#FFEBCD",papayawhip:"#FFEFD5",lavenderblush:"#FFF0F5",seashell:"#FFF5EE",cornsilk:"#FFF8DC",lemonchiffon:"#FFFACD",floralwhite:"#FFFAF0",snow:"#FFFAFA",lightyellow:"#FFFFE0",ivory:"#FFFFF0"},R_=new Int8Array(4),os=new Int32Array(R_.buffer,0,1),L_=new Float32Array(R_.buffer,0,1),WI=/^\s*rgba?\s*\(/,KI=/^\s*rgba?\s*\(\s*([0-9]*)\s*,\s*([0-9]*)\s*,\s*([0-9]*)(?:\s*,\s*(.*)?)?\)\s*$/;function JI(e){var t=0,n=0,r=0,i=1;if(e[0]==="#")e.length===4?(t=parseInt(e.charAt(1)+e.charAt(1),16),n=parseInt(e.charAt(2)+e.charAt(2),16),r=parseInt(e.charAt(3)+e.charAt(3),16)):(t=parseInt(e.charAt(1)+e.charAt(2),16),n=parseInt(e.charAt(3)+e.charAt(4),16),r=parseInt(e.charAt(5)+e.charAt(6),16)),e.length===9&&(i=parseInt(e.charAt(7)+e.charAt(8),16)/255);else if(WI.test(e)){var o=e.match(KI);o&&(t=+o[1],n=+o[2],r=+o[3],o[4]&&(i=+o[4]))}return{r:t,g:n,b:r,a:i}}var ur={};for(var Ko in Eu)ur[Ko]=Pn(Eu[Ko]),ur[Eu[Ko]]=ur[Ko];function z_(e,t,n,r,i){return os[0]=r<<24|n<<16|t<<8|e,os[0]=os[0]&4278190079,L_[0]}function Pn(e){if(e=e.toLowerCase(),typeof ur[e]<"u")return ur[e];var t=JI(e),n=t.r,r=t.g,i=t.b,o=t.a;o=o*255|0;var s=z_(n,r,i,o);return ur[e]=s,s}function YI(e,t){L_[0]=Pn(e);var n=os[0],r=n&255,i=n>>8&255,o=n>>16&255,s=n>>24&255;return[r,i,o,s]}var $u={};function P_(e){if(typeof $u[e]<"u")return $u[e];var t=(e&16711680)>>>16,n=(e&65280)>>>8,r=e&255,i=255,o=z_(t,n,r,i);return $u[e]=o,o}function Zp(e,t,n,r){return n+(t<<8)+(e<<16)}function Bp(e,t,n,r,i,o){var s=Math.floor(n/o*i),a=Math.floor(e.drawingBufferHeight/o-r/o*i),u=new Uint8Array(4);e.bindFramebuffer(e.FRAMEBUFFER,t),e.readPixels(s,a,1,1,e.RGBA,e.UNSIGNED_BYTE,u);var c=Sr(u,4),l=c[0],d=c[1],f=c[2],h=c[3];return[l,d,f,h]}function D(e,t,n){return(t=li(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Vp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Q(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Vp(Object(n),!0).forEach(function(r){D(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Vp(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function XI(e,t){for(;!{}.hasOwnProperty.call(e,t)&&(e=kr(e))!==null;);return e}function pc(){return pc=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=XI(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},pc.apply(null,arguments)}function D_(e,t,n,r){var i=pc(kr(e.prototype),t,n);return typeof i=="function"?function(o){return i.apply(n,o)}:i}function QI(e){return e.normalized?1:e.size}function Tu(e){var t=0;return e.forEach(function(n){return t+=QI(n)}),t}function O_(e,t,n){var r=e==="VERTEX"?t.VERTEX_SHADER:t.FRAGMENT_SHADER,i=t.createShader(r);if(i===null)throw new Error("loadShader: error while creating the shader");t.shaderSource(i,n),t.compileShader(i);var o=t.getShaderParameter(i,t.COMPILE_STATUS);if(!o){var s=t.getShaderInfoLog(i);throw t.deleteShader(i),new Error(`loadShader: error while compiling the shader:
112
112
  `.concat(s,`
113
- `).concat(n))}return i}function YI(e,t){return z_("VERTEX",e,t)}function XI(e,t){return z_("FRAGMENT",e,t)}function QI(e,t){var n=e.createProgram();if(n===null)throw new Error("loadProgram: error while creating the program.");var r,i;for(r=0,i=t.length;r<i;r++)e.attachShader(n,t[r]);e.linkProgram(n);var o=e.getProgramParameter(n,e.LINK_STATUS);if(!o){var s=e.getProgramInfoLog(n);throw e.deleteProgram(n),new Error("loadProgram: error while linking the program: ".concat(s))}return n}function Bp(e){var t=e.gl,n=e.buffer,r=e.program,i=e.vertexShader,o=e.fragmentShader;t.deleteShader(i),t.deleteShader(o),t.deleteProgram(r),t.deleteBuffer(n)}function Hp(e){return e%1===0?e.toFixed(1):e.toString()}var Vp=`#define PICKING_MODE
114
- `,eN=O(O(O(O(O(O(O(O({},WebGL2RenderingContext.BOOL,1),WebGL2RenderingContext.BYTE,1),WebGL2RenderingContext.UNSIGNED_BYTE,1),WebGL2RenderingContext.SHORT,2),WebGL2RenderingContext.UNSIGNED_SHORT,2),WebGL2RenderingContext.INT,4),WebGL2RenderingContext.UNSIGNED_INT,4),WebGL2RenderingContext.FLOAT,4),P_=(function(){function e(t,n,r){ht(this,e),O(this,"array",new Float32Array),O(this,"constantArray",new Float32Array),O(this,"capacity",0),O(this,"verticesCount",0);var i=this.getDefinition();if(this.VERTICES=i.VERTICES,this.VERTEX_SHADER_SOURCE=i.VERTEX_SHADER_SOURCE,this.FRAGMENT_SHADER_SOURCE=i.FRAGMENT_SHADER_SOURCE,this.UNIFORMS=i.UNIFORMS,this.ATTRIBUTES=i.ATTRIBUTES,this.METHOD=i.METHOD,this.CONSTANT_ATTRIBUTES="CONSTANT_ATTRIBUTES"in i?i.CONSTANT_ATTRIBUTES:[],this.CONSTANT_DATA="CONSTANT_DATA"in i?i.CONSTANT_DATA:[],this.isInstanced="CONSTANT_ATTRIBUTES"in i,this.ATTRIBUTES_ITEMS_COUNT=$u(this.ATTRIBUTES),this.STRIDE=this.VERTICES*this.ATTRIBUTES_ITEMS_COUNT,this.renderer=r,this.normalProgram=this.getProgramInfo("normal",t,i.VERTEX_SHADER_SOURCE,i.FRAGMENT_SHADER_SOURCE,null),this.pickProgram=n?this.getProgramInfo("pick",t,Vp+i.VERTEX_SHADER_SOURCE,Vp+i.FRAGMENT_SHADER_SOURCE,n):null,this.isInstanced){var o=$u(this.CONSTANT_ATTRIBUTES);if(this.CONSTANT_DATA.length!==this.VERTICES)throw new Error("Program: error while getting constant data (expected ".concat(this.VERTICES," items, received ").concat(this.CONSTANT_DATA.length," instead)"));this.constantArray=new Float32Array(this.CONSTANT_DATA.length*o);for(var s=0;s<this.CONSTANT_DATA.length;s++){var a=this.CONSTANT_DATA[s];if(a.length!==o)throw new Error("Program: error while getting constant data (one vector has ".concat(a.length," items instead of ").concat(o,")"));for(var u=0;u<a.length;u++)this.constantArray[s*o+u]=a[u]}this.STRIDE=this.ATTRIBUTES_ITEMS_COUNT}}return pt(e,[{key:"kill",value:function(){Bp(this.normalProgram),this.pickProgram&&(Bp(this.pickProgram),this.pickProgram=null)}},{key:"getProgramInfo",value:function(n,r,i,o,s){var a=this.getDefinition(),u=r.createBuffer();if(u===null)throw new Error("Program: error while creating the WebGL buffer.");var c=YI(r,i),l=XI(r,o),d=QI(r,[c,l]),f={};a.UNIFORMS.forEach(function(m){var y=r.getUniformLocation(d,m);y&&(f[m]=y)});var h={};a.ATTRIBUTES.forEach(function(m){h[m.name]=r.getAttribLocation(d,m.name)});var p;if("CONSTANT_ATTRIBUTES"in a&&(a.CONSTANT_ATTRIBUTES.forEach(function(m){h[m.name]=r.getAttribLocation(d,m.name)}),p=r.createBuffer(),p===null))throw new Error("Program: error while creating the WebGL constant buffer.");return{name:n,program:d,gl:r,frameBuffer:s,buffer:u,constantBuffer:p||{},uniformLocations:f,attributeLocations:h,isPicking:n==="pick",vertexShader:c,fragmentShader:l}}},{key:"bindProgram",value:function(n){var r=this,i=0,o=n.gl,s=n.buffer;this.isInstanced?(o.bindBuffer(o.ARRAY_BUFFER,n.constantBuffer),i=0,this.CONSTANT_ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i,!1)}),o.bufferData(o.ARRAY_BUFFER,this.constantArray,o.STATIC_DRAW),o.bindBuffer(o.ARRAY_BUFFER,n.buffer),i=0,this.ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i,!0)}),o.bufferData(o.ARRAY_BUFFER,this.array,o.DYNAMIC_DRAW)):(o.bindBuffer(o.ARRAY_BUFFER,s),i=0,this.ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i)}),o.bufferData(o.ARRAY_BUFFER,this.array,o.DYNAMIC_DRAW)),o.bindBuffer(o.ARRAY_BUFFER,null)}},{key:"unbindProgram",value:function(n){var r=this;this.isInstanced?(this.CONSTANT_ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n,!1)}),this.ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n,!0)})):this.ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n)})}},{key:"bindAttribute",value:function(n,r,i,o){var s=eN[n.type];if(typeof s!="number")throw new Error('Program.bind: yet unsupported attribute type "'.concat(n.type,'"'));var a=r.attributeLocations[n.name],u=r.gl;if(a!==-1){u.enableVertexAttribArray(a);var c=this.isInstanced?(o?this.ATTRIBUTES_ITEMS_COUNT:$u(this.CONSTANT_ATTRIBUTES))*Float32Array.BYTES_PER_ELEMENT:this.ATTRIBUTES_ITEMS_COUNT*Float32Array.BYTES_PER_ELEMENT;if(u.vertexAttribPointer(a,n.size,n.type,n.normalized||!1,c,i),this.isInstanced&&o)if(u instanceof WebGL2RenderingContext)u.vertexAttribDivisor(a,1);else{var l=u.getExtension("ANGLE_instanced_arrays");l&&l.vertexAttribDivisorANGLE(a,1)}}return n.size*s}},{key:"unbindAttribute",value:function(n,r,i){var o=r.attributeLocations[n.name],s=r.gl;if(o!==-1&&(s.disableVertexAttribArray(o),this.isInstanced&&i))if(s instanceof WebGL2RenderingContext)s.vertexAttribDivisor(o,0);else{var a=s.getExtension("ANGLE_instanced_arrays");a&&a.vertexAttribDivisorANGLE(o,0)}}},{key:"reallocate",value:function(n){n!==this.capacity&&(this.capacity=n,this.verticesCount=this.VERTICES*n,this.array=new Float32Array(this.isInstanced?this.capacity*this.ATTRIBUTES_ITEMS_COUNT:this.verticesCount*this.ATTRIBUTES_ITEMS_COUNT))}},{key:"hasNothingToRender",value:function(){return this.verticesCount===0}},{key:"renderProgram",value:function(n,r){var i=r.gl,o=r.program;i.enable(i.BLEND),i.useProgram(o),this.setUniforms(n,r),this.drawWebGL(this.METHOD,r)}},{key:"render",value:function(n){this.hasNothingToRender()||(this.pickProgram&&(this.pickProgram.gl.viewport(0,0,n.width*n.pixelRatio/n.downSizingRatio,n.height*n.pixelRatio/n.downSizingRatio),this.bindProgram(this.pickProgram),this.renderProgram(te(te({},n),{},{pixelRatio:n.pixelRatio/n.downSizingRatio}),this.pickProgram),this.unbindProgram(this.pickProgram)),this.normalProgram.gl.viewport(0,0,n.width*n.pixelRatio,n.height*n.pixelRatio),this.bindProgram(this.normalProgram),this.renderProgram(n,this.normalProgram),this.unbindProgram(this.normalProgram))}},{key:"drawWebGL",value:function(n,r){var i=r.gl,o=r.frameBuffer;if(i.bindFramebuffer(i.FRAMEBUFFER,o),!this.isInstanced)i.drawArrays(n,0,this.verticesCount);else if(i instanceof WebGL2RenderingContext)i.drawArraysInstanced(n,0,this.VERTICES,this.capacity);else{var s=i.getExtension("ANGLE_instanced_arrays");s&&s.drawArraysInstancedANGLE(n,0,this.VERTICES,this.capacity)}}}])})(),D_=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"kill",value:function(){L_(t,"kill",this)([])}},{key:"process",value:function(r,i,o){var s=i*this.STRIDE;if(o.hidden){for(var a=s+this.STRIDE;s<a;s++)this.array[s]=0;return}return this.processVisibleItem(R_(r),s,o)}}])})(P_),Xa=(function(e){function t(){var n;ht(this,t);for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return n=Gt(this,t,[].concat(i)),O(n,"drawLabel",void 0),n}return jt(t,e),pt(t,[{key:"kill",value:function(){L_(t,"kill",this)([])}},{key:"process",value:function(r,i,o,s,a){var u=i*this.STRIDE;if(a.hidden||o.hidden||s.hidden){for(var c=u+this.STRIDE;u<c;u++)this.array[u]=0;return}return this.processVisibleItem(R_(r),u,o,s,a)}}])})(P_);function tN(e,t){return(function(){function n(r,i,o){ht(this,n),O(this,"drawLabel",t),this.programs=e.map(function(s){return new s(r,i,o)})}return pt(n,[{key:"reallocate",value:function(i){this.programs.forEach(function(o){return o.reallocate(i)})}},{key:"process",value:function(i,o,s,a,u){this.programs.forEach(function(c){return c.process(i,o,s,a,u)})}},{key:"render",value:function(i){this.programs.forEach(function(o){return o.render(i)})}},{key:"kill",value:function(){this.programs.forEach(function(i){return i.kill()})}}])})()}function nN(e,t,n,r,i){var o=i.edgeLabelSize,s=i.edgeLabelFont,a=i.edgeLabelWeight,u=i.edgeLabelColor.attribute?t[i.edgeLabelColor.attribute]||i.edgeLabelColor.color||"#000":i.edgeLabelColor.color,c=t.label;if(c){e.fillStyle=u,e.font="".concat(a," ").concat(o,"px ").concat(s);var l=n.size,d=r.size,f=n.x,h=n.y,p=r.x,m=r.y,y=(f+p)/2,w=(h+m)/2,g=p-f,b=m-h,v=Math.sqrt(g*g+b*b);if(!(v<l+d)){f+=g*l/v,h+=b*l/v,p-=g*d/v,m-=b*d/v,y=(f+p)/2,w=(h+m)/2,g=p-f,b=m-h,v=Math.sqrt(g*g+b*b);var k=e.measureText(c).width;if(k>v){var S="…";for(c=c+S,k=e.measureText(c).width;k>v&&c.length>1;)c=c.slice(0,-2)+S,k=e.measureText(c).width;if(c.length<4)return}var _;g>0?b>0?_=Math.acos(g/v):_=Math.asin(b/v):b>0?_=Math.acos(g/v)+Math.PI:_=Math.asin(g/v)+Math.PI/2,e.save(),e.translate(y,w),e.rotate(_),e.fillText(c,-k/2,t.size/2+o),e.restore()}}}function O_(e,t,n){if(t.label){var r=n.labelSize,i=n.labelFont,o=n.labelWeight,s=n.labelColor.attribute?t[n.labelColor.attribute]||n.labelColor.color||"#000":n.labelColor.color;e.fillStyle=s,e.font="".concat(o," ").concat(r,"px ").concat(i),e.fillText(t.label,t.x+t.size+3,t.y+r/3)}}function rN(e,t,n){var r=n.labelSize,i=n.labelFont,o=n.labelWeight;e.font="".concat(o," ").concat(r,"px ").concat(i),e.fillStyle="#FFF",e.shadowOffsetX=0,e.shadowOffsetY=0,e.shadowBlur=8,e.shadowColor="#000";var s=2;if(typeof t.label=="string"){var a=e.measureText(t.label).width,u=Math.round(a+5),c=Math.round(r+2*s),l=Math.max(t.size,r/2)+s,d=Math.asin(c/2/l),f=Math.sqrt(Math.abs(Math.pow(l,2)-Math.pow(c/2,2)));e.beginPath(),e.moveTo(t.x+f,t.y+c/2),e.lineTo(t.x+l+u,t.y+c/2),e.lineTo(t.x+l+u,t.y-c/2),e.lineTo(t.x+f,t.y-c/2),e.arc(t.x,t.y,l,d,-d),e.closePath(),e.fill()}else e.beginPath(),e.arc(t.x,t.y,t.size+s,0,Math.PI*2),e.closePath(),e.fill();e.shadowOffsetX=0,e.shadowOffsetY=0,e.shadowBlur=0,O_(e,t,n)}var iN=`
113
+ `).concat(n))}return i}function eN(e,t){return O_("VERTEX",e,t)}function tN(e,t){return O_("FRAGMENT",e,t)}function nN(e,t){var n=e.createProgram();if(n===null)throw new Error("loadProgram: error while creating the program.");var r,i;for(r=0,i=t.length;r<i;r++)e.attachShader(n,t[r]);e.linkProgram(n);var o=e.getProgramParameter(n,e.LINK_STATUS);if(!o){var s=e.getProgramInfoLog(n);throw e.deleteProgram(n),new Error("loadProgram: error while linking the program: ".concat(s))}return n}function Hp(e){var t=e.gl,n=e.buffer,r=e.program,i=e.vertexShader,o=e.fragmentShader;t.deleteShader(i),t.deleteShader(o),t.deleteProgram(r),t.deleteBuffer(n)}function qp(e){return e%1===0?e.toFixed(1):e.toString()}var Wp=`#define PICKING_MODE
114
+ `,rN=D(D(D(D(D(D(D(D({},WebGL2RenderingContext.BOOL,1),WebGL2RenderingContext.BYTE,1),WebGL2RenderingContext.UNSIGNED_BYTE,1),WebGL2RenderingContext.SHORT,2),WebGL2RenderingContext.UNSIGNED_SHORT,2),WebGL2RenderingContext.INT,4),WebGL2RenderingContext.UNSIGNED_INT,4),WebGL2RenderingContext.FLOAT,4),M_=(function(){function e(t,n,r){ht(this,e),D(this,"array",new Float32Array),D(this,"constantArray",new Float32Array),D(this,"capacity",0),D(this,"verticesCount",0);var i=this.getDefinition();if(this.VERTICES=i.VERTICES,this.VERTEX_SHADER_SOURCE=i.VERTEX_SHADER_SOURCE,this.FRAGMENT_SHADER_SOURCE=i.FRAGMENT_SHADER_SOURCE,this.UNIFORMS=i.UNIFORMS,this.ATTRIBUTES=i.ATTRIBUTES,this.METHOD=i.METHOD,this.CONSTANT_ATTRIBUTES="CONSTANT_ATTRIBUTES"in i?i.CONSTANT_ATTRIBUTES:[],this.CONSTANT_DATA="CONSTANT_DATA"in i?i.CONSTANT_DATA:[],this.isInstanced="CONSTANT_ATTRIBUTES"in i,this.ATTRIBUTES_ITEMS_COUNT=Tu(this.ATTRIBUTES),this.STRIDE=this.VERTICES*this.ATTRIBUTES_ITEMS_COUNT,this.renderer=r,this.normalProgram=this.getProgramInfo("normal",t,i.VERTEX_SHADER_SOURCE,i.FRAGMENT_SHADER_SOURCE,null),this.pickProgram=n?this.getProgramInfo("pick",t,Wp+i.VERTEX_SHADER_SOURCE,Wp+i.FRAGMENT_SHADER_SOURCE,n):null,this.isInstanced){var o=Tu(this.CONSTANT_ATTRIBUTES);if(this.CONSTANT_DATA.length!==this.VERTICES)throw new Error("Program: error while getting constant data (expected ".concat(this.VERTICES," items, received ").concat(this.CONSTANT_DATA.length," instead)"));this.constantArray=new Float32Array(this.CONSTANT_DATA.length*o);for(var s=0;s<this.CONSTANT_DATA.length;s++){var a=this.CONSTANT_DATA[s];if(a.length!==o)throw new Error("Program: error while getting constant data (one vector has ".concat(a.length," items instead of ").concat(o,")"));for(var u=0;u<a.length;u++)this.constantArray[s*o+u]=a[u]}this.STRIDE=this.ATTRIBUTES_ITEMS_COUNT}}return pt(e,[{key:"kill",value:function(){Hp(this.normalProgram),this.pickProgram&&(Hp(this.pickProgram),this.pickProgram=null)}},{key:"getProgramInfo",value:function(n,r,i,o,s){var a=this.getDefinition(),u=r.createBuffer();if(u===null)throw new Error("Program: error while creating the WebGL buffer.");var c=eN(r,i),l=tN(r,o),d=nN(r,[c,l]),f={};a.UNIFORMS.forEach(function(m){var y=r.getUniformLocation(d,m);y&&(f[m]=y)});var h={};a.ATTRIBUTES.forEach(function(m){h[m.name]=r.getAttribLocation(d,m.name)});var p;if("CONSTANT_ATTRIBUTES"in a&&(a.CONSTANT_ATTRIBUTES.forEach(function(m){h[m.name]=r.getAttribLocation(d,m.name)}),p=r.createBuffer(),p===null))throw new Error("Program: error while creating the WebGL constant buffer.");return{name:n,program:d,gl:r,frameBuffer:s,buffer:u,constantBuffer:p||{},uniformLocations:f,attributeLocations:h,isPicking:n==="pick",vertexShader:c,fragmentShader:l}}},{key:"bindProgram",value:function(n){var r=this,i=0,o=n.gl,s=n.buffer;this.isInstanced?(o.bindBuffer(o.ARRAY_BUFFER,n.constantBuffer),i=0,this.CONSTANT_ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i,!1)}),o.bufferData(o.ARRAY_BUFFER,this.constantArray,o.STATIC_DRAW),o.bindBuffer(o.ARRAY_BUFFER,n.buffer),i=0,this.ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i,!0)}),o.bufferData(o.ARRAY_BUFFER,this.array,o.DYNAMIC_DRAW)):(o.bindBuffer(o.ARRAY_BUFFER,s),i=0,this.ATTRIBUTES.forEach(function(a){return i+=r.bindAttribute(a,n,i)}),o.bufferData(o.ARRAY_BUFFER,this.array,o.DYNAMIC_DRAW)),o.bindBuffer(o.ARRAY_BUFFER,null)}},{key:"unbindProgram",value:function(n){var r=this;this.isInstanced?(this.CONSTANT_ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n,!1)}),this.ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n,!0)})):this.ATTRIBUTES.forEach(function(i){return r.unbindAttribute(i,n)})}},{key:"bindAttribute",value:function(n,r,i,o){var s=rN[n.type];if(typeof s!="number")throw new Error('Program.bind: yet unsupported attribute type "'.concat(n.type,'"'));var a=r.attributeLocations[n.name],u=r.gl;if(a!==-1){u.enableVertexAttribArray(a);var c=this.isInstanced?(o?this.ATTRIBUTES_ITEMS_COUNT:Tu(this.CONSTANT_ATTRIBUTES))*Float32Array.BYTES_PER_ELEMENT:this.ATTRIBUTES_ITEMS_COUNT*Float32Array.BYTES_PER_ELEMENT;if(u.vertexAttribPointer(a,n.size,n.type,n.normalized||!1,c,i),this.isInstanced&&o)if(u instanceof WebGL2RenderingContext)u.vertexAttribDivisor(a,1);else{var l=u.getExtension("ANGLE_instanced_arrays");l&&l.vertexAttribDivisorANGLE(a,1)}}return n.size*s}},{key:"unbindAttribute",value:function(n,r,i){var o=r.attributeLocations[n.name],s=r.gl;if(o!==-1&&(s.disableVertexAttribArray(o),this.isInstanced&&i))if(s instanceof WebGL2RenderingContext)s.vertexAttribDivisor(o,0);else{var a=s.getExtension("ANGLE_instanced_arrays");a&&a.vertexAttribDivisorANGLE(o,0)}}},{key:"reallocate",value:function(n){n!==this.capacity&&(this.capacity=n,this.verticesCount=this.VERTICES*n,this.array=new Float32Array(this.isInstanced?this.capacity*this.ATTRIBUTES_ITEMS_COUNT:this.verticesCount*this.ATTRIBUTES_ITEMS_COUNT))}},{key:"hasNothingToRender",value:function(){return this.verticesCount===0}},{key:"renderProgram",value:function(n,r){var i=r.gl,o=r.program;i.enable(i.BLEND),i.useProgram(o),this.setUniforms(n,r),this.drawWebGL(this.METHOD,r)}},{key:"render",value:function(n){this.hasNothingToRender()||(this.pickProgram&&(this.pickProgram.gl.viewport(0,0,n.width*n.pixelRatio/n.downSizingRatio,n.height*n.pixelRatio/n.downSizingRatio),this.bindProgram(this.pickProgram),this.renderProgram(Q(Q({},n),{},{pixelRatio:n.pixelRatio/n.downSizingRatio}),this.pickProgram),this.unbindProgram(this.pickProgram)),this.normalProgram.gl.viewport(0,0,n.width*n.pixelRatio,n.height*n.pixelRatio),this.bindProgram(this.normalProgram),this.renderProgram(n,this.normalProgram),this.unbindProgram(this.normalProgram))}},{key:"drawWebGL",value:function(n,r){var i=r.gl,o=r.frameBuffer;if(i.bindFramebuffer(i.FRAMEBUFFER,o),!this.isInstanced)i.drawArrays(n,0,this.verticesCount);else if(i instanceof WebGL2RenderingContext)i.drawArraysInstanced(n,0,this.VERTICES,this.capacity);else{var s=i.getExtension("ANGLE_instanced_arrays");s&&s.drawArraysInstancedANGLE(n,0,this.VERTICES,this.capacity)}}}])})(),F_=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"kill",value:function(){D_(t,"kill",this)([])}},{key:"process",value:function(r,i,o){var s=i*this.STRIDE;if(o.hidden){for(var a=s+this.STRIDE;s<a;s++)this.array[s]=0;return}return this.processVisibleItem(P_(r),s,o)}}])})(M_),Qa=(function(e){function t(){var n;ht(this,t);for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return n=Gt(this,t,[].concat(i)),D(n,"drawLabel",void 0),n}return jt(t,e),pt(t,[{key:"kill",value:function(){D_(t,"kill",this)([])}},{key:"process",value:function(r,i,o,s,a){var u=i*this.STRIDE;if(a.hidden||o.hidden||s.hidden){for(var c=u+this.STRIDE;u<c;u++)this.array[u]=0;return}return this.processVisibleItem(P_(r),u,o,s,a)}}])})(M_);function iN(e,t){return(function(){function n(r,i,o){ht(this,n),D(this,"drawLabel",t),this.programs=e.map(function(s){return new s(r,i,o)})}return pt(n,[{key:"reallocate",value:function(i){this.programs.forEach(function(o){return o.reallocate(i)})}},{key:"process",value:function(i,o,s,a,u){this.programs.forEach(function(c){return c.process(i,o,s,a,u)})}},{key:"render",value:function(i){this.programs.forEach(function(o){return o.render(i)})}},{key:"kill",value:function(){this.programs.forEach(function(i){return i.kill()})}}])})()}function oN(e,t,n,r,i){var o=i.edgeLabelSize,s=i.edgeLabelFont,a=i.edgeLabelWeight,u=i.edgeLabelColor.attribute?t[i.edgeLabelColor.attribute]||i.edgeLabelColor.color||"#000":i.edgeLabelColor.color,c=t.label;if(c){e.fillStyle=u,e.font="".concat(a," ").concat(o,"px ").concat(s);var l=n.size,d=r.size,f=n.x,h=n.y,p=r.x,m=r.y,y=(f+p)/2,_=(h+m)/2,g=p-f,b=m-h,v=Math.sqrt(g*g+b*b);if(!(v<l+d)){f+=g*l/v,h+=b*l/v,p-=g*d/v,m-=b*d/v,y=(f+p)/2,_=(h+m)/2,g=p-f,b=m-h,v=Math.sqrt(g*g+b*b);var w=e.measureText(c).width;if(w>v){var k="…";for(c=c+k,w=e.measureText(c).width;w>v&&c.length>1;)c=c.slice(0,-2)+k,w=e.measureText(c).width;if(c.length<4)return}var x;g>0?b>0?x=Math.acos(g/v):x=Math.asin(b/v):b>0?x=Math.acos(g/v)+Math.PI:x=Math.asin(g/v)+Math.PI/2,e.save(),e.translate(y,_),e.rotate(x),e.fillText(c,-w/2,t.size/2+o),e.restore()}}}function U_(e,t,n){if(t.label){var r=n.labelSize,i=n.labelFont,o=n.labelWeight,s=n.labelColor.attribute?t[n.labelColor.attribute]||n.labelColor.color||"#000":n.labelColor.color;e.fillStyle=s,e.font="".concat(o," ").concat(r,"px ").concat(i),e.fillText(t.label,t.x+t.size+3,t.y+r/3)}}function sN(e,t,n){var r=n.labelSize,i=n.labelFont,o=n.labelWeight;e.font="".concat(o," ").concat(r,"px ").concat(i),e.fillStyle="#FFF",e.shadowOffsetX=0,e.shadowOffsetY=0,e.shadowBlur=8,e.shadowColor="#000";var s=2;if(typeof t.label=="string"){var a=e.measureText(t.label).width,u=Math.round(a+5),c=Math.round(r+2*s),l=Math.max(t.size,r/2)+s,d=Math.asin(c/2/l),f=Math.sqrt(Math.abs(Math.pow(l,2)-Math.pow(c/2,2)));e.beginPath(),e.moveTo(t.x+f,t.y+c/2),e.lineTo(t.x+l+u,t.y+c/2),e.lineTo(t.x+l+u,t.y-c/2),e.lineTo(t.x+f,t.y-c/2),e.arc(t.x,t.y,l,d,-d),e.closePath(),e.fill()}else e.beginPath(),e.arc(t.x,t.y,t.size+s,0,Math.PI*2),e.closePath(),e.fill();e.shadowOffsetX=0,e.shadowOffsetY=0,e.shadowBlur=0,U_(e,t,n)}var aN=`
115
115
  precision highp float;
116
116
 
117
117
  varying vec4 v_color;
@@ -143,7 +143,7 @@ void main(void) {
143
143
  gl_FragColor = mix(v_color, transparent, t);
144
144
  #endif
145
145
  }
146
- `,oN=iN,sN=`
146
+ `,uN=aN,cN=`
147
147
  attribute vec4 a_id;
148
148
  attribute vec4 a_color;
149
149
  attribute vec2 a_position;
@@ -184,7 +184,7 @@ void main() {
184
184
 
185
185
  v_color.a *= bias;
186
186
  }
187
- `,aN=sN,M_=WebGLRenderingContext,qp=M_.UNSIGNED_BYTE,Tu=M_.FLOAT,uN=["u_sizeRatio","u_correctionRatio","u_matrix"],Qa=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:aN,FRAGMENT_SHADER_SOURCE:oN,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:uN,ATTRIBUTES:[{name:"a_position",size:2,type:Tu},{name:"a_size",size:1,type:Tu},{name:"a_color",size:4,type:qp,normalized:!0},{name:"a_id",size:4,type:qp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_angle",size:1,type:Tu}],CONSTANT_DATA:[[t.ANGLE_1],[t.ANGLE_2],[t.ANGLE_3]]}}},{key:"processVisibleItem",value:function(r,i,o){var s=this.array,a=zn(o.color);s[i++]=o.x,s[i++]=o.y,s[i++]=o.size,s[i++]=a,s[i++]=r}},{key:"setUniforms",value:function(r,i){var o=i.gl,s=i.uniformLocations,a=s.u_sizeRatio,u=s.u_correctionRatio,c=s.u_matrix;o.uniform1f(u,r.correctionRatio),o.uniform1f(a,r.sizeRatio),o.uniformMatrix3fv(c,!1,r.matrix)}}])})(D_);O(Qa,"ANGLE_1",0);O(Qa,"ANGLE_2",2*Math.PI/3);O(Qa,"ANGLE_3",4*Math.PI/3);var cN=`
187
+ `,lN=cN,G_=WebGLRenderingContext,Kp=G_.UNSIGNED_BYTE,Cu=G_.FLOAT,dN=["u_sizeRatio","u_correctionRatio","u_matrix"],eu=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:lN,FRAGMENT_SHADER_SOURCE:uN,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:dN,ATTRIBUTES:[{name:"a_position",size:2,type:Cu},{name:"a_size",size:1,type:Cu},{name:"a_color",size:4,type:Kp,normalized:!0},{name:"a_id",size:4,type:Kp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_angle",size:1,type:Cu}],CONSTANT_DATA:[[t.ANGLE_1],[t.ANGLE_2],[t.ANGLE_3]]}}},{key:"processVisibleItem",value:function(r,i,o){var s=this.array,a=Pn(o.color);s[i++]=o.x,s[i++]=o.y,s[i++]=o.size,s[i++]=a,s[i++]=r}},{key:"setUniforms",value:function(r,i){var o=i.gl,s=i.uniformLocations,a=s.u_sizeRatio,u=s.u_correctionRatio,c=s.u_matrix;o.uniform1f(u,r.correctionRatio),o.uniform1f(a,r.sizeRatio),o.uniformMatrix3fv(c,!1,r.matrix)}}])})(F_);D(eu,"ANGLE_1",0);D(eu,"ANGLE_2",2*Math.PI/3);D(eu,"ANGLE_3",4*Math.PI/3);var fN=`
188
188
  precision mediump float;
189
189
 
190
190
  varying vec4 v_color;
@@ -192,7 +192,7 @@ varying vec4 v_color;
192
192
  void main(void) {
193
193
  gl_FragColor = v_color;
194
194
  }
195
- `,lN=cN,dN=`
195
+ `,hN=fN,pN=`
196
196
  attribute vec2 a_position;
197
197
  attribute vec2 a_normal;
198
198
  attribute float a_radius;
@@ -258,7 +258,7 @@ void main() {
258
258
 
259
259
  v_color.a *= bias;
260
260
  }
261
- `,fN=dN,F_=WebGLRenderingContext,Wp=F_.UNSIGNED_BYTE,Wo=F_.FLOAT,hN=["u_matrix","u_sizeRatio","u_correctionRatio","u_minEdgeThickness","u_lengthToThicknessRatio","u_widenessToThicknessRatio"],eu={extremity:"target",lengthToThicknessRatio:2.5,widenessToThicknessRatio:2};function U_(e){var t=te(te({},eu),e||{});return(function(n){function r(){return ht(this,r),Gt(this,r,arguments)}return jt(r,n),pt(r,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:fN,FRAGMENT_SHADER_SOURCE:lN,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:hN,ATTRIBUTES:[{name:"a_position",size:2,type:Wo},{name:"a_normal",size:2,type:Wo},{name:"a_radius",size:1,type:Wo},{name:"a_color",size:4,type:Wp,normalized:!0},{name:"a_id",size:4,type:Wp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_barycentric",size:3,type:Wo}],CONSTANT_DATA:[[1,0,0],[0,1,0],[0,0,1]]}}},{key:"processVisibleItem",value:function(o,s,a,u,c){if(t.extremity==="source"){var l=[u,a];a=l[0],u=l[1]}var d=c.size||1,f=u.size||1,h=a.x,p=a.y,m=u.x,y=u.y,w=zn(c.color),g=m-h,b=y-p,v=g*g+b*b,k=0,S=0;v&&(v=1/Math.sqrt(v),k=-b*v*d,S=g*v*d);var _=this.array;_[s++]=m,_[s++]=y,_[s++]=-k,_[s++]=-S,_[s++]=f,_[s++]=w,_[s++]=o}},{key:"setUniforms",value:function(o,s){var a=s.gl,u=s.uniformLocations,c=u.u_matrix,l=u.u_sizeRatio,d=u.u_correctionRatio,f=u.u_minEdgeThickness,h=u.u_lengthToThicknessRatio,p=u.u_widenessToThicknessRatio;a.uniformMatrix3fv(c,!1,o.matrix),a.uniform1f(l,o.sizeRatio),a.uniform1f(d,o.correctionRatio),a.uniform1f(f,o.minEdgeThickness),a.uniform1f(h,t.lengthToThicknessRatio),a.uniform1f(p,t.widenessToThicknessRatio)}}])})(Xa)}U_();var pN=`
261
+ `,mN=pN,j_=WebGLRenderingContext,Jp=j_.UNSIGNED_BYTE,Jo=j_.FLOAT,gN=["u_matrix","u_sizeRatio","u_correctionRatio","u_minEdgeThickness","u_lengthToThicknessRatio","u_widenessToThicknessRatio"],tu={extremity:"target",lengthToThicknessRatio:2.5,widenessToThicknessRatio:2};function Z_(e){var t=Q(Q({},tu),e||{});return(function(n){function r(){return ht(this,r),Gt(this,r,arguments)}return jt(r,n),pt(r,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:mN,FRAGMENT_SHADER_SOURCE:hN,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:gN,ATTRIBUTES:[{name:"a_position",size:2,type:Jo},{name:"a_normal",size:2,type:Jo},{name:"a_radius",size:1,type:Jo},{name:"a_color",size:4,type:Jp,normalized:!0},{name:"a_id",size:4,type:Jp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_barycentric",size:3,type:Jo}],CONSTANT_DATA:[[1,0,0],[0,1,0],[0,0,1]]}}},{key:"processVisibleItem",value:function(o,s,a,u,c){if(t.extremity==="source"){var l=[u,a];a=l[0],u=l[1]}var d=c.size||1,f=u.size||1,h=a.x,p=a.y,m=u.x,y=u.y,_=Pn(c.color),g=m-h,b=y-p,v=g*g+b*b,w=0,k=0;v&&(v=1/Math.sqrt(v),w=-b*v*d,k=g*v*d);var x=this.array;x[s++]=m,x[s++]=y,x[s++]=-w,x[s++]=-k,x[s++]=f,x[s++]=_,x[s++]=o}},{key:"setUniforms",value:function(o,s){var a=s.gl,u=s.uniformLocations,c=u.u_matrix,l=u.u_sizeRatio,d=u.u_correctionRatio,f=u.u_minEdgeThickness,h=u.u_lengthToThicknessRatio,p=u.u_widenessToThicknessRatio;a.uniformMatrix3fv(c,!1,o.matrix),a.uniform1f(l,o.sizeRatio),a.uniform1f(d,o.correctionRatio),a.uniform1f(f,o.minEdgeThickness),a.uniform1f(h,t.lengthToThicknessRatio),a.uniform1f(p,t.widenessToThicknessRatio)}}])})(Qa)}Z_();var yN=`
262
262
  precision mediump float;
263
263
 
264
264
  varying vec4 v_color;
@@ -284,7 +284,7 @@ void main(void) {
284
284
  gl_FragColor = mix(v_color, transparent, t);
285
285
  #endif
286
286
  }
287
- `,G_=pN,mN=`
287
+ `,B_=yN,vN=`
288
288
  attribute vec4 a_id;
289
289
  attribute vec4 a_color;
290
290
  attribute vec2 a_normal;
@@ -352,7 +352,7 @@ void main() {
352
352
 
353
353
  v_color.a *= bias;
354
354
  }
355
- `,gN=mN,j_=WebGLRenderingContext,Kp=j_.UNSIGNED_BYTE,Fn=j_.FLOAT,yN=["u_matrix","u_zoomRatio","u_sizeRatio","u_correctionRatio","u_pixelRatio","u_feather","u_minEdgeThickness","u_lengthToThicknessRatio"],vN={lengthToThicknessRatio:eu.lengthToThicknessRatio};function Z_(e){var t=te(te({},vN),e||{});return(function(n){function r(){return ht(this,r),Gt(this,r,arguments)}return jt(r,n),pt(r,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:gN,FRAGMENT_SHADER_SOURCE:G_,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:yN,ATTRIBUTES:[{name:"a_positionStart",size:2,type:Fn},{name:"a_positionEnd",size:2,type:Fn},{name:"a_normal",size:2,type:Fn},{name:"a_color",size:4,type:Kp,normalized:!0},{name:"a_id",size:4,type:Kp,normalized:!0},{name:"a_radius",size:1,type:Fn}],CONSTANT_ATTRIBUTES:[{name:"a_positionCoef",size:1,type:Fn},{name:"a_normalCoef",size:1,type:Fn},{name:"a_radiusCoef",size:1,type:Fn}],CONSTANT_DATA:[[0,1,0],[0,-1,0],[1,1,1],[1,1,1],[0,-1,0],[1,-1,-1]]}}},{key:"processVisibleItem",value:function(o,s,a,u,c){var l=c.size||1,d=a.x,f=a.y,h=u.x,p=u.y,m=zn(c.color),y=h-d,w=p-f,g=u.size||1,b=y*y+w*w,v=0,k=0;b&&(b=1/Math.sqrt(b),v=-w*b*l,k=y*b*l);var S=this.array;S[s++]=d,S[s++]=f,S[s++]=h,S[s++]=p,S[s++]=v,S[s++]=k,S[s++]=m,S[s++]=o,S[s++]=g}},{key:"setUniforms",value:function(o,s){var a=s.gl,u=s.uniformLocations,c=u.u_matrix,l=u.u_zoomRatio,d=u.u_feather,f=u.u_pixelRatio,h=u.u_correctionRatio,p=u.u_sizeRatio,m=u.u_minEdgeThickness,y=u.u_lengthToThicknessRatio;a.uniformMatrix3fv(c,!1,o.matrix),a.uniform1f(l,o.zoomRatio),a.uniform1f(p,o.sizeRatio),a.uniform1f(h,o.correctionRatio),a.uniform1f(f,o.pixelRatio),a.uniform1f(d,o.antiAliasingFeather),a.uniform1f(m,o.minEdgeThickness),a.uniform1f(y,t.lengthToThicknessRatio)}}])})(Xa)}Z_();function B_(e){return tN([Z_(e),U_(e)])}var bN=B_(),wN=bN,_N=`
355
+ `,bN=vN,V_=WebGLRenderingContext,Yp=V_.UNSIGNED_BYTE,Un=V_.FLOAT,wN=["u_matrix","u_zoomRatio","u_sizeRatio","u_correctionRatio","u_pixelRatio","u_feather","u_minEdgeThickness","u_lengthToThicknessRatio"],_N={lengthToThicknessRatio:tu.lengthToThicknessRatio};function H_(e){var t=Q(Q({},_N),e||{});return(function(n){function r(){return ht(this,r),Gt(this,r,arguments)}return jt(r,n),pt(r,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:bN,FRAGMENT_SHADER_SOURCE:B_,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:wN,ATTRIBUTES:[{name:"a_positionStart",size:2,type:Un},{name:"a_positionEnd",size:2,type:Un},{name:"a_normal",size:2,type:Un},{name:"a_color",size:4,type:Yp,normalized:!0},{name:"a_id",size:4,type:Yp,normalized:!0},{name:"a_radius",size:1,type:Un}],CONSTANT_ATTRIBUTES:[{name:"a_positionCoef",size:1,type:Un},{name:"a_normalCoef",size:1,type:Un},{name:"a_radiusCoef",size:1,type:Un}],CONSTANT_DATA:[[0,1,0],[0,-1,0],[1,1,1],[1,1,1],[0,-1,0],[1,-1,-1]]}}},{key:"processVisibleItem",value:function(o,s,a,u,c){var l=c.size||1,d=a.x,f=a.y,h=u.x,p=u.y,m=Pn(c.color),y=h-d,_=p-f,g=u.size||1,b=y*y+_*_,v=0,w=0;b&&(b=1/Math.sqrt(b),v=-_*b*l,w=y*b*l);var k=this.array;k[s++]=d,k[s++]=f,k[s++]=h,k[s++]=p,k[s++]=v,k[s++]=w,k[s++]=m,k[s++]=o,k[s++]=g}},{key:"setUniforms",value:function(o,s){var a=s.gl,u=s.uniformLocations,c=u.u_matrix,l=u.u_zoomRatio,d=u.u_feather,f=u.u_pixelRatio,h=u.u_correctionRatio,p=u.u_sizeRatio,m=u.u_minEdgeThickness,y=u.u_lengthToThicknessRatio;a.uniformMatrix3fv(c,!1,o.matrix),a.uniform1f(l,o.zoomRatio),a.uniform1f(p,o.sizeRatio),a.uniform1f(h,o.correctionRatio),a.uniform1f(f,o.pixelRatio),a.uniform1f(d,o.antiAliasingFeather),a.uniform1f(m,o.minEdgeThickness),a.uniform1f(y,t.lengthToThicknessRatio)}}])})(Qa)}H_();function q_(e){return iN([H_(e),Z_(e)])}var kN=q_(),SN=kN,xN=`
356
356
  attribute vec4 a_id;
357
357
  attribute vec4 a_color;
358
358
  attribute vec2 a_normal;
@@ -417,9 +417,9 @@ void main() {
417
417
 
418
418
  v_color.a *= bias;
419
419
  }
420
- `,kN=_N,H_=WebGLRenderingContext,Jp=H_.UNSIGNED_BYTE,Qr=H_.FLOAT,SN=["u_matrix","u_zoomRatio","u_sizeRatio","u_correctionRatio","u_pixelRatio","u_feather","u_minEdgeThickness"],xN=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:kN,FRAGMENT_SHADER_SOURCE:G_,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:SN,ATTRIBUTES:[{name:"a_positionStart",size:2,type:Qr},{name:"a_positionEnd",size:2,type:Qr},{name:"a_normal",size:2,type:Qr},{name:"a_color",size:4,type:Jp,normalized:!0},{name:"a_id",size:4,type:Jp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_positionCoef",size:1,type:Qr},{name:"a_normalCoef",size:1,type:Qr}],CONSTANT_DATA:[[0,1],[0,-1],[1,1],[1,1],[0,-1],[1,-1]]}}},{key:"processVisibleItem",value:function(r,i,o,s,a){var u=a.size||1,c=o.x,l=o.y,d=s.x,f=s.y,h=zn(a.color),p=d-c,m=f-l,y=p*p+m*m,w=0,g=0;y&&(y=1/Math.sqrt(y),w=-m*y*u,g=p*y*u);var b=this.array;b[i++]=c,b[i++]=l,b[i++]=d,b[i++]=f,b[i++]=w,b[i++]=g,b[i++]=h,b[i++]=r}},{key:"setUniforms",value:function(r,i){var o=i.gl,s=i.uniformLocations,a=s.u_matrix,u=s.u_zoomRatio,c=s.u_feather,l=s.u_pixelRatio,d=s.u_correctionRatio,f=s.u_sizeRatio,h=s.u_minEdgeThickness;o.uniformMatrix3fv(a,!1,r.matrix),o.uniform1f(u,r.zoomRatio),o.uniform1f(f,r.sizeRatio),o.uniform1f(d,r.correctionRatio),o.uniform1f(l,r.pixelRatio),o.uniform1f(c,r.antiAliasingFeather),o.uniform1f(h,r.minEdgeThickness)}}])})(Xa),sh=(function(e){function t(){var n;return ht(this,t),n=Gt(this,t),n.rawEmitter=n,n}return jt(t,e),pt(t)})(f_.EventEmitter),Cu,Yp;function EN(){return Yp||(Yp=1,Cu=function(t){return t!==null&&typeof t=="object"&&typeof t.addUndirectedEdgeWithKey=="function"&&typeof t.dropNode=="function"&&typeof t.multi=="boolean"}),Cu}var $N=EN();const TN=R1($N);var CN=function(t){return t},AN=function(t){return t*t},IN=function(t){return t*(2-t)},NN=function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},RN=function(t){return t*t*t},LN=function(t){return--t*t*t+1},zN=function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},PN={linear:CN,quadraticIn:AN,quadraticOut:IN,quadraticInOut:NN,cubicIn:RN,cubicOut:LN,cubicInOut:zN},DN={easing:"quadraticInOut",duration:150};function Vt(){return Float32Array.of(1,0,0,0,1,0,0,0,1)}function Ko(e,t,n){return e[0]=t,e[4]=typeof n=="number"?n:t,e}function Xp(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[3]=-n,e[4]=r,e}function Qp(e,t,n){return e[6]=t,e[7]=n,e}function bn(e,t){var n=e[0],r=e[1],i=e[2],o=e[3],s=e[4],a=e[5],u=e[6],c=e[7],l=e[8],d=t[0],f=t[1],h=t[2],p=t[3],m=t[4],y=t[5],w=t[6],g=t[7],b=t[8];return e[0]=d*n+f*o+h*u,e[1]=d*r+f*s+h*c,e[2]=d*i+f*a+h*l,e[3]=p*n+m*o+y*u,e[4]=p*r+m*s+y*c,e[5]=p*i+m*a+y*l,e[6]=w*n+g*o+b*u,e[7]=w*r+g*s+b*c,e[8]=w*i+g*a+b*l,e}function pc(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=e[0],i=e[1],o=e[3],s=e[4],a=e[6],u=e[7],c=t.x,l=t.y;return{x:c*r+l*o+a*n,y:c*i+l*s+u*n}}function ON(e,t){var n=e.height/e.width,r=t.height/t.width;return n<1&&r>1||n>1&&r<1?1:Math.min(Math.max(r,1/r),Math.max(1/n,n))}function ei(e,t,n,r,i){var o=e.angle,s=e.ratio,a=e.x,u=e.y,c=t.width,l=t.height,d=Vt(),f=Math.min(c,l)-2*r,h=ON(t,n);return i?(bn(d,Qp(Vt(),a,u)),bn(d,Ko(Vt(),s)),bn(d,Xp(Vt(),o)),bn(d,Ko(Vt(),c/f/2/h,l/f/2/h))):(bn(d,Ko(Vt(),2*(f/c)*h,2*(f/l)*h)),bn(d,Xp(Vt(),-o)),bn(d,Ko(Vt(),1/s)),bn(d,Qp(Vt(),-a,-u))),d}function MN(e,t,n){var r=pc(e,{x:Math.cos(t.angle),y:Math.sin(t.angle)},0),i=r.x,o=r.y;return 1/Math.sqrt(Math.pow(i,2)+Math.pow(o,2))/n.width}function FN(e){if(!e.order)return{x:[0,1],y:[0,1]};var t=1/0,n=-1/0,r=1/0,i=-1/0;return e.forEachNode(function(o,s){var a=s.x,u=s.y;a<t&&(t=a),a>n&&(n=a),u<r&&(r=u),u>i&&(i=u)}),{x:[t,n],y:[r,i]}}function UN(e){if(!TN(e))throw new Error("Sigma: invalid graph instance.");e.forEachNode(function(t,n){if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw new Error("Sigma: Coordinates of node ".concat(t," are invalid. A node must have a numeric 'x' and 'y' attribute."))})}function GN(e,t,n){var r=document.createElement(e);if(t)for(var i in t)r.style[i]=t[i];if(n)for(var o in n)r.setAttribute(o,n[o]);return r}function em(){return typeof window.devicePixelRatio<"u"?window.devicePixelRatio:1}function tm(e,t,n){return n.sort(function(r,i){var o=t(r)||0,s=t(i)||0;return o<s?-1:o>s?1:0})}function nm(e){var t=_r(e.x,2),n=t[0],r=t[1],i=_r(e.y,2),o=i[0],s=i[1],a=Math.max(r-n,s-o),u=(r+n)/2,c=(s+o)/2;(a===0||Math.abs(a)===1/0||isNaN(a))&&(a=1),isNaN(u)&&(u=0),isNaN(c)&&(c=0);var l=function(f){return{x:.5+(f.x-u)/a,y:.5+(f.y-c)/a}};return l.applyTo=function(d){d.x=.5+(d.x-u)/a,d.y=.5+(d.y-c)/a},l.inverse=function(d){return{x:u+a*(d.x-.5),y:c+a*(d.y-.5)}},l.ratio=a,l}function mc(e){"@babel/helpers - typeof";return mc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mc(e)}function rm(e,t){var n=t.size;if(n!==0){var r=e.length;e.length+=n;var i=0;t.forEach(function(o){e[r+i]=o,i++})}}function Au(e){e=e||{};for(var t=0,n=arguments.length<=1?0:arguments.length-1;t<n;t++){var r=t+1<1||arguments.length<=t+1?void 0:arguments[t+1];r&&Object.assign(e,r)}return e}var ah={hideEdgesOnMove:!1,hideLabelsOnMove:!1,renderLabels:!0,renderEdgeLabels:!1,enableEdgeEvents:!1,defaultNodeColor:"#999",defaultNodeType:"circle",defaultEdgeColor:"#ccc",defaultEdgeType:"line",labelFont:"Arial",labelSize:14,labelWeight:"normal",labelColor:{color:"#000"},edgeLabelFont:"Arial",edgeLabelSize:14,edgeLabelWeight:"normal",edgeLabelColor:{attribute:"color"},stagePadding:30,defaultDrawEdgeLabel:nN,defaultDrawNodeLabel:O_,defaultDrawNodeHover:rN,minEdgeThickness:1.7,antiAliasingFeather:1,dragTimeout:100,draggedEventsTolerance:3,inertiaDuration:200,inertiaRatio:3,zoomDuration:250,zoomingRatio:1.7,doubleClickTimeout:300,doubleClickZoomingRatio:2.2,doubleClickZoomingDuration:200,tapMoveTolerance:10,zoomToSizeRatioFunction:Math.sqrt,itemSizesReference:"screen",autoRescale:!0,autoCenter:!0,labelDensity:1,labelGridCellSize:100,labelRenderedSizeThreshold:6,nodeReducer:null,edgeReducer:null,zIndex:!1,minCameraRatio:null,maxCameraRatio:null,enableCameraZooming:!0,enableCameraPanning:!0,enableCameraRotation:!0,cameraPanBoundaries:null,allowInvalidContainer:!1,nodeProgramClasses:{},nodeHoverProgramClasses:{},edgeProgramClasses:{}},jN={circle:Qa},ZN={arrow:wN,line:xN};function Iu(e){if(typeof e.labelDensity!="number"||e.labelDensity<0)throw new Error("Settings: invalid `labelDensity`. Expecting a positive number.");var t=e.minCameraRatio,n=e.maxCameraRatio;if(typeof t=="number"&&typeof n=="number"&&n<t)throw new Error("Settings: invalid camera ratio boundaries. Expecting `maxCameraRatio` to be greater than `minCameraRatio`.")}function BN(e){var t=Au({},ah,e);return t.nodeProgramClasses=Au({},jN,t.nodeProgramClasses),t.edgeProgramClasses=Au({},ZN,t.edgeProgramClasses),t}var Jo=1.5,im=(function(e){function t(){var n;return ht(this,t),n=Gt(this,t),O(n,"x",.5),O(n,"y",.5),O(n,"angle",0),O(n,"ratio",1),O(n,"minRatio",null),O(n,"maxRatio",null),O(n,"enabledZooming",!0),O(n,"enabledPanning",!0),O(n,"enabledRotation",!0),O(n,"clean",null),O(n,"nextFrame",null),O(n,"previousState",null),O(n,"enabled",!0),n.previousState=n.getState(),n}return jt(t,e),pt(t,[{key:"enable",value:function(){return this.enabled=!0,this}},{key:"disable",value:function(){return this.enabled=!1,this}},{key:"getState",value:function(){return{x:this.x,y:this.y,angle:this.angle,ratio:this.ratio}}},{key:"hasState",value:function(r){return this.x===r.x&&this.y===r.y&&this.ratio===r.ratio&&this.angle===r.angle}},{key:"getPreviousState",value:function(){var r=this.previousState;return r?{x:r.x,y:r.y,angle:r.angle,ratio:r.ratio}:null}},{key:"getBoundedRatio",value:function(r){var i=r;return typeof this.minRatio=="number"&&(i=Math.max(i,this.minRatio)),typeof this.maxRatio=="number"&&(i=Math.min(i,this.maxRatio)),i}},{key:"validateState",value:function(r){var i={};return this.enabledPanning&&typeof r.x=="number"&&(i.x=r.x),this.enabledPanning&&typeof r.y=="number"&&(i.y=r.y),this.enabledZooming&&typeof r.ratio=="number"&&(i.ratio=this.getBoundedRatio(r.ratio)),this.enabledRotation&&typeof r.angle=="number"&&(i.angle=r.angle),this.clean?this.clean(te(te({},this.getState()),i)):i}},{key:"isAnimated",value:function(){return!!this.nextFrame}},{key:"setState",value:function(r){if(!this.enabled)return this;this.previousState=this.getState();var i=this.validateState(r);return typeof i.x=="number"&&(this.x=i.x),typeof i.y=="number"&&(this.y=i.y),typeof i.ratio=="number"&&(this.ratio=i.ratio),typeof i.angle=="number"&&(this.angle=i.angle),this.hasState(this.previousState)||this.emit("updated",this.getState()),this}},{key:"updateState",value:function(r){return this.setState(r(this.getState())),this}},{key:"animate",value:function(r){var i=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;if(!s)return new Promise(function(h){return i.animate(r,o,h)});if(this.enabled){var a=te(te({},DN),o),u=this.validateState(r),c=typeof a.easing=="function"?a.easing:PN[a.easing],l=Date.now(),d=this.getState(),f=function(){var p=(Date.now()-l)/a.duration;if(p>=1){i.nextFrame=null,i.setState(u),i.animationCallback&&(i.animationCallback.call(null),i.animationCallback=void 0);return}var m=c(p),y={};typeof u.x=="number"&&(y.x=d.x+(u.x-d.x)*m),typeof u.y=="number"&&(y.y=d.y+(u.y-d.y)*m),i.enabledRotation&&typeof u.angle=="number"&&(y.angle=d.angle+(u.angle-d.angle)*m),typeof u.ratio=="number"&&(y.ratio=d.ratio+(u.ratio-d.ratio)*m),i.setState(y),i.nextFrame=requestAnimationFrame(f)};this.nextFrame?(cancelAnimationFrame(this.nextFrame),this.animationCallback&&this.animationCallback.call(null),this.nextFrame=requestAnimationFrame(f)):f(),this.animationCallback=s}}},{key:"animatedZoom",value:function(r){return r?typeof r=="number"?this.animate({ratio:this.ratio/r}):this.animate({ratio:this.ratio/(r.factor||Jo)},r):this.animate({ratio:this.ratio/Jo})}},{key:"animatedUnzoom",value:function(r){return r?typeof r=="number"?this.animate({ratio:this.ratio*r}):this.animate({ratio:this.ratio*(r.factor||Jo)},r):this.animate({ratio:this.ratio*Jo})}},{key:"animatedReset",value:function(r){return this.animate({x:.5,y:.5,ratio:1,angle:0},r)}},{key:"copy",value:function(){return t.from(this.getState())}}],[{key:"from",value:function(r){var i=new t;return i.setState(r)}}])})(sh);function Wt(e,t){var n=t.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}function rn(e,t){var n=te(te({},Wt(e,t)),{},{sigmaDefaultPrevented:!1,preventSigmaDefault:function(){n.sigmaDefaultPrevented=!0},original:e});return n}function ti(e){var t="x"in e?e:te(te({},e.touches[0]||e.previousTouches[0]),{},{original:e.original,sigmaDefaultPrevented:e.sigmaDefaultPrevented,preventSigmaDefault:function(){e.sigmaDefaultPrevented=!0,t.sigmaDefaultPrevented=!0}});return t}function HN(e,t){return te(te({},rn(e,t)),{},{delta:V_(e)})}var VN=2;function is(e){for(var t=[],n=0,r=Math.min(e.length,VN);n<r;n++)t.push(e[n]);return t}function ni(e,t,n){var r={touches:is(e.touches).map(function(i){return Wt(i,n)}),previousTouches:t.map(function(i){return Wt(i,n)}),sigmaDefaultPrevented:!1,preventSigmaDefault:function(){r.sigmaDefaultPrevented=!0},original:e};return r}function V_(e){if(typeof e.deltaY<"u")return e.deltaY*-3/360;if(typeof e.detail<"u")return e.detail/-9;throw new Error("Captor: could not extract delta from event.")}var q_=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t),i.container=n,i.renderer=r,i}return jt(t,e),pt(t)})(sh),qN=["doubleClickTimeout","doubleClickZoomingDuration","doubleClickZoomingRatio","dragTimeout","draggedEventsTolerance","inertiaDuration","inertiaRatio","zoomDuration","zoomingRatio"],WN=qN.reduce(function(e,t){return te(te({},e),{},O({},t,ah[t]))},{}),KN=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t,[n,r]),O(i,"enabled",!0),O(i,"draggedEvents",0),O(i,"downStartTime",null),O(i,"lastMouseX",null),O(i,"lastMouseY",null),O(i,"isMouseDown",!1),O(i,"isMoving",!1),O(i,"movingTimeout",null),O(i,"startCameraState",null),O(i,"clicks",0),O(i,"doubleClickTimeout",null),O(i,"currentWheelDirection",0),O(i,"settings",WN),i.handleClick=i.handleClick.bind(i),i.handleRightClick=i.handleRightClick.bind(i),i.handleDown=i.handleDown.bind(i),i.handleUp=i.handleUp.bind(i),i.handleMove=i.handleMove.bind(i),i.handleWheel=i.handleWheel.bind(i),i.handleLeave=i.handleLeave.bind(i),i.handleEnter=i.handleEnter.bind(i),n.addEventListener("click",i.handleClick,{capture:!1}),n.addEventListener("contextmenu",i.handleRightClick,{capture:!1}),n.addEventListener("mousedown",i.handleDown,{capture:!1}),n.addEventListener("wheel",i.handleWheel,{capture:!1}),n.addEventListener("mouseleave",i.handleLeave,{capture:!1}),n.addEventListener("mouseenter",i.handleEnter,{capture:!1}),document.addEventListener("mousemove",i.handleMove,{capture:!1}),document.addEventListener("mouseup",i.handleUp,{capture:!1}),i}return jt(t,e),pt(t,[{key:"kill",value:function(){var r=this.container;r.removeEventListener("click",this.handleClick),r.removeEventListener("contextmenu",this.handleRightClick),r.removeEventListener("mousedown",this.handleDown),r.removeEventListener("wheel",this.handleWheel),r.removeEventListener("mouseleave",this.handleLeave),r.removeEventListener("mouseenter",this.handleEnter),document.removeEventListener("mousemove",this.handleMove),document.removeEventListener("mouseup",this.handleUp)}},{key:"handleClick",value:function(r){var i=this;if(this.enabled){if(this.clicks++,this.clicks===2)return this.clicks=0,typeof this.doubleClickTimeout=="number"&&(clearTimeout(this.doubleClickTimeout),this.doubleClickTimeout=null),this.handleDoubleClick(r);setTimeout(function(){i.clicks=0,i.doubleClickTimeout=null},this.settings.doubleClickTimeout),this.draggedEvents<this.settings.draggedEventsTolerance&&this.emit("click",rn(r,this.container))}}},{key:"handleRightClick",value:function(r){this.enabled&&this.emit("rightClick",rn(r,this.container))}},{key:"handleDoubleClick",value:function(r){if(this.enabled){r.preventDefault(),r.stopPropagation();var i=rn(r,this.container);if(this.emit("doubleClick",i),!i.sigmaDefaultPrevented){var o=this.renderer.getCamera(),s=o.getBoundedRatio(o.getState().ratio/this.settings.doubleClickZoomingRatio);o.animate(this.renderer.getViewportZoomedState(Wt(r,this.container),s),{easing:"quadraticInOut",duration:this.settings.doubleClickZoomingDuration})}}}},{key:"handleDown",value:function(r){if(this.enabled){if(r.button===0){this.startCameraState=this.renderer.getCamera().getState();var i=Wt(r,this.container),o=i.x,s=i.y;this.lastMouseX=o,this.lastMouseY=s,this.draggedEvents=0,this.downStartTime=Date.now(),this.isMouseDown=!0}this.emit("mousedown",rn(r,this.container))}}},{key:"handleUp",value:function(r){var i=this;if(!(!this.enabled||!this.isMouseDown)){var o=this.renderer.getCamera();this.isMouseDown=!1,typeof this.movingTimeout=="number"&&(clearTimeout(this.movingTimeout),this.movingTimeout=null);var s=Wt(r,this.container),a=s.x,u=s.y,c=o.getState(),l=o.getPreviousState()||{x:0,y:0};this.isMoving?o.animate({x:c.x+this.settings.inertiaRatio*(c.x-l.x),y:c.y+this.settings.inertiaRatio*(c.y-l.y)},{duration:this.settings.inertiaDuration,easing:"quadraticOut"}):(this.lastMouseX!==a||this.lastMouseY!==u)&&o.setState({x:c.x,y:c.y}),this.isMoving=!1,setTimeout(function(){var d=i.draggedEvents>0;i.draggedEvents=0,d&&i.renderer.getSetting("hideEdgesOnMove")&&i.renderer.refresh()},0),this.emit("mouseup",rn(r,this.container))}}},{key:"handleMove",value:function(r){var i=this;if(this.enabled){var o=rn(r,this.container);if(this.emit("mousemovebody",o),(r.target===this.container||r.composedPath()[0]===this.container)&&this.emit("mousemove",o),!o.sigmaDefaultPrevented&&this.isMouseDown){this.isMoving=!0,this.draggedEvents++,typeof this.movingTimeout=="number"&&clearTimeout(this.movingTimeout),this.movingTimeout=window.setTimeout(function(){i.movingTimeout=null,i.isMoving=!1},this.settings.dragTimeout);var s=this.renderer.getCamera(),a=Wt(r,this.container),u=a.x,c=a.y,l=this.renderer.viewportToFramedGraph({x:this.lastMouseX,y:this.lastMouseY}),d=this.renderer.viewportToFramedGraph({x:u,y:c}),f=l.x-d.x,h=l.y-d.y,p=s.getState(),m=p.x+f,y=p.y+h;s.setState({x:m,y}),this.lastMouseX=u,this.lastMouseY=c,r.preventDefault(),r.stopPropagation()}}}},{key:"handleLeave",value:function(r){this.emit("mouseleave",rn(r,this.container))}},{key:"handleEnter",value:function(r){this.emit("mouseenter",rn(r,this.container))}},{key:"handleWheel",value:function(r){var i=this,o=this.renderer.getCamera();if(!(!this.enabled||!o.enabledZooming)){var s=V_(r);if(s){var a=HN(r,this.container);if(this.emit("wheel",a),a.sigmaDefaultPrevented){r.preventDefault(),r.stopPropagation();return}var u=o.getState().ratio,c=s>0?1/this.settings.zoomingRatio:this.settings.zoomingRatio,l=o.getBoundedRatio(u*c),d=s>0?1:-1,f=Date.now();u!==l&&(r.preventDefault(),r.stopPropagation(),!(this.currentWheelDirection===d&&this.lastWheelTriggerTime&&f-this.lastWheelTriggerTime<this.settings.zoomDuration/5)&&(o.animate(this.renderer.getViewportZoomedState(Wt(r,this.container),l),{easing:"quadraticOut",duration:this.settings.zoomDuration},function(){i.currentWheelDirection=0}),this.currentWheelDirection=d,this.lastWheelTriggerTime=f))}}}},{key:"setSettings",value:function(r){this.settings=r}}])})(q_),JN=["dragTimeout","inertiaDuration","inertiaRatio","doubleClickTimeout","doubleClickZoomingRatio","doubleClickZoomingDuration","tapMoveTolerance"],YN=JN.reduce(function(e,t){return te(te({},e),{},O({},t,ah[t]))},{}),XN=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t,[n,r]),O(i,"enabled",!0),O(i,"isMoving",!1),O(i,"hasMoved",!1),O(i,"touchMode",0),O(i,"startTouchesPositions",[]),O(i,"lastTouches",[]),O(i,"lastTap",null),O(i,"settings",YN),i.handleStart=i.handleStart.bind(i),i.handleLeave=i.handleLeave.bind(i),i.handleMove=i.handleMove.bind(i),n.addEventListener("touchstart",i.handleStart,{capture:!1}),n.addEventListener("touchcancel",i.handleLeave,{capture:!1}),document.addEventListener("touchend",i.handleLeave,{capture:!1,passive:!1}),document.addEventListener("touchmove",i.handleMove,{capture:!1,passive:!1}),i}return jt(t,e),pt(t,[{key:"kill",value:function(){var r=this.container;r.removeEventListener("touchstart",this.handleStart),r.removeEventListener("touchcancel",this.handleLeave),document.removeEventListener("touchend",this.handleLeave),document.removeEventListener("touchmove",this.handleMove)}},{key:"getDimensions",value:function(){return{width:this.container.offsetWidth,height:this.container.offsetHeight}}},{key:"handleStart",value:function(r){var i=this;if(this.enabled){r.preventDefault();var o=is(r.touches);if(this.touchMode=o.length,this.startCameraState=this.renderer.getCamera().getState(),this.startTouchesPositions=o.map(function(h){return Wt(h,i.container)}),this.touchMode===2){var s=_r(this.startTouchesPositions,2),a=s[0],u=a.x,c=a.y,l=s[1],d=l.x,f=l.y;this.startTouchesAngle=Math.atan2(f-c,d-u),this.startTouchesDistance=Math.sqrt(Math.pow(d-u,2)+Math.pow(f-c,2))}this.emit("touchdown",ni(r,this.lastTouches,this.container)),this.lastTouches=o,this.lastTouchesPositions=this.startTouchesPositions}}},{key:"handleLeave",value:function(r){if(!(!this.enabled||!this.startTouchesPositions.length)){switch(r.cancelable&&r.preventDefault(),this.movingTimeout&&(this.isMoving=!1,clearTimeout(this.movingTimeout)),this.touchMode){case 2:if(r.touches.length===1){this.handleStart(r),r.preventDefault();break}case 1:if(this.isMoving){var i=this.renderer.getCamera(),o=i.getState(),s=i.getPreviousState()||{x:0,y:0};i.animate({x:o.x+this.settings.inertiaRatio*(o.x-s.x),y:o.y+this.settings.inertiaRatio*(o.y-s.y)},{duration:this.settings.inertiaDuration,easing:"quadraticOut"})}this.hasMoved=!1,this.isMoving=!1,this.touchMode=0;break}if(this.emit("touchup",ni(r,this.lastTouches,this.container)),!r.touches.length){var a=Wt(this.lastTouches[0],this.container),u=this.startTouchesPositions[0],c=Math.pow(a.x-u.x,2)+Math.pow(a.y-u.y,2);if(!r.touches.length&&c<Math.pow(this.settings.tapMoveTolerance,2))if(this.lastTap&&Date.now()-this.lastTap.time<this.settings.doubleClickTimeout){var l=ni(r,this.lastTouches,this.container);if(this.emit("doubletap",l),this.lastTap=null,!l.sigmaDefaultPrevented){var d=this.renderer.getCamera(),f=d.getBoundedRatio(d.getState().ratio/this.settings.doubleClickZoomingRatio);d.animate(this.renderer.getViewportZoomedState(a,f),{easing:"quadraticInOut",duration:this.settings.doubleClickZoomingDuration})}}else{var h=ni(r,this.lastTouches,this.container);this.emit("tap",h),this.lastTap={time:Date.now(),position:h.touches[0]||h.previousTouches[0]}}}this.lastTouches=is(r.touches),this.startTouchesPositions=[]}}},{key:"handleMove",value:function(r){var i=this;if(!(!this.enabled||!this.startTouchesPositions.length)){r.preventDefault();var o=is(r.touches),s=o.map(function(I){return Wt(I,i.container)}),a=this.lastTouches;this.lastTouches=o,this.lastTouchesPositions=s;var u=ni(r,a,this.container);if(this.emit("touchmove",u),!u.sigmaDefaultPrevented&&(this.hasMoved||(this.hasMoved=s.some(function(I,L){var G=i.startTouchesPositions[L];return G&&(I.x!==G.x||I.y!==G.y)})),!!this.hasMoved)){this.isMoving=!0,this.movingTimeout&&clearTimeout(this.movingTimeout),this.movingTimeout=window.setTimeout(function(){i.isMoving=!1},this.settings.dragTimeout);var c=this.renderer.getCamera(),l=this.startCameraState,d=this.renderer.getSetting("stagePadding");switch(this.touchMode){case 1:{var f=this.renderer.viewportToFramedGraph((this.startTouchesPositions||[])[0]),h=f.x,p=f.y,m=this.renderer.viewportToFramedGraph(s[0]),y=m.x,w=m.y;c.setState({x:l.x+h-y,y:l.y+p-w});break}case 2:{var g={x:.5,y:.5,angle:0,ratio:1},b=s[0],v=b.x,k=b.y,S=s[1],_=S.x,N=S.y,P=Math.atan2(N-k,_-v)-this.startTouchesAngle,z=Math.hypot(N-k,_-v)/this.startTouchesDistance,j=c.getBoundedRatio(l.ratio/z);g.ratio=j,g.angle=l.angle+P;var K=this.getDimensions(),Y=this.renderer.viewportToFramedGraph((this.startTouchesPositions||[])[0],{cameraState:l}),re=Math.min(K.width,K.height)-2*d,he=re/K.width,M=re/K.height,H=j/re,Q=v-re/2/he,ie=k-re/2/M,J=[Q*Math.cos(-g.angle)-ie*Math.sin(-g.angle),ie*Math.cos(-g.angle)+Q*Math.sin(-g.angle)];Q=J[0],ie=J[1],g.x=Y.x-Q*H,g.y=Y.y+ie*H,c.setState(g);break}}}}}},{key:"setSettings",value:function(r){this.settings=r}}])})(q_);function QN(e){if(Array.isArray(e))return fc(e)}function eR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function tR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
421
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function om(e){return QN(e)||eR(e)||C_(e)||tR()}function nR(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Nu(e,t){if(e==null)return{};var n,r,i=nR(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var sm=(function(){function e(t,n){ht(this,e),this.key=t,this.size=n}return pt(e,null,[{key:"compare",value:function(n,r){return n.size>r.size?-1:n.size<r.size||n.key>r.key?1:-1}}])})(),am=(function(){function e(){ht(this,e),O(this,"width",0),O(this,"height",0),O(this,"cellSize",0),O(this,"columns",0),O(this,"rows",0),O(this,"cells",{})}return pt(e,[{key:"resizeAndClear",value:function(n,r){this.width=n.width,this.height=n.height,this.cellSize=r,this.columns=Math.ceil(n.width/r),this.rows=Math.ceil(n.height/r),this.cells={}}},{key:"getIndex",value:function(n){var r=Math.floor(n.x/this.cellSize),i=Math.floor(n.y/this.cellSize);return i*this.columns+r}},{key:"add",value:function(n,r,i){var o=new sm(n,r),s=this.getIndex(i),a=this.cells[s];a||(a=[],this.cells[s]=a),a.push(o)}},{key:"organize",value:function(){for(var n in this.cells){var r=this.cells[n];r.sort(sm.compare)}}},{key:"getLabelsToDisplay",value:function(n,r){var i=this.cellSize*this.cellSize,o=i/n/n,s=o*r/i,a=Math.ceil(s),u=[];for(var c in this.cells)for(var l=this.cells[c],d=0;d<Math.min(a,l.length);d++)u.push(l[d].key);return u}}])})();function rR(e){var t=e.graph,n=e.hoveredNode,r=e.highlightedNodes,i=e.displayedNodeLabels,o=[];return t.forEachEdge(function(s,a,u,c){(u===n||c===n||r.has(u)||r.has(c)||i.has(u)&&i.has(c))&&o.push(s)}),o}var um=150,cm=50,on=Object.prototype.hasOwnProperty;function iR(e,t,n){if(!on.call(n,"x")||!on.call(n,"y"))throw new Error('Sigma: could not find a valid position (x, y) for node "'.concat(t,'". All your nodes must have a number "x" and "y". Maybe your forgot to apply a layout or your "nodeReducer" is not returning the correct data?'));return n.color||(n.color=e.defaultNodeColor),!n.label&&n.label!==""&&(n.label=null),n.label!==void 0&&n.label!==null?n.label=""+n.label:n.label=null,n.size||(n.size=2),on.call(n,"hidden")||(n.hidden=!1),on.call(n,"highlighted")||(n.highlighted=!1),on.call(n,"forceLabel")||(n.forceLabel=!1),(!n.type||n.type==="")&&(n.type=e.defaultNodeType),n.zIndex||(n.zIndex=0),n}function oR(e,t,n){return n.color||(n.color=e.defaultEdgeColor),n.label||(n.label=""),n.size||(n.size=.5),on.call(n,"hidden")||(n.hidden=!1),on.call(n,"forceLabel")||(n.forceLabel=!1),(!n.type||n.type==="")&&(n.type=e.defaultEdgeType),n.zIndex||(n.zIndex=0),n}var sR=(function(e){function t(n,r){var i,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(ht(this,t),i=Gt(this,t),O(i,"elements",{}),O(i,"canvasContexts",{}),O(i,"webGLContexts",{}),O(i,"pickingLayers",new Set),O(i,"textures",{}),O(i,"frameBuffers",{}),O(i,"activeListeners",{}),O(i,"labelGrid",new am),O(i,"nodeDataCache",{}),O(i,"edgeDataCache",{}),O(i,"nodeProgramIndex",{}),O(i,"edgeProgramIndex",{}),O(i,"nodesWithForcedLabels",new Set),O(i,"edgesWithForcedLabels",new Set),O(i,"nodeExtent",{x:[0,1],y:[0,1]}),O(i,"nodeZExtent",[1/0,-1/0]),O(i,"edgeZExtent",[1/0,-1/0]),O(i,"matrix",Vt()),O(i,"invMatrix",Vt()),O(i,"correctionRatio",1),O(i,"customBBox",null),O(i,"normalizationFunction",nm({x:[0,1],y:[0,1]})),O(i,"graphToViewportRatio",1),O(i,"itemIDsIndex",{}),O(i,"nodeIndices",{}),O(i,"edgeIndices",{}),O(i,"width",0),O(i,"height",0),O(i,"pixelRatio",em()),O(i,"pickingDownSizingRatio",2*i.pixelRatio),O(i,"displayedNodeLabels",new Set),O(i,"displayedEdgeLabels",new Set),O(i,"highlightedNodes",new Set),O(i,"hoveredNode",null),O(i,"hoveredEdge",null),O(i,"renderFrame",null),O(i,"renderHighlightedNodesFrame",null),O(i,"needToProcess",!1),O(i,"checkEdgesEventsFrame",null),O(i,"nodePrograms",{}),O(i,"nodeHoverPrograms",{}),O(i,"edgePrograms",{}),i.settings=BN(o),Iu(i.settings),UN(n),!(r instanceof HTMLElement))throw new Error("Sigma: container should be an html element.");i.graph=n,i.container=r,i.createWebGLContext("edges",{picking:o.enableEdgeEvents}),i.createCanvasContext("edgeLabels"),i.createWebGLContext("nodes",{picking:!0}),i.createCanvasContext("labels"),i.createCanvasContext("hovers"),i.createWebGLContext("hoverNodes"),i.createCanvasContext("mouse",{style:{touchAction:"none",userSelect:"none"}}),i.resize();for(var s in i.settings.nodeProgramClasses)i.registerNodeProgram(s,i.settings.nodeProgramClasses[s],i.settings.nodeHoverProgramClasses[s]);for(var a in i.settings.edgeProgramClasses)i.registerEdgeProgram(a,i.settings.edgeProgramClasses[a]);return i.camera=new im,i.bindCameraHandlers(),i.mouseCaptor=new KN(i.elements.mouse,i),i.mouseCaptor.setSettings(i.settings),i.touchCaptor=new XN(i.elements.mouse,i),i.touchCaptor.setSettings(i.settings),i.bindEventHandlers(),i.bindGraphHandlers(),i.handleSettingsUpdate(),i.refresh(),i}return jt(t,e),pt(t,[{key:"registerNodeProgram",value:function(r,i,o){return this.nodePrograms[r]&&this.nodePrograms[r].kill(),this.nodeHoverPrograms[r]&&this.nodeHoverPrograms[r].kill(),this.nodePrograms[r]=new i(this.webGLContexts.nodes,this.frameBuffers.nodes,this),this.nodeHoverPrograms[r]=new(o||i)(this.webGLContexts.hoverNodes,null,this),this}},{key:"registerEdgeProgram",value:function(r,i){return this.edgePrograms[r]&&this.edgePrograms[r].kill(),this.edgePrograms[r]=new i(this.webGLContexts.edges,this.frameBuffers.edges,this),this}},{key:"unregisterNodeProgram",value:function(r){if(this.nodePrograms[r]){var i=this.nodePrograms,o=i[r],s=Nu(i,[r].map(ui));o.kill(),this.nodePrograms=s}if(this.nodeHoverPrograms[r]){var a=this.nodeHoverPrograms,u=a[r],c=Nu(a,[r].map(ui));u.kill(),this.nodePrograms=c}return this}},{key:"unregisterEdgeProgram",value:function(r){if(this.edgePrograms[r]){var i=this.edgePrograms,o=i[r],s=Nu(i,[r].map(ui));o.kill(),this.edgePrograms=s}return this}},{key:"resetWebGLTexture",value:function(r){var i=this.webGLContexts[r],o=this.frameBuffers[r],s=this.textures[r];s&&i.deleteTexture(s);var a=i.createTexture();return i.bindFramebuffer(i.FRAMEBUFFER,o),i.bindTexture(i.TEXTURE_2D,a),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,a,0),this.textures[r]=a,this}},{key:"bindCameraHandlers",value:function(){var r=this;return this.activeListeners.camera=function(){r.scheduleRender()},this.camera.on("updated",this.activeListeners.camera),this}},{key:"unbindCameraHandlers",value:function(){return this.camera.removeListener("updated",this.activeListeners.camera),this}},{key:"getNodeAtPosition",value:function(r){var i=r.x,o=r.y,s=jp(this.webGLContexts.nodes,this.frameBuffers.nodes,i,o,this.pixelRatio,this.pickingDownSizingRatio),a=Gp.apply(void 0,om(s)),u=this.itemIDsIndex[a];return u&&u.type==="node"?u.id:null}},{key:"bindEventHandlers",value:function(){var r=this;this.activeListeners.handleResize=function(){r.scheduleRefresh()},window.addEventListener("resize",this.activeListeners.handleResize),this.activeListeners.handleMove=function(o){var s=ti(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}},u=r.getNodeAtPosition(s);if(u&&r.hoveredNode!==u&&!r.nodeDataCache[u].hidden){r.hoveredNode&&r.emit("leaveNode",te(te({},a),{},{node:r.hoveredNode})),r.hoveredNode=u,r.emit("enterNode",te(te({},a),{},{node:u})),r.scheduleHighlightedNodesRender();return}if(r.hoveredNode&&r.getNodeAtPosition(s)!==r.hoveredNode){var c=r.hoveredNode;r.hoveredNode=null,r.emit("leaveNode",te(te({},a),{},{node:c})),r.scheduleHighlightedNodesRender();return}if(r.settings.enableEdgeEvents){var l=r.hoveredNode?null:r.getEdgeAtPoint(a.event.x,a.event.y);l!==r.hoveredEdge&&(r.hoveredEdge&&r.emit("leaveEdge",te(te({},a),{},{edge:r.hoveredEdge})),l&&r.emit("enterEdge",te(te({},a),{},{edge:l})),r.hoveredEdge=l)}},this.activeListeners.handleMoveBody=function(o){var s=ti(o);r.emit("moveBody",{event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}})},this.activeListeners.handleLeave=function(o){var s=ti(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}};r.hoveredNode&&(r.emit("leaveNode",te(te({},a),{},{node:r.hoveredNode})),r.scheduleHighlightedNodesRender()),r.settings.enableEdgeEvents&&r.hoveredEdge&&(r.emit("leaveEdge",te(te({},a),{},{edge:r.hoveredEdge})),r.scheduleHighlightedNodesRender()),r.emit("leaveStage",te({},a))},this.activeListeners.handleEnter=function(o){var s=ti(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}};r.emit("enterStage",te({},a))};var i=function(s){return function(a){var u=ti(a),c={event:u,preventSigmaDefault:function(){u.preventSigmaDefault()}},l=r.getNodeAtPosition(u);if(l)return r.emit("".concat(s,"Node"),te(te({},c),{},{node:l}));if(r.settings.enableEdgeEvents){var d=r.getEdgeAtPoint(u.x,u.y);if(d)return r.emit("".concat(s,"Edge"),te(te({},c),{},{edge:d}))}return r.emit("".concat(s,"Stage"),c)}};return this.activeListeners.handleClick=i("click"),this.activeListeners.handleRightClick=i("rightClick"),this.activeListeners.handleDoubleClick=i("doubleClick"),this.activeListeners.handleWheel=i("wheel"),this.activeListeners.handleDown=i("down"),this.activeListeners.handleUp=i("up"),this.mouseCaptor.on("mousemove",this.activeListeners.handleMove),this.mouseCaptor.on("mousemovebody",this.activeListeners.handleMoveBody),this.mouseCaptor.on("click",this.activeListeners.handleClick),this.mouseCaptor.on("rightClick",this.activeListeners.handleRightClick),this.mouseCaptor.on("doubleClick",this.activeListeners.handleDoubleClick),this.mouseCaptor.on("wheel",this.activeListeners.handleWheel),this.mouseCaptor.on("mousedown",this.activeListeners.handleDown),this.mouseCaptor.on("mouseup",this.activeListeners.handleUp),this.mouseCaptor.on("mouseleave",this.activeListeners.handleLeave),this.mouseCaptor.on("mouseenter",this.activeListeners.handleEnter),this.touchCaptor.on("touchdown",this.activeListeners.handleDown),this.touchCaptor.on("touchdown",this.activeListeners.handleMove),this.touchCaptor.on("touchup",this.activeListeners.handleUp),this.touchCaptor.on("touchmove",this.activeListeners.handleMove),this.touchCaptor.on("tap",this.activeListeners.handleClick),this.touchCaptor.on("doubletap",this.activeListeners.handleDoubleClick),this.touchCaptor.on("touchmove",this.activeListeners.handleMoveBody),this}},{key:"bindGraphHandlers",value:function(){var r=this,i=this.graph,o=new Set(["x","y","zIndex","type"]);return this.activeListeners.eachNodeAttributesUpdatedGraphUpdate=function(s){var a,u=(a=s.hints)===null||a===void 0?void 0:a.attributes;r.graph.forEachNode(function(l){return r.updateNode(l)});var c=!u||u.some(function(l){return o.has(l)});r.refresh({partialGraph:{nodes:i.nodes()},skipIndexation:!c,schedule:!0})},this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate=function(s){var a,u=(a=s.hints)===null||a===void 0?void 0:a.attributes;r.graph.forEachEdge(function(l){return r.updateEdge(l)});var c=u&&["zIndex","type"].some(function(l){return u?.includes(l)});r.refresh({partialGraph:{edges:i.edges()},skipIndexation:!c,schedule:!0})},this.activeListeners.addNodeGraphUpdate=function(s){var a=s.key;r.addNode(a),r.refresh({partialGraph:{nodes:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.updateNodeGraphUpdate=function(s){var a=s.key;r.refresh({partialGraph:{nodes:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.dropNodeGraphUpdate=function(s){var a=s.key;r.removeNode(a),r.refresh({schedule:!0})},this.activeListeners.addEdgeGraphUpdate=function(s){var a=s.key;r.addEdge(a),r.refresh({partialGraph:{edges:[a]},schedule:!0})},this.activeListeners.updateEdgeGraphUpdate=function(s){var a=s.key;r.refresh({partialGraph:{edges:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.dropEdgeGraphUpdate=function(s){var a=s.key;r.removeEdge(a),r.refresh({schedule:!0})},this.activeListeners.clearEdgesGraphUpdate=function(){r.clearEdgeState(),r.clearEdgeIndices(),r.refresh({schedule:!0})},this.activeListeners.clearGraphUpdate=function(){r.clearEdgeState(),r.clearNodeState(),r.clearEdgeIndices(),r.clearNodeIndices(),r.refresh({schedule:!0})},i.on("nodeAdded",this.activeListeners.addNodeGraphUpdate),i.on("nodeDropped",this.activeListeners.dropNodeGraphUpdate),i.on("nodeAttributesUpdated",this.activeListeners.updateNodeGraphUpdate),i.on("eachNodeAttributesUpdated",this.activeListeners.eachNodeAttributesUpdatedGraphUpdate),i.on("edgeAdded",this.activeListeners.addEdgeGraphUpdate),i.on("edgeDropped",this.activeListeners.dropEdgeGraphUpdate),i.on("edgeAttributesUpdated",this.activeListeners.updateEdgeGraphUpdate),i.on("eachEdgeAttributesUpdated",this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate),i.on("edgesCleared",this.activeListeners.clearEdgesGraphUpdate),i.on("cleared",this.activeListeners.clearGraphUpdate),this}},{key:"unbindGraphHandlers",value:function(){var r=this.graph;r.removeListener("nodeAdded",this.activeListeners.addNodeGraphUpdate),r.removeListener("nodeDropped",this.activeListeners.dropNodeGraphUpdate),r.removeListener("nodeAttributesUpdated",this.activeListeners.updateNodeGraphUpdate),r.removeListener("eachNodeAttributesUpdated",this.activeListeners.eachNodeAttributesUpdatedGraphUpdate),r.removeListener("edgeAdded",this.activeListeners.addEdgeGraphUpdate),r.removeListener("edgeDropped",this.activeListeners.dropEdgeGraphUpdate),r.removeListener("edgeAttributesUpdated",this.activeListeners.updateEdgeGraphUpdate),r.removeListener("eachEdgeAttributesUpdated",this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate),r.removeListener("edgesCleared",this.activeListeners.clearEdgesGraphUpdate),r.removeListener("cleared",this.activeListeners.clearGraphUpdate)}},{key:"getEdgeAtPoint",value:function(r,i){var o=jp(this.webGLContexts.edges,this.frameBuffers.edges,r,i,this.pixelRatio,this.pickingDownSizingRatio),s=Gp.apply(void 0,om(o)),a=this.itemIDsIndex[s];return a&&a.type==="edge"?a.id:null}},{key:"process",value:function(){var r=this;this.emit("beforeProcess");var i=this.graph,o=this.settings,s=this.getDimensions();if(this.nodeExtent=FN(this.graph),!this.settings.autoRescale){var a=s.width,u=s.height,c=this.nodeExtent,l=c.x,d=c.y;this.nodeExtent={x:[(l[0]+l[1])/2-a/2,(l[0]+l[1])/2+a/2],y:[(d[0]+d[1])/2-u/2,(d[0]+d[1])/2+u/2]}}this.normalizationFunction=nm(this.customBBox||this.nodeExtent);var f=new im,h=ei(f.getState(),s,this.getGraphDimensions(),this.getStagePadding());this.labelGrid.resizeAndClear(s,o.labelGridCellSize);for(var p={},m={},y={},w={},g=1,b=i.nodes(),v=0,k=b.length;v<k;v++){var S=b[v],_=this.nodeDataCache[S],N=i.getNodeAttributes(S);_.x=N.x,_.y=N.y,this.normalizationFunction.applyTo(_),typeof _.label=="string"&&!_.hidden&&this.labelGrid.add(S,_.size,this.framedGraphToViewport(_,{matrix:h})),p[_.type]=(p[_.type]||0)+1}this.labelGrid.organize();for(var P in this.nodePrograms){if(!on.call(this.nodePrograms,P))throw new Error('Sigma: could not find a suitable program for node type "'.concat(P,'"!'));this.nodePrograms[P].reallocate(p[P]||0),p[P]=0}this.settings.zIndex&&this.nodeZExtent[0]!==this.nodeZExtent[1]&&(b=tm(this.nodeZExtent,function(se){return r.nodeDataCache[se].zIndex},b));for(var z=0,j=b.length;z<j;z++){var K=b[z];m[K]=g,w[m[K]]={type:"node",id:K},g++;var Y=this.nodeDataCache[K];this.addNodeToProgram(K,m[K],p[Y.type]++)}for(var re={},he=i.edges(),M=0,H=he.length;M<H;M++){var Q=he[M],ie=this.edgeDataCache[Q];re[ie.type]=(re[ie.type]||0)+1}this.settings.zIndex&&this.edgeZExtent[0]!==this.edgeZExtent[1]&&(he=tm(this.edgeZExtent,function(se){return r.edgeDataCache[se].zIndex},he));for(var J in this.edgePrograms){if(!on.call(this.edgePrograms,J))throw new Error('Sigma: could not find a suitable program for edge type "'.concat(J,'"!'));this.edgePrograms[J].reallocate(re[J]||0),re[J]=0}for(var I=0,L=he.length;I<L;I++){var G=he[I];y[G]=g,w[y[G]]={type:"edge",id:G},g++;var pe=this.edgeDataCache[G];this.addEdgeToProgram(G,y[G],re[pe.type]++)}return this.itemIDsIndex=w,this.nodeIndices=m,this.edgeIndices=y,this.emit("afterProcess"),this}},{key:"handleSettingsUpdate",value:function(r){var i=this,o=this.settings;if(this.camera.minRatio=o.minCameraRatio,this.camera.maxRatio=o.maxCameraRatio,this.camera.enabledZooming=o.enableCameraZooming,this.camera.enabledPanning=o.enableCameraPanning,this.camera.enabledRotation=o.enableCameraRotation,o.cameraPanBoundaries?this.camera.clean=function(l){return i.cleanCameraState(l,o.cameraPanBoundaries&&mc(o.cameraPanBoundaries)==="object"?o.cameraPanBoundaries:{})}:this.camera.clean=null,this.camera.setState(this.camera.validateState(this.camera.getState())),r){if(r.edgeProgramClasses!==o.edgeProgramClasses){for(var s in o.edgeProgramClasses)o.edgeProgramClasses[s]!==r.edgeProgramClasses[s]&&this.registerEdgeProgram(s,o.edgeProgramClasses[s]);for(var a in r.edgeProgramClasses)o.edgeProgramClasses[a]||this.unregisterEdgeProgram(a)}if(r.nodeProgramClasses!==o.nodeProgramClasses||r.nodeHoverProgramClasses!==o.nodeHoverProgramClasses){for(var u in o.nodeProgramClasses)(o.nodeProgramClasses[u]!==r.nodeProgramClasses[u]||o.nodeHoverProgramClasses[u]!==r.nodeHoverProgramClasses[u])&&this.registerNodeProgram(u,o.nodeProgramClasses[u],o.nodeHoverProgramClasses[u]);for(var c in r.nodeProgramClasses)o.nodeProgramClasses[c]||this.unregisterNodeProgram(c)}}return this.mouseCaptor.setSettings(this.settings),this.touchCaptor.setSettings(this.settings),this}},{key:"cleanCameraState",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=i.tolerance,s=o===void 0?0:o,a=i.boundaries,u=te({},r),c=a||this.nodeExtent,l=_r(c.x,2),d=l[0],f=l[1],h=_r(c.y,2),p=h[0],m=h[1],y=[this.graphToViewport({x:d,y:p},{cameraState:r}),this.graphToViewport({x:f,y:p},{cameraState:r}),this.graphToViewport({x:d,y:m},{cameraState:r}),this.graphToViewport({x:f,y:m},{cameraState:r})],w=1/0,g=-1/0,b=1/0,v=-1/0;y.forEach(function(re){var he=re.x,M=re.y;w=Math.min(w,he),g=Math.max(g,he),b=Math.min(b,M),v=Math.max(v,M)});var k=g-w,S=v-b,_=this.getDimensions(),N=_.width,P=_.height,z=0,j=0;if(k>=N?g<N-s?z=g-(N-s):w>s&&(z=w-s):g>N+s?z=g-(N+s):w<-s&&(z=w+s),S>=P?v<P-s?j=v-(P-s):b>s&&(j=b-s):v>P+s?j=v-(P+s):b<-s&&(j=b+s),z||j){var K=this.viewportToFramedGraph({x:0,y:0},{cameraState:r}),Y=this.viewportToFramedGraph({x:z,y:j},{cameraState:r});z=Y.x-K.x,j=Y.y-K.y,u.x+=z,u.y+=j}return u}},{key:"renderLabels",value:function(){if(!this.settings.renderLabels)return this;var r=this.camera.getState(),i=this.labelGrid.getLabelsToDisplay(r.ratio,this.settings.labelDensity);rm(i,this.nodesWithForcedLabels),this.displayedNodeLabels=new Set;for(var o=this.canvasContexts.labels,s=0,a=i.length;s<a;s++){var u=i[s],c=this.nodeDataCache[u];if(!this.displayedNodeLabels.has(u)&&!c.hidden){var l=this.framedGraphToViewport(c),d=l.x,f=l.y,h=this.scaleSize(c.size);if(!(!c.forceLabel&&h<this.settings.labelRenderedSizeThreshold)&&!(d<-um||d>this.width+um||f<-cm||f>this.height+cm)){this.displayedNodeLabels.add(u);var p=this.settings.defaultDrawNodeLabel,m=this.nodePrograms[c.type],y=m?.drawLabel||p;y(o,te(te({key:u},c),{},{size:h,x:d,y:f}),this.settings)}}}return this}},{key:"renderEdgeLabels",value:function(){if(!this.settings.renderEdgeLabels)return this;var r=this.canvasContexts.edgeLabels;r.clearRect(0,0,this.width,this.height);var i=rR({graph:this.graph,hoveredNode:this.hoveredNode,displayedNodeLabels:this.displayedNodeLabels,highlightedNodes:this.highlightedNodes});rm(i,this.edgesWithForcedLabels);for(var o=new Set,s=0,a=i.length;s<a;s++){var u=i[s],c=this.graph.extremities(u),l=this.nodeDataCache[c[0]],d=this.nodeDataCache[c[1]],f=this.edgeDataCache[u];if(!o.has(u)&&!(f.hidden||l.hidden||d.hidden)){var h=this.settings.defaultDrawEdgeLabel,p=this.edgePrograms[f.type],m=p?.drawLabel||h;m(r,te(te({key:u},f),{},{size:this.scaleSize(f.size)}),te(te(te({key:c[0]},l),this.framedGraphToViewport(l)),{},{size:this.scaleSize(l.size)}),te(te(te({key:c[1]},d),this.framedGraphToViewport(d)),{},{size:this.scaleSize(d.size)}),this.settings),o.add(u)}}return this.displayedEdgeLabels=o,this}},{key:"renderHighlightedNodes",value:function(){var r=this,i=this.canvasContexts.hovers;i.clearRect(0,0,this.width,this.height);var o=function(h){var p=r.nodeDataCache[h],m=r.framedGraphToViewport(p),y=m.x,w=m.y,g=r.scaleSize(p.size),b=r.settings.defaultDrawNodeHover,v=r.nodePrograms[p.type],k=v?.drawHover||b;k(i,te(te({key:h},p),{},{size:g,x:y,y:w}),r.settings)},s=[];this.hoveredNode&&!this.nodeDataCache[this.hoveredNode].hidden&&s.push(this.hoveredNode),this.highlightedNodes.forEach(function(f){f!==r.hoveredNode&&s.push(f)}),s.forEach(function(f){return o(f)});var a={};s.forEach(function(f){var h=r.nodeDataCache[f].type;a[h]=(a[h]||0)+1});for(var u in this.nodeHoverPrograms)this.nodeHoverPrograms[u].reallocate(a[u]||0),a[u]=0;s.forEach(function(f){var h=r.nodeDataCache[f];r.nodeHoverPrograms[h.type].process(0,a[h.type]++,h)}),this.webGLContexts.hoverNodes.clear(this.webGLContexts.hoverNodes.COLOR_BUFFER_BIT);var c=this.getRenderParams();for(var l in this.nodeHoverPrograms){var d=this.nodeHoverPrograms[l];d.render(c)}}},{key:"scheduleHighlightedNodesRender",value:function(){var r=this;this.renderHighlightedNodesFrame||this.renderFrame||(this.renderHighlightedNodesFrame=requestAnimationFrame(function(){r.renderHighlightedNodesFrame=null,r.renderHighlightedNodes(),r.renderEdgeLabels()}))}},{key:"render",value:function(){var r=this;this.emit("beforeRender");var i=function(){return r.emit("afterRender"),r};if(this.renderFrame&&(cancelAnimationFrame(this.renderFrame),this.renderFrame=null),this.resize(),this.needToProcess&&this.process(),this.needToProcess=!1,this.clear(),this.pickingLayers.forEach(function(y){return r.resetWebGLTexture(y)}),!this.graph.order)return i();var o=this.mouseCaptor,s=this.camera.isAnimated()||o.isMoving||o.draggedEvents||o.currentWheelDirection,a=this.camera.getState(),u=this.getDimensions(),c=this.getGraphDimensions(),l=this.getStagePadding();this.matrix=ei(a,u,c,l),this.invMatrix=ei(a,u,c,l,!0),this.correctionRatio=MN(this.matrix,a,u),this.graphToViewportRatio=this.getGraphToViewportRatio();var d=this.getRenderParams();for(var f in this.nodePrograms){var h=this.nodePrograms[f];h.render(d)}if(!this.settings.hideEdgesOnMove||!s)for(var p in this.edgePrograms){var m=this.edgePrograms[p];m.render(d)}return this.settings.hideLabelsOnMove&&s||(this.renderLabels(),this.renderEdgeLabels(),this.renderHighlightedNodes()),i()}},{key:"addNode",value:function(r){var i=Object.assign({},this.graph.getNodeAttributes(r));this.settings.nodeReducer&&(i=this.settings.nodeReducer(r,i));var o=iR(this.settings,r,i);this.nodeDataCache[r]=o,this.nodesWithForcedLabels.delete(r),o.forceLabel&&!o.hidden&&this.nodesWithForcedLabels.add(r),this.highlightedNodes.delete(r),o.highlighted&&!o.hidden&&this.highlightedNodes.add(r),this.settings.zIndex&&(o.zIndex<this.nodeZExtent[0]&&(this.nodeZExtent[0]=o.zIndex),o.zIndex>this.nodeZExtent[1]&&(this.nodeZExtent[1]=o.zIndex))}},{key:"updateNode",value:function(r){this.addNode(r);var i=this.nodeDataCache[r];this.normalizationFunction.applyTo(i)}},{key:"removeNode",value:function(r){delete this.nodeDataCache[r],delete this.nodeProgramIndex[r],this.highlightedNodes.delete(r),this.hoveredNode===r&&(this.hoveredNode=null),this.nodesWithForcedLabels.delete(r)}},{key:"addEdge",value:function(r){var i=Object.assign({},this.graph.getEdgeAttributes(r));this.settings.edgeReducer&&(i=this.settings.edgeReducer(r,i));var o=oR(this.settings,r,i);this.edgeDataCache[r]=o,this.edgesWithForcedLabels.delete(r),o.forceLabel&&!o.hidden&&this.edgesWithForcedLabels.add(r),this.settings.zIndex&&(o.zIndex<this.edgeZExtent[0]&&(this.edgeZExtent[0]=o.zIndex),o.zIndex>this.edgeZExtent[1]&&(this.edgeZExtent[1]=o.zIndex))}},{key:"updateEdge",value:function(r){this.addEdge(r)}},{key:"removeEdge",value:function(r){delete this.edgeDataCache[r],delete this.edgeProgramIndex[r],this.hoveredEdge===r&&(this.hoveredEdge=null),this.edgesWithForcedLabels.delete(r)}},{key:"clearNodeIndices",value:function(){this.labelGrid=new am,this.nodeExtent={x:[0,1],y:[0,1]},this.nodeDataCache={},this.edgeProgramIndex={},this.nodesWithForcedLabels=new Set,this.nodeZExtent=[1/0,-1/0],this.highlightedNodes=new Set}},{key:"clearEdgeIndices",value:function(){this.edgeDataCache={},this.edgeProgramIndex={},this.edgesWithForcedLabels=new Set,this.edgeZExtent=[1/0,-1/0]}},{key:"clearIndices",value:function(){this.clearEdgeIndices(),this.clearNodeIndices()}},{key:"clearNodeState",value:function(){this.displayedNodeLabels=new Set,this.highlightedNodes=new Set,this.hoveredNode=null}},{key:"clearEdgeState",value:function(){this.displayedEdgeLabels=new Set,this.highlightedNodes=new Set,this.hoveredEdge=null}},{key:"clearState",value:function(){this.clearEdgeState(),this.clearNodeState()}},{key:"addNodeToProgram",value:function(r,i,o){var s=this.nodeDataCache[r],a=this.nodePrograms[s.type];if(!a)throw new Error('Sigma: could not find a suitable program for node type "'.concat(s.type,'"!'));a.process(i,o,s),this.nodeProgramIndex[r]=o}},{key:"addEdgeToProgram",value:function(r,i,o){var s=this.edgeDataCache[r],a=this.edgePrograms[s.type];if(!a)throw new Error('Sigma: could not find a suitable program for edge type "'.concat(s.type,'"!'));var u=this.graph.extremities(r),c=this.nodeDataCache[u[0]],l=this.nodeDataCache[u[1]];a.process(i,o,c,l,s),this.edgeProgramIndex[r]=o}},{key:"getRenderParams",value:function(){return{matrix:this.matrix,invMatrix:this.invMatrix,width:this.width,height:this.height,pixelRatio:this.pixelRatio,zoomRatio:this.camera.ratio,cameraAngle:this.camera.angle,sizeRatio:1/this.scaleSize(),correctionRatio:this.correctionRatio,downSizingRatio:this.pickingDownSizingRatio,minEdgeThickness:this.settings.minEdgeThickness,antiAliasingFeather:this.settings.antiAliasingFeather}}},{key:"getStagePadding",value:function(){var r=this.settings,i=r.stagePadding,o=r.autoRescale;return o&&i||0}},{key:"createLayer",value:function(r,i){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.elements[r])throw new Error('Sigma: a layer named "'.concat(r,'" already exists'));var s=GN(i,{position:"absolute"},{class:"sigma-".concat(r)});return o.style&&Object.assign(s.style,o.style),this.elements[r]=s,"beforeLayer"in o&&o.beforeLayer?this.elements[o.beforeLayer].before(s):"afterLayer"in o&&o.afterLayer?this.elements[o.afterLayer].after(s):this.container.appendChild(s),s}},{key:"createCanvas",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.createLayer(r,"canvas",i)}},{key:"createCanvasContext",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=this.createCanvas(r,i),s={preserveDrawingBuffer:!1,antialias:!1};return this.canvasContexts[r]=o.getContext("2d",s),this}},{key:"createWebGLContext",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=i?.canvas||this.createCanvas(r,i);i.hidden&&o.remove();var s=te({preserveDrawingBuffer:!1,antialias:!1},i),a;a=o.getContext("webgl2",s),a||(a=o.getContext("webgl",s)),a||(a=o.getContext("experimental-webgl",s));var u=a;if(this.webGLContexts[r]=u,u.blendFunc(u.ONE,u.ONE_MINUS_SRC_ALPHA),i.picking){this.pickingLayers.add(r);var c=u.createFramebuffer();if(!c)throw new Error("Sigma: cannot create a new frame buffer for layer ".concat(r));this.frameBuffers[r]=c}return u}},{key:"killLayer",value:function(r){var i=this.elements[r];if(!i)throw new Error("Sigma: cannot kill layer ".concat(r,", which does not exist"));if(this.webGLContexts[r]){var o,s=this.webGLContexts[r];(o=s.getExtension("WEBGL_lose_context"))===null||o===void 0||o.loseContext(),delete this.webGLContexts[r]}else this.canvasContexts[r]&&delete this.canvasContexts[r];return i.remove(),delete this.elements[r],this}},{key:"getCamera",value:function(){return this.camera}},{key:"setCamera",value:function(r){this.unbindCameraHandlers(),this.camera=r,this.bindCameraHandlers()}},{key:"getContainer",value:function(){return this.container}},{key:"getGraph",value:function(){return this.graph}},{key:"setGraph",value:function(r){r!==this.graph&&(this.hoveredNode&&!r.hasNode(this.hoveredNode)&&(this.hoveredNode=null),this.hoveredEdge&&!r.hasEdge(this.hoveredEdge)&&(this.hoveredEdge=null),this.unbindGraphHandlers(),this.checkEdgesEventsFrame!==null&&(cancelAnimationFrame(this.checkEdgesEventsFrame),this.checkEdgesEventsFrame=null),this.graph=r,this.bindGraphHandlers(),this.refresh())}},{key:"getMouseCaptor",value:function(){return this.mouseCaptor}},{key:"getTouchCaptor",value:function(){return this.touchCaptor}},{key:"getDimensions",value:function(){return{width:this.width,height:this.height}}},{key:"getGraphDimensions",value:function(){var r=this.customBBox||this.nodeExtent;return{width:r.x[1]-r.x[0]||1,height:r.y[1]-r.y[0]||1}}},{key:"getNodeDisplayData",value:function(r){var i=this.nodeDataCache[r];return i?Object.assign({},i):void 0}},{key:"getEdgeDisplayData",value:function(r){var i=this.edgeDataCache[r];return i?Object.assign({},i):void 0}},{key:"getNodeDisplayedLabels",value:function(){return new Set(this.displayedNodeLabels)}},{key:"getEdgeDisplayedLabels",value:function(){return new Set(this.displayedEdgeLabels)}},{key:"getSettings",value:function(){return te({},this.settings)}},{key:"getSetting",value:function(r){return this.settings[r]}},{key:"setSetting",value:function(r,i){var o=te({},this.settings);return this.settings[r]=i,Iu(this.settings),this.handleSettingsUpdate(o),this.scheduleRefresh(),this}},{key:"updateSetting",value:function(r,i){return this.setSetting(r,i(this.settings[r])),this}},{key:"setSettings",value:function(r){var i=te({},this.settings);return this.settings=te(te({},this.settings),r),Iu(this.settings),this.handleSettingsUpdate(i),this.scheduleRefresh(),this}},{key:"resize",value:function(r){var i=this.width,o=this.height;if(this.width=this.container.offsetWidth,this.height=this.container.offsetHeight,this.pixelRatio=em(),this.width===0)if(this.settings.allowInvalidContainer)this.width=1;else throw new Error("Sigma: Container has no width. You can set the allowInvalidContainer setting to true to stop seeing this error.");if(this.height===0)if(this.settings.allowInvalidContainer)this.height=1;else throw new Error("Sigma: Container has no height. You can set the allowInvalidContainer setting to true to stop seeing this error.");if(!r&&i===this.width&&o===this.height)return this;for(var s in this.elements){var a=this.elements[s];a.style.width=this.width+"px",a.style.height=this.height+"px"}for(var u in this.canvasContexts)this.elements[u].setAttribute("width",this.width*this.pixelRatio+"px"),this.elements[u].setAttribute("height",this.height*this.pixelRatio+"px"),this.pixelRatio!==1&&this.canvasContexts[u].scale(this.pixelRatio,this.pixelRatio);for(var c in this.webGLContexts){this.elements[c].setAttribute("width",this.width*this.pixelRatio+"px"),this.elements[c].setAttribute("height",this.height*this.pixelRatio+"px");var l=this.webGLContexts[c];if(l.viewport(0,0,this.width*this.pixelRatio,this.height*this.pixelRatio),this.pickingLayers.has(c)){var d=this.textures[c];d&&l.deleteTexture(d)}}return this.emit("resize"),this}},{key:"clear",value:function(){return this.emit("beforeClear"),this.webGLContexts.nodes.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER,null),this.webGLContexts.nodes.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.webGLContexts.edges.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER,null),this.webGLContexts.edges.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.webGLContexts.hoverNodes.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.canvasContexts.labels.clearRect(0,0,this.width,this.height),this.canvasContexts.hovers.clearRect(0,0,this.width,this.height),this.canvasContexts.edgeLabels.clearRect(0,0,this.width,this.height),this.emit("afterClear"),this}},{key:"refresh",value:function(r){var i=this,o=r?.skipIndexation!==void 0?r?.skipIndexation:!1,s=r?.schedule!==void 0?r.schedule:!1,a=!r||!r.partialGraph;if(a)this.clearEdgeIndices(),this.clearNodeIndices(),this.graph.forEachNode(function(v){return i.addNode(v)}),this.graph.forEachEdge(function(v){return i.addEdge(v)});else{for(var u,c,l=((u=r.partialGraph)===null||u===void 0?void 0:u.nodes)||[],d=0,f=l?.length||0;d<f;d++){var h=l[d];if(this.updateNode(h),o){var p=this.nodeProgramIndex[h];if(p===void 0)throw new Error('Sigma: node "'.concat(h,`" can't be repaint`));this.addNodeToProgram(h,this.nodeIndices[h],p)}}for(var m=(r==null||(c=r.partialGraph)===null||c===void 0?void 0:c.edges)||[],y=0,w=m.length;y<w;y++){var g=m[y];if(this.updateEdge(g),o){var b=this.edgeProgramIndex[g];if(b===void 0)throw new Error('Sigma: edge "'.concat(g,`" can't be repaint`));this.addEdgeToProgram(g,this.edgeIndices[g],b)}}}return(a||!o)&&(this.needToProcess=!0),s?this.scheduleRender():this.render(),this}},{key:"scheduleRender",value:function(){var r=this;return this.renderFrame||(this.renderFrame=requestAnimationFrame(function(){r.render()})),this}},{key:"scheduleRefresh",value:function(r){return this.refresh(te(te({},r),{},{schedule:!0}))}},{key:"getViewportZoomedState",value:function(r,i){var o=this.camera.getState(),s=o.ratio,a=o.angle,u=o.x,c=o.y,l=this.settings,d=l.minCameraRatio,f=l.maxCameraRatio;typeof f=="number"&&(i=Math.min(i,f)),typeof d=="number"&&(i=Math.max(i,d));var h=i/s,p={x:this.width/2,y:this.height/2},m=this.viewportToFramedGraph(r),y=this.viewportToFramedGraph(p);return{angle:a,x:(m.x-y.x)*(1-h)+u,y:(m.y-y.y)*(1-h)+c,ratio:i}}},{key:"viewRectangle",value:function(){var r=this.viewportToFramedGraph({x:0,y:0}),i=this.viewportToFramedGraph({x:this.width,y:0}),o=this.viewportToFramedGraph({x:0,y:this.height});return{x1:r.x,y1:r.y,x2:i.x,y2:i.y,height:i.y-o.y}}},{key:"framedGraphToViewport",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=!!i.cameraState||!!i.viewportDimensions||!!i.graphDimensions,s=i.matrix?i.matrix:o?ei(i.cameraState||this.camera.getState(),i.viewportDimensions||this.getDimensions(),i.graphDimensions||this.getGraphDimensions(),i.padding||this.getStagePadding()):this.matrix,a=pc(s,r);return{x:(1+a.x)*this.width/2,y:(1-a.y)*this.height/2}}},{key:"viewportToFramedGraph",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=!!i.cameraState||!!i.viewportDimensions||!i.graphDimensions,s=i.matrix?i.matrix:o?ei(i.cameraState||this.camera.getState(),i.viewportDimensions||this.getDimensions(),i.graphDimensions||this.getGraphDimensions(),i.padding||this.getStagePadding(),!0):this.invMatrix,a=pc(s,{x:r.x/this.width*2-1,y:1-r.y/this.height*2});return isNaN(a.x)&&(a.x=0),isNaN(a.y)&&(a.y=0),a}},{key:"viewportToGraph",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.normalizationFunction.inverse(this.viewportToFramedGraph(r,i))}},{key:"graphToViewport",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.framedGraphToViewport(this.normalizationFunction(r),i)}},{key:"getGraphToViewportRatio",value:function(){var r={x:0,y:0},i={x:1,y:1},o=Math.sqrt(Math.pow(r.x-i.x,2)+Math.pow(r.y-i.y,2)),s=this.graphToViewport(r),a=this.graphToViewport(i),u=Math.sqrt(Math.pow(s.x-a.x,2)+Math.pow(s.y-a.y,2));return u/o}},{key:"getBBox",value:function(){return this.nodeExtent}},{key:"getCustomBBox",value:function(){return this.customBBox}},{key:"setCustomBBox",value:function(r){return this.customBBox=r,this.scheduleRender(),this}},{key:"kill",value:function(){this.emit("kill"),this.removeAllListeners(),this.unbindCameraHandlers(),window.removeEventListener("resize",this.activeListeners.handleResize),this.mouseCaptor.kill(),this.touchCaptor.kill(),this.unbindGraphHandlers(),this.clearIndices(),this.clearState(),this.nodeDataCache={},this.edgeDataCache={},this.highlightedNodes.clear(),this.renderFrame&&(cancelAnimationFrame(this.renderFrame),this.renderFrame=null),this.renderHighlightedNodesFrame&&(cancelAnimationFrame(this.renderHighlightedNodesFrame),this.renderHighlightedNodesFrame=null);for(var r=this.container;r.firstChild;)r.removeChild(r.firstChild);for(var i in this.nodePrograms)this.nodePrograms[i].kill();for(var o in this.nodeHoverPrograms)this.nodeHoverPrograms[o].kill();for(var s in this.edgePrograms)this.edgePrograms[s].kill();this.nodePrograms={},this.nodeHoverPrograms={},this.edgePrograms={};for(var a in this.elements)this.killLayer(a);this.canvasContexts={},this.webGLContexts={},this.elements={}}},{key:"scaleSize",value:function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.camera.ratio;return r/this.settings.zoomToSizeRatioFunction(i)*(this.getSetting("itemSizesReference")==="positions"?i*this.graphToViewportRatio:1)}},{key:"getCanvases",value:function(){var r={};for(var i in this.elements)this.elements[i]instanceof HTMLCanvasElement&&(r[i]=this.elements[i]);return r}}])})(sh),aR=sR;function uR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function W_(e){var t=uR(e,"string");return typeof t=="symbol"?t:t+""}function K_(e,t,n){return(t=W_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lm(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function _s(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lm(Object(n),!0).forEach(function(r){K_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lm(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function cR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function lR(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,W_(r.key),r)}}function dR(e,t,n){return t&&lR(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function ks(e){return ks=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ks(e)}function J_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(J_=function(){return!!e})()}function Y_(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function fR(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Y_(e)}function hR(e,t,n){return t=ks(t),fR(e,J_()?Reflect.construct(t,n||[],ks(e).constructor):t.apply(e,n))}function gc(e,t){return gc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},gc(e,t)}function pR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&gc(e,t)}function yc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function mR(e){if(Array.isArray(e))return yc(e)}function gR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function yR(e,t){if(e){if(typeof e=="string")return yc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?yc(e,t):void 0}}function vR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
422
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ru(e){return mR(e)||gR(e)||yR(e)||vR()}function X_(e,t,n,r){var i=Math.pow(1-e,2)*t.x+2*(1-e)*e*n.x+Math.pow(e,2)*r.x,o=Math.pow(1-e,2)*t.y+2*(1-e)*e*n.y+Math.pow(e,2)*r.y;return{x:i,y:o}}function bR(e,t,n){for(var r=20,i=0,o=e,s=0;s<r;s++){var a=X_((s+1)/r,e,t,n);i+=Math.sqrt(Math.pow(o.x-a.x,2)+Math.pow(o.y-a.y,2)),o=a}return i}function wR(e){var t=e.curvatureAttribute,n=e.defaultCurvature,r=e.keepLabelUpright,i=r===void 0?!0:r;return function(o,s,a,u,c){var l=c.edgeLabelSize,d=s[t]||n,f=c.edgeLabelFont,h=c.edgeLabelWeight,p=c.edgeLabelColor.attribute?s[c.edgeLabelColor.attribute]||c.edgeLabelColor.color||"#000":c.edgeLabelColor.color,m=s.label;if(m){o.fillStyle=p,o.font="".concat(h," ").concat(l,"px ").concat(f);var y=!i||a.x<u.x,w=y?a.x:u.x,g=y?a.y:u.y,b=y?u.x:a.x,v=y?u.y:a.y,k=(w+b)/2,S=(g+v)/2,_=b-w,N=v-g,P=Math.sqrt(Math.pow(_,2)+Math.pow(N,2)),z=y?1:-1,j=k+N*d*z,K=S-_*d*z,Y=s.size*.7+5,re={x:K-g,y:-(j-w)},he=Math.sqrt(Math.pow(re.x,2)+Math.pow(re.y,2)),M={x:v-K,y:-(b-j)},H=Math.sqrt(Math.pow(M.x,2)+Math.pow(M.y,2));w+=Y*re.x/he,g+=Y*re.y/he,b+=Y*M.x/H,v+=Y*M.y/H,j+=Y*N/P,K-=Y*_/P;var Q={x:j,y:K},ie={x:w,y:g},J={x:b,y:v},I=bR(ie,Q,J);if(!(I<a.size+u.size)){var L=o.measureText(m).width,G=I-a.size-u.size;if(L>G){var pe="…";for(m=m+pe,L=o.measureText(m).width;L>G&&m.length>1;)m=m.slice(0,-2)+pe,L=o.measureText(m).width;if(m.length<4)return}for(var se={},ne=0,ke=m.length;ne<ke;ne++){var xe=m[ne];se[xe]||(se[xe]=o.measureText(xe).width*(1+d*.35))}for(var Ze=.5-L/I/2,U=0,Z=m.length;U<Z;U++){var V=m[U],ee=X_(Ze,ie,Q,J),Ee=2*(1-Ze)*(j-w)+2*Ze*(b-j),ce=2*(1-Ze)*(K-g)+2*Ze*(v-K),ge=Math.atan2(ce,Ee);o.save(),o.translate(ee.x,ee.y),o.rotate(ge),o.fillText(V,0,0),o.restore(),Ze+=se[V]/I}}}}}function _R(e){var t=e.arrowHead,n=t?.extremity==="target"||t?.extremity==="both",r=t?.extremity==="source"||t?.extremity==="both",i=`
420
+ `,EN=xN,W_=WebGLRenderingContext,Xp=W_.UNSIGNED_BYTE,ti=W_.FLOAT,$N=["u_matrix","u_zoomRatio","u_sizeRatio","u_correctionRatio","u_pixelRatio","u_feather","u_minEdgeThickness"],TN=(function(e){function t(){return ht(this,t),Gt(this,t,arguments)}return jt(t,e),pt(t,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:EN,FRAGMENT_SHADER_SOURCE:B_,METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:$N,ATTRIBUTES:[{name:"a_positionStart",size:2,type:ti},{name:"a_positionEnd",size:2,type:ti},{name:"a_normal",size:2,type:ti},{name:"a_color",size:4,type:Xp,normalized:!0},{name:"a_id",size:4,type:Xp,normalized:!0}],CONSTANT_ATTRIBUTES:[{name:"a_positionCoef",size:1,type:ti},{name:"a_normalCoef",size:1,type:ti}],CONSTANT_DATA:[[0,1],[0,-1],[1,1],[1,1],[0,-1],[1,-1]]}}},{key:"processVisibleItem",value:function(r,i,o,s,a){var u=a.size||1,c=o.x,l=o.y,d=s.x,f=s.y,h=Pn(a.color),p=d-c,m=f-l,y=p*p+m*m,_=0,g=0;y&&(y=1/Math.sqrt(y),_=-m*y*u,g=p*y*u);var b=this.array;b[i++]=c,b[i++]=l,b[i++]=d,b[i++]=f,b[i++]=_,b[i++]=g,b[i++]=h,b[i++]=r}},{key:"setUniforms",value:function(r,i){var o=i.gl,s=i.uniformLocations,a=s.u_matrix,u=s.u_zoomRatio,c=s.u_feather,l=s.u_pixelRatio,d=s.u_correctionRatio,f=s.u_sizeRatio,h=s.u_minEdgeThickness;o.uniformMatrix3fv(a,!1,r.matrix),o.uniform1f(u,r.zoomRatio),o.uniform1f(f,r.sizeRatio),o.uniform1f(d,r.correctionRatio),o.uniform1f(l,r.pixelRatio),o.uniform1f(c,r.antiAliasingFeather),o.uniform1f(h,r.minEdgeThickness)}}])})(Qa),uh=(function(e){function t(){var n;return ht(this,t),n=Gt(this,t),n.rawEmitter=n,n}return jt(t,e),pt(t)})(m_.EventEmitter),Au,Qp;function CN(){return Qp||(Qp=1,Au=function(t){return t!==null&&typeof t=="object"&&typeof t.addUndirectedEdgeWithKey=="function"&&typeof t.dropNode=="function"&&typeof t.multi=="boolean"}),Au}var AN=CN();const IN=P1(AN);var NN=function(t){return t},RN=function(t){return t*t},LN=function(t){return t*(2-t)},zN=function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},PN=function(t){return t*t*t},DN=function(t){return--t*t*t+1},ON=function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},MN={linear:NN,quadraticIn:RN,quadraticOut:LN,quadraticInOut:zN,cubicIn:PN,cubicOut:DN,cubicInOut:ON},FN={easing:"quadraticInOut",duration:150};function Ht(){return Float32Array.of(1,0,0,0,1,0,0,0,1)}function Yo(e,t,n){return e[0]=t,e[4]=typeof n=="number"?n:t,e}function em(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[3]=-n,e[4]=r,e}function tm(e,t,n){return e[6]=t,e[7]=n,e}function bn(e,t){var n=e[0],r=e[1],i=e[2],o=e[3],s=e[4],a=e[5],u=e[6],c=e[7],l=e[8],d=t[0],f=t[1],h=t[2],p=t[3],m=t[4],y=t[5],_=t[6],g=t[7],b=t[8];return e[0]=d*n+f*o+h*u,e[1]=d*r+f*s+h*c,e[2]=d*i+f*a+h*l,e[3]=p*n+m*o+y*u,e[4]=p*r+m*s+y*c,e[5]=p*i+m*a+y*l,e[6]=_*n+g*o+b*u,e[7]=_*r+g*s+b*c,e[8]=_*i+g*a+b*l,e}function mc(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=e[0],i=e[1],o=e[3],s=e[4],a=e[6],u=e[7],c=t.x,l=t.y;return{x:c*r+l*o+a*n,y:c*i+l*s+u*n}}function UN(e,t){var n=e.height/e.width,r=t.height/t.width;return n<1&&r>1||n>1&&r<1?1:Math.min(Math.max(r,1/r),Math.max(1/n,n))}function ni(e,t,n,r,i){var o=e.angle,s=e.ratio,a=e.x,u=e.y,c=t.width,l=t.height,d=Ht(),f=Math.min(c,l)-2*r,h=UN(t,n);return i?(bn(d,tm(Ht(),a,u)),bn(d,Yo(Ht(),s)),bn(d,em(Ht(),o)),bn(d,Yo(Ht(),c/f/2/h,l/f/2/h))):(bn(d,Yo(Ht(),2*(f/c)*h,2*(f/l)*h)),bn(d,em(Ht(),-o)),bn(d,Yo(Ht(),1/s)),bn(d,tm(Ht(),-a,-u))),d}function GN(e,t,n){var r=mc(e,{x:Math.cos(t.angle),y:Math.sin(t.angle)},0),i=r.x,o=r.y;return 1/Math.sqrt(Math.pow(i,2)+Math.pow(o,2))/n.width}function jN(e){if(!e.order)return{x:[0,1],y:[0,1]};var t=1/0,n=-1/0,r=1/0,i=-1/0;return e.forEachNode(function(o,s){var a=s.x,u=s.y;a<t&&(t=a),a>n&&(n=a),u<r&&(r=u),u>i&&(i=u)}),{x:[t,n],y:[r,i]}}function ZN(e){if(!IN(e))throw new Error("Sigma: invalid graph instance.");e.forEachNode(function(t,n){if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw new Error("Sigma: Coordinates of node ".concat(t," are invalid. A node must have a numeric 'x' and 'y' attribute."))})}function BN(e,t,n){var r=document.createElement(e);if(t)for(var i in t)r.style[i]=t[i];if(n)for(var o in n)r.setAttribute(o,n[o]);return r}function nm(){return typeof window.devicePixelRatio<"u"?window.devicePixelRatio:1}function rm(e,t,n){return n.sort(function(r,i){var o=t(r)||0,s=t(i)||0;return o<s?-1:o>s?1:0})}function im(e){var t=Sr(e.x,2),n=t[0],r=t[1],i=Sr(e.y,2),o=i[0],s=i[1],a=Math.max(r-n,s-o),u=(r+n)/2,c=(s+o)/2;(a===0||Math.abs(a)===1/0||isNaN(a))&&(a=1),isNaN(u)&&(u=0),isNaN(c)&&(c=0);var l=function(f){return{x:.5+(f.x-u)/a,y:.5+(f.y-c)/a}};return l.applyTo=function(d){d.x=.5+(d.x-u)/a,d.y=.5+(d.y-c)/a},l.inverse=function(d){return{x:u+a*(d.x-.5),y:c+a*(d.y-.5)}},l.ratio=a,l}function gc(e){"@babel/helpers - typeof";return gc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},gc(e)}function om(e,t){var n=t.size;if(n!==0){var r=e.length;e.length+=n;var i=0;t.forEach(function(o){e[r+i]=o,i++})}}function Iu(e){e=e||{};for(var t=0,n=arguments.length<=1?0:arguments.length-1;t<n;t++){var r=t+1<1||arguments.length<=t+1?void 0:arguments[t+1];r&&Object.assign(e,r)}return e}var ch={hideEdgesOnMove:!1,hideLabelsOnMove:!1,renderLabels:!0,renderEdgeLabels:!1,enableEdgeEvents:!1,defaultNodeColor:"#999",defaultNodeType:"circle",defaultEdgeColor:"#ccc",defaultEdgeType:"line",labelFont:"Arial",labelSize:14,labelWeight:"normal",labelColor:{color:"#000"},edgeLabelFont:"Arial",edgeLabelSize:14,edgeLabelWeight:"normal",edgeLabelColor:{attribute:"color"},stagePadding:30,defaultDrawEdgeLabel:oN,defaultDrawNodeLabel:U_,defaultDrawNodeHover:sN,minEdgeThickness:1.7,antiAliasingFeather:1,dragTimeout:100,draggedEventsTolerance:3,inertiaDuration:200,inertiaRatio:3,zoomDuration:250,zoomingRatio:1.7,doubleClickTimeout:300,doubleClickZoomingRatio:2.2,doubleClickZoomingDuration:200,tapMoveTolerance:10,zoomToSizeRatioFunction:Math.sqrt,itemSizesReference:"screen",autoRescale:!0,autoCenter:!0,labelDensity:1,labelGridCellSize:100,labelRenderedSizeThreshold:6,nodeReducer:null,edgeReducer:null,zIndex:!1,minCameraRatio:null,maxCameraRatio:null,enableCameraZooming:!0,enableCameraPanning:!0,enableCameraRotation:!0,cameraPanBoundaries:null,allowInvalidContainer:!1,nodeProgramClasses:{},nodeHoverProgramClasses:{},edgeProgramClasses:{}},VN={circle:eu},HN={arrow:SN,line:TN};function Nu(e){if(typeof e.labelDensity!="number"||e.labelDensity<0)throw new Error("Settings: invalid `labelDensity`. Expecting a positive number.");var t=e.minCameraRatio,n=e.maxCameraRatio;if(typeof t=="number"&&typeof n=="number"&&n<t)throw new Error("Settings: invalid camera ratio boundaries. Expecting `maxCameraRatio` to be greater than `minCameraRatio`.")}function qN(e){var t=Iu({},ch,e);return t.nodeProgramClasses=Iu({},VN,t.nodeProgramClasses),t.edgeProgramClasses=Iu({},HN,t.edgeProgramClasses),t}var Xo=1.5,sm=(function(e){function t(){var n;return ht(this,t),n=Gt(this,t),D(n,"x",.5),D(n,"y",.5),D(n,"angle",0),D(n,"ratio",1),D(n,"minRatio",null),D(n,"maxRatio",null),D(n,"enabledZooming",!0),D(n,"enabledPanning",!0),D(n,"enabledRotation",!0),D(n,"clean",null),D(n,"nextFrame",null),D(n,"previousState",null),D(n,"enabled",!0),n.previousState=n.getState(),n}return jt(t,e),pt(t,[{key:"enable",value:function(){return this.enabled=!0,this}},{key:"disable",value:function(){return this.enabled=!1,this}},{key:"getState",value:function(){return{x:this.x,y:this.y,angle:this.angle,ratio:this.ratio}}},{key:"hasState",value:function(r){return this.x===r.x&&this.y===r.y&&this.ratio===r.ratio&&this.angle===r.angle}},{key:"getPreviousState",value:function(){var r=this.previousState;return r?{x:r.x,y:r.y,angle:r.angle,ratio:r.ratio}:null}},{key:"getBoundedRatio",value:function(r){var i=r;return typeof this.minRatio=="number"&&(i=Math.max(i,this.minRatio)),typeof this.maxRatio=="number"&&(i=Math.min(i,this.maxRatio)),i}},{key:"validateState",value:function(r){var i={};return this.enabledPanning&&typeof r.x=="number"&&(i.x=r.x),this.enabledPanning&&typeof r.y=="number"&&(i.y=r.y),this.enabledZooming&&typeof r.ratio=="number"&&(i.ratio=this.getBoundedRatio(r.ratio)),this.enabledRotation&&typeof r.angle=="number"&&(i.angle=r.angle),this.clean?this.clean(Q(Q({},this.getState()),i)):i}},{key:"isAnimated",value:function(){return!!this.nextFrame}},{key:"setState",value:function(r){if(!this.enabled)return this;this.previousState=this.getState();var i=this.validateState(r);return typeof i.x=="number"&&(this.x=i.x),typeof i.y=="number"&&(this.y=i.y),typeof i.ratio=="number"&&(this.ratio=i.ratio),typeof i.angle=="number"&&(this.angle=i.angle),this.hasState(this.previousState)||this.emit("updated",this.getState()),this}},{key:"updateState",value:function(r){return this.setState(r(this.getState())),this}},{key:"animate",value:function(r){var i=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;if(!s)return new Promise(function(h){return i.animate(r,o,h)});if(this.enabled){var a=Q(Q({},FN),o),u=this.validateState(r),c=typeof a.easing=="function"?a.easing:MN[a.easing],l=Date.now(),d=this.getState(),f=function(){var p=(Date.now()-l)/a.duration;if(p>=1){i.nextFrame=null,i.setState(u),i.animationCallback&&(i.animationCallback.call(null),i.animationCallback=void 0);return}var m=c(p),y={};typeof u.x=="number"&&(y.x=d.x+(u.x-d.x)*m),typeof u.y=="number"&&(y.y=d.y+(u.y-d.y)*m),i.enabledRotation&&typeof u.angle=="number"&&(y.angle=d.angle+(u.angle-d.angle)*m),typeof u.ratio=="number"&&(y.ratio=d.ratio+(u.ratio-d.ratio)*m),i.setState(y),i.nextFrame=requestAnimationFrame(f)};this.nextFrame?(cancelAnimationFrame(this.nextFrame),this.animationCallback&&this.animationCallback.call(null),this.nextFrame=requestAnimationFrame(f)):f(),this.animationCallback=s}}},{key:"animatedZoom",value:function(r){return r?typeof r=="number"?this.animate({ratio:this.ratio/r}):this.animate({ratio:this.ratio/(r.factor||Xo)},r):this.animate({ratio:this.ratio/Xo})}},{key:"animatedUnzoom",value:function(r){return r?typeof r=="number"?this.animate({ratio:this.ratio*r}):this.animate({ratio:this.ratio*(r.factor||Xo)},r):this.animate({ratio:this.ratio*Xo})}},{key:"animatedReset",value:function(r){return this.animate({x:.5,y:.5,ratio:1,angle:0},r)}},{key:"copy",value:function(){return t.from(this.getState())}}],[{key:"from",value:function(r){var i=new t;return i.setState(r)}}])})(uh);function Wt(e,t){var n=t.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}function rn(e,t){var n=Q(Q({},Wt(e,t)),{},{sigmaDefaultPrevented:!1,preventSigmaDefault:function(){n.sigmaDefaultPrevented=!0},original:e});return n}function ri(e){var t="x"in e?e:Q(Q({},e.touches[0]||e.previousTouches[0]),{},{original:e.original,sigmaDefaultPrevented:e.sigmaDefaultPrevented,preventSigmaDefault:function(){e.sigmaDefaultPrevented=!0,t.sigmaDefaultPrevented=!0}});return t}function WN(e,t){return Q(Q({},rn(e,t)),{},{delta:K_(e)})}var KN=2;function ss(e){for(var t=[],n=0,r=Math.min(e.length,KN);n<r;n++)t.push(e[n]);return t}function ii(e,t,n){var r={touches:ss(e.touches).map(function(i){return Wt(i,n)}),previousTouches:t.map(function(i){return Wt(i,n)}),sigmaDefaultPrevented:!1,preventSigmaDefault:function(){r.sigmaDefaultPrevented=!0},original:e};return r}function K_(e){if(typeof e.deltaY<"u")return e.deltaY*-3/360;if(typeof e.detail<"u")return e.detail/-9;throw new Error("Captor: could not extract delta from event.")}var J_=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t),i.container=n,i.renderer=r,i}return jt(t,e),pt(t)})(uh),JN=["doubleClickTimeout","doubleClickZoomingDuration","doubleClickZoomingRatio","dragTimeout","draggedEventsTolerance","inertiaDuration","inertiaRatio","zoomDuration","zoomingRatio"],YN=JN.reduce(function(e,t){return Q(Q({},e),{},D({},t,ch[t]))},{}),XN=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t,[n,r]),D(i,"enabled",!0),D(i,"draggedEvents",0),D(i,"downStartTime",null),D(i,"lastMouseX",null),D(i,"lastMouseY",null),D(i,"isMouseDown",!1),D(i,"isMoving",!1),D(i,"movingTimeout",null),D(i,"startCameraState",null),D(i,"clicks",0),D(i,"doubleClickTimeout",null),D(i,"currentWheelDirection",0),D(i,"settings",YN),i.handleClick=i.handleClick.bind(i),i.handleRightClick=i.handleRightClick.bind(i),i.handleDown=i.handleDown.bind(i),i.handleUp=i.handleUp.bind(i),i.handleMove=i.handleMove.bind(i),i.handleWheel=i.handleWheel.bind(i),i.handleLeave=i.handleLeave.bind(i),i.handleEnter=i.handleEnter.bind(i),n.addEventListener("click",i.handleClick,{capture:!1}),n.addEventListener("contextmenu",i.handleRightClick,{capture:!1}),n.addEventListener("mousedown",i.handleDown,{capture:!1}),n.addEventListener("wheel",i.handleWheel,{capture:!1}),n.addEventListener("mouseleave",i.handleLeave,{capture:!1}),n.addEventListener("mouseenter",i.handleEnter,{capture:!1}),document.addEventListener("mousemove",i.handleMove,{capture:!1}),document.addEventListener("mouseup",i.handleUp,{capture:!1}),i}return jt(t,e),pt(t,[{key:"kill",value:function(){var r=this.container;r.removeEventListener("click",this.handleClick),r.removeEventListener("contextmenu",this.handleRightClick),r.removeEventListener("mousedown",this.handleDown),r.removeEventListener("wheel",this.handleWheel),r.removeEventListener("mouseleave",this.handleLeave),r.removeEventListener("mouseenter",this.handleEnter),document.removeEventListener("mousemove",this.handleMove),document.removeEventListener("mouseup",this.handleUp)}},{key:"handleClick",value:function(r){var i=this;if(this.enabled){if(this.clicks++,this.clicks===2)return this.clicks=0,typeof this.doubleClickTimeout=="number"&&(clearTimeout(this.doubleClickTimeout),this.doubleClickTimeout=null),this.handleDoubleClick(r);setTimeout(function(){i.clicks=0,i.doubleClickTimeout=null},this.settings.doubleClickTimeout),this.draggedEvents<this.settings.draggedEventsTolerance&&this.emit("click",rn(r,this.container))}}},{key:"handleRightClick",value:function(r){this.enabled&&this.emit("rightClick",rn(r,this.container))}},{key:"handleDoubleClick",value:function(r){if(this.enabled){r.preventDefault(),r.stopPropagation();var i=rn(r,this.container);if(this.emit("doubleClick",i),!i.sigmaDefaultPrevented){var o=this.renderer.getCamera(),s=o.getBoundedRatio(o.getState().ratio/this.settings.doubleClickZoomingRatio);o.animate(this.renderer.getViewportZoomedState(Wt(r,this.container),s),{easing:"quadraticInOut",duration:this.settings.doubleClickZoomingDuration})}}}},{key:"handleDown",value:function(r){if(this.enabled){if(r.button===0){this.startCameraState=this.renderer.getCamera().getState();var i=Wt(r,this.container),o=i.x,s=i.y;this.lastMouseX=o,this.lastMouseY=s,this.draggedEvents=0,this.downStartTime=Date.now(),this.isMouseDown=!0}this.emit("mousedown",rn(r,this.container))}}},{key:"handleUp",value:function(r){var i=this;if(!(!this.enabled||!this.isMouseDown)){var o=this.renderer.getCamera();this.isMouseDown=!1,typeof this.movingTimeout=="number"&&(clearTimeout(this.movingTimeout),this.movingTimeout=null);var s=Wt(r,this.container),a=s.x,u=s.y,c=o.getState(),l=o.getPreviousState()||{x:0,y:0};this.isMoving?o.animate({x:c.x+this.settings.inertiaRatio*(c.x-l.x),y:c.y+this.settings.inertiaRatio*(c.y-l.y)},{duration:this.settings.inertiaDuration,easing:"quadraticOut"}):(this.lastMouseX!==a||this.lastMouseY!==u)&&o.setState({x:c.x,y:c.y}),this.isMoving=!1,setTimeout(function(){var d=i.draggedEvents>0;i.draggedEvents=0,d&&i.renderer.getSetting("hideEdgesOnMove")&&i.renderer.refresh()},0),this.emit("mouseup",rn(r,this.container))}}},{key:"handleMove",value:function(r){var i=this;if(this.enabled){var o=rn(r,this.container);if(this.emit("mousemovebody",o),(r.target===this.container||r.composedPath()[0]===this.container)&&this.emit("mousemove",o),!o.sigmaDefaultPrevented&&this.isMouseDown){this.isMoving=!0,this.draggedEvents++,typeof this.movingTimeout=="number"&&clearTimeout(this.movingTimeout),this.movingTimeout=window.setTimeout(function(){i.movingTimeout=null,i.isMoving=!1},this.settings.dragTimeout);var s=this.renderer.getCamera(),a=Wt(r,this.container),u=a.x,c=a.y,l=this.renderer.viewportToFramedGraph({x:this.lastMouseX,y:this.lastMouseY}),d=this.renderer.viewportToFramedGraph({x:u,y:c}),f=l.x-d.x,h=l.y-d.y,p=s.getState(),m=p.x+f,y=p.y+h;s.setState({x:m,y}),this.lastMouseX=u,this.lastMouseY=c,r.preventDefault(),r.stopPropagation()}}}},{key:"handleLeave",value:function(r){this.emit("mouseleave",rn(r,this.container))}},{key:"handleEnter",value:function(r){this.emit("mouseenter",rn(r,this.container))}},{key:"handleWheel",value:function(r){var i=this,o=this.renderer.getCamera();if(!(!this.enabled||!o.enabledZooming)){var s=K_(r);if(s){var a=WN(r,this.container);if(this.emit("wheel",a),a.sigmaDefaultPrevented){r.preventDefault(),r.stopPropagation();return}var u=o.getState().ratio,c=s>0?1/this.settings.zoomingRatio:this.settings.zoomingRatio,l=o.getBoundedRatio(u*c),d=s>0?1:-1,f=Date.now();u!==l&&(r.preventDefault(),r.stopPropagation(),!(this.currentWheelDirection===d&&this.lastWheelTriggerTime&&f-this.lastWheelTriggerTime<this.settings.zoomDuration/5)&&(o.animate(this.renderer.getViewportZoomedState(Wt(r,this.container),l),{easing:"quadraticOut",duration:this.settings.zoomDuration},function(){i.currentWheelDirection=0}),this.currentWheelDirection=d,this.lastWheelTriggerTime=f))}}}},{key:"setSettings",value:function(r){this.settings=r}}])})(J_),QN=["dragTimeout","inertiaDuration","inertiaRatio","doubleClickTimeout","doubleClickZoomingRatio","doubleClickZoomingDuration","tapMoveTolerance"],eR=QN.reduce(function(e,t){return Q(Q({},e),{},D({},t,ch[t]))},{}),tR=(function(e){function t(n,r){var i;return ht(this,t),i=Gt(this,t,[n,r]),D(i,"enabled",!0),D(i,"isMoving",!1),D(i,"hasMoved",!1),D(i,"touchMode",0),D(i,"startTouchesPositions",[]),D(i,"lastTouches",[]),D(i,"lastTap",null),D(i,"settings",eR),i.handleStart=i.handleStart.bind(i),i.handleLeave=i.handleLeave.bind(i),i.handleMove=i.handleMove.bind(i),n.addEventListener("touchstart",i.handleStart,{capture:!1}),n.addEventListener("touchcancel",i.handleLeave,{capture:!1}),document.addEventListener("touchend",i.handleLeave,{capture:!1,passive:!1}),document.addEventListener("touchmove",i.handleMove,{capture:!1,passive:!1}),i}return jt(t,e),pt(t,[{key:"kill",value:function(){var r=this.container;r.removeEventListener("touchstart",this.handleStart),r.removeEventListener("touchcancel",this.handleLeave),document.removeEventListener("touchend",this.handleLeave),document.removeEventListener("touchmove",this.handleMove)}},{key:"getDimensions",value:function(){return{width:this.container.offsetWidth,height:this.container.offsetHeight}}},{key:"handleStart",value:function(r){var i=this;if(this.enabled){r.preventDefault();var o=ss(r.touches);if(this.touchMode=o.length,this.startCameraState=this.renderer.getCamera().getState(),this.startTouchesPositions=o.map(function(h){return Wt(h,i.container)}),this.touchMode===2){var s=Sr(this.startTouchesPositions,2),a=s[0],u=a.x,c=a.y,l=s[1],d=l.x,f=l.y;this.startTouchesAngle=Math.atan2(f-c,d-u),this.startTouchesDistance=Math.sqrt(Math.pow(d-u,2)+Math.pow(f-c,2))}this.emit("touchdown",ii(r,this.lastTouches,this.container)),this.lastTouches=o,this.lastTouchesPositions=this.startTouchesPositions}}},{key:"handleLeave",value:function(r){if(!(!this.enabled||!this.startTouchesPositions.length)){switch(r.cancelable&&r.preventDefault(),this.movingTimeout&&(this.isMoving=!1,clearTimeout(this.movingTimeout)),this.touchMode){case 2:if(r.touches.length===1){this.handleStart(r),r.preventDefault();break}case 1:if(this.isMoving){var i=this.renderer.getCamera(),o=i.getState(),s=i.getPreviousState()||{x:0,y:0};i.animate({x:o.x+this.settings.inertiaRatio*(o.x-s.x),y:o.y+this.settings.inertiaRatio*(o.y-s.y)},{duration:this.settings.inertiaDuration,easing:"quadraticOut"})}this.hasMoved=!1,this.isMoving=!1,this.touchMode=0;break}if(this.emit("touchup",ii(r,this.lastTouches,this.container)),!r.touches.length){var a=Wt(this.lastTouches[0],this.container),u=this.startTouchesPositions[0],c=Math.pow(a.x-u.x,2)+Math.pow(a.y-u.y,2);if(!r.touches.length&&c<Math.pow(this.settings.tapMoveTolerance,2))if(this.lastTap&&Date.now()-this.lastTap.time<this.settings.doubleClickTimeout){var l=ii(r,this.lastTouches,this.container);if(this.emit("doubletap",l),this.lastTap=null,!l.sigmaDefaultPrevented){var d=this.renderer.getCamera(),f=d.getBoundedRatio(d.getState().ratio/this.settings.doubleClickZoomingRatio);d.animate(this.renderer.getViewportZoomedState(a,f),{easing:"quadraticInOut",duration:this.settings.doubleClickZoomingDuration})}}else{var h=ii(r,this.lastTouches,this.container);this.emit("tap",h),this.lastTap={time:Date.now(),position:h.touches[0]||h.previousTouches[0]}}}this.lastTouches=ss(r.touches),this.startTouchesPositions=[]}}},{key:"handleMove",value:function(r){var i=this;if(!(!this.enabled||!this.startTouchesPositions.length)){r.preventDefault();var o=ss(r.touches),s=o.map(function(I){return Wt(I,i.container)}),a=this.lastTouches;this.lastTouches=o,this.lastTouchesPositions=s;var u=ii(r,a,this.container);if(this.emit("touchmove",u),!u.sigmaDefaultPrevented&&(this.hasMoved||(this.hasMoved=s.some(function(I,L){var U=i.startTouchesPositions[L];return U&&(I.x!==U.x||I.y!==U.y)})),!!this.hasMoved)){this.isMoving=!0,this.movingTimeout&&clearTimeout(this.movingTimeout),this.movingTimeout=window.setTimeout(function(){i.isMoving=!1},this.settings.dragTimeout);var c=this.renderer.getCamera(),l=this.startCameraState,d=this.renderer.getSetting("stagePadding");switch(this.touchMode){case 1:{var f=this.renderer.viewportToFramedGraph((this.startTouchesPositions||[])[0]),h=f.x,p=f.y,m=this.renderer.viewportToFramedGraph(s[0]),y=m.x,_=m.y;c.setState({x:l.x+h-y,y:l.y+p-_});break}case 2:{var g={x:.5,y:.5,angle:0,ratio:1},b=s[0],v=b.x,w=b.y,k=s[1],x=k.x,N=k.y,z=Math.atan2(N-w,x-v)-this.startTouchesAngle,O=Math.hypot(N-w,x-v)/this.startTouchesDistance,Z=c.getBoundedRatio(l.ratio/O);g.ratio=Z,g.angle=l.angle+z;var ee=this.getDimensions(),ae=this.renderer.viewportToFramedGraph((this.startTouchesPositions||[])[0],{cameraState:l}),we=Math.min(ee.width,ee.height)-2*d,Re=we/ee.width,G=we/ee.height,q=Z/we,Y=v-we/2/Re,ne=w-we/2/G,K=[Y*Math.cos(-g.angle)-ne*Math.sin(-g.angle),ne*Math.cos(-g.angle)+Y*Math.sin(-g.angle)];Y=K[0],ne=K[1],g.x=ae.x-Y*q,g.y=ae.y+ne*q,c.setState(g);break}}}}}},{key:"setSettings",value:function(r){this.settings=r}}])})(J_);function nR(e){if(Array.isArray(e))return hc(e)}function rR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function iR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
421
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function am(e){return nR(e)||rR(e)||N_(e)||iR()}function oR(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Ru(e,t){if(e==null)return{};var n,r,i=oR(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var um=(function(){function e(t,n){ht(this,e),this.key=t,this.size=n}return pt(e,null,[{key:"compare",value:function(n,r){return n.size>r.size?-1:n.size<r.size||n.key>r.key?1:-1}}])})(),cm=(function(){function e(){ht(this,e),D(this,"width",0),D(this,"height",0),D(this,"cellSize",0),D(this,"columns",0),D(this,"rows",0),D(this,"cells",{})}return pt(e,[{key:"resizeAndClear",value:function(n,r){this.width=n.width,this.height=n.height,this.cellSize=r,this.columns=Math.ceil(n.width/r),this.rows=Math.ceil(n.height/r),this.cells={}}},{key:"getIndex",value:function(n){var r=Math.floor(n.x/this.cellSize),i=Math.floor(n.y/this.cellSize);return i*this.columns+r}},{key:"add",value:function(n,r,i){var o=new um(n,r),s=this.getIndex(i),a=this.cells[s];a||(a=[],this.cells[s]=a),a.push(o)}},{key:"organize",value:function(){for(var n in this.cells){var r=this.cells[n];r.sort(um.compare)}}},{key:"getLabelsToDisplay",value:function(n,r){var i=this.cellSize*this.cellSize,o=i/n/n,s=o*r/i,a=Math.ceil(s),u=[];for(var c in this.cells)for(var l=this.cells[c],d=0;d<Math.min(a,l.length);d++)u.push(l[d].key);return u}}])})();function sR(e){var t=e.graph,n=e.hoveredNode,r=e.highlightedNodes,i=e.displayedNodeLabels,o=[];return t.forEachEdge(function(s,a,u,c){(u===n||c===n||r.has(u)||r.has(c)||i.has(u)&&i.has(c))&&o.push(s)}),o}var lm=150,dm=50,on=Object.prototype.hasOwnProperty;function aR(e,t,n){if(!on.call(n,"x")||!on.call(n,"y"))throw new Error('Sigma: could not find a valid position (x, y) for node "'.concat(t,'". All your nodes must have a number "x" and "y". Maybe your forgot to apply a layout or your "nodeReducer" is not returning the correct data?'));return n.color||(n.color=e.defaultNodeColor),!n.label&&n.label!==""&&(n.label=null),n.label!==void 0&&n.label!==null?n.label=""+n.label:n.label=null,n.size||(n.size=2),on.call(n,"hidden")||(n.hidden=!1),on.call(n,"highlighted")||(n.highlighted=!1),on.call(n,"forceLabel")||(n.forceLabel=!1),(!n.type||n.type==="")&&(n.type=e.defaultNodeType),n.zIndex||(n.zIndex=0),n}function uR(e,t,n){return n.color||(n.color=e.defaultEdgeColor),n.label||(n.label=""),n.size||(n.size=.5),on.call(n,"hidden")||(n.hidden=!1),on.call(n,"forceLabel")||(n.forceLabel=!1),(!n.type||n.type==="")&&(n.type=e.defaultEdgeType),n.zIndex||(n.zIndex=0),n}var cR=(function(e){function t(n,r){var i,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(ht(this,t),i=Gt(this,t),D(i,"elements",{}),D(i,"canvasContexts",{}),D(i,"webGLContexts",{}),D(i,"pickingLayers",new Set),D(i,"textures",{}),D(i,"frameBuffers",{}),D(i,"activeListeners",{}),D(i,"labelGrid",new cm),D(i,"nodeDataCache",{}),D(i,"edgeDataCache",{}),D(i,"nodeProgramIndex",{}),D(i,"edgeProgramIndex",{}),D(i,"nodesWithForcedLabels",new Set),D(i,"edgesWithForcedLabels",new Set),D(i,"nodeExtent",{x:[0,1],y:[0,1]}),D(i,"nodeZExtent",[1/0,-1/0]),D(i,"edgeZExtent",[1/0,-1/0]),D(i,"matrix",Ht()),D(i,"invMatrix",Ht()),D(i,"correctionRatio",1),D(i,"customBBox",null),D(i,"normalizationFunction",im({x:[0,1],y:[0,1]})),D(i,"graphToViewportRatio",1),D(i,"itemIDsIndex",{}),D(i,"nodeIndices",{}),D(i,"edgeIndices",{}),D(i,"width",0),D(i,"height",0),D(i,"pixelRatio",nm()),D(i,"pickingDownSizingRatio",2*i.pixelRatio),D(i,"displayedNodeLabels",new Set),D(i,"displayedEdgeLabels",new Set),D(i,"highlightedNodes",new Set),D(i,"hoveredNode",null),D(i,"hoveredEdge",null),D(i,"renderFrame",null),D(i,"renderHighlightedNodesFrame",null),D(i,"needToProcess",!1),D(i,"checkEdgesEventsFrame",null),D(i,"nodePrograms",{}),D(i,"nodeHoverPrograms",{}),D(i,"edgePrograms",{}),i.settings=qN(o),Nu(i.settings),ZN(n),!(r instanceof HTMLElement))throw new Error("Sigma: container should be an html element.");i.graph=n,i.container=r,i.createWebGLContext("edges",{picking:o.enableEdgeEvents}),i.createCanvasContext("edgeLabels"),i.createWebGLContext("nodes",{picking:!0}),i.createCanvasContext("labels"),i.createCanvasContext("hovers"),i.createWebGLContext("hoverNodes"),i.createCanvasContext("mouse",{style:{touchAction:"none",userSelect:"none"}}),i.resize();for(var s in i.settings.nodeProgramClasses)i.registerNodeProgram(s,i.settings.nodeProgramClasses[s],i.settings.nodeHoverProgramClasses[s]);for(var a in i.settings.edgeProgramClasses)i.registerEdgeProgram(a,i.settings.edgeProgramClasses[a]);return i.camera=new sm,i.bindCameraHandlers(),i.mouseCaptor=new XN(i.elements.mouse,i),i.mouseCaptor.setSettings(i.settings),i.touchCaptor=new tR(i.elements.mouse,i),i.touchCaptor.setSettings(i.settings),i.bindEventHandlers(),i.bindGraphHandlers(),i.handleSettingsUpdate(),i.refresh(),i}return jt(t,e),pt(t,[{key:"registerNodeProgram",value:function(r,i,o){return this.nodePrograms[r]&&this.nodePrograms[r].kill(),this.nodeHoverPrograms[r]&&this.nodeHoverPrograms[r].kill(),this.nodePrograms[r]=new i(this.webGLContexts.nodes,this.frameBuffers.nodes,this),this.nodeHoverPrograms[r]=new(o||i)(this.webGLContexts.hoverNodes,null,this),this}},{key:"registerEdgeProgram",value:function(r,i){return this.edgePrograms[r]&&this.edgePrograms[r].kill(),this.edgePrograms[r]=new i(this.webGLContexts.edges,this.frameBuffers.edges,this),this}},{key:"unregisterNodeProgram",value:function(r){if(this.nodePrograms[r]){var i=this.nodePrograms,o=i[r],s=Ru(i,[r].map(li));o.kill(),this.nodePrograms=s}if(this.nodeHoverPrograms[r]){var a=this.nodeHoverPrograms,u=a[r],c=Ru(a,[r].map(li));u.kill(),this.nodePrograms=c}return this}},{key:"unregisterEdgeProgram",value:function(r){if(this.edgePrograms[r]){var i=this.edgePrograms,o=i[r],s=Ru(i,[r].map(li));o.kill(),this.edgePrograms=s}return this}},{key:"resetWebGLTexture",value:function(r){var i=this.webGLContexts[r],o=this.frameBuffers[r],s=this.textures[r];s&&i.deleteTexture(s);var a=i.createTexture();return i.bindFramebuffer(i.FRAMEBUFFER,o),i.bindTexture(i.TEXTURE_2D,a),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,a,0),this.textures[r]=a,this}},{key:"bindCameraHandlers",value:function(){var r=this;return this.activeListeners.camera=function(){r.scheduleRender()},this.camera.on("updated",this.activeListeners.camera),this}},{key:"unbindCameraHandlers",value:function(){return this.camera.removeListener("updated",this.activeListeners.camera),this}},{key:"getNodeAtPosition",value:function(r){var i=r.x,o=r.y,s=Bp(this.webGLContexts.nodes,this.frameBuffers.nodes,i,o,this.pixelRatio,this.pickingDownSizingRatio),a=Zp.apply(void 0,am(s)),u=this.itemIDsIndex[a];return u&&u.type==="node"?u.id:null}},{key:"bindEventHandlers",value:function(){var r=this;this.activeListeners.handleResize=function(){r.scheduleRefresh()},window.addEventListener("resize",this.activeListeners.handleResize),this.activeListeners.handleMove=function(o){var s=ri(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}},u=r.getNodeAtPosition(s);if(u&&r.hoveredNode!==u&&!r.nodeDataCache[u].hidden){r.hoveredNode&&r.emit("leaveNode",Q(Q({},a),{},{node:r.hoveredNode})),r.hoveredNode=u,r.emit("enterNode",Q(Q({},a),{},{node:u})),r.scheduleHighlightedNodesRender();return}if(r.hoveredNode&&r.getNodeAtPosition(s)!==r.hoveredNode){var c=r.hoveredNode;r.hoveredNode=null,r.emit("leaveNode",Q(Q({},a),{},{node:c})),r.scheduleHighlightedNodesRender();return}if(r.settings.enableEdgeEvents){var l=r.hoveredNode?null:r.getEdgeAtPoint(a.event.x,a.event.y);l!==r.hoveredEdge&&(r.hoveredEdge&&r.emit("leaveEdge",Q(Q({},a),{},{edge:r.hoveredEdge})),l&&r.emit("enterEdge",Q(Q({},a),{},{edge:l})),r.hoveredEdge=l)}},this.activeListeners.handleMoveBody=function(o){var s=ri(o);r.emit("moveBody",{event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}})},this.activeListeners.handleLeave=function(o){var s=ri(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}};r.hoveredNode&&(r.emit("leaveNode",Q(Q({},a),{},{node:r.hoveredNode})),r.scheduleHighlightedNodesRender()),r.settings.enableEdgeEvents&&r.hoveredEdge&&(r.emit("leaveEdge",Q(Q({},a),{},{edge:r.hoveredEdge})),r.scheduleHighlightedNodesRender()),r.emit("leaveStage",Q({},a))},this.activeListeners.handleEnter=function(o){var s=ri(o),a={event:s,preventSigmaDefault:function(){s.preventSigmaDefault()}};r.emit("enterStage",Q({},a))};var i=function(s){return function(a){var u=ri(a),c={event:u,preventSigmaDefault:function(){u.preventSigmaDefault()}},l=r.getNodeAtPosition(u);if(l)return r.emit("".concat(s,"Node"),Q(Q({},c),{},{node:l}));if(r.settings.enableEdgeEvents){var d=r.getEdgeAtPoint(u.x,u.y);if(d)return r.emit("".concat(s,"Edge"),Q(Q({},c),{},{edge:d}))}return r.emit("".concat(s,"Stage"),c)}};return this.activeListeners.handleClick=i("click"),this.activeListeners.handleRightClick=i("rightClick"),this.activeListeners.handleDoubleClick=i("doubleClick"),this.activeListeners.handleWheel=i("wheel"),this.activeListeners.handleDown=i("down"),this.activeListeners.handleUp=i("up"),this.mouseCaptor.on("mousemove",this.activeListeners.handleMove),this.mouseCaptor.on("mousemovebody",this.activeListeners.handleMoveBody),this.mouseCaptor.on("click",this.activeListeners.handleClick),this.mouseCaptor.on("rightClick",this.activeListeners.handleRightClick),this.mouseCaptor.on("doubleClick",this.activeListeners.handleDoubleClick),this.mouseCaptor.on("wheel",this.activeListeners.handleWheel),this.mouseCaptor.on("mousedown",this.activeListeners.handleDown),this.mouseCaptor.on("mouseup",this.activeListeners.handleUp),this.mouseCaptor.on("mouseleave",this.activeListeners.handleLeave),this.mouseCaptor.on("mouseenter",this.activeListeners.handleEnter),this.touchCaptor.on("touchdown",this.activeListeners.handleDown),this.touchCaptor.on("touchdown",this.activeListeners.handleMove),this.touchCaptor.on("touchup",this.activeListeners.handleUp),this.touchCaptor.on("touchmove",this.activeListeners.handleMove),this.touchCaptor.on("tap",this.activeListeners.handleClick),this.touchCaptor.on("doubletap",this.activeListeners.handleDoubleClick),this.touchCaptor.on("touchmove",this.activeListeners.handleMoveBody),this}},{key:"bindGraphHandlers",value:function(){var r=this,i=this.graph,o=new Set(["x","y","zIndex","type"]);return this.activeListeners.eachNodeAttributesUpdatedGraphUpdate=function(s){var a,u=(a=s.hints)===null||a===void 0?void 0:a.attributes;r.graph.forEachNode(function(l){return r.updateNode(l)});var c=!u||u.some(function(l){return o.has(l)});r.refresh({partialGraph:{nodes:i.nodes()},skipIndexation:!c,schedule:!0})},this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate=function(s){var a,u=(a=s.hints)===null||a===void 0?void 0:a.attributes;r.graph.forEachEdge(function(l){return r.updateEdge(l)});var c=u&&["zIndex","type"].some(function(l){return u?.includes(l)});r.refresh({partialGraph:{edges:i.edges()},skipIndexation:!c,schedule:!0})},this.activeListeners.addNodeGraphUpdate=function(s){var a=s.key;r.addNode(a),r.refresh({partialGraph:{nodes:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.updateNodeGraphUpdate=function(s){var a=s.key;r.refresh({partialGraph:{nodes:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.dropNodeGraphUpdate=function(s){var a=s.key;r.removeNode(a),r.refresh({schedule:!0})},this.activeListeners.addEdgeGraphUpdate=function(s){var a=s.key;r.addEdge(a),r.refresh({partialGraph:{edges:[a]},schedule:!0})},this.activeListeners.updateEdgeGraphUpdate=function(s){var a=s.key;r.refresh({partialGraph:{edges:[a]},skipIndexation:!1,schedule:!0})},this.activeListeners.dropEdgeGraphUpdate=function(s){var a=s.key;r.removeEdge(a),r.refresh({schedule:!0})},this.activeListeners.clearEdgesGraphUpdate=function(){r.clearEdgeState(),r.clearEdgeIndices(),r.refresh({schedule:!0})},this.activeListeners.clearGraphUpdate=function(){r.clearEdgeState(),r.clearNodeState(),r.clearEdgeIndices(),r.clearNodeIndices(),r.refresh({schedule:!0})},i.on("nodeAdded",this.activeListeners.addNodeGraphUpdate),i.on("nodeDropped",this.activeListeners.dropNodeGraphUpdate),i.on("nodeAttributesUpdated",this.activeListeners.updateNodeGraphUpdate),i.on("eachNodeAttributesUpdated",this.activeListeners.eachNodeAttributesUpdatedGraphUpdate),i.on("edgeAdded",this.activeListeners.addEdgeGraphUpdate),i.on("edgeDropped",this.activeListeners.dropEdgeGraphUpdate),i.on("edgeAttributesUpdated",this.activeListeners.updateEdgeGraphUpdate),i.on("eachEdgeAttributesUpdated",this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate),i.on("edgesCleared",this.activeListeners.clearEdgesGraphUpdate),i.on("cleared",this.activeListeners.clearGraphUpdate),this}},{key:"unbindGraphHandlers",value:function(){var r=this.graph;r.removeListener("nodeAdded",this.activeListeners.addNodeGraphUpdate),r.removeListener("nodeDropped",this.activeListeners.dropNodeGraphUpdate),r.removeListener("nodeAttributesUpdated",this.activeListeners.updateNodeGraphUpdate),r.removeListener("eachNodeAttributesUpdated",this.activeListeners.eachNodeAttributesUpdatedGraphUpdate),r.removeListener("edgeAdded",this.activeListeners.addEdgeGraphUpdate),r.removeListener("edgeDropped",this.activeListeners.dropEdgeGraphUpdate),r.removeListener("edgeAttributesUpdated",this.activeListeners.updateEdgeGraphUpdate),r.removeListener("eachEdgeAttributesUpdated",this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate),r.removeListener("edgesCleared",this.activeListeners.clearEdgesGraphUpdate),r.removeListener("cleared",this.activeListeners.clearGraphUpdate)}},{key:"getEdgeAtPoint",value:function(r,i){var o=Bp(this.webGLContexts.edges,this.frameBuffers.edges,r,i,this.pixelRatio,this.pickingDownSizingRatio),s=Zp.apply(void 0,am(o)),a=this.itemIDsIndex[s];return a&&a.type==="edge"?a.id:null}},{key:"process",value:function(){var r=this;this.emit("beforeProcess");var i=this.graph,o=this.settings,s=this.getDimensions();if(this.nodeExtent=jN(this.graph),!this.settings.autoRescale){var a=s.width,u=s.height,c=this.nodeExtent,l=c.x,d=c.y;this.nodeExtent={x:[(l[0]+l[1])/2-a/2,(l[0]+l[1])/2+a/2],y:[(d[0]+d[1])/2-u/2,(d[0]+d[1])/2+u/2]}}this.normalizationFunction=im(this.customBBox||this.nodeExtent);var f=new sm,h=ni(f.getState(),s,this.getGraphDimensions(),this.getStagePadding());this.labelGrid.resizeAndClear(s,o.labelGridCellSize);for(var p={},m={},y={},_={},g=1,b=i.nodes(),v=0,w=b.length;v<w;v++){var k=b[v],x=this.nodeDataCache[k],N=i.getNodeAttributes(k);x.x=N.x,x.y=N.y,this.normalizationFunction.applyTo(x),typeof x.label=="string"&&!x.hidden&&this.labelGrid.add(k,x.size,this.framedGraphToViewport(x,{matrix:h})),p[x.type]=(p[x.type]||0)+1}this.labelGrid.organize();for(var z in this.nodePrograms){if(!on.call(this.nodePrograms,z))throw new Error('Sigma: could not find a suitable program for node type "'.concat(z,'"!'));this.nodePrograms[z].reallocate(p[z]||0),p[z]=0}this.settings.zIndex&&this.nodeZExtent[0]!==this.nodeZExtent[1]&&(b=rm(this.nodeZExtent,function(ie){return r.nodeDataCache[ie].zIndex},b));for(var O=0,Z=b.length;O<Z;O++){var ee=b[O];m[ee]=g,_[m[ee]]={type:"node",id:ee},g++;var ae=this.nodeDataCache[ee];this.addNodeToProgram(ee,m[ee],p[ae.type]++)}for(var we={},Re=i.edges(),G=0,q=Re.length;G<q;G++){var Y=Re[G],ne=this.edgeDataCache[Y];we[ne.type]=(we[ne.type]||0)+1}this.settings.zIndex&&this.edgeZExtent[0]!==this.edgeZExtent[1]&&(Re=rm(this.edgeZExtent,function(ie){return r.edgeDataCache[ie].zIndex},Re));for(var K in this.edgePrograms){if(!on.call(this.edgePrograms,K))throw new Error('Sigma: could not find a suitable program for edge type "'.concat(K,'"!'));this.edgePrograms[K].reallocate(we[K]||0),we[K]=0}for(var I=0,L=Re.length;I<L;I++){var U=Re[I];y[U]=g,_[y[U]]={type:"edge",id:U},g++;var fe=this.edgeDataCache[U];this.addEdgeToProgram(U,y[U],we[fe.type]++)}return this.itemIDsIndex=_,this.nodeIndices=m,this.edgeIndices=y,this.emit("afterProcess"),this}},{key:"handleSettingsUpdate",value:function(r){var i=this,o=this.settings;if(this.camera.minRatio=o.minCameraRatio,this.camera.maxRatio=o.maxCameraRatio,this.camera.enabledZooming=o.enableCameraZooming,this.camera.enabledPanning=o.enableCameraPanning,this.camera.enabledRotation=o.enableCameraRotation,o.cameraPanBoundaries?this.camera.clean=function(l){return i.cleanCameraState(l,o.cameraPanBoundaries&&gc(o.cameraPanBoundaries)==="object"?o.cameraPanBoundaries:{})}:this.camera.clean=null,this.camera.setState(this.camera.validateState(this.camera.getState())),r){if(r.edgeProgramClasses!==o.edgeProgramClasses){for(var s in o.edgeProgramClasses)o.edgeProgramClasses[s]!==r.edgeProgramClasses[s]&&this.registerEdgeProgram(s,o.edgeProgramClasses[s]);for(var a in r.edgeProgramClasses)o.edgeProgramClasses[a]||this.unregisterEdgeProgram(a)}if(r.nodeProgramClasses!==o.nodeProgramClasses||r.nodeHoverProgramClasses!==o.nodeHoverProgramClasses){for(var u in o.nodeProgramClasses)(o.nodeProgramClasses[u]!==r.nodeProgramClasses[u]||o.nodeHoverProgramClasses[u]!==r.nodeHoverProgramClasses[u])&&this.registerNodeProgram(u,o.nodeProgramClasses[u],o.nodeHoverProgramClasses[u]);for(var c in r.nodeProgramClasses)o.nodeProgramClasses[c]||this.unregisterNodeProgram(c)}}return this.mouseCaptor.setSettings(this.settings),this.touchCaptor.setSettings(this.settings),this}},{key:"cleanCameraState",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=i.tolerance,s=o===void 0?0:o,a=i.boundaries,u=Q({},r),c=a||this.nodeExtent,l=Sr(c.x,2),d=l[0],f=l[1],h=Sr(c.y,2),p=h[0],m=h[1],y=[this.graphToViewport({x:d,y:p},{cameraState:r}),this.graphToViewport({x:f,y:p},{cameraState:r}),this.graphToViewport({x:d,y:m},{cameraState:r}),this.graphToViewport({x:f,y:m},{cameraState:r})],_=1/0,g=-1/0,b=1/0,v=-1/0;y.forEach(function(we){var Re=we.x,G=we.y;_=Math.min(_,Re),g=Math.max(g,Re),b=Math.min(b,G),v=Math.max(v,G)});var w=g-_,k=v-b,x=this.getDimensions(),N=x.width,z=x.height,O=0,Z=0;if(w>=N?g<N-s?O=g-(N-s):_>s&&(O=_-s):g>N+s?O=g-(N+s):_<-s&&(O=_+s),k>=z?v<z-s?Z=v-(z-s):b>s&&(Z=b-s):v>z+s?Z=v-(z+s):b<-s&&(Z=b+s),O||Z){var ee=this.viewportToFramedGraph({x:0,y:0},{cameraState:r}),ae=this.viewportToFramedGraph({x:O,y:Z},{cameraState:r});O=ae.x-ee.x,Z=ae.y-ee.y,u.x+=O,u.y+=Z}return u}},{key:"renderLabels",value:function(){if(!this.settings.renderLabels)return this;var r=this.camera.getState(),i=this.labelGrid.getLabelsToDisplay(r.ratio,this.settings.labelDensity);om(i,this.nodesWithForcedLabels),this.displayedNodeLabels=new Set;for(var o=this.canvasContexts.labels,s=0,a=i.length;s<a;s++){var u=i[s],c=this.nodeDataCache[u];if(!this.displayedNodeLabels.has(u)&&!c.hidden){var l=this.framedGraphToViewport(c),d=l.x,f=l.y,h=this.scaleSize(c.size);if(!(!c.forceLabel&&h<this.settings.labelRenderedSizeThreshold)&&!(d<-lm||d>this.width+lm||f<-dm||f>this.height+dm)){this.displayedNodeLabels.add(u);var p=this.settings.defaultDrawNodeLabel,m=this.nodePrograms[c.type],y=m?.drawLabel||p;y(o,Q(Q({key:u},c),{},{size:h,x:d,y:f}),this.settings)}}}return this}},{key:"renderEdgeLabels",value:function(){if(!this.settings.renderEdgeLabels)return this;var r=this.canvasContexts.edgeLabels;r.clearRect(0,0,this.width,this.height);var i=sR({graph:this.graph,hoveredNode:this.hoveredNode,displayedNodeLabels:this.displayedNodeLabels,highlightedNodes:this.highlightedNodes});om(i,this.edgesWithForcedLabels);for(var o=new Set,s=0,a=i.length;s<a;s++){var u=i[s],c=this.graph.extremities(u),l=this.nodeDataCache[c[0]],d=this.nodeDataCache[c[1]],f=this.edgeDataCache[u];if(!o.has(u)&&!(f.hidden||l.hidden||d.hidden)){var h=this.settings.defaultDrawEdgeLabel,p=this.edgePrograms[f.type],m=p?.drawLabel||h;m(r,Q(Q({key:u},f),{},{size:this.scaleSize(f.size)}),Q(Q(Q({key:c[0]},l),this.framedGraphToViewport(l)),{},{size:this.scaleSize(l.size)}),Q(Q(Q({key:c[1]},d),this.framedGraphToViewport(d)),{},{size:this.scaleSize(d.size)}),this.settings),o.add(u)}}return this.displayedEdgeLabels=o,this}},{key:"renderHighlightedNodes",value:function(){var r=this,i=this.canvasContexts.hovers;i.clearRect(0,0,this.width,this.height);var o=function(h){var p=r.nodeDataCache[h],m=r.framedGraphToViewport(p),y=m.x,_=m.y,g=r.scaleSize(p.size),b=r.settings.defaultDrawNodeHover,v=r.nodePrograms[p.type],w=v?.drawHover||b;w(i,Q(Q({key:h},p),{},{size:g,x:y,y:_}),r.settings)},s=[];this.hoveredNode&&!this.nodeDataCache[this.hoveredNode].hidden&&s.push(this.hoveredNode),this.highlightedNodes.forEach(function(f){f!==r.hoveredNode&&s.push(f)}),s.forEach(function(f){return o(f)});var a={};s.forEach(function(f){var h=r.nodeDataCache[f].type;a[h]=(a[h]||0)+1});for(var u in this.nodeHoverPrograms)this.nodeHoverPrograms[u].reallocate(a[u]||0),a[u]=0;s.forEach(function(f){var h=r.nodeDataCache[f];r.nodeHoverPrograms[h.type].process(0,a[h.type]++,h)}),this.webGLContexts.hoverNodes.clear(this.webGLContexts.hoverNodes.COLOR_BUFFER_BIT);var c=this.getRenderParams();for(var l in this.nodeHoverPrograms){var d=this.nodeHoverPrograms[l];d.render(c)}}},{key:"scheduleHighlightedNodesRender",value:function(){var r=this;this.renderHighlightedNodesFrame||this.renderFrame||(this.renderHighlightedNodesFrame=requestAnimationFrame(function(){r.renderHighlightedNodesFrame=null,r.renderHighlightedNodes(),r.renderEdgeLabels()}))}},{key:"render",value:function(){var r=this;this.emit("beforeRender");var i=function(){return r.emit("afterRender"),r};if(this.renderFrame&&(cancelAnimationFrame(this.renderFrame),this.renderFrame=null),this.resize(),this.needToProcess&&this.process(),this.needToProcess=!1,this.clear(),this.pickingLayers.forEach(function(y){return r.resetWebGLTexture(y)}),!this.graph.order)return i();var o=this.mouseCaptor,s=this.camera.isAnimated()||o.isMoving||o.draggedEvents||o.currentWheelDirection,a=this.camera.getState(),u=this.getDimensions(),c=this.getGraphDimensions(),l=this.getStagePadding();this.matrix=ni(a,u,c,l),this.invMatrix=ni(a,u,c,l,!0),this.correctionRatio=GN(this.matrix,a,u),this.graphToViewportRatio=this.getGraphToViewportRatio();var d=this.getRenderParams();for(var f in this.nodePrograms){var h=this.nodePrograms[f];h.render(d)}if(!this.settings.hideEdgesOnMove||!s)for(var p in this.edgePrograms){var m=this.edgePrograms[p];m.render(d)}return this.settings.hideLabelsOnMove&&s||(this.renderLabels(),this.renderEdgeLabels(),this.renderHighlightedNodes()),i()}},{key:"addNode",value:function(r){var i=Object.assign({},this.graph.getNodeAttributes(r));this.settings.nodeReducer&&(i=this.settings.nodeReducer(r,i));var o=aR(this.settings,r,i);this.nodeDataCache[r]=o,this.nodesWithForcedLabels.delete(r),o.forceLabel&&!o.hidden&&this.nodesWithForcedLabels.add(r),this.highlightedNodes.delete(r),o.highlighted&&!o.hidden&&this.highlightedNodes.add(r),this.settings.zIndex&&(o.zIndex<this.nodeZExtent[0]&&(this.nodeZExtent[0]=o.zIndex),o.zIndex>this.nodeZExtent[1]&&(this.nodeZExtent[1]=o.zIndex))}},{key:"updateNode",value:function(r){this.addNode(r);var i=this.nodeDataCache[r];this.normalizationFunction.applyTo(i)}},{key:"removeNode",value:function(r){delete this.nodeDataCache[r],delete this.nodeProgramIndex[r],this.highlightedNodes.delete(r),this.hoveredNode===r&&(this.hoveredNode=null),this.nodesWithForcedLabels.delete(r)}},{key:"addEdge",value:function(r){var i=Object.assign({},this.graph.getEdgeAttributes(r));this.settings.edgeReducer&&(i=this.settings.edgeReducer(r,i));var o=uR(this.settings,r,i);this.edgeDataCache[r]=o,this.edgesWithForcedLabels.delete(r),o.forceLabel&&!o.hidden&&this.edgesWithForcedLabels.add(r),this.settings.zIndex&&(o.zIndex<this.edgeZExtent[0]&&(this.edgeZExtent[0]=o.zIndex),o.zIndex>this.edgeZExtent[1]&&(this.edgeZExtent[1]=o.zIndex))}},{key:"updateEdge",value:function(r){this.addEdge(r)}},{key:"removeEdge",value:function(r){delete this.edgeDataCache[r],delete this.edgeProgramIndex[r],this.hoveredEdge===r&&(this.hoveredEdge=null),this.edgesWithForcedLabels.delete(r)}},{key:"clearNodeIndices",value:function(){this.labelGrid=new cm,this.nodeExtent={x:[0,1],y:[0,1]},this.nodeDataCache={},this.edgeProgramIndex={},this.nodesWithForcedLabels=new Set,this.nodeZExtent=[1/0,-1/0],this.highlightedNodes=new Set}},{key:"clearEdgeIndices",value:function(){this.edgeDataCache={},this.edgeProgramIndex={},this.edgesWithForcedLabels=new Set,this.edgeZExtent=[1/0,-1/0]}},{key:"clearIndices",value:function(){this.clearEdgeIndices(),this.clearNodeIndices()}},{key:"clearNodeState",value:function(){this.displayedNodeLabels=new Set,this.highlightedNodes=new Set,this.hoveredNode=null}},{key:"clearEdgeState",value:function(){this.displayedEdgeLabels=new Set,this.highlightedNodes=new Set,this.hoveredEdge=null}},{key:"clearState",value:function(){this.clearEdgeState(),this.clearNodeState()}},{key:"addNodeToProgram",value:function(r,i,o){var s=this.nodeDataCache[r],a=this.nodePrograms[s.type];if(!a)throw new Error('Sigma: could not find a suitable program for node type "'.concat(s.type,'"!'));a.process(i,o,s),this.nodeProgramIndex[r]=o}},{key:"addEdgeToProgram",value:function(r,i,o){var s=this.edgeDataCache[r],a=this.edgePrograms[s.type];if(!a)throw new Error('Sigma: could not find a suitable program for edge type "'.concat(s.type,'"!'));var u=this.graph.extremities(r),c=this.nodeDataCache[u[0]],l=this.nodeDataCache[u[1]];a.process(i,o,c,l,s),this.edgeProgramIndex[r]=o}},{key:"getRenderParams",value:function(){return{matrix:this.matrix,invMatrix:this.invMatrix,width:this.width,height:this.height,pixelRatio:this.pixelRatio,zoomRatio:this.camera.ratio,cameraAngle:this.camera.angle,sizeRatio:1/this.scaleSize(),correctionRatio:this.correctionRatio,downSizingRatio:this.pickingDownSizingRatio,minEdgeThickness:this.settings.minEdgeThickness,antiAliasingFeather:this.settings.antiAliasingFeather}}},{key:"getStagePadding",value:function(){var r=this.settings,i=r.stagePadding,o=r.autoRescale;return o&&i||0}},{key:"createLayer",value:function(r,i){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.elements[r])throw new Error('Sigma: a layer named "'.concat(r,'" already exists'));var s=BN(i,{position:"absolute"},{class:"sigma-".concat(r)});return o.style&&Object.assign(s.style,o.style),this.elements[r]=s,"beforeLayer"in o&&o.beforeLayer?this.elements[o.beforeLayer].before(s):"afterLayer"in o&&o.afterLayer?this.elements[o.afterLayer].after(s):this.container.appendChild(s),s}},{key:"createCanvas",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.createLayer(r,"canvas",i)}},{key:"createCanvasContext",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=this.createCanvas(r,i),s={preserveDrawingBuffer:!1,antialias:!1};return this.canvasContexts[r]=o.getContext("2d",s),this}},{key:"createWebGLContext",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=i?.canvas||this.createCanvas(r,i);i.hidden&&o.remove();var s=Q({preserveDrawingBuffer:!1,antialias:!1},i),a;a=o.getContext("webgl2",s),a||(a=o.getContext("webgl",s)),a||(a=o.getContext("experimental-webgl",s));var u=a;if(this.webGLContexts[r]=u,u.blendFunc(u.ONE,u.ONE_MINUS_SRC_ALPHA),i.picking){this.pickingLayers.add(r);var c=u.createFramebuffer();if(!c)throw new Error("Sigma: cannot create a new frame buffer for layer ".concat(r));this.frameBuffers[r]=c}return u}},{key:"killLayer",value:function(r){var i=this.elements[r];if(!i)throw new Error("Sigma: cannot kill layer ".concat(r,", which does not exist"));if(this.webGLContexts[r]){var o,s=this.webGLContexts[r];(o=s.getExtension("WEBGL_lose_context"))===null||o===void 0||o.loseContext(),delete this.webGLContexts[r]}else this.canvasContexts[r]&&delete this.canvasContexts[r];return i.remove(),delete this.elements[r],this}},{key:"getCamera",value:function(){return this.camera}},{key:"setCamera",value:function(r){this.unbindCameraHandlers(),this.camera=r,this.bindCameraHandlers()}},{key:"getContainer",value:function(){return this.container}},{key:"getGraph",value:function(){return this.graph}},{key:"setGraph",value:function(r){r!==this.graph&&(this.hoveredNode&&!r.hasNode(this.hoveredNode)&&(this.hoveredNode=null),this.hoveredEdge&&!r.hasEdge(this.hoveredEdge)&&(this.hoveredEdge=null),this.unbindGraphHandlers(),this.checkEdgesEventsFrame!==null&&(cancelAnimationFrame(this.checkEdgesEventsFrame),this.checkEdgesEventsFrame=null),this.graph=r,this.bindGraphHandlers(),this.refresh())}},{key:"getMouseCaptor",value:function(){return this.mouseCaptor}},{key:"getTouchCaptor",value:function(){return this.touchCaptor}},{key:"getDimensions",value:function(){return{width:this.width,height:this.height}}},{key:"getGraphDimensions",value:function(){var r=this.customBBox||this.nodeExtent;return{width:r.x[1]-r.x[0]||1,height:r.y[1]-r.y[0]||1}}},{key:"getNodeDisplayData",value:function(r){var i=this.nodeDataCache[r];return i?Object.assign({},i):void 0}},{key:"getEdgeDisplayData",value:function(r){var i=this.edgeDataCache[r];return i?Object.assign({},i):void 0}},{key:"getNodeDisplayedLabels",value:function(){return new Set(this.displayedNodeLabels)}},{key:"getEdgeDisplayedLabels",value:function(){return new Set(this.displayedEdgeLabels)}},{key:"getSettings",value:function(){return Q({},this.settings)}},{key:"getSetting",value:function(r){return this.settings[r]}},{key:"setSetting",value:function(r,i){var o=Q({},this.settings);return this.settings[r]=i,Nu(this.settings),this.handleSettingsUpdate(o),this.scheduleRefresh(),this}},{key:"updateSetting",value:function(r,i){return this.setSetting(r,i(this.settings[r])),this}},{key:"setSettings",value:function(r){var i=Q({},this.settings);return this.settings=Q(Q({},this.settings),r),Nu(this.settings),this.handleSettingsUpdate(i),this.scheduleRefresh(),this}},{key:"resize",value:function(r){var i=this.width,o=this.height;if(this.width=this.container.offsetWidth,this.height=this.container.offsetHeight,this.pixelRatio=nm(),this.width===0)if(this.settings.allowInvalidContainer)this.width=1;else throw new Error("Sigma: Container has no width. You can set the allowInvalidContainer setting to true to stop seeing this error.");if(this.height===0)if(this.settings.allowInvalidContainer)this.height=1;else throw new Error("Sigma: Container has no height. You can set the allowInvalidContainer setting to true to stop seeing this error.");if(!r&&i===this.width&&o===this.height)return this;for(var s in this.elements){var a=this.elements[s];a.style.width=this.width+"px",a.style.height=this.height+"px"}for(var u in this.canvasContexts)this.elements[u].setAttribute("width",this.width*this.pixelRatio+"px"),this.elements[u].setAttribute("height",this.height*this.pixelRatio+"px"),this.pixelRatio!==1&&this.canvasContexts[u].scale(this.pixelRatio,this.pixelRatio);for(var c in this.webGLContexts){this.elements[c].setAttribute("width",this.width*this.pixelRatio+"px"),this.elements[c].setAttribute("height",this.height*this.pixelRatio+"px");var l=this.webGLContexts[c];if(l.viewport(0,0,this.width*this.pixelRatio,this.height*this.pixelRatio),this.pickingLayers.has(c)){var d=this.textures[c];d&&l.deleteTexture(d)}}return this.emit("resize"),this}},{key:"clear",value:function(){return this.emit("beforeClear"),this.webGLContexts.nodes.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER,null),this.webGLContexts.nodes.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.webGLContexts.edges.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER,null),this.webGLContexts.edges.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.webGLContexts.hoverNodes.clear(WebGLRenderingContext.COLOR_BUFFER_BIT),this.canvasContexts.labels.clearRect(0,0,this.width,this.height),this.canvasContexts.hovers.clearRect(0,0,this.width,this.height),this.canvasContexts.edgeLabels.clearRect(0,0,this.width,this.height),this.emit("afterClear"),this}},{key:"refresh",value:function(r){var i=this,o=r?.skipIndexation!==void 0?r?.skipIndexation:!1,s=r?.schedule!==void 0?r.schedule:!1,a=!r||!r.partialGraph;if(a)this.clearEdgeIndices(),this.clearNodeIndices(),this.graph.forEachNode(function(v){return i.addNode(v)}),this.graph.forEachEdge(function(v){return i.addEdge(v)});else{for(var u,c,l=((u=r.partialGraph)===null||u===void 0?void 0:u.nodes)||[],d=0,f=l?.length||0;d<f;d++){var h=l[d];if(this.updateNode(h),o){var p=this.nodeProgramIndex[h];if(p===void 0)throw new Error('Sigma: node "'.concat(h,`" can't be repaint`));this.addNodeToProgram(h,this.nodeIndices[h],p)}}for(var m=(r==null||(c=r.partialGraph)===null||c===void 0?void 0:c.edges)||[],y=0,_=m.length;y<_;y++){var g=m[y];if(this.updateEdge(g),o){var b=this.edgeProgramIndex[g];if(b===void 0)throw new Error('Sigma: edge "'.concat(g,`" can't be repaint`));this.addEdgeToProgram(g,this.edgeIndices[g],b)}}}return(a||!o)&&(this.needToProcess=!0),s?this.scheduleRender():this.render(),this}},{key:"scheduleRender",value:function(){var r=this;return this.renderFrame||(this.renderFrame=requestAnimationFrame(function(){r.render()})),this}},{key:"scheduleRefresh",value:function(r){return this.refresh(Q(Q({},r),{},{schedule:!0}))}},{key:"getViewportZoomedState",value:function(r,i){var o=this.camera.getState(),s=o.ratio,a=o.angle,u=o.x,c=o.y,l=this.settings,d=l.minCameraRatio,f=l.maxCameraRatio;typeof f=="number"&&(i=Math.min(i,f)),typeof d=="number"&&(i=Math.max(i,d));var h=i/s,p={x:this.width/2,y:this.height/2},m=this.viewportToFramedGraph(r),y=this.viewportToFramedGraph(p);return{angle:a,x:(m.x-y.x)*(1-h)+u,y:(m.y-y.y)*(1-h)+c,ratio:i}}},{key:"viewRectangle",value:function(){var r=this.viewportToFramedGraph({x:0,y:0}),i=this.viewportToFramedGraph({x:this.width,y:0}),o=this.viewportToFramedGraph({x:0,y:this.height});return{x1:r.x,y1:r.y,x2:i.x,y2:i.y,height:i.y-o.y}}},{key:"framedGraphToViewport",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=!!i.cameraState||!!i.viewportDimensions||!!i.graphDimensions,s=i.matrix?i.matrix:o?ni(i.cameraState||this.camera.getState(),i.viewportDimensions||this.getDimensions(),i.graphDimensions||this.getGraphDimensions(),i.padding||this.getStagePadding()):this.matrix,a=mc(s,r);return{x:(1+a.x)*this.width/2,y:(1-a.y)*this.height/2}}},{key:"viewportToFramedGraph",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=!!i.cameraState||!!i.viewportDimensions||!i.graphDimensions,s=i.matrix?i.matrix:o?ni(i.cameraState||this.camera.getState(),i.viewportDimensions||this.getDimensions(),i.graphDimensions||this.getGraphDimensions(),i.padding||this.getStagePadding(),!0):this.invMatrix,a=mc(s,{x:r.x/this.width*2-1,y:1-r.y/this.height*2});return isNaN(a.x)&&(a.x=0),isNaN(a.y)&&(a.y=0),a}},{key:"viewportToGraph",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.normalizationFunction.inverse(this.viewportToFramedGraph(r,i))}},{key:"graphToViewport",value:function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.framedGraphToViewport(this.normalizationFunction(r),i)}},{key:"getGraphToViewportRatio",value:function(){var r={x:0,y:0},i={x:1,y:1},o=Math.sqrt(Math.pow(r.x-i.x,2)+Math.pow(r.y-i.y,2)),s=this.graphToViewport(r),a=this.graphToViewport(i),u=Math.sqrt(Math.pow(s.x-a.x,2)+Math.pow(s.y-a.y,2));return u/o}},{key:"getBBox",value:function(){return this.nodeExtent}},{key:"getCustomBBox",value:function(){return this.customBBox}},{key:"setCustomBBox",value:function(r){return this.customBBox=r,this.scheduleRender(),this}},{key:"kill",value:function(){this.emit("kill"),this.removeAllListeners(),this.unbindCameraHandlers(),window.removeEventListener("resize",this.activeListeners.handleResize),this.mouseCaptor.kill(),this.touchCaptor.kill(),this.unbindGraphHandlers(),this.clearIndices(),this.clearState(),this.nodeDataCache={},this.edgeDataCache={},this.highlightedNodes.clear(),this.renderFrame&&(cancelAnimationFrame(this.renderFrame),this.renderFrame=null),this.renderHighlightedNodesFrame&&(cancelAnimationFrame(this.renderHighlightedNodesFrame),this.renderHighlightedNodesFrame=null);for(var r=this.container;r.firstChild;)r.removeChild(r.firstChild);for(var i in this.nodePrograms)this.nodePrograms[i].kill();for(var o in this.nodeHoverPrograms)this.nodeHoverPrograms[o].kill();for(var s in this.edgePrograms)this.edgePrograms[s].kill();this.nodePrograms={},this.nodeHoverPrograms={},this.edgePrograms={};for(var a in this.elements)this.killLayer(a);this.canvasContexts={},this.webGLContexts={},this.elements={}}},{key:"scaleSize",value:function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.camera.ratio;return r/this.settings.zoomToSizeRatioFunction(i)*(this.getSetting("itemSizesReference")==="positions"?i*this.graphToViewportRatio:1)}},{key:"getCanvases",value:function(){var r={};for(var i in this.elements)this.elements[i]instanceof HTMLCanvasElement&&(r[i]=this.elements[i]);return r}}])})(uh),lR=cR;function dR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Y_(e){var t=dR(e,"string");return typeof t=="symbol"?t:t+""}function X_(e,t,n){return(t=Y_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fm(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Ss(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?fm(Object(n),!0).forEach(function(r){X_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):fm(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function fR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function hR(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Y_(r.key),r)}}function pR(e,t,n){return t&&hR(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function xs(e){return xs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},xs(e)}function Q_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Q_=function(){return!!e})()}function ek(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function mR(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ek(e)}function gR(e,t,n){return t=xs(t),mR(e,Q_()?Reflect.construct(t,n||[],xs(e).constructor):t.apply(e,n))}function yc(e,t){return yc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},yc(e,t)}function yR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&yc(e,t)}function vc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function vR(e){if(Array.isArray(e))return vc(e)}function bR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function wR(e,t){if(e){if(typeof e=="string")return vc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vc(e,t):void 0}}function _R(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
422
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lu(e){return vR(e)||bR(e)||wR(e)||_R()}function tk(e,t,n,r){var i=Math.pow(1-e,2)*t.x+2*(1-e)*e*n.x+Math.pow(e,2)*r.x,o=Math.pow(1-e,2)*t.y+2*(1-e)*e*n.y+Math.pow(e,2)*r.y;return{x:i,y:o}}function kR(e,t,n){for(var r=20,i=0,o=e,s=0;s<r;s++){var a=tk((s+1)/r,e,t,n);i+=Math.sqrt(Math.pow(o.x-a.x,2)+Math.pow(o.y-a.y,2)),o=a}return i}function SR(e){var t=e.curvatureAttribute,n=e.defaultCurvature,r=e.keepLabelUpright,i=r===void 0?!0:r;return function(o,s,a,u,c){var l=c.edgeLabelSize,d=s[t]||n,f=c.edgeLabelFont,h=c.edgeLabelWeight,p=c.edgeLabelColor.attribute?s[c.edgeLabelColor.attribute]||c.edgeLabelColor.color||"#000":c.edgeLabelColor.color,m=s.label;if(m){o.fillStyle=p,o.font="".concat(h," ").concat(l,"px ").concat(f);var y=!i||a.x<u.x,_=y?a.x:u.x,g=y?a.y:u.y,b=y?u.x:a.x,v=y?u.y:a.y,w=(_+b)/2,k=(g+v)/2,x=b-_,N=v-g,z=Math.sqrt(Math.pow(x,2)+Math.pow(N,2)),O=y?1:-1,Z=w+N*d*O,ee=k-x*d*O,ae=s.size*.7+5,we={x:ee-g,y:-(Z-_)},Re=Math.sqrt(Math.pow(we.x,2)+Math.pow(we.y,2)),G={x:v-ee,y:-(b-Z)},q=Math.sqrt(Math.pow(G.x,2)+Math.pow(G.y,2));_+=ae*we.x/Re,g+=ae*we.y/Re,b+=ae*G.x/q,v+=ae*G.y/q,Z+=ae*N/z,ee-=ae*x/z;var Y={x:Z,y:ee},ne={x:_,y:g},K={x:b,y:v},I=kR(ne,Y,K);if(!(I<a.size+u.size)){var L=o.measureText(m).width,U=I-a.size-u.size;if(L>U){var fe="…";for(m=m+fe,L=o.measureText(m).width;L>U&&m.length>1;)m=m.slice(0,-2)+fe,L=o.measureText(m).width;if(m.length<4)return}for(var ie={},te=0,_e=m.length;te<_e;te++){var Se=m[te];ie[Se]||(ie[Se]=o.measureText(Se).width*(1+d*.35))}for(var Ze=.5-L/I/2,F=0,j=m.length;F<j;F++){var V=m[F],X=tk(Ze,ne,Y,K),xe=2*(1-Ze)*(Z-_)+2*Ze*(b-Z),ue=2*(1-Ze)*(ee-g)+2*Ze*(v-ee),pe=Math.atan2(ue,xe);o.save(),o.translate(X.x,X.y),o.rotate(pe),o.fillText(V,0,0),o.restore(),Ze+=ie[V]/I}}}}}function xR(e){var t=e.arrowHead,n=t?.extremity==="target"||t?.extremity==="both",r=t?.extremity==="source"||t?.extremity==="both",i=`
423
423
  precision highp float;
424
424
 
425
425
  varying vec4 v_color;
@@ -494,7 +494,7 @@ void main(void) {
494
494
  gl_FragColor = transparent;
495
495
  }
496
496
  }
497
- `);return i}function kR(e){var t=e.arrowHead,n=t?.extremity==="target"||t?.extremity==="both",r=t?.extremity==="source"||t?.extremity==="both",i=`
497
+ `);return i}function ER(e){var t=e.arrowHead,n=t?.extremity==="target"||t?.extremity==="both",r=t?.extremity==="source"||t?.extremity==="both",i=`
498
498
  attribute vec4 a_id;
499
499
  attribute vec4 a_color;
500
500
  attribute float a_direction;
@@ -604,9 +604,9 @@ void main() {
604
604
 
605
605
  v_color.a *= bias;
606
606
  }
607
- `);return i}var Q_=.25,SR={arrowHead:null,curvatureAttribute:"curvature",defaultCurvature:Q_},ek=WebGLRenderingContext,dm=ek.UNSIGNED_BYTE,wn=ek.FLOAT;function tu(e){var t=_s(_s({},SR),e||{}),n=t,r=n.arrowHead,i=n.curvatureAttribute,o=n.drawLabel,s=r?.extremity==="target"||r?.extremity==="both",a=r?.extremity==="source"||r?.extremity==="both",u=["u_matrix","u_sizeRatio","u_dimensions","u_pixelRatio","u_feather","u_minEdgeThickness"].concat(Ru(r?["u_lengthToThicknessRatio","u_widenessToThicknessRatio"]:[]));return(function(c){pR(l,c);function l(){var d;cR(this,l);for(var f=arguments.length,h=new Array(f),p=0;p<f;p++)h[p]=arguments[p];return d=hR(this,l,[].concat(h)),K_(Y_(d),"drawLabel",o||wR(t)),d}return dR(l,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:kR(t),FRAGMENT_SHADER_SOURCE:_R(t),METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:u,ATTRIBUTES:[{name:"a_source",size:2,type:wn},{name:"a_target",size:2,type:wn}].concat(Ru(s?[{name:"a_targetSize",size:1,type:wn}]:[]),Ru(a?[{name:"a_sourceSize",size:1,type:wn}]:[]),[{name:"a_thickness",size:1,type:wn},{name:"a_curvature",size:1,type:wn},{name:"a_color",size:4,type:dm,normalized:!0},{name:"a_id",size:4,type:dm,normalized:!0}]),CONSTANT_ATTRIBUTES:[{name:"a_current",size:1,type:wn},{name:"a_direction",size:1,type:wn}],CONSTANT_DATA:[[0,1],[0,-1],[1,1],[0,-1],[1,1],[1,-1]]}}},{key:"processVisibleItem",value:function(f,h,p,m,y){var w,g=y.size||1,b=p.x,v=p.y,k=m.x,S=m.y,_=zn(y.color),N=(w=y[i])!==null&&w!==void 0?w:Q_,P=this.array;P[h++]=b,P[h++]=v,P[h++]=k,P[h++]=S,s&&(P[h++]=m.size),a&&(P[h++]=p.size),P[h++]=g,P[h++]=N,P[h++]=_,P[h++]=f}},{key:"setUniforms",value:function(f,h){var p=h.gl,m=h.uniformLocations,y=m.u_matrix,w=m.u_pixelRatio,g=m.u_feather,b=m.u_sizeRatio,v=m.u_dimensions,k=m.u_minEdgeThickness;if(p.uniformMatrix3fv(y,!1,f.matrix),p.uniform1f(w,f.pixelRatio),p.uniform1f(b,f.sizeRatio),p.uniform1f(g,f.antiAliasingFeather),p.uniform2f(v,f.width*f.pixelRatio,f.height*f.pixelRatio),p.uniform1f(k,f.minEdgeThickness),r){var S=m.u_lengthToThicknessRatio,_=m.u_widenessToThicknessRatio;p.uniform1f(S,r.lengthToThicknessRatio),p.uniform1f(_,r.widenessToThicknessRatio)}}}]),l})(Xa)}tu();tu({arrowHead:eu});tu({arrowHead:_s(_s({},eu),{},{extremity:"both"})});function xR(e){if(Array.isArray(e))return e}function ER(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,a=[],u=!0,c=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(l){c=!0,i=l}finally{try{if(!u&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function vc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function tk(e,t){if(e){if(typeof e=="string")return vc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vc(e,t):void 0}}function $R(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
608
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function TR(e,t){return xR(e)||ER(e,t)||tk(e,t)||$R()}function CR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function AR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function nk(e){var t=AR(e,"string");return typeof t=="symbol"?t:t+""}function IR(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,nk(r.key),r)}}function NR(e,t,n){return t&&IR(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ss(e){return Ss=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ss(e)}function rk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(rk=function(){return!!e})()}function bc(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function RR(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return bc(e)}function LR(e,t,n){return t=Ss(t),RR(e,rk()?Reflect.construct(t,n||[],Ss(e).constructor):t.apply(e,n))}function wc(e,t){return wc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},wc(e,t)}function zR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&wc(e,t)}function or(e,t,n){return(t=nk(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PR(e){if(Array.isArray(e))return vc(e)}function DR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function OR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
609
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lu(e){return PR(e)||DR(e)||tk(e)||OR()}function fm(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function hm(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?fm(Object(n),!0).forEach(function(r){or(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):fm(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var MR="relative",FR={drawLabel:void 0,drawHover:void 0,borders:[{size:{value:.1},color:{attribute:"borderColor"}},{size:{fill:!0},color:{attribute:"color"}}]},UR="#000000";function GR(e){var t=e.borders,n=Hp(t.filter(function(i){var o=i.size;return"fill"in o}).length),r=`
607
+ `);return i}var nk=.25,$R={arrowHead:null,curvatureAttribute:"curvature",defaultCurvature:nk},rk=WebGLRenderingContext,hm=rk.UNSIGNED_BYTE,wn=rk.FLOAT;function nu(e){var t=Ss(Ss({},$R),e||{}),n=t,r=n.arrowHead,i=n.curvatureAttribute,o=n.drawLabel,s=r?.extremity==="target"||r?.extremity==="both",a=r?.extremity==="source"||r?.extremity==="both",u=["u_matrix","u_sizeRatio","u_dimensions","u_pixelRatio","u_feather","u_minEdgeThickness"].concat(Lu(r?["u_lengthToThicknessRatio","u_widenessToThicknessRatio"]:[]));return(function(c){yR(l,c);function l(){var d;fR(this,l);for(var f=arguments.length,h=new Array(f),p=0;p<f;p++)h[p]=arguments[p];return d=gR(this,l,[].concat(h)),X_(ek(d),"drawLabel",o||SR(t)),d}return pR(l,[{key:"getDefinition",value:function(){return{VERTICES:6,VERTEX_SHADER_SOURCE:ER(t),FRAGMENT_SHADER_SOURCE:xR(t),METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:u,ATTRIBUTES:[{name:"a_source",size:2,type:wn},{name:"a_target",size:2,type:wn}].concat(Lu(s?[{name:"a_targetSize",size:1,type:wn}]:[]),Lu(a?[{name:"a_sourceSize",size:1,type:wn}]:[]),[{name:"a_thickness",size:1,type:wn},{name:"a_curvature",size:1,type:wn},{name:"a_color",size:4,type:hm,normalized:!0},{name:"a_id",size:4,type:hm,normalized:!0}]),CONSTANT_ATTRIBUTES:[{name:"a_current",size:1,type:wn},{name:"a_direction",size:1,type:wn}],CONSTANT_DATA:[[0,1],[0,-1],[1,1],[0,-1],[1,1],[1,-1]]}}},{key:"processVisibleItem",value:function(f,h,p,m,y){var _,g=y.size||1,b=p.x,v=p.y,w=m.x,k=m.y,x=Pn(y.color),N=(_=y[i])!==null&&_!==void 0?_:nk,z=this.array;z[h++]=b,z[h++]=v,z[h++]=w,z[h++]=k,s&&(z[h++]=m.size),a&&(z[h++]=p.size),z[h++]=g,z[h++]=N,z[h++]=x,z[h++]=f}},{key:"setUniforms",value:function(f,h){var p=h.gl,m=h.uniformLocations,y=m.u_matrix,_=m.u_pixelRatio,g=m.u_feather,b=m.u_sizeRatio,v=m.u_dimensions,w=m.u_minEdgeThickness;if(p.uniformMatrix3fv(y,!1,f.matrix),p.uniform1f(_,f.pixelRatio),p.uniform1f(b,f.sizeRatio),p.uniform1f(g,f.antiAliasingFeather),p.uniform2f(v,f.width*f.pixelRatio,f.height*f.pixelRatio),p.uniform1f(w,f.minEdgeThickness),r){var k=m.u_lengthToThicknessRatio,x=m.u_widenessToThicknessRatio;p.uniform1f(k,r.lengthToThicknessRatio),p.uniform1f(x,r.widenessToThicknessRatio)}}}]),l})(Qa)}nu();nu({arrowHead:tu});nu({arrowHead:Ss(Ss({},tu),{},{extremity:"both"})});function TR(e){if(Array.isArray(e))return e}function CR(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,a=[],u=!0,c=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);u=!0);}catch(l){c=!0,i=l}finally{try{if(!u&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function bc(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ik(e,t){if(e){if(typeof e=="string")return bc(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?bc(e,t):void 0}}function AR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
608
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function IR(e,t){return TR(e)||CR(e,t)||ik(e,t)||AR()}function NR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function RR(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ok(e){var t=RR(e,"string");return typeof t=="symbol"?t:t+""}function LR(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,ok(r.key),r)}}function zR(e,t,n){return t&&LR(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Es(e){return Es=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Es(e)}function sk(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(sk=function(){return!!e})()}function wc(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function PR(e,t){if(t&&(typeof t=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return wc(e)}function DR(e,t,n){return t=Es(t),PR(e,sk()?Reflect.construct(t,n||[],Es(e).constructor):t.apply(e,n))}function _c(e,t){return _c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},_c(e,t)}function OR(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_c(e,t)}function sr(e,t,n){return(t=ok(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MR(e){if(Array.isArray(e))return bc(e)}function FR(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function UR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
609
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zu(e){return MR(e)||FR(e)||ik(e)||UR()}function pm(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function mm(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?pm(Object(n),!0).forEach(function(r){sr(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pm(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var GR="relative",jR={drawLabel:void 0,drawHover:void 0,borders:[{size:{value:.1},color:{attribute:"borderColor"}},{size:{fill:!0},color:{attribute:"color"}}]},ZR="#000000";function BR(e){var t=e.borders,n=qp(t.filter(function(i){var o=i.size;return"fill"in o}).length),r=`
610
610
  precision highp float;
611
611
 
612
612
  varying vec2 v_diffVector;
@@ -643,7 +643,7 @@ void main(void) {
643
643
  }
644
644
  #else
645
645
  // Sizes:
646
- `).concat(t.flatMap(function(i,o){var s=i.size;if("fill"in s)return[];s=s;var a="attribute"in s?"v_borderSize_".concat(o+1):Hp(s.value),u=(s.mode||MR)==="pixels"?"u_correctionRatio":"v_radius";return[" float borderSize_".concat(o+1," = ").concat(u," * ").concat(a,";")]}).join(`
646
+ `).concat(t.flatMap(function(i,o){var s=i.size;if("fill"in s)return[];s=s;var a="attribute"in s?"v_borderSize_".concat(o+1):qp(s.value),u=(s.mode||GR)==="pixels"?"u_correctionRatio":"v_radius";return[" float borderSize_".concat(o+1," = ").concat(u," * ").concat(a,";")]}).join(`
647
647
  `),`
648
648
  // Now, let's split the remaining space between "fill" borders:
649
649
  float fillBorderSize = (v_radius - (`).concat(t.flatMap(function(i,o){var s=i.size;return"fill"in s?[]:["borderSize_".concat(o+1)]}).join(" + "),") ) / ").concat(n,`;
@@ -669,7 +669,7 @@ void main(void) {
669
669
  } else `)}).join(""),` { /* Nothing to add here */ }
670
670
  #endif
671
671
  }
672
- `);return r}function jR(e){var t=e.borders,n=`
672
+ `);return r}function VR(e){var t=e.borders,n=`
673
673
  attribute vec2 a_position;
674
674
  attribute float a_size;
675
675
  attribute float a_angle;
@@ -716,7 +716,7 @@ void main() {
716
716
  `),`
717
717
  #endif
718
718
  }
719
- `);return n}var ik=WebGLRenderingContext,pm=ik.UNSIGNED_BYTE,Yo=ik.FLOAT;function ok(e){var t,n=hm(hm({},FR),e||{}),r=n.borders,i=n.drawLabel,o=n.drawHover,s=["u_sizeRatio","u_correctionRatio","u_matrix"].concat(Lu(r.flatMap(function(a,u){var c=a.color;return"value"in c?["u_borderColor_".concat(u+1)]:[]})));return t=(function(a){zR(u,a);function u(){var c;CR(this,u);for(var l=arguments.length,d=new Array(l),f=0;f<l;f++)d[f]=arguments[f];return c=LR(this,u,[].concat(d)),or(bc(c),"drawLabel",i),or(bc(c),"drawHover",o),c}return NR(u,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:jR(n),FRAGMENT_SHADER_SOURCE:GR(n),METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:s,ATTRIBUTES:[{name:"a_position",size:2,type:Yo},{name:"a_id",size:4,type:pm,normalized:!0},{name:"a_size",size:1,type:Yo}].concat(Lu(r.flatMap(function(l,d){var f=l.color;return"attribute"in f?[{name:"a_borderColor_".concat(d+1),size:4,type:pm,normalized:!0}]:[]})),Lu(r.flatMap(function(l,d){var f=l.size;return"attribute"in f?[{name:"a_borderSize_".concat(d+1),size:1,type:Yo}]:[]}))),CONSTANT_ATTRIBUTES:[{name:"a_angle",size:1,type:Yo}],CONSTANT_DATA:[[u.ANGLE_1],[u.ANGLE_2],[u.ANGLE_3]]}}},{key:"processVisibleItem",value:function(l,d,f){var h=this.array;h[d++]=f.x,h[d++]=f.y,h[d++]=l,h[d++]=f.size,r.forEach(function(p){var m=p.color;"attribute"in m&&(h[d++]=zn(f[m.attribute]||m.defaultValue||UR))}),r.forEach(function(p){var m=p.size;"attribute"in m&&(h[d++]=f[m.attribute]||m.defaultValue)})}},{key:"setUniforms",value:function(l,d){var f=d.gl,h=d.uniformLocations,p=h.u_sizeRatio,m=h.u_correctionRatio,y=h.u_matrix;f.uniform1f(m,l.correctionRatio),f.uniform1f(p,l.sizeRatio),f.uniformMatrix3fv(y,!1,l.matrix),r.forEach(function(w,g){var b=w.color;if("value"in b){var v=h["u_borderColor_".concat(g+1)],k=WI(b.value),S=TR(k,4),_=S[0],N=S[1],P=S[2],z=S[3];f.uniform4f(v,_/255,N/255,P/255,z/255)}})}}]),u})(D_),or(t,"ANGLE_1",0),or(t,"ANGLE_2",2*Math.PI/3),or(t,"ANGLE_3",4*Math.PI/3),t}ok();const xs=.18,ZR=500,BR=2,HR=3,Xo={rest:2,selected:4,expanded:5},VR=6,zu=2,qR=8,mm=6,Pu=400,WR=2e3,KR={x:[0,1e3],y:[0,1e3]},Du=1e3,gm=500,JR={role:{size:13,font:e=>`600 ${e}px Inter, system-ui, sans-serif`},address:{size:11,font:e=>`400 ${e}px ui-monospace, monospace`},note:{size:11,font:e=>`italic 400 ${e}px Inter, system-ui, sans-serif`}};function Qo(e){return Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0")}function YR(e,t,n){const r=Math.min(1,Math.max(0,n));return{r:e.r+(t.r-e.r)*r,g:e.g+(t.g-e.g)*r,b:e.b+(t.b-e.b)*r,a:1}}function zt(e,t=1){return`#${Qo(e.r)}${Qo(e.g)}${Qo(e.b)}${Qo(e.a*t*255)}`}function sk(e,t,n,r){const i=1-r;return{x:i*i*e.x+2*i*r*t.x+r*r*n.x,y:i*i*e.y+2*i*r*t.y+r*r*n.y}}function ak(e,t,n=xs){const r=t.x-e.x,i=t.y-e.y;return{x:(e.x+t.x)/2+i*n,y:(e.y+t.y)/2-r*n}}function uk(e,t,n){const r=n.x-t.x,i=n.y-t.y,o=r*r+i*i,s=o?Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/o)):0;return Math.hypot(e.x-(t.x+s*r),e.y-(t.y+s*i))}function XR(e,t,n,r=xs){const i=ak(t,n,r);let o=1/0,s=t;for(let a=1;a<=12;a++){const u=sk(t,i,n,a/12);o=Math.min(o,uk(e,s,u)),s=u}return o}function QR(e,t,n,r){const i=e.ownerDocument,o=i.defaultView,s=i.createElement("div");s.className="cia-graph-webgl",s.tabIndex=0,s.setAttribute("role","group"),s.setAttribute("aria-label",r.label??"Money-flow graph. Drag the background or use arrow keys to pan, plus and minus to zoom. Select an address or a link for details.");const a=i.createElement("span");a.hidden=!0,s.append(a),e.append(s);const u=new Map;function c(U){const Z=u.get(U);if(Z)return Z;a.style.color="",a.style.color=U;const V=o.getComputedStyle(a).color.match(/[\d.]+/g)?.map(Number)??[0,0,0],ee={r:V[0]??0,g:V[1]??0,b:V[2]??0,a:V[3]??1};return u.set(U,ee),ee}const l=U=>c(`var(--cia-graph-${U})`);let d;function f(){u.clear(),d={node:l("node"),edge:l("edge"),halo:l("halo"),selected:l("selected"),expanded:l("expanded"),text:l("text"),muted:l("muted"),canvas:l("canvas")}}f();function h(U,Z){if(!Z.texts?.length||!Z.outer)return;const V=Z.size/Z.outer;U.textAlign="center",U.textBaseline="alphabetic",U.lineJoin="round";for(const ee of Z.texts){const Ee=JR[ee.kind],ce=Ee.size*V;if(ce<mm)continue;U.font=Ee.font(ce);const ge=Z.y+ee.y*V;U.lineWidth=4*V,U.strokeStyle=Z.haloColor??"#000",U.strokeText(ee.text,Z.x,ge),U.fillStyle=ee.kind==="role"?Z.toneColor??"#fff":ee.kind==="address"?Z.mutedColor??"#aaa":Z.textColor??"#fff",U.fillText(ee.text,Z.x,ge)}}const p=()=>{},m=ok({borders:[{size:{attribute:"ringSize",defaultValue:0},color:{attribute:"ringColor"}},{size:{attribute:"gapSize",defaultValue:0},color:{transparent:!0}},{size:{attribute:"strokeSize",defaultValue:.1},color:{attribute:"strokeColor"}},{size:{fill:!0},color:{attribute:"bodyColor"}},{size:{attribute:"dotSize",defaultValue:.25},color:{attribute:"dotColor"}}],drawLabel:h,drawHover:p}),y=tu({arrowHead:{extremity:"target",lengthToThicknessRatio:6,widenessToThicknessRatio:4}}),w=B_({lengthToThicknessRatio:6,widenessToThicknessRatio:4});let g=new Fe({type:"directed",multi:!1,allowSelfLoops:!1}),b=!0;const v=new aR(g,s,{allowInvalidContainer:!0,autoRescale:!0,stagePadding:0,itemSizesReference:"positions",zoomToSizeRatioFunction:U=>U,enableCameraPanning:!0,enableCameraZooming:!0,enableCameraRotation:!1,enableEdgeEvents:!1,hideEdgesOnMove:!1,hideLabelsOnMove:!1,renderEdgeLabels:!0,edgeLabelSize:10,edgeLabelFont:"Inter, system-ui, sans-serif",edgeLabelWeight:"500",renderLabels:!0,labelRenderedSizeThreshold:mm,labelDensity:1,labelGridCellSize:120,minEdgeThickness:1.6,defaultNodeType:"address",defaultEdgeType:"link",nodeProgramClasses:{address:m},edgeProgramClasses:{link:y,straight:w},defaultDrawNodeLabel:h,defaultDrawNodeHover:p});v.setCustomBBox(KR);const k=v.getMouseCaptor(),S=v.getTouchCaptor();k.removeAllListeners(),S.removeAllListeners(),k.enabled=!1,S.enabled=!1;const _=new Map;let N=xs;function P(U){const Z=t.flags().get(U),V=t.selected();return Z?.has("expanded")?{width:Xo.expanded,color:d.expanded}:V?.kind==="node"&&V.id===U||t.highlighted()===U?{width:Xo.selected,color:d.selected}:{width:Xo.rest,color:c(t.colorOf(_.get(U)))}}function z(U,Z,V){const ee=t.model(),Ee=t.notes().get(U.id)??null,ce=Nn(U,ee.checked_address,Ee),ge=c(t.colorOf(U)),Le=P(U.id),le=ce.radius+Le.width/2,ze=ce.ring?ce.radius+VR+zu/2:le,rt=ce.ring?zu/ze:0,et=ce.ring?Math.max(0,ze-zu-le)/ze:0,me=t.selected(),Je=ce.ring||Le.width!==Xo.rest||me?.kind==="node"&&me.id===U.id;return{x:Z.x,y:-Z.y,size:ze,label:ce.texts.find(T=>T.kind==="address")?.text??U.address,color:zt(ge),forceLabel:!V||Je,ringColor:zt(d.edge),ringSize:rt,gapSize:et,strokeColor:zt(Le.color,Ee?.5:1),strokeSize:Le.width/ze,bodyColor:zt(d.node),dotColor:zt(ge),dotSize:ce.dot/ze,outer:ze,texts:ce.texts,toneColor:zt(ge),mutedColor:zt(d.muted),textColor:zt(d.text),haloColor:zt(d.halo)}}function j(U,Z){const V=t.selected(),ee=V?.kind==="node"?_.get(V.id)?.address??null:null,Ee=V?.kind==="edge"&&V.id===U.id,ce=V?.kind==="edge"?Ee?qt.related:qt.faded:Iw(U,ee),ge=c(t.colorOf(Z)),Le=ce===qt.faded?zt(YR(ge,d.canvas,1-ce)):zt(ge,ce),le=b?Pw(U):"";return{size:Ee?HR:BR,color:Le,curvature:N,type:N?"link":"straight",...le?{label:le}:{}}}function K(){const U=t.model(),Z=t.positions(),{width:V,height:ee}=t.dimensions();_.clear();for(const le of U.nodes)_.set(le.id,le);const Ee=U.nodes.length>Pu;N=U.edges.length>ZR?0:xs,b=U.edges.length<=zw,v.setSetting("edgeLabelColor",{color:zt(d.muted)});const ce=new Fe({type:"directed",multi:!1,allowSelfLoops:!1}),ge=new Map(U.nodes.map(le=>[le.address,le]));for(const le of U.nodes)ce.addNode(le.id,z(le,Z[le.id]??{x:V/2,y:ee/2},Ee));for(const le of U.edges){const ze=ge.get(le.from),rt=ge.get(le.to);!ze||!rt||ze.id===rt.id||ce.hasEdge(le.id)||ce.hasDirectedEdge(ze.id,rt.id)||ce.addDirectedEdgeWithKey(le.id,ze.id,rt.id,j(le,ze))}g=ce;const Le=t.selected();he=[Le?.kind==="node"?Le.id:null,t.highlighted()].filter(le=>!!le),v.setGraph(g),Q()}function Y(){const Z=t.model().nodes.length>Pu,V=t.positions();g.updateEachNodeAttributes((ee,Ee)=>{const ce=_.get(ee);return ce?z(ce,V[ee]??{x:Ee.x,y:-Ee.y},Z):Ee}),H()}function re(U){const Z=U?_.get(U):null;if(!Z||!g.hasNode(Z.id))return;const V=t.positions()[Z.id],ee=g.getNodeAttributes(Z.id);g.replaceNodeAttributes(Z.id,z(Z,V??{x:ee.x,y:-ee.y},t.model().nodes.length>Pu))}let he=[];function M(){const U=t.selected(),Z=[U?.kind==="node"?U.id:null,t.highlighted()].filter(V=>!!V);for(const V of new Set([...he,...Z]))re(V);he=Z,H()}function H(){const U=t.model(),Z=new Map(U.nodes.map(ee=>[ee.address,ee])),V=new Map(U.edges.map(ee=>[ee.id,ee]));g.updateEachEdgeAttributes((ee,Ee)=>{const ce=V.get(ee),ge=ce&&Z.get(ce.from);return ce&&ge?j(ce,ge):Ee})}function Q(){const{width:U,height:Z}=t.dimensions(),V=v.getDimensions();if(!V.width||!V.height)return;const ee=Math.min(V.width/U,V.height/Z),Ee=t.transform(),ce=Ee.scale*ee,ge=(V.width-U*ee)/2+Ee.x*ee,Le=(V.height-Z*ee)/2+Ee.y*ee,le={x:.5,y:.5,ratio:1,angle:0},ze=v.framedGraphToViewport({x:.5,y:.5},{cameraState:le}),rt=(v.framedGraphToViewport({x:.6,y:.5},{cameraState:le}).x-ze.x)/.1,et=(v.framedGraphToViewport({x:.5,y:.6},{cameraState:le}).y-ze.y)/.1,me=rt/(Du*ce);v.getCamera().setState({ratio:me,angle:0,x:.5-gm/Du-(ge-ze.x)*me/rt,y:.5-gm/Du-(Le-ze.y)*me/et})}function ie(U){const Z=t.transform(),V={x:(U.x-Z.x)/Z.scale,y:(U.y-Z.y)/Z.scale},ee=t.positions();let Ee=null,ce=1/0;if(g.forEachNode((ze,rt)=>{const et=ee[ze];if(!et)return;const me=Math.hypot(V.x-et.x,V.y-et.y);me<=rt.size+1/Z.scale&&me<ce&&(Ee=ze,ce=me)}),Ee)return{kind:"node",id:Ee};const ge=qR/Z.scale;let Le=null,le=1/0;return g.forEachEdge((ze,rt,et,me)=>{const Je=ee[et],T=ee[me];if(!Je||!T)return;const F=Math.hypot(T.x-Je.x,T.y-Je.y)*(.5+N)+ge;if(Math.hypot(V.x-(Je.x+T.x)/2,V.y-(Je.y+T.y)/2)>F)return;const X=N?XR(V,Je,T,N):uk(V,Je,T);X<=ge&&X<le&&(Le=ze,le=X)}),Le?{kind:"edge",id:Le}:{kind:"canvas",id:null}}let J=0,I=null,L=null;const G=U=>{U.buttons||(L=U,!J&&(J=o.requestAnimationFrame(()=>{J=0;const Z=L;if(!Z)return;const V=s.getBoundingClientRect(),{width:ee,height:Ee}=t.dimensions(),ce=Math.min(V.width/ee,V.height/Ee)||1,ge=ie({x:(Z.clientX-V.left-(V.width-ee*ce)/2)/ce,y:(Z.clientY-V.top-(V.height-Ee*ce)/2)/ce}),Le=ge.kind==="canvas"?null:`${ge.kind}:${ge.id}`;if(s.style.cursor=Le?"pointer":"",Le!==I){if(I=Le,!Le){n.hideTooltip();return}if(ge.kind==="node"){const le=_.get(ge.id);le&&n.showTooltip(Z,ic(le))}else{const le=t.model().edges.find(ze=>ze.id===ge.id);le&&n.showTooltip(Z,oc(le,t.now()))}}})))},pe=()=>{I=null,s.style.cursor="",n.hideTooltip()};s.addEventListener("pointermove",G),s.addEventListener("pointerleave",pe);let se=null;const ne=U=>{U.preventDefault(),!se&&(se=setTimeout(()=>{se=null,n.lost()},WR))},ke=()=>{se&&clearTimeout(se),se=null,n.lost()},xe=Object.values(v.getCanvases());for(const U of xe)U.addEventListener("webglcontextlost",ne),U.addEventListener("webglcontextrestored",ke);function Ze(){const U=t.positions();let Z=null;return g.forEachEdge((V,ee,Ee,ce)=>{const ge=U[Ee],Le=U[ce];if(!ge||!Le||!N)return;const le=sk(ge,ak(ge,Le,N),Le,.5);Z=Z??{x1:le.x,y1:le.y,x2:le.x,y2:le.y},Z.x1=Math.min(Z.x1,le.x),Z.y1=Math.min(Z.y1,le.y),Z.x2=Math.max(Z.x2,le.x),Z.y2=Math.max(Z.y2,le.y)}),Z}return{kind:"webgl",surface:s,build:K,geometry(){const U=t.positions();g.updateEachNodeAttributes((Z,V)=>{const ee=U[Z];return ee?{...V,x:ee.x,y:-ee.y}:V},{attributes:["x","y"]}),Q()},moveNode(U){const Z=t.positions()[U];Z&&g.hasNode(U)&&g.mergeNodeAttributes(U,{x:Z.x,y:-Z.y})},endMove(){},camera:Q,selection:M,flag:U=>re(U),theme(){f(),Y()},resize(){v.resize(!0),Q()},pick:ie,linkBounds:Ze,destroy(){se&&clearTimeout(se),J&&o.cancelAnimationFrame(J),s.removeEventListener("pointermove",G),s.removeEventListener("pointerleave",pe);for(const U of xe)U.removeEventListener("webglcontextlost",ne),U.removeEventListener("webglcontextrestored",ke);v.kill(),s.remove()}}}oT("webgl",QR);const Tn=document.getElementById("view"),Es=()=>typeof matchMedia=="function"&&matchMedia("(prefers-color-scheme: dark)").matches;let Sn={},sn=ws(document,Sn,{prefersDark:Es}),yt=null,ym=null;eh(Tn);const vm=nT(location);vm?eL(vm):tL();async function eL(e){document.documentElement.dataset.mode="browser",document.title=Y$,sn=ws(document,{},{prefersDark:Es}),typeof matchMedia=="function"&&matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change",()=>{const n=sn;sn=ws(document,{},{prefersDark:Es}),yt&&sn!==n&&yt.setTheme(sn)}),eh(Tn,"Loading the graph");const t=await rT(e,(n,r)=>fetch(n,r),document);if(!t){wi(Tn,null,X$),document.documentElement.dataset.view="text";return}yt=d_(Tn,t.result,{host:iT((n,r)=>fetch(n,r),(n,r,i)=>window.open(n,r,i)),displayMode:"fullscreen",availableDisplayModes:["fullscreen"],toolInput:t.arguments,browser:!0}),document.documentElement.dataset.view=yt.kind}function tL(){const e=new qf({name:"chain-insights-view",version:"1.0.0"},{});function t(r){const i=sn;sn=ws(document,r,{prefersDark:Es,applyVariables:(o,s)=>K$(o,s),applyFonts:J$}),yt&&sn!==i&&yt.setTheme(sn),yt?.setDisplayMode(r.displayMode,r.availableDisplayModes)}function n(r){yt?.destroy(),yt=null;const i=_u(e.getHostContext(),Sn);yt=d_(Tn,r,{host:e,availableDisplayModes:i.availableDisplayModes,displayMode:i.displayMode,toolInput:ym}),document.documentElement.dataset.view=yt.kind}e.ontoolinput=r=>{ym=r.arguments&&typeof r.arguments=="object"?r.arguments:null;const i=typeof r.arguments?.address=="string"?r.arguments.address:null;yt||eh(Tn,i?`Loading the graph of ${i}`:"Loading the Chain Insights view")},e.ontoolresult=r=>{n(r)},e.ontoolcancelled=()=>{yt||wi(Tn,null,"The tool call was cancelled. Nothing to draw.")},e.onhostcontextchanged=r=>{Sn=_u(Sn,r),t(Sn)},e.onteardown=async()=>(yt?.destroy(),yt=null,{}),e.onerror=r=>{console.warn("chain-insights-view:",r)},e.connect(new _w(window.parent,window.parent)).then(()=>{Sn=_u(Sn,e.getHostContext()),t(Sn)},r=>{console.warn("chain-insights-view: no host answered",r),wi(Tn,null,"This view opens inside Claude, next to a Chain Insights tool answer.")})}
719
+ `);return n}var ak=WebGLRenderingContext,gm=ak.UNSIGNED_BYTE,Qo=ak.FLOAT;function uk(e){var t,n=mm(mm({},jR),e||{}),r=n.borders,i=n.drawLabel,o=n.drawHover,s=["u_sizeRatio","u_correctionRatio","u_matrix"].concat(zu(r.flatMap(function(a,u){var c=a.color;return"value"in c?["u_borderColor_".concat(u+1)]:[]})));return t=(function(a){OR(u,a);function u(){var c;NR(this,u);for(var l=arguments.length,d=new Array(l),f=0;f<l;f++)d[f]=arguments[f];return c=DR(this,u,[].concat(d)),sr(wc(c),"drawLabel",i),sr(wc(c),"drawHover",o),c}return zR(u,[{key:"getDefinition",value:function(){return{VERTICES:3,VERTEX_SHADER_SOURCE:VR(n),FRAGMENT_SHADER_SOURCE:BR(n),METHOD:WebGLRenderingContext.TRIANGLES,UNIFORMS:s,ATTRIBUTES:[{name:"a_position",size:2,type:Qo},{name:"a_id",size:4,type:gm,normalized:!0},{name:"a_size",size:1,type:Qo}].concat(zu(r.flatMap(function(l,d){var f=l.color;return"attribute"in f?[{name:"a_borderColor_".concat(d+1),size:4,type:gm,normalized:!0}]:[]})),zu(r.flatMap(function(l,d){var f=l.size;return"attribute"in f?[{name:"a_borderSize_".concat(d+1),size:1,type:Qo}]:[]}))),CONSTANT_ATTRIBUTES:[{name:"a_angle",size:1,type:Qo}],CONSTANT_DATA:[[u.ANGLE_1],[u.ANGLE_2],[u.ANGLE_3]]}}},{key:"processVisibleItem",value:function(l,d,f){var h=this.array;h[d++]=f.x,h[d++]=f.y,h[d++]=l,h[d++]=f.size,r.forEach(function(p){var m=p.color;"attribute"in m&&(h[d++]=Pn(f[m.attribute]||m.defaultValue||ZR))}),r.forEach(function(p){var m=p.size;"attribute"in m&&(h[d++]=f[m.attribute]||m.defaultValue)})}},{key:"setUniforms",value:function(l,d){var f=d.gl,h=d.uniformLocations,p=h.u_sizeRatio,m=h.u_correctionRatio,y=h.u_matrix;f.uniform1f(m,l.correctionRatio),f.uniform1f(p,l.sizeRatio),f.uniformMatrix3fv(y,!1,l.matrix),r.forEach(function(_,g){var b=_.color;if("value"in b){var v=h["u_borderColor_".concat(g+1)],w=YI(b.value),k=IR(w,4),x=k[0],N=k[1],z=k[2],O=k[3];f.uniform4f(v,x/255,N/255,z/255,O/255)}})}}]),u})(F_),sr(t,"ANGLE_1",0),sr(t,"ANGLE_2",2*Math.PI/3),sr(t,"ANGLE_3",4*Math.PI/3),t}uk();const $s=.18,HR=500,qR=2,WR=3,es={rest:2,selected:4,expanded:5},KR=6,Pu=2,JR=8,ym=6,Du=400,YR=2e3,XR={x:[0,1e3],y:[0,1e3]},Ou=1e3,vm=500,QR={role:{size:13,font:e=>`600 ${e}px Inter, system-ui, sans-serif`},address:{size:11,font:e=>`400 ${e}px ui-monospace, monospace`},note:{size:11,font:e=>`italic 400 ${e}px Inter, system-ui, sans-serif`}};function ts(e){return Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0")}function eL(e,t,n){const r=Math.min(1,Math.max(0,n));return{r:e.r+(t.r-e.r)*r,g:e.g+(t.g-e.g)*r,b:e.b+(t.b-e.b)*r,a:1}}function Lt(e,t=1){return`#${ts(e.r)}${ts(e.g)}${ts(e.b)}${ts(e.a*t*255)}`}function ck(e,t,n,r){const i=1-r;return{x:i*i*e.x+2*i*r*t.x+r*r*n.x,y:i*i*e.y+2*i*r*t.y+r*r*n.y}}function lk(e,t,n=$s){const r=t.x-e.x,i=t.y-e.y;return{x:(e.x+t.x)/2+i*n,y:(e.y+t.y)/2-r*n}}function dk(e,t,n){const r=n.x-t.x,i=n.y-t.y,o=r*r+i*i,s=o?Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*i)/o)):0;return Math.hypot(e.x-(t.x+s*r),e.y-(t.y+s*i))}function tL(e,t,n,r=$s){const i=lk(t,n,r);let o=1/0,s=t;for(let a=1;a<=12;a++){const u=ck(t,i,n,a/12);o=Math.min(o,dk(e,s,u)),s=u}return o}function nL(e,t,n,r){const i=e.ownerDocument,o=i.defaultView,s=i.createElement("div");s.className="cia-graph-webgl",s.tabIndex=0,s.setAttribute("role","group"),s.setAttribute("aria-label",r.label??"Money-flow graph. Drag the background or use arrow keys to pan, plus and minus to zoom. Select an address or a link for details.");const a=i.createElement("span");a.hidden=!0,s.append(a),e.append(s);const u=new Map;function c(F){const j=u.get(F);if(j)return j;a.style.color="",a.style.color=F;const V=o.getComputedStyle(a).color.match(/[\d.]+/g)?.map(Number)??[0,0,0],X={r:V[0]??0,g:V[1]??0,b:V[2]??0,a:V[3]??1};return u.set(F,X),X}const l=F=>c(`var(--cia-graph-${F})`);let d;function f(){u.clear(),d={node:l("node"),edge:l("edge"),halo:l("halo"),selected:l("selected"),expanded:l("expanded"),text:l("text"),muted:l("muted"),canvas:l("canvas")}}f();function h(F,j){if(!j.texts?.length||!j.outer)return;const V=j.size/j.outer;F.textAlign="center",F.textBaseline="alphabetic",F.lineJoin="round";for(const X of j.texts){const xe=QR[X.kind],ue=xe.size*V;if(ue<ym)continue;F.font=xe.font(ue);const pe=j.y+X.y*V;F.lineWidth=4*V,F.strokeStyle=j.haloColor??"#000",F.strokeText(X.text,j.x,pe),F.fillStyle=X.kind==="role"?j.toneColor??"#fff":X.kind==="address"?j.mutedColor??"#aaa":j.textColor??"#fff",F.fillText(X.text,j.x,pe)}}const p=()=>{},m=uk({borders:[{size:{attribute:"ringSize",defaultValue:0},color:{attribute:"ringColor"}},{size:{attribute:"gapSize",defaultValue:0},color:{transparent:!0}},{size:{attribute:"strokeSize",defaultValue:.1},color:{attribute:"strokeColor"}},{size:{fill:!0},color:{attribute:"bodyColor"}},{size:{attribute:"dotSize",defaultValue:.25},color:{attribute:"dotColor"}}],drawLabel:h,drawHover:p}),y=nu({arrowHead:{extremity:"target",lengthToThicknessRatio:6,widenessToThicknessRatio:4}}),_=q_({lengthToThicknessRatio:6,widenessToThicknessRatio:4});let g=new Fe({type:"directed",multi:!1,allowSelfLoops:!1}),b=!0;const v=new lR(g,s,{allowInvalidContainer:!0,autoRescale:!0,stagePadding:0,itemSizesReference:"positions",zoomToSizeRatioFunction:F=>F,enableCameraPanning:!0,enableCameraZooming:!0,enableCameraRotation:!1,enableEdgeEvents:!1,hideEdgesOnMove:!1,hideLabelsOnMove:!1,renderEdgeLabels:!0,edgeLabelSize:10,edgeLabelFont:"Inter, system-ui, sans-serif",edgeLabelWeight:"500",renderLabels:!0,labelRenderedSizeThreshold:ym,labelDensity:1,labelGridCellSize:120,minEdgeThickness:1.6,defaultNodeType:"address",defaultEdgeType:"link",nodeProgramClasses:{address:m},edgeProgramClasses:{link:y,straight:_},defaultDrawNodeLabel:h,defaultDrawNodeHover:p});v.setCustomBBox(XR);const w=v.getMouseCaptor(),k=v.getTouchCaptor();w.removeAllListeners(),k.removeAllListeners(),w.enabled=!1,k.enabled=!1;const x=new Map;let N=$s;function z(F){const j=t.flags().get(F),V=t.selected();return j?.has("expanded")?{width:es.expanded,color:d.expanded}:V?.kind==="node"&&V.id===F||t.highlighted()===F?{width:es.selected,color:d.selected}:{width:es.rest,color:c(t.colorOf(x.get(F)))}}function O(F,j,V){const X=t.model(),xe=t.notes().get(F.id)??null,ue=Rn(F,X.checked_address,xe),pe=c(t.colorOf(F)),Le=z(F.id),ce=ue.radius+Le.width/2,ze=ue.ring?ue.radius+KR+Pu/2:ce,rt=ue.ring?Pu/ze:0,et=ue.ring?Math.max(0,ze-Pu-ce)/ze:0,he=t.selected(),Je=ue.ring||Le.width!==es.rest||he?.kind==="node"&&he.id===F.id;return{x:j.x,y:-j.y,size:ze,label:ue.texts.find(T=>T.kind==="address")?.text??F.address,color:Lt(pe),forceLabel:!V||Je,ringColor:Lt(d.edge),ringSize:rt,gapSize:et,strokeColor:Lt(Le.color,xe?.5:1),strokeSize:Le.width/ze,bodyColor:Lt(d.node),dotColor:Lt(pe),dotSize:ue.dot/ze,outer:ze,texts:ue.texts,toneColor:Lt(pe),mutedColor:Lt(d.muted),textColor:Lt(d.text),haloColor:Lt(d.halo)}}function Z(F,j){const V=t.selected(),X=V?.kind==="node"?x.get(V.id)?.address??null:null,xe=V?.kind==="edge"&&V.id===F.id,ue=V?.kind==="edge"?xe?qt.related:qt.faded:Lw(F,X),pe=c(t.colorOf(j)),Le=ue===qt.faded?Lt(eL(pe,d.canvas,1-ue)):Lt(pe,ue),ce=b?Mw(F):"";return{size:xe?WR:qR,color:Le,curvature:N,type:N?"link":"straight",...ce?{label:ce}:{}}}function ee(){const F=t.model(),j=t.positions(),{width:V,height:X}=t.dimensions();x.clear();for(const ce of F.nodes)x.set(ce.id,ce);const xe=F.nodes.length>Du;N=F.edges.length>HR?0:$s,b=F.edges.length<=Ow,v.setSetting("edgeLabelColor",{color:Lt(d.muted)});const ue=new Fe({type:"directed",multi:!1,allowSelfLoops:!1}),pe=new Map(F.nodes.map(ce=>[ce.address,ce]));for(const ce of F.nodes)ue.addNode(ce.id,O(ce,j[ce.id]??{x:V/2,y:X/2},xe));for(const ce of F.edges){const ze=pe.get(ce.from),rt=pe.get(ce.to);!ze||!rt||ze.id===rt.id||ue.hasEdge(ce.id)||ue.hasDirectedEdge(ze.id,rt.id)||ue.addDirectedEdgeWithKey(ce.id,ze.id,rt.id,Z(ce,ze))}g=ue;const Le=t.selected();Re=[Le?.kind==="node"?Le.id:null,t.highlighted()].filter(ce=>!!ce),v.setGraph(g),Y()}function ae(){const j=t.model().nodes.length>Du,V=t.positions();g.updateEachNodeAttributes((X,xe)=>{const ue=x.get(X);return ue?O(ue,V[X]??{x:xe.x,y:-xe.y},j):xe}),q()}function we(F){const j=F?x.get(F):null;if(!j||!g.hasNode(j.id))return;const V=t.positions()[j.id],X=g.getNodeAttributes(j.id);g.replaceNodeAttributes(j.id,O(j,V??{x:X.x,y:-X.y},t.model().nodes.length>Du))}let Re=[];function G(){const F=t.selected(),j=[F?.kind==="node"?F.id:null,t.highlighted()].filter(V=>!!V);for(const V of new Set([...Re,...j]))we(V);Re=j,q()}function q(){const F=t.model(),j=new Map(F.nodes.map(X=>[X.address,X])),V=new Map(F.edges.map(X=>[X.id,X]));g.updateEachEdgeAttributes((X,xe)=>{const ue=V.get(X),pe=ue&&j.get(ue.from);return ue&&pe?Z(ue,pe):xe})}function Y(){const{width:F,height:j}=t.dimensions(),V=v.getDimensions();if(!V.width||!V.height)return;const X=Math.min(V.width/F,V.height/j),xe=t.transform(),ue=xe.scale*X,pe=(V.width-F*X)/2+xe.x*X,Le=(V.height-j*X)/2+xe.y*X,ce={x:.5,y:.5,ratio:1,angle:0},ze=v.framedGraphToViewport({x:.5,y:.5},{cameraState:ce}),rt=(v.framedGraphToViewport({x:.6,y:.5},{cameraState:ce}).x-ze.x)/.1,et=(v.framedGraphToViewport({x:.5,y:.6},{cameraState:ce}).y-ze.y)/.1,he=rt/(Ou*ue);v.getCamera().setState({ratio:he,angle:0,x:.5-vm/Ou-(pe-ze.x)*he/rt,y:.5-vm/Ou-(Le-ze.y)*he/et})}function ne(F){const j=t.transform(),V={x:(F.x-j.x)/j.scale,y:(F.y-j.y)/j.scale},X=t.positions();let xe=null,ue=1/0;if(g.forEachNode((ze,rt)=>{const et=X[ze];if(!et)return;const he=Math.hypot(V.x-et.x,V.y-et.y);he<=rt.size+1/j.scale&&he<ue&&(xe=ze,ue=he)}),xe)return{kind:"node",id:xe};const pe=JR/j.scale;let Le=null,ce=1/0;return g.forEachEdge((ze,rt,et,he)=>{const Je=X[et],T=X[he];if(!Je||!T)return;const M=Math.hypot(T.x-Je.x,T.y-Je.y)*(.5+N)+pe;if(Math.hypot(V.x-(Je.x+T.x)/2,V.y-(Je.y+T.y)/2)>M)return;const J=N?tL(V,Je,T,N):dk(V,Je,T);J<=pe&&J<ce&&(Le=ze,ce=J)}),Le?{kind:"edge",id:Le}:{kind:"canvas",id:null}}let K=0,I=null,L=null;const U=F=>{F.buttons||(L=F,!K&&(K=o.requestAnimationFrame(()=>{K=0;const j=L;if(!j)return;const V=s.getBoundingClientRect(),{width:X,height:xe}=t.dimensions(),ue=Math.min(V.width/X,V.height/xe)||1,pe=ne({x:(j.clientX-V.left-(V.width-X*ue)/2)/ue,y:(j.clientY-V.top-(V.height-xe*ue)/2)/ue}),Le=pe.kind==="canvas"?null:`${pe.kind}:${pe.id}`;if(s.style.cursor=Le?"pointer":"",Le!==I){if(I=Le,!Le){n.hideTooltip();return}if(pe.kind==="node"){const ce=x.get(pe.id);ce&&n.showTooltip(j,oc(ce))}else{const ce=t.model().edges.find(ze=>ze.id===pe.id);ce&&n.showTooltip(j,sc(ce,t.now()))}}})))},fe=()=>{I=null,s.style.cursor="",n.hideTooltip()};s.addEventListener("pointermove",U),s.addEventListener("pointerleave",fe);let ie=null;const te=F=>{F.preventDefault(),!ie&&(ie=setTimeout(()=>{ie=null,n.lost()},YR))},_e=()=>{ie&&clearTimeout(ie),ie=null,n.lost()},Se=Object.values(v.getCanvases());for(const F of Se)F.addEventListener("webglcontextlost",te),F.addEventListener("webglcontextrestored",_e);function Ze(){const F=t.positions();let j=null;return g.forEachEdge((V,X,xe,ue)=>{const pe=F[xe],Le=F[ue];if(!pe||!Le||!N)return;const ce=ck(pe,lk(pe,Le,N),Le,.5);j=j??{x1:ce.x,y1:ce.y,x2:ce.x,y2:ce.y},j.x1=Math.min(j.x1,ce.x),j.y1=Math.min(j.y1,ce.y),j.x2=Math.max(j.x2,ce.x),j.y2=Math.max(j.y2,ce.y)}),j}return{kind:"webgl",surface:s,build:ee,geometry(){const F=t.positions();g.updateEachNodeAttributes((j,V)=>{const X=F[j];return X?{...V,x:X.x,y:-X.y}:V},{attributes:["x","y"]}),Y()},moveNode(F){const j=t.positions()[F];j&&g.hasNode(F)&&g.mergeNodeAttributes(F,{x:j.x,y:-j.y})},endMove(){},camera:Y,selection:G,flag:F=>we(F),theme(){f(),ae()},resize(){v.resize(!0),Y()},pick:ne,linkBounds:Ze,destroy(){ie&&clearTimeout(ie),K&&o.cancelAnimationFrame(K),s.removeEventListener("pointermove",U),s.removeEventListener("pointerleave",fe);for(const F of Se)F.removeEventListener("webglcontextlost",te),F.removeEventListener("webglcontextrestored",_e);v.kill(),s.remove()}}}uT("webgl",nL);const Cn=document.getElementById("view"),Ts=()=>typeof matchMedia=="function"&&matchMedia("(prefers-color-scheme: dark)").matches;let xn={},sn=ks(document,xn,{prefersDark:Ts}),yt=null,bm=null;nh(Cn);const wm=oT(location);wm?rL(wm):iL();async function rL(e){document.documentElement.dataset.mode="browser",document.title=eT,sn=ks(document,{},{prefersDark:Ts}),typeof matchMedia=="function"&&matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change",()=>{const n=sn;sn=ks(document,{},{prefersDark:Ts}),yt&&sn!==n&&yt.setTheme(sn)}),nh(Cn,"Loading the graph");const t=await sT(e,(n,r)=>fetch(n,r),document);if(!t){ki(Cn,null,tT),document.documentElement.dataset.view="text";return}yt=p_(Cn,t.result,{host:aT((n,r)=>fetch(n,r),(n,r,i)=>window.open(n,r,i)),displayMode:"fullscreen",availableDisplayModes:["fullscreen"],toolInput:t.arguments,browser:!0}),document.documentElement.dataset.view=yt.kind}function iL(){const e=new Wf({name:"chain-insights-view",version:"1.0.0"},{});function t(r){const i=sn;sn=ks(document,r,{prefersDark:Ts,applyVariables:(o,s)=>X$(o,s),applyFonts:Q$}),yt&&sn!==i&&yt.setTheme(sn),yt?.setDisplayMode(r.displayMode,r.availableDisplayModes)}function n(r){yt?.destroy(),yt=null;const i=ku(e.getHostContext(),xn);yt=p_(Cn,r,{host:e,availableDisplayModes:i.availableDisplayModes,displayMode:i.displayMode,toolInput:bm}),document.documentElement.dataset.view=yt.kind}e.ontoolinput=r=>{bm=r.arguments&&typeof r.arguments=="object"?r.arguments:null;const i=typeof r.arguments?.address=="string"?r.arguments.address:null;yt||nh(Cn,i?`Loading the graph of ${i}`:"Loading the Chain Insights view")},e.ontoolresult=r=>{n(r)},e.ontoolcancelled=()=>{yt||ki(Cn,null,"The tool call was cancelled. Nothing to draw.")},e.onhostcontextchanged=r=>{xn=ku(xn,r),t(xn)},e.onteardown=async()=>(yt?.destroy(),yt=null,{}),e.onerror=r=>{console.warn("chain-insights-view:",r)},e.connect(new Sw(window.parent,window.parent)).then(()=>{xn=ku(xn,e.getHostContext()),t(xn)},r=>{console.warn("chain-insights-view: no host answered",r),ki(Cn,null,"This view opens inside Claude, next to a Chain Insights tool answer.")})}
720
720
  </script>
721
721
  <style>.cia-graph-surface{--cia-graph-surface:linear-gradient(140deg,#171a20,#0d0f13);--cia-graph-canvas:#101318;--cia-graph-dot:#f2dda621;--cia-graph-text:#e2e8f0;--cia-graph-muted:#adb1ba;--cia-graph-border:#f2dda640;--cia-graph-divider:#ffffff10;--cia-graph-control:#14161a;--cia-graph-hover:#f2dda626;--cia-graph-active:#f2dda6;--cia-graph-active-text:#0b0e13;--cia-graph-node:#14161a;--cia-graph-edge:#f2dda6;--cia-graph-halo:#07090d;--cia-graph-selected:#ffffff;--cia-graph-expanded:#4da3ff;--cia-graph-danger:#d89087;--cia-graph-target:#8bb6b0;--cia-graph-trail:#b49bc4;--cia-graph-infrastructure:#94b58b;--cia-graph-neutral:#f2dda6;--cia-graph-critical:#d89087;--cia-graph-high:#d6a07d;--cia-graph-medium:#b49bc4;--cia-graph-low:#94b58b;--cia-graph-role-exchange:var(--cia-graph-infrastructure);--cia-graph-role-scam:var(--cia-graph-danger);--cia-graph-role-sanctioned:var(--cia-graph-danger);--cia-graph-role-victim:var(--cia-graph-target);--cia-graph-role-pool:var(--cia-graph-trail);--cia-graph-role-other:var(--cia-graph-neutral);--cia-graph-series-1:var(--cia-graph-edge);--cia-graph-series-2:var(--cia-graph-target);--cia-graph-series-3:var(--cia-graph-trail);--cia-graph-series-4:var(--cia-graph-infrastructure);--cia-graph-series-5:var(--cia-graph-danger);--cia-graph-series-6:var(--cia-graph-high);color:var(--cia-graph-text);background:var(--cia-graph-surface);border:1px solid var(--cia-graph-border);border-radius:14px;overflow:hidden}html[data-theme=light] .cia-graph-surface{--cia-graph-surface:#f9f9f9;--cia-graph-canvas:#fff;--cia-graph-dot:#dedede;--cia-graph-text:#242424;--cia-graph-muted:#686868;--cia-graph-border:#dedede;--cia-graph-divider:#e6e6e6;--cia-graph-control:#fff;--cia-graph-hover:#ececec;--cia-graph-active:#4e708a;--cia-graph-active-text:#fff;--cia-graph-node:#fff;--cia-graph-edge:#4e708a;--cia-graph-halo:#fff;--cia-graph-selected:#242424;--cia-graph-expanded:#0057d9;--cia-graph-danger:#a64d4b;--cia-graph-target:#356e68;--cia-graph-trail:#78538f;--cia-graph-infrastructure:#416c4a;--cia-graph-neutral:#4e708a;--cia-graph-critical:#a64d4b;--cia-graph-high:#a15432;--cia-graph-medium:#78538f;--cia-graph-low:#416c4a}.cia-graph-canvas{background:radial-gradient(circle,var(--cia-graph-dot) 1px,transparent 1px) 0 0/24px 24px,var(--cia-graph-canvas)}.graph-detail{border-top:1px solid var(--cia-graph-divider,#ffffff10);padding:1rem 1.5rem;font-size:.85rem;color:var(--cia-graph-muted,#adb1ba);line-height:1.6}.graph-detail strong{color:var(--cia-graph-text,#f2dda6)}.graph-detail p{margin:0}.graph-detail ul{padding-left:1.25rem;margin-bottom:0}.graph-detail strong,.graph-detail li{overflow-wrap:anywhere}.graph-legend{border-top:1px solid var(--cia-graph-divider,#ffffff10);padding:1rem 1.5rem;font-size:.85rem}.graph-legend summary{cursor:pointer}.graph-legend ul{list-style:none;padding:0}.graph-legend li{display:flex;flex-wrap:wrap;gap:.4rem 1rem;padding:.6rem 0;border-bottom:1px solid var(--cia-graph-divider,#ffffff0a)}.graph-legend button{color:var(--cia-graph-edge,#f2dda6);background:none;border:0;padding:0;text-align:left;cursor:pointer;font:inherit;font-family:ui-monospace,monospace;overflow-wrap:anywhere;max-width:100%}.graph-legend span{color:var(--cia-graph-muted,#adb1ba)}.graph-detail a,.graph-legend a{color:var(--cia-graph-edge,#f2dda6);text-decoration:none;border-bottom:1px solid var(--cia-graph-border,#f2dda659)}.graph-detail a:hover,.graph-legend a:hover{border-bottom-color:var(--cia-graph-edge,#f2dda6)}.graph-legend .graph-legend-link{overflow-wrap:normal;flex:none}.cia-graph-node-body{fill:var(--cia-graph-node,#14161a)}.cia-graph-node-ring{stroke:var(--cia-graph-edge,#f2dda6)}.cia-graph-node-address{fill:var(--cia-graph-muted,#adb1ba)}.cia-graph-edge-underlay{stroke:var(--cia-graph-halo,#07090d)}.cia-graph-edge-direction{stroke:var(--cia-graph-edge,#f2dda6)}.cia-graph-edge-arrow{fill:var(--cia-graph-edge,#f2dda6);stroke:var(--cia-graph-halo,#07090d)}.cia-graph-surface .graph-tooltip{background:var(--cia-graph-control);color:var(--cia-graph-text);border-color:var(--cia-graph-border)}.cia-graph-engine{position:relative;min-height:240px}.cia-graph-svg{display:block;width:100%;height:100%;touch-action:none;font-family:Inter,system-ui,sans-serif;outline:none}.cia-graph-svg:focus-visible{outline:2px solid var(--cia-graph-active);outline-offset:-2px}.cia-graph-backdrop{fill:var(--cia-graph-canvas)}.cia-graph-dot{fill:var(--cia-graph-dot)}.cia-graph-edge{cursor:pointer;outline:none;transition:opacity .15s}.cia-graph-edge-hit{fill:none;stroke:transparent}.cia-graph-edge-line{fill:none;stroke:var(--edge-tone,var(--cia-graph-edge));stroke-linecap:round}.cia-graph-edge:focus-visible .cia-graph-edge-line,.cia-graph-edge[aria-pressed=true] .cia-graph-edge-line{stroke-width:3}.cia-graph-node{cursor:pointer;outline:none}.cia-graph-engine .cia-graph-node-body{fill:var(--cia-graph-node);stroke:var(--node-tone,var(--cia-graph-neutral));stroke-width:2}.cia-graph-engine .cia-graph-node-ring{fill:none;stroke:var(--cia-graph-edge);stroke-width:2}.cia-graph-node-dot{fill:var(--node-tone,var(--cia-graph-neutral))}.cia-graph-node.is-selected .cia-graph-node-body,.cia-graph-node.is-focused .cia-graph-node-body,.cia-graph-node:focus-visible .cia-graph-node-body{stroke:var(--cia-graph-selected);stroke-width:4}.cia-graph-node text{paint-order:stroke;stroke:var(--cia-graph-halo);stroke-width:4px;stroke-linejoin:round}.cia-graph-node-role{fill:var(--node-tone,var(--cia-graph-neutral));font-size:13px;font-weight:600}.cia-graph-engine .cia-graph-node-address{fill:var(--cia-graph-muted);font:400 11px ui-monospace,monospace}.cia-graph-node-note{fill:var(--cia-graph-text);font-size:11px;font-style:italic}.cia-graph-node[data-state=refused] .cia-graph-node-body{stroke-dasharray:4 3}.cia-graph-engine .cia-graph-node[data-flag-expanded] .cia-graph-node-body{stroke:var(--cia-graph-expanded);stroke-width:5}.cia-graph-engine>.graph-tooltip{position:absolute;z-index:2;max-width:320px;padding:.5rem .65rem;border:1px solid;border-radius:6px;font:12px/1.45 Inter,system-ui,sans-serif;overflow-wrap:anywhere;pointer-events:none}.cia-graph-webgl{position:relative;display:block;width:100%;height:100%;min-height:inherit;touch-action:none;outline:none;overflow:hidden;background:radial-gradient(circle,var(--cia-graph-dot) 1px,transparent 1px) 0 0/24px 24px,var(--cia-graph-canvas)}.cia-graph-webgl:focus-visible{outline:2px solid var(--cia-graph-active);outline-offset:-2px}.cia-graph-edge-caption{font:500 10px var(--font-sans,Inter,system-ui,sans-serif);fill:var(--cia-graph-muted);paint-order:stroke;stroke:var(--cia-graph-canvas);stroke-width:3px;stroke-linejoin:round;-webkit-user-select:none;user-select:none}.cia-graph-edge[data-state=faded] .cia-graph-edge-caption{opacity:.35}:root{color-scheme:light dark}html,body{margin:0;padding:0;background:transparent}html[data-theme=dark]{color-scheme:dark;--cv-text:var(--color-text-primary,#ececec);--cv-muted:var(--color-text-secondary,#b4b4b4);--cv-surface:var(--color-background-secondary,#262624);--cv-raised:var(--color-background-tertiary,#30302e);--cv-border:var(--color-border-primary,#4a4a46);--cv-ring:var(--color-ring-primary,#8fb5ff);--cv-skeleton:#3a3a37}html[data-theme=light]{color-scheme:light;--cv-text:var(--color-text-primary,#1f1f1e);--cv-muted:var(--color-text-secondary,#5c5c58);--cv-surface:var(--color-background-secondary,#f5f4ef);--cv-raised:var(--color-background-tertiary,#ecebe5);--cv-border:var(--color-border-primary,#d6d4cc);--cv-ring:var(--color-ring-primary,#2f5fb8);--cv-skeleton:#e4e2db}body{color:var(--cv-text);font-family:var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--font-text-sm-size,14px);line-height:var(--font-text-sm-line-height,1.45)}.cv-root{display:block}.cv-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.cv-visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap}.cv-muted{color:var(--cv-muted)}button:focus-visible{outline:2px solid var(--cv-ring);outline-offset:2px}.cv-card{box-sizing:border-box;border:var(--border-width-regular,1px) solid var(--cv-border);border-radius:var(--border-radius-lg,12px);background:var(--cv-surface);padding:14px 16px;overflow:hidden}.cv-card-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px;margin-bottom:10px}.cv-card-head strong{font-size:var(--font-text-md-size,15px);font-weight:var(--font-weight-semibold,600)}.cv-note{margin:0 0 10px;padding:6px 10px;border-radius:var(--border-radius-sm,6px);background:var(--color-background-warning,var(--cv-raised));color:var(--color-text-warning,var(--cv-text))}.cv-text-view p{margin:0 0 6px}.cv-text-body{white-space:pre-wrap;overflow-wrap:anywhere}.cia-graph-surface.cv-notice{box-sizing:border-box;margin:0;padding:6px 12px;border-radius:8px;font:400 13px/1.4 var(--font-sans,system-ui,-apple-system,"Segoe UI",sans-serif)}.cia-graph-surface.cv-notice-refused{border-left:3px solid var(--cia-graph-danger)}.cv-notice-empty{color:var(--cia-graph-muted)}.cv-notice p{margin:0}.cv-notice-line{overflow-wrap:anywhere}.cv-notice summary{cursor:pointer}.cv-notice summary:focus-visible{outline:2px solid var(--cia-graph-active);outline-offset:2px}.cv-notice-full{margin:4px 0 0;color:var(--cia-graph-muted);white-space:pre-wrap;overflow-wrap:anywhere}.cv-skeleton{min-height:220px}.cv-skel-line,.cv-skel-block{background:var(--cv-skeleton);border-radius:6px;margin-bottom:10px}.cv-skel-title{width:32%;height:16px}.cv-skel-sub{width:54%;height:12px}.cv-skel-block{height:160px;border-radius:10px}@media(prefers-reduced-motion:no-preference){.cv-skel-line,.cv-skel-block{animation:cv-pulse 1.6s ease-in-out infinite}}@keyframes cv-pulse{50%{opacity:.55}}.cv-table-wrap{overflow-x:auto}.cv-table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}.cv-table th{position:sticky;top:0;text-align:left;font-weight:var(--font-weight-semibold,600);color:var(--cv-muted);background:var(--cv-surface);border-bottom:1px solid var(--cv-border);padding:6px 10px;white-space:nowrap}.cv-table td{padding:5px 10px;border-bottom:1px solid var(--color-border-secondary,var(--cv-border));white-space:nowrap}.cv-table tr:last-child td{border-bottom:0}.cv-null{color:var(--cv-muted)}.cv-addr-cell{display:inline-flex;align-items:center;gap:6px}.cv-addr{font-family:var(--font-mono,ui-monospace,monospace);font-size:.92em}.cv-addr.is-full{-webkit-user-select:all;user-select:all}.cv-copy{font:inherit;font-size:.8em;padding:1px 7px;border:1px solid var(--cv-border);border-radius:var(--border-radius-sm,5px);background:transparent;color:var(--cv-muted);cursor:pointer}.cv-copy:hover{color:var(--cv-text);background:var(--cv-raised)}.cv-meter{height:8px;border-radius:999px;background:var(--cv-raised);overflow:hidden;margin:2px 0 12px}.cv-meter span{display:block;height:100%;background:var(--cv-ring)}.cv-balance-note{margin:2px 0 12px;font-weight:var(--font-weight-semibold,600)}.cv-facts{display:grid;grid-template-columns:max-content 1fr;gap:6px 18px;margin:0}.cv-facts dt{color:var(--cv-muted)}.cv-facts dd{margin:0;font-weight:var(--font-weight-medium,500)}.cv-flows{box-sizing:border-box;display:flex;flex-direction:column;height:640px;max-height:640px;font-family:var(--font-sans,system-ui,sans-serif)}.cv-flows[data-display-mode=fullscreen]{height:calc(100vh - var(--cv-tabs-h,0px));max-height:none;border-radius:0}.cv-flows-head{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px 12px;padding:10px 14px 6px}.cv-title{display:flex;flex-direction:column;min-width:0}.cv-title strong{font-size:15px;font-weight:600}.cv-title .cv-muted,.cv-flows .cv-muted{color:var(--cia-graph-muted);font-size:12px;overflow-wrap:anywhere}.cv-actions{display:flex;gap:6px;align-items:center;flex-wrap:wrap;justify-content:flex-end}.cv-hint{font-size:12px;color:var(--cia-graph-muted);margin-right:2px}.cv-hint[hidden]{display:none}.cv-button{min-height:30px;min-width:30px;padding:0 10px;border:1px solid var(--cia-graph-border);border-radius:6px;background:var(--cia-graph-control);color:var(--cia-graph-text);font:500 12px var(--font-sans,system-ui,sans-serif);cursor:pointer}.cv-button:hover{background:var(--cia-graph-hover)}.cv-button:focus-visible{outline:2px solid var(--cia-graph-active);outline-offset:1px}.cv-icon{padding:0;font-size:16px;line-height:1}.cv-roles{display:flex;flex-wrap:wrap;gap:4px 14px;margin:0;padding:0 14px 6px;list-style:none;font-size:12px;color:var(--cia-graph-muted)}.cv-roles li{display:inline-flex;align-items:center;gap:5px}.cv-roles i{width:9px;height:9px;border-radius:50%}.cv-canvas{position:relative;flex:1;min-height:0;border-top:1px solid var(--cia-graph-divider);border-bottom:1px solid var(--cia-graph-divider)}.cv-canvas.cia-graph-engine{min-height:0}.cv-canvas .cia-graph-svg{font-family:var(--font-sans,Inter,system-ui,sans-serif)}.cv-status{margin:0;padding:6px 14px 8px;font-size:12px;color:var(--cia-graph-muted)}.cv-detail{flex:none;padding:0 0 8px;color:var(--cia-graph-text);font-size:12px;display:flex;flex-direction:column;gap:4px}.cv-detail[hidden]{display:none}.cv-detail>strong{color:var(--cia-graph-muted);font-weight:500}.cv-detail>code{font:11px var(--font-mono,ui-monospace,monospace);overflow-wrap:anywhere;word-break:break-all}.cv-detail-meta{display:flex;flex-direction:column;gap:3px}.cv-detail-meta .meta-item{display:inline-flex;gap:5px;align-items:baseline}.cv-detail-meta .meta-item span{color:var(--cia-graph-muted)}.cv-detail-meta .meta-item strong{color:var(--cia-graph-text);font-weight:600;overflow-wrap:anywhere}.cv-detail-meta .cia-graph-explorer-link{font:inherit;font-weight:600;padding:0;border:0;border-bottom:1px solid var(--cia-graph-border);background:none;color:var(--cia-graph-edge);cursor:pointer;overflow-wrap:anywhere;text-align:left}.cv-detail-meta .cia-graph-explorer-link:hover{border-bottom-color:var(--cia-graph-edge)}.cv-face[hidden],.cv-tabpanel[hidden]{display:none}.cv-toggle{display:inline-flex;flex:none;border:1px solid var(--cia-graph-border,var(--cv-border));border-radius:6px;overflow:hidden}.cv-card-head .cv-toggle{margin-left:auto}.cv-toggle-button{min-height:28px;padding:0 12px;border:0;background:var(--cia-graph-control,var(--cv-raised));color:var(--cia-graph-text,var(--cv-text));font:500 12px var(--font-sans,system-ui,sans-serif);cursor:pointer}.cv-toggle-button+.cv-toggle-button{border-left:1px solid var(--cia-graph-border,var(--cv-border))}.cv-toggle-button:hover{background:var(--cia-graph-hover,var(--cv-border))}.cv-toggle-button[aria-pressed=true]{background:var(--cia-graph-active,var(--cv-text));color:var(--cia-graph-active-text,var(--cv-surface))}.cv-toggle-button:focus-visible{outline:2px solid var(--cia-graph-active,var(--cv-ring));outline-offset:-2px}.cia-graph-surface .cv-note{margin:0 14px 6px;background:var(--cia-graph-control);color:var(--cia-graph-text);border:1px solid var(--cia-graph-border)}.cv-tabs{display:flex;flex-wrap:wrap;gap:4px;margin:0 0 8px}.cv-tab{padding:6px 12px;border:1px solid var(--cv-border);border-radius:var(--border-radius-md,8px);background:transparent;color:var(--cv-muted);font:500 13px var(--font-sans,system-ui,sans-serif);cursor:pointer}.cv-tab:hover{color:var(--cv-text)}.cv-tab[aria-selected=true]{background:var(--cv-raised);color:var(--cv-text);border-color:var(--cv-ring)}.cv-tab:focus-visible{outline:2px solid var(--cv-ring);outline-offset:2px}.cv-chart{box-sizing:border-box;max-height:640px;overflow:auto;font-family:var(--font-sans,system-ui,sans-serif)}.cv-chart .cv-muted{color:var(--cia-graph-muted);font-size:12px}.cv-chart-summary{line-height:1.45}.cv-chart-bar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;padding:2px 14px 4px}.cv-chart-legend{display:flex;flex-wrap:wrap;gap:6px}.cv-chart-series,.cv-chart-reset{display:inline-flex;align-items:center;gap:6px;min-height:28px;padding:0 10px;border:1px solid var(--cia-graph-border);border-radius:6px;background:var(--cia-graph-control);color:var(--cia-graph-text);font:500 12px var(--font-sans,system-ui,sans-serif);cursor:pointer}.cv-chart-series:hover,.cv-chart-reset:hover{background:var(--cia-graph-hover)}.cv-chart-series[aria-pressed=false]{color:var(--cia-graph-muted);text-decoration:line-through}.cv-chart-series[aria-disabled=true]{cursor:default}.cv-chart-reset{margin-left:auto}.cv-chart-bar>.cv-toggle{margin-left:auto}.cv-chart-reset:not([hidden])+.cv-toggle{margin-left:0}.cv-chart-failure{fill:var(--cia-graph-hover)}.cv-chart-reset[hidden]{display:none}.cv-chart-key{display:inline-block;flex:none;width:10px;height:10px;box-sizing:border-box;border-radius:3px;border:2px solid var(--cv-key);background:var(--cv-key)}.cv-chart-series[aria-pressed=false] .cv-chart-key{background:transparent}.cv-chart-series:focus-visible,.cv-chart-reset:focus-visible,.cv-chart-plot:focus-visible{outline:2px solid var(--cia-graph-active);outline-offset:2px}.cv-chart-body{position:relative;padding:4px 14px 12px}.cv-chart-plot{border-radius:4px;cursor:crosshair;touch-action:pan-y;user-select:none;-webkit-user-select:none}.cv-chart-svg{display:block;width:100%;height:auto}.cv-chart-brush{fill:var(--cia-graph-hover);stroke:var(--cia-graph-active);stroke-width:1}.cv-chart-crossline{stroke:var(--cia-graph-muted);stroke-width:1;stroke-dasharray:3 3}.cv-chart-focus{stroke:var(--cia-graph-canvas);stroke-width:2}.cv-chart-readout{position:absolute;z-index:2;box-sizing:border-box;min-width:170px;max-width:280px;padding:8px 10px;border:1px solid var(--cia-graph-border);border-radius:8px;background:var(--cia-graph-canvas);color:var(--cia-graph-text);font:12px/1.4 var(--font-sans,system-ui,sans-serif);pointer-events:none}.cv-chart-readout[hidden]{display:none}.cv-chart-readout[data-side=left]{transform:translate(-100%)}.cv-chart-readout time{display:block;margin-bottom:4px;font-weight:600}.cv-chart-readout-note{margin:0 0 4px;color:var(--cia-graph-muted)}.cv-chart-readout dl{display:grid;grid-template-columns:auto auto;gap:2px 12px;margin:0}.cv-chart-readout dt{display:flex;align-items:center;gap:6px;min-width:0;color:var(--cia-graph-muted);overflow-wrap:anywhere}.cv-chart-readout dd{margin:0;text-align:right;font-variant-numeric:tabular-nums;font-weight:600}.cv-chart-name{fill:var(--cia-graph-text);font:600 12px var(--font-sans,Inter,system-ui,sans-serif)}.cv-chart-tick{fill:var(--cia-graph-muted);font:400 11px var(--font-sans,Inter,system-ui,sans-serif)}.cv-chart-grid{stroke:var(--cia-graph-divider);stroke-width:1}.cv-chart-base{stroke:var(--cia-graph-border);stroke-width:1}.cv-chart-line{stroke-width:2;stroke-linejoin:round;stroke-linecap:round}.cv-body{position:relative;display:flex;flex:1;min-height:0;min-width:0}.cv-body>.cv-canvas{flex:1;min-width:0}.cv-linkpanel{display:flex;flex-direction:column;flex:none;box-sizing:border-box;width:min(46%,320px);overflow:hidden;padding:10px 12px;border-top:1px solid var(--cia-graph-divider);border-bottom:1px solid var(--cia-graph-divider);border-left:1px solid var(--cia-graph-divider);font-size:12px;color:var(--cia-graph-text)}.cv-linkpanel[hidden]{display:none}.cv-link-body{flex:1;min-height:0;overflow:auto}.cv-linkpanel>[data-link-more]{flex:none;align-self:flex-start;margin-top:8px}.cv-linkpanel>[data-link-more][hidden]{display:none}.cv-link-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px}.cv-link-head strong{font-size:13px}.cv-link-pair{margin:0;color:var(--cia-graph-muted)}.cv-link-pair code{font:11px var(--font-mono,ui-monospace,monospace)}.cv-link-day{margin:6px 0 4px;font-weight:600}.cv-transfers+.cv-link-day{margin-top:10px}.cv-link-body p{margin:0 0 8px}.cv-link-error{color:var(--cia-graph-danger);overflow-wrap:anywhere}.cv-transfers{list-style:none;margin:0 0 8px;padding:0}.cv-transfer{display:grid;grid-template-columns:auto 1fr auto;gap:2px 8px;padding:6px 0;border-bottom:1px solid var(--cia-graph-divider)}.cv-transfer-time{color:var(--cia-graph-muted);font-variant-numeric:tabular-nums}.cv-transfer-amount{font-weight:600;overflow-wrap:anywhere}.cv-transfer-usd{text-align:right;font-variant-numeric:tabular-nums}.cv-transfer>code,.cv-transfer>.cia-graph-explorer-link{grid-column:1/-1;font:11px var(--font-mono,ui-monospace,monospace);color:var(--cia-graph-muted)}.cv-transfer>.cia-graph-explorer-link{padding:0;border:0;border-bottom:1px solid var(--cia-graph-border);background:none;text-align:left;cursor:pointer;justify-self:start;color:var(--cia-graph-edge)}.cv-transfer>.cia-graph-explorer-link:hover{border-bottom-color:var(--cia-graph-edge)}.cv-linkpanel .cv-button:disabled{opacity:.5;cursor:default}@media(max-width:560px){.cv-linkpanel{position:absolute;inset:0;width:auto;border-left:0;background:var(--cia-graph-surface)}}.cv-side{display:flex;flex-direction:column;flex:none;box-sizing:border-box;width:min(46%,340px);overflow:hidden;padding:10px 12px;border-top:1px solid var(--cia-graph-divider);border-bottom:1px solid var(--cia-graph-divider);border-left:1px solid var(--cia-graph-divider);font-size:12px;color:var(--cia-graph-text)}.cv-side[hidden]{display:none}.cv-side-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:6px}.cv-side-head strong{font-size:13px}.cv-side-actions{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}.cv-remaining{margin:0 0 8px;font-size:12px;color:var(--cia-graph-muted)}.cv-remaining[hidden]{display:none}.cv-side-actions:not(:has(button:not([hidden]))){display:none}.cv-side .cv-button:disabled{opacity:.5;cursor:default}.cv-linkpanel-embedded{flex:1;min-height:0;width:auto;padding:8px 0 0;border:0;border-top:1px solid var(--cia-graph-divider);overflow:hidden}.cv-side>.cv-detail{max-height:40%;overflow:auto}.cv-linkpanel-embedded>[data-link-pair]{display:none}.cv-linkpanel-embedded .cv-link-body{min-height:44px}.cv-side:not(:has(.cv-linkpanel-embedded:not([hidden])))>.cv-detail{max-height:none}.cv-link-pair code{word-break:break-all}@media(max-width:560px){.cv-side{position:absolute;inset:0;width:auto;border-left:0;background:var(--cia-graph-surface)}.cv-side .cv-linkpanel-embedded{position:static;width:auto;border:0;border-top:1px solid var(--cia-graph-divider);background:none}}html[data-mode=browser],html[data-mode=browser] body{height:100%}html[data-mode=browser] body{background:var(--cv-surface)}.cv-view-link{user-select:all;-webkit-user-select:all;overflow-wrap:anywhere;font-size:.85em}
722
722
  </style>