@gram-ai/elements 1.20.2 → 1.21.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.
- package/bin/cli.js +14 -12
- package/dist/components/Chat/stories/ConnectionConfiguration.stories.d.ts +2 -2
- package/dist/components/Chat/stories/ToolApproval.stories.d.ts +2 -0
- package/dist/components/ui/dialog.d.ts +1 -1
- package/dist/components/ui/tooltip.d.ts +3 -1
- package/dist/constants/tailwind.d.ts +1 -0
- package/dist/contexts/portal-container-context.d.ts +2 -0
- package/dist/contexts/portal-container.d.ts +7 -0
- package/dist/elements.cjs +1 -160
- package/dist/elements.cjs.map +1 -1
- package/dist/elements.css +1 -1
- package/dist/elements.js +11 -47215
- package/dist/elements.js.map +1 -1
- package/dist/hooks/usePortalContainer.d.ts +8 -0
- package/dist/hooks/useSession.d.ts +1 -2
- package/dist/index-BVvrv2G3.cjs +169 -0
- package/dist/index-BVvrv2G3.cjs.map +1 -0
- package/dist/index-OU3wjArm.js +54670 -0
- package/dist/index-OU3wjArm.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/lib/auth.d.ts +2 -2
- package/dist/lib/errorTracking.config.d.ts +16 -0
- package/dist/lib/errorTracking.d.ts +24 -0
- package/dist/lib/tools.d.ts +3 -2
- package/dist/profiler-DPH9zydw.cjs +2 -0
- package/dist/profiler-DPH9zydw.cjs.map +1 -0
- package/dist/profiler-D_HNXmyv.js +278 -0
- package/dist/profiler-D_HNXmyv.js.map +1 -0
- package/dist/startRecording-B97e4Mlu.cjs +3 -0
- package/dist/startRecording-B97e4Mlu.cjs.map +1 -0
- package/dist/startRecording-DOMzQAAr.js +1212 -0
- package/dist/startRecording-DOMzQAAr.js.map +1 -0
- package/dist/types/index.d.ts +45 -15
- package/package.json +16 -2
- package/src/components/Chat/index.tsx +31 -3
- package/src/components/Chat/stories/Composer.stories.tsx +0 -7
- package/src/components/Chat/stories/ConnectionConfiguration.stories.tsx +7 -14
- package/src/components/Chat/stories/CustomComponents.stories.tsx +0 -7
- package/src/components/Chat/stories/Density.stories.tsx +0 -7
- package/src/components/Chat/stories/ErrorBoundary.stories.tsx +4 -23
- package/src/components/Chat/stories/FrontendTools.stories.tsx +0 -7
- package/src/components/Chat/stories/Model.stories.tsx +0 -7
- package/src/components/Chat/stories/Plugins.stories.tsx +0 -7
- package/src/components/Chat/stories/Radius.stories.tsx +0 -7
- package/src/components/Chat/stories/ToolApproval.stories.tsx +51 -7
- package/src/components/Chat/stories/Tools.stories.tsx +0 -7
- package/src/components/Chat/stories/Variants.stories.tsx +5 -2
- package/src/components/Chat/stories/Welcome.stories.tsx +0 -8
- package/src/components/assistant-ui/assistant-sidecar.tsx +1 -4
- package/src/components/assistant-ui/attachment.tsx +1 -4
- package/src/components/assistant-ui/error-boundary.tsx +6 -0
- package/src/components/assistant-ui/thread-list.tsx +3 -1
- package/src/components/assistant-ui/thread.tsx +10 -12
- package/src/components/ui/dialog.tsx +10 -1
- package/src/components/ui/popover.tsx +10 -12
- package/src/components/ui/tooltip.tsx +7 -2
- package/src/constants/tailwind.ts +2 -0
- package/src/contexts/ElementsProvider.tsx +13 -1
- package/src/contexts/portal-container-context.ts +4 -0
- package/src/contexts/portal-container.tsx +20 -0
- package/src/global.css +129 -16
- package/src/hooks/useAuth.ts +6 -16
- package/src/hooks/usePortalContainer.ts +16 -0
- package/src/hooks/useSession.ts +1 -3
- package/src/index.ts +5 -0
- package/src/lib/api.test.ts +5 -5
- package/src/lib/auth.ts +4 -4
- package/src/lib/errorTracking.config.ts +16 -0
- package/src/lib/errorTracking.ts +104 -0
- package/src/lib/tools.ts +37 -8
- package/src/types/index.ts +48 -16
- package/src/vite-env.d.ts +3 -0
- package/dist/components/Chat/stories/ColorScheme.stories.d.ts +0 -8
- package/src/components/Chat/stories/ColorScheme.stories.tsx +0 -52
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"use strict";const g=require("react/jsx-runtime"),O=require("./index-D8g4LkEy.cjs"),I=require("react"),ko=require("zustand"),vr=require("motion/react"),nD=require("motion/react-m"),wS=require("zustand/shallow"),xS=require("react-dom"),rD=require("remark-gfm"),iD=require("shiki");function Qh(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const x=Qh(I),pr=Qh(nD),SS=Qh(xS);function ES({tools:e}){return g.jsx(g.Fragment,{children:Object.entries(e).map(([,t])=>t({}))})}var IS="vercel.ai.error",oD=Symbol.for(IS),TS,sD=class kS extends Error{constructor({name:t,message:n,cause:i}){super(n),this[TS]=!0,this.name=t,this.cause=i}static isInstance(t){return kS.hasMarker(t,IS)}static hasMarker(t,n){const i=Symbol.for(n);return t!=null&&typeof t=="object"&&i in t&&typeof t[i]=="boolean"&&t[i]===!0}};TS=oD;var fe=sD,CS="AI_APICallError",AS=`vercel.ai.error.${CS}`,aD=Symbol.for(AS),RS,Dt=class extends fe{constructor({message:t,url:n,requestBodyValues:i,statusCode:r,responseHeaders:o,responseBody:s,cause:a,isRetryable:l=r!=null&&(r===408||r===409||r===429||r>=500),data:u}){super({name:CS,message:t,cause:a}),this[RS]=!0,this.url=n,this.requestBodyValues=i,this.statusCode=r,this.responseHeaders=o,this.responseBody=s,this.isRetryable=l,this.data=u}static isInstance(t){return fe.hasMarker(t,AS)}};RS=aD;var $S="AI_EmptyResponseBodyError",OS=`vercel.ai.error.${$S}`,uD=Symbol.for(OS),NS,lD=class extends fe{constructor({message:t="Empty response body"}={}){super({name:$S,message:t}),this[NS]=!0}static isInstance(t){return fe.hasMarker(t,OS)}};NS=uD;function Wo(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var PS="AI_InvalidArgumentError",MS=`vercel.ai.error.${PS}`,cD=Symbol.for(MS),jS,xc=class extends fe{constructor({message:t,cause:n,argument:i}){super({name:PS,message:t,cause:n}),this[jS]=!0,this.argument=i}static isInstance(t){return fe.hasMarker(t,MS)}};jS=cD;var DS="AI_InvalidPromptError",zS=`vercel.ai.error.${DS}`,dD=Symbol.for(zS),LS,Yi=class extends fe{constructor({prompt:t,message:n,cause:i}){super({name:DS,message:`Invalid prompt: ${n}`,cause:i}),this[LS]=!0,this.prompt=t}static isInstance(t){return fe.hasMarker(t,zS)}};LS=dD;var US="AI_JSONParseError",FS=`vercel.ai.error.${US}`,fD=Symbol.for(FS),BS,Co=class extends fe{constructor({text:t,cause:n}){super({name:US,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
+
Error message: ${Wo(n)}`,cause:n}),this[BS]=!0,this.text=t}static isInstance(t){return fe.hasMarker(t,FS)}};BS=fD;var VS="AI_NoSuchModelError",qS=`vercel.ai.error.${VS}`,pD=Symbol.for(qS),ZS,hD=class extends fe{constructor({errorName:e=VS,modelId:t,modelType:n,message:i=`No such ${n}: ${t}`}){super({name:e,message:i}),this[ZS]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return fe.hasMarker(e,qS)}};ZS=pD;var HS="AI_TypeValidationError",GS=`vercel.ai.error.${HS}`,mD=Symbol.for(GS),WS,gD=class Dp extends fe{constructor({value:t,cause:n}){super({name:HS,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
3
|
+
Error message: ${Wo(n)}`,cause:n}),this[WS]=!0,this.value=t}static isInstance(t){return fe.hasMarker(t,GS)}static wrap({value:t,cause:n}){return Dp.isInstance(n)&&n.value===t?n:new Dp({value:t,cause:n})}};WS=mD;var yr=gD;let Jy=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};function mf(e){}function vD(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=mf,onError:n=mf,onRetry:i=mf,onComment:r}=e;let o="",s=!0,a,l="",u="";function c(h){const v=s?h.replace(/^\xEF\xBB\xBF/,""):h,[y,w]=yD(`${o}${v}`);for(const S of y)d(S);o=w,s=!1}function d(h){if(h===""){p();return}if(h.startsWith(":")){r&&r(h.slice(h.startsWith(": ")?2:1));return}const v=h.indexOf(":");if(v!==-1){const y=h.slice(0,v),w=h[v+1]===" "?2:1,S=h.slice(v+w);f(y,S,h);return}f(h,"",h)}function f(h,v,y){switch(h){case"event":u=v;break;case"data":l=`${l}${v}
|
|
4
|
+
`;break;case"id":a=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?i(parseInt(v,10)):n(new Jy(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:y}));break;default:n(new Jy(`Unknown field "${h.length>20?`${h.slice(0,20)}…`:h}"`,{type:"unknown-field",field:h,value:v,line:y}));break}}function p(){l.length>0&&t({id:a,event:u||void 0,data:l.endsWith(`
|
|
5
|
+
`)?l.slice(0,-1):l}),a=void 0,l="",u=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",u="",o=""}return{feed:c,reset:m}}function yD(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
6
|
+
`,i);let s=-1;if(r!==-1&&o!==-1?s=Math.min(r,o):r!==-1?r===e.length-1?s=-1:s=r:o!==-1&&(s=o),s===-1){n=e.slice(i);break}else{const a=e.slice(i,s);t.push(a),i=s+1,e[i-1]==="\r"&&e[i]===`
|
|
7
|
+
`&&i++}}return[t,n]}let Gs=class extends TransformStream{constructor({onError:t,onRetry:n,onComment:i}={}){let r;super({start(o){r=vD({onEvent:s=>{o.enqueue(s)},onError(s){t==="terminate"?o.error(s):typeof t=="function"&&t(s)},onRetry:n,onComment:i})},transform(o){r.feed(o)}})}};const em=Object.freeze({status:"aborted"});function $(e,t,n){function i(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);const u=s.prototype,c=Object.keys(u);for(let d=0;d<c.length;d++){const f=c[d];f in a||(a[f]=u[f].bind(a))}}const r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var l;const u=n?.Parent?new o:this;i(u,a),(l=u._zod).deferred??(l.deferred=[]);for(const c of u._zod.deferred)c();return u}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const JS=Symbol("zod_brand");class Ei extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Sc extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Al={};function It(e){return e&&Object.assign(Al,e),Al}function bD(e){return e}function _D(e){return e}function wD(e){}function xD(e){throw new Error("Unexpected value in exhaustive check")}function SD(e){}function tm(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function q(e,t="|"){return e.map(n=>ue(n)).join(t)}function Rl(e,t){return typeof t=="bigint"?t.toString():t}function Aa(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Di(e){return e==null}function Ec(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function KS(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let r=(i.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(i)){const l=i.match(/\d?e-(\d?)/);l?.[1]&&(r=Number.parseInt(l[1]))}const o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}const Ky=Symbol("evaluating");function Ee(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==Ky)return i===void 0&&(i=Ky,i=n()),i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ED(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function ti(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Cr(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function ID(e){return Cr(e._zod.def)}function TD(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function kD(e){const t=Object.keys(e),n=t.map(i=>e[i]);return Promise.all(n).then(i=>{const r={};for(let o=0;o<t.length;o++)r[t[o]]=i[o];return r})}function CD(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let i=0;i<e;i++)n+=t[Math.floor(Math.random()*t.length)];return n}function zp(e){return JSON.stringify(e)}function YS(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const nm="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const XS=Aa(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ci(e){if(Ao(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ao(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ic(e){return Ci(e)?{...e}:Array.isArray(e)?[...e]:e}function AD(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const RD=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}`)}},$l=new Set(["string","number","symbol"]),QS=new Set(["string","number","bigint","boolean","symbol","undefined"]);function br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sn(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function D(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 $D(e){let t;return new Proxy({},{get(n,i,r){return t??(t=e()),Reflect.get(t,i,r)},set(n,i,r,o){return t??(t=e()),Reflect.set(t,i,r,o)},has(n,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(n,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(n,i,r){return t??(t=e()),Reflect.defineProperty(t,i,r)}})}function ue(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function eE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const tE={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]},nE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rE(e,t){const n=e._zod.def,i=Cr(e._zod.def,{get shape(){const r={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return ti(this,"shape",r),r},checks:[]});return Sn(e,i)}function iE(e,t){const n=e._zod.def,i=Cr(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return ti(this,"shape",r),r},checks:[]});return Sn(e,i)}function oE(e,t){if(!Ci(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=Cr(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return ti(this,"shape",o),o},checks:[]});return Sn(e,r)}function sE(e,t){if(!Ci(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const i={...e._zod.def.shape,...t};return ti(this,"shape",i),i},checks:e._zod.def.checks};return Sn(e,n)}function aE(e,t){const n=Cr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return ti(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Sn(e,n)}function uE(e,t,n){const i=Cr(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return ti(this,"shape",o),o},checks:[]});return Sn(t,i)}function lE(e,t,n){const i=Cr(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return ti(this,"shape",o),o},checks:[]});return Sn(t,i)}function yi(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 $n(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function ks(e){return typeof e=="string"?e:e?.message}function wn(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const r=ks(e.inst?._zod.def?.error?.(e))??ks(t?.error?.(e))??ks(n.customError?.(e))??ks(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Tc(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function kc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ro(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function OD(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function cE(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}function dE(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ND(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return cE(t+n)}function PD(e){return dE(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function MD(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 i=0;i<t.length;i+=2)n[i/2]=Number.parseInt(t.slice(i,i+2),16);return n}function jD(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class DD{constructor(...t){}}const fE=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:nE,Class:DD,NUMBER_FORMAT_RANGES:tE,aborted:yi,allowsEval:XS,assert:SD,assertEqual:bD,assertIs:wD,assertNever:xD,assertNotEqual:_D,assignProp:ti,base64ToUint8Array:cE,base64urlToUint8Array:ND,cached:Aa,captureStackTrace:nm,cleanEnum:OD,cleanRegex:Ec,clone:Sn,cloneDef:ID,createTransparentProxy:$D,defineLazy:Ee,esc:zp,escapeRegex:br,extend:oE,finalizeIssue:wn,floatSafeRemainder:KS,getElementAtPath:TD,getEnumValues:tm,getLengthableOrigin:kc,getParsedType:RD,getSizableOrigin:Tc,hexToUint8Array:MD,isObject:Ao,isPlainObject:Ci,issue:Ro,joinValues:q,jsonStringifyReplacer:Rl,merge:aE,mergeDefs:Cr,normalizeParams:D,nullish:Di,numKeys:AD,objectClone:ED,omit:iE,optionalKeys:eE,partial:uE,pick:rE,prefixIssues:$n,primitiveTypes:QS,promiseAllObject:kD,propertyKeyTypes:$l,randomString:CD,required:lE,safeExtend:sE,shallowClone:Ic,slugify:YS,stringifyPrimitive:ue,uint8ArrayToBase64:dE,uint8ArrayToBase64url:PD,uint8ArrayToHex:jD,unwrapMessage:ks},Symbol.toStringTag,{value:"Module"})),pE=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Rl,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},rm=$("$ZodError",pE),cn=$("$ZodError",pE,{Parent:Error});function im(e,t=n=>n.message){const n={},i=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}function om(e,t=n=>n.message){const n={_errors:[]},i=r=>{for(const o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let s=n,a=0;for(;a<o.path.length;){const l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return i(e),n}function hE(e,t=n=>n.message){const n={errors:[]},i=(r,o=[])=>{var s,a;for(const l of r.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(u=>i({issues:u},l.path));else if(l.code==="invalid_key")i({issues:l.issues},l.path);else if(l.code==="invalid_element")i({issues:l.issues},l.path);else{const u=[...o,...l.path];if(u.length===0){n.errors.push(t(l));continue}let c=n,d=0;for(;d<u.length;){const f=u[d],p=d===u.length-1;typeof f=="string"?(c.properties??(c.properties={}),(s=c.properties)[f]??(s[f]={errors:[]}),c=c.properties[f]):(c.items??(c.items=[]),(a=c.items)[f]??(a[f]={errors:[]}),c=c.items[f]),p&&c.errors.push(t(l)),d++}}};return i(e),n}function mE(e){const t=[],n=e.map(i=>typeof i=="object"?i.key:i);for(const i of n)typeof i=="number"?t.push(`[${i}]`):typeof i=="symbol"?t.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?t.push(`[${JSON.stringify(i)}]`):(t.length&&t.push("."),t.push(i));return t.join("")}function gE(e){const t=[],n=[...e.issues].sort((i,r)=>(i.path??[]).length-(r.path??[]).length);for(const i of n)t.push(`✖ ${i.message}`),i.path?.length&&t.push(` → at ${mE(i.path)}`);return t.join(`
|
|
8
|
+
`)}const Ra=e=>(t,n,i,r)=>{const o=i?Object.assign(i,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ei;if(s.issues.length){const a=new(r?.Err??e)(s.issues.map(l=>wn(l,o,It())));throw nm(a,r?.callee),a}return s.value},Lp=Ra(cn),$a=e=>async(t,n,i,r)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(r?.Err??e)(s.issues.map(l=>wn(l,o,It())));throw nm(a,r?.callee),a}return s.value},Up=$a(cn),Oa=e=>(t,n,i)=>{const r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new Ei;return o.issues.length?{success:!1,error:new(e??rm)(o.issues.map(s=>wn(s,r,It())))}:{success:!0,data:o.value}},vE=Oa(cn),Na=e=>async(t,n,i)=>{const r=i?Object.assign(i,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>wn(s,r,It())))}:{success:!0,data:o.value}},yE=Na(cn),sm=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Ra(e)(t,n,r)},zD=sm(cn),am=e=>(t,n,i)=>Ra(e)(t,n,i),LD=am(cn),um=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return $a(e)(t,n,r)},UD=um(cn),lm=e=>async(t,n,i)=>$a(e)(t,n,i),FD=lm(cn),cm=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Oa(e)(t,n,r)},BD=cm(cn),dm=e=>(t,n,i)=>Oa(e)(t,n,i),VD=dm(cn),fm=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Na(e)(t,n,r)},qD=fm(cn),pm=e=>async(t,n,i)=>Na(e)(t,n,i),ZD=pm(cn),bE=/^[cC][^\s-]{8,}$/,_E=/^[0-9a-z]+$/,wE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xE=/^[0-9a-vA-V]{20}$/,SE=/^[A-Za-z0-9]{27}$/,EE=/^[a-zA-Z0-9_-]{21}$/,IE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,HD=/^[-+]?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)?)??$/,TE=/^([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})$/,$o=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)$/,GD=$o(4),WD=$o(6),JD=$o(7),kE=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,KD=/^[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])?)*$/,YD=/^(([^<>()\[\]\\.,;:\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,}))$/,CE=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,XD=CE,QD=/^[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])?)*$/,ez="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function AE(){return new RegExp(ez,"u")}const RE=/^(?:(?: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])$/,$E=/^(([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}|:))$/,OE=e=>{const t=br(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},NE=/^((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])$/,PE=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ME=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hm=/^[A-Za-z0-9_-]*$/,jE=/^(?=.{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])?)*\.?$/,DE=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,zE=/^\+(?:[0-9]){6,14}[0-9]$/,LE="(?:(?:\\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])))",UE=new RegExp(`^${LE}$`);function FE(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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function BE(e){return new RegExp(`^${FE(e)}$`)}function VE(e){const t=FE({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${LE}T(?:${i})$`)}const qE=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},ZE=/^-?\d+n?$/,HE=/^-?\d+$/,GE=/^-?\d+(?:\.\d+)?/,WE=/^(?:true|false)$/i,JE=/^null$/i,KE=/^undefined$/i,YE=/^[^A-Z]*$/,XE=/^[^a-z]*$/,QE=/^[0-9a-fA-F]*$/;function Pa(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ma(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const tz=/^[0-9a-fA-F]{32}$/,nz=Pa(22,"=="),rz=Ma(22),iz=/^[0-9a-fA-F]{40}$/,oz=Pa(27,"="),sz=Ma(27),az=/^[0-9a-fA-F]{64}$/,uz=Pa(43,"="),lz=Ma(43),cz=/^[0-9a-fA-F]{96}$/,dz=Pa(64,""),fz=Ma(64),pz=/^[0-9a-fA-F]{128}$/,hz=Pa(86,"=="),mz=Ma(86),mm=Object.freeze(Object.defineProperty({__proto__:null,base64:ME,base64url:hm,bigint:ZE,boolean:WE,browserEmail:QD,cidrv4:NE,cidrv6:PE,cuid:bE,cuid2:_E,date:UE,datetime:VE,domain:DE,duration:IE,e164:zE,email:kE,emoji:AE,extendedDuration:HD,guid:TE,hex:QE,hostname:jE,html5Email:KD,idnEmail:XD,integer:HE,ipv4:RE,ipv6:$E,ksuid:SE,lowercase:YE,mac:OE,md5_base64:nz,md5_base64url:rz,md5_hex:tz,nanoid:EE,null:JE,number:GE,rfc5322Email:YD,sha1_base64:oz,sha1_base64url:sz,sha1_hex:iz,sha256_base64:uz,sha256_base64url:lz,sha256_hex:az,sha384_base64:dz,sha384_base64url:fz,sha384_hex:cz,sha512_base64:hz,sha512_base64url:mz,sha512_hex:pz,string:qE,time:BE,ulid:wE,undefined:KE,unicodeEmail:CE,uppercase:XE,uuid:$o,uuid4:GD,uuid6:WD,uuid7:JD,xid:xE},Symbol.toStringTag,{value:"Module"})),Ye=$("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),eI={number:"number",bigint:"bigint",object:"date"},gm=$("$ZodCheckLessThan",(e,t)=>{Ye.init(e,t);const n=eI[typeof t.value];e._zod.onattach.push(i=>{const r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vm=$("$ZodCheckGreaterThan",(e,t)=>{Ye.init(e,t);const n=eI[typeof t.value];e._zod.onattach.push(i=>{const r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tI=$("$ZodCheckMultipleOf",(e,t)=>{Ye.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),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"?n.value%t.value===BigInt(0):KS(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})}}),nI=$("$ZodCheckNumberFormat",(e,t)=>{Ye.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[r,o]=tE[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=r,a.maximum=o,n&&(a.pattern=HE)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:i,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:i,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:i,continue:!t.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:e})}}),rI=$("$ZodCheckBigIntFormat",(e,t)=>{Ye.init(e,t);const[n,i]=nE[t.format];e._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,o.minimum=n,o.maximum=i}),e._zod.check=r=>{const o=r.value;o<n&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:e})}}),iI=$("$ZodCheckMaxSize",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const r=i.value;r.size<=t.maximum||i.issues.push({origin:Tc(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),oI=$("$ZodCheckMinSize",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const r=i.value;r.size>=t.minimum||i.issues.push({origin:Tc(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sI=$("$ZodCheckSizeEquals",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=i=>{const r=i.value,o=r.size;if(o===t.size)return;const s=o>t.size;i.issues.push({origin:Tc(r),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),aI=$("$ZodCheckMaxLength",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const r=i.value;if(r.length<=t.maximum)return;const s=kc(r);i.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),uI=$("$ZodCheckMinLength",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const r=i.value;if(r.length>=t.minimum)return;const s=kc(r);i.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),lI=$("$ZodCheckLengthEquals",(e,t)=>{var n;Ye.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Di(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=i=>{const r=i.value,o=r.length;if(o===t.length)return;const s=kc(r),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),ja=$("$ZodCheckStringFormat",(e,t)=>{var n,i;Ye.init(e,t),e._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),cI=$("$ZodCheckRegex",(e,t)=>{ja.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})}}),dI=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=YE),ja.init(e,t)}),fI=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=XE),ja.init(e,t)}),pI=$("$ZodCheckIncludes",(e,t)=>{Ye.init(e,t);const n=br(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),hI=$("$ZodCheckStartsWith",(e,t)=>{Ye.init(e,t);const n=new RegExp(`^${br(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),mI=$("$ZodCheckEndsWith",(e,t)=>{Ye.init(e,t);const n=new RegExp(`.*${br(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});function Yy(e,t,n){e.issues.length&&t.issues.push(...$n(n,e.issues))}const gI=$("$ZodCheckProperty",(e,t)=>{Ye.init(e,t),e._zod.check=n=>{const i=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(i instanceof Promise)return i.then(r=>Yy(r,n,t.property));Yy(i,n,t.property)}}),vI=$("$ZodCheckMimeType",(e,t)=>{Ye.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(i=>{i._zod.bag.mime=t.mime}),e._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e,continue:!t.abort})}}),yI=$("$ZodCheckOverwrite",(e,t)=>{Ye.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class bI{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(`
|
|
9
|
+
`).filter(s=>s),r=Math.min(...i.map(s=>s.length-s.trimStart().length)),o=i.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of o)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,r.join(`
|
|
10
|
+
`))}}const _I={major:4,minor:2,patch:1},pe=$("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_I;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const r of i)for(const o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,a,l)=>{let u=yi(s),c;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(u)continue;const f=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new Ei;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(u||(u=yi(s,f)))});else{if(s.issues.length===f)continue;u||(u=yi(s,f))}}return c?c.then(()=>s):s},o=(s,a,l)=>{if(yi(s))return s.aborted=!0,s;const u=r(a,i,l);if(u instanceof Promise){if(l.async===!1)throw new Ei;return u.then(c=>e._zod.parse(c,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(c=>o(c,s,a)):o(u,s,a)}const l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Ei;return l.then(u=>r(u,i,a))}return r(l,i,a)}}e["~standard"]={validate:r=>{try{const o=vE(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return yE(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Da=$("$ZodString",(e,t)=>{pe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??qE(e._zod.bag),e._zod.parse=(n,i)=>{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}}),Fe=$("$ZodStringFormat",(e,t)=>{ja.init(e,t),Da.init(e,t)}),wI=$("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=TE),Fe.init(e,t)}),xI=$("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=$o(i))}else t.pattern??(t.pattern=$o());Fe.init(e,t)}),SI=$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=kE),Fe.init(e,t)}),EI=$("$ZodURL",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),r=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.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&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),II=$("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=AE()),Fe.init(e,t)}),TI=$("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=EE),Fe.init(e,t)}),kI=$("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=bE),Fe.init(e,t)}),CI=$("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=_E),Fe.init(e,t)}),AI=$("$ZodULID",(e,t)=>{t.pattern??(t.pattern=wE),Fe.init(e,t)}),RI=$("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xE),Fe.init(e,t)}),$I=$("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=SE),Fe.init(e,t)}),OI=$("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=VE(t)),Fe.init(e,t)}),NI=$("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=UE),Fe.init(e,t)}),PI=$("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=BE(t)),Fe.init(e,t)}),MI=$("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=IE),Fe.init(e,t)}),jI=$("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=RE),Fe.init(e,t),e._zod.bag.format="ipv4"}),DI=$("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=$E),Fe.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),zI=$("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=OE(t.delimiter)),Fe.init(e,t),e._zod.bag.format="mac"}),LI=$("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=NE),Fe.init(e,t)}),UI=$("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=PE),Fe.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[r,o]=i;if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ym(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const FI=$("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ME),Fe.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ym(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function BI(e){if(!hm.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ym(n)}const VI=$("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=hm),Fe.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{BI(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),qI=$("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zE),Fe.init(e,t)});function ZI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const r=JSON.parse(atob(i));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const HI=$("$ZodJWT",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{ZI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),GI=$("$ZodCustomStringFormat",(e,t)=>{Fe.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})}}),bm=$("$ZodNumber",(e,t)=>{pe.init(e,t),e._zod.pattern=e._zod.bag.pattern??GE,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),WI=$("$ZodNumberFormat",(e,t)=>{nI.init(e,t),bm.init(e,t)}),_m=$("$ZodBoolean",(e,t)=>{pe.init(e,t),e._zod.pattern=WE,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),wm=$("$ZodBigInt",(e,t)=>{pe.init(e,t),e._zod.pattern=ZE,e._zod.parse=(n,i)=>{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}}),JI=$("$ZodBigIntFormat",(e,t)=>{rI.init(e,t),wm.init(e,t)}),KI=$("$ZodSymbol",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),YI=$("$ZodUndefined",(e,t)=>{pe.init(e,t),e._zod.pattern=KE,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,i)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),XI=$("$ZodNull",(e,t)=>{pe.init(e,t),e._zod.pattern=JE,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),QI=$("$ZodAny",(e,t)=>{pe.init(e,t),e._zod.parse=n=>n}),eT=$("$ZodUnknown",(e,t)=>{pe.init(e,t),e._zod.parse=n=>n}),tT=$("$ZodNever",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),nT=$("$ZodVoid",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),rT=$("$ZodDate",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const r=n.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function Xy(e,t,n){e.issues.length&&t.issues.push(...$n(n,e.issues)),t.value[n]=e.value}const iT=$("$ZodArray",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let s=0;s<r.length;s++){const a=r[s],l=t.element._zod.run({value:a,issues:[]},i);l instanceof Promise?o.push(l.then(u=>Xy(u,n,s))):Xy(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Ol(e,t,n,i){e.issues.length&&t.issues.push(...$n(n,e.issues)),e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function oT(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=eE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function sT(e,t,n,i,r,o){const s=[],a=r.keySet,l=r.catchall._zod,u=l.def.type;for(const c in t){if(a.has(c))continue;if(u==="never"){s.push(c);continue}const d=l.run({value:t[c],issues:[]},i);d instanceof Promise?e.push(d.then(f=>Ol(f,n,c,t))):Ol(d,n,c,t)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const aT=$("$ZodObject",(e,t)=>{if(pe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}const i=Aa(()=>oT(t));Ee(e._zod,"propValues",()=>{const a=t.shape,l={};for(const u in a){const c=a[u]._zod;if(c.values){l[u]??(l[u]=new Set);for(const d of c.values)l[u].add(d)}}return l});const r=Ao,o=t.catchall;let s;e._zod.parse=(a,l)=>{s??(s=i.value);const u=a.value;if(!r(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};const c=[],d=s.shape;for(const f of s.keys){const m=d[f]._zod.run({value:u[f],issues:[]},l);m instanceof Promise?c.push(m.then(h=>Ol(h,a,f,u))):Ol(m,a,f,u)}return o?sT(c,u,a,l,i.value,e):c.length?Promise.all(c).then(()=>a):a}}),uT=$("$ZodObjectJIT",(e,t)=>{aT.init(e,t);const n=e._zod.parse,i=Aa(()=>oT(t)),r=f=>{const p=new bI(["shape","payload","ctx"]),m=i.value,h=S=>{const b=zp(S);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const S of m.keys)v[S]=`key_${y++}`;p.write("const newResult = {};");for(const S of m.keys){const b=v[S],C=zp(S);p.write(`const ${b} = ${h(S)};`),p.write(`
|
|
11
|
+
if (${b}.issues.length) {
|
|
12
|
+
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
13
|
+
...iss,
|
|
14
|
+
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
15
|
+
})));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
if (${b}.value === undefined) {
|
|
20
|
+
if (${C} in input) {
|
|
21
|
+
newResult[${C}] = undefined;
|
|
22
|
+
}
|
|
23
|
+
} else {
|
|
24
|
+
newResult[${C}] = ${b}.value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(S,b)=>w(f,S,b)};let o;const s=Ao,a=!Al.jitless,u=a&&XS.value,c=t.catchall;let d;e._zod.parse=(f,p)=>{d??(d=i.value);const m=f.value;return s(m)?a&&u&&p?.async===!1&&p.jitless!==!0?(o||(o=r(t.shape)),f=o(f,p),c?sT([],m,f,p,d,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),f)}});function Qy(e,t,n,i){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const r=e.filter(o=>!yi(o));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>wn(s,i,It())))}),t)}const Cc=$("$ZodUnion",(e,t)=>{pe.init(e,t),Ee(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ee(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ee(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ee(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Ec(o.source)).join("|")})$`)}});const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let s=!1;const a=[];for(const l of t.options){const u=l._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(l=>Qy(l,r,e,o)):Qy(a,r,e,o)}});function eb(e,t,n,i){const r=e.filter(o=>o.issues.length===0);return r.length===1?(t.value=r[0].value,t):(r.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>wn(s,i,It())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const lT=$("$ZodXor",(e,t)=>{Cc.init(e,t),t.inclusive=!1;const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let s=!1;const a=[];for(const l of t.options){const u=l._zod.run({value:r.value,issues:[]},o);u instanceof Promise?(a.push(u),s=!0):a.push(u)}return s?Promise.all(a).then(l=>eb(l,r,e,o)):eb(a,r,e,o)}}),cT=$("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Cc.init(e,t);const n=e._zod.parse;Ee(e._zod,"propValues",()=>{const r={};for(const o of t.options){const s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const[a,l]of Object.entries(s)){r[a]||(r[a]=new Set);for(const u of l)r[a].add(u)}}return r});const i=Aa(()=>{const r=t.options,o=new Map;for(const s of r){const a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});e._zod.parse=(r,o)=>{const s=r.value;if(!Ao(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const a=i.value.get(s?.[t.discriminator]);return a?a._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),r)}}),dT=$("$ZodIntersection",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value,o=t.left._zod.run({value:r,issues:[]},i),s=t.right._zod.run({value:r,issues:[]},i);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,u])=>tb(n,l,u)):tb(n,o,s)}});function Fp(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(Ci(e)&&Ci(t)){const n=Object.keys(t),i=Object.keys(e).filter(o=>n.indexOf(o)!==-1),r={...e,...t};for(const o of i){const s=Fp(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const r=e[i],o=t[i],s=Fp(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function tb(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),yi(e))return e;const i=Fp(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const xm=$("$ZodTuple",(e,t)=>{pe.init(e,t);const n=t.items;e._zod.parse=(i,r)=>{const o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const s=[],a=[...n].reverse().findIndex(c=>c._zod.optin!=="optional"),l=a===-1?0:n.length-a;if(!t.rest){const c=o.length>n.length,d=o.length<l-1;if(c||d)return i.issues.push({...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),i}let u=-1;for(const c of n){if(u++,u>=o.length&&u>=l)continue;const d=c._zod.run({value:o[u],issues:[]},r);d instanceof Promise?s.push(d.then(f=>Nu(f,i,u))):Nu(d,i,u)}if(t.rest){const c=o.slice(n.length);for(const d of c){u++;const f=t.rest._zod.run({value:d,issues:[]},r);f instanceof Promise?s.push(f.then(p=>Nu(p,i,u))):Nu(f,i,u)}}return s.length?Promise.all(s).then(()=>i):i}});function Nu(e,t,n){e.issues.length&&t.issues.push(...$n(n,e.issues)),t.value[n]=e.value}const fT=$("$ZodRecord",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Ci(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],s=t.keyType._zod.values;if(s){n.value={};const a=new Set;for(const u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);const c=t.valueType._zod.run({value:r[u],issues:[]},i);c instanceof Promise?o.push(c.then(d=>{d.issues.length&&n.issues.push(...$n(u,d.issues)),n.value[u]=d.value})):(c.issues.length&&n.issues.push(...$n(u,c.issues)),n.value[u]=c.value)}let l;for(const u in r)a.has(u)||(l=l??[],l.push(u));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:l})}else{n.value={};for(const a of Reflect.ownKeys(r)){if(a==="__proto__")continue;const l=t.keyType._zod.run({value:a,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){t.mode==="loose"?n.value[a]=r[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(c=>wn(c,i,It())),input:a,path:[a],inst:e});continue}const u=t.valueType._zod.run({value:r[a],issues:[]},i);u instanceof Promise?o.push(u.then(c=>{c.issues.length&&n.issues.push(...$n(a,c.issues)),n.value[l.value]=c.value})):(u.issues.length&&n.issues.push(...$n(a,u.issues)),n.value[l.value]=u.value)}}return o.length?Promise.all(o).then(()=>n):n}}),pT=$("$ZodMap",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:r,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of r){const l=t.keyType._zod.run({value:s,issues:[]},i),u=t.valueType._zod.run({value:a,issues:[]},i);l instanceof Promise||u instanceof Promise?o.push(Promise.all([l,u]).then(([c,d])=>{nb(c,d,n,s,r,e,i)})):nb(l,u,n,s,r,e,i)}return o.length?Promise.all(o).then(()=>n):n}});function nb(e,t,n,i,r,o,s){e.issues.length&&($l.has(typeof i)?n.issues.push(...$n(i,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:e.issues.map(a=>wn(a,s,It()))})),t.issues.length&&($l.has(typeof i)?n.issues.push(...$n(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(a=>wn(a,s,It()))})),n.value.set(e.value,t.value)}const hT=$("$ZodSet",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Set))return n.issues.push({input:r,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const s of r){const a=t.valueType._zod.run({value:s,issues:[]},i);a instanceof Promise?o.push(a.then(l=>rb(l,n))):rb(a,n)}return o.length?Promise.all(o).then(()=>n):n}});function rb(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const mT=$("$ZodEnum",(e,t)=>{pe.init(e,t);const n=tm(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(r=>$l.has(typeof r)).map(r=>typeof r=="string"?br(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return i.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),gT=$("$ZodLiteral",(e,t)=>{if(pe.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?br(i):i?br(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),vT=$("$ZodFile",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return r instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),n}}),yT=$("$ZodTransform",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Sc(e.constructor.name);const r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n));if(r instanceof Promise)throw new Ei;return n.value=r,n}});function ib(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const bT=$("$ZodOptional",(e,t)=>{pe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ee(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ec(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>ib(o,n.value)):ib(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),_T=$("$ZodNullable",(e,t)=>{pe.init(e,t),Ee(e._zod,"optin",()=>t.innerType._zod.optin),Ee(e._zod,"optout",()=>t.innerType._zod.optout),Ee(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ec(n.source)}|null)$`):void 0}),Ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),wT=$("$ZodDefault",(e,t)=>{pe.init(e,t),e._zod.optin="optional",Ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>ob(o,t)):ob(r,t)}});function ob(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const xT=$("$ZodPrefault",(e,t)=>{pe.init(e,t),e._zod.optin="optional",Ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),ST=$("$ZodNonOptional",(e,t)=>{pe.init(e,t),Ee(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>sb(o,e)):sb(r,e)}});function sb(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 ET=$("$ZodSuccess",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Sc("ZodSuccess");const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.issues.length===0,n)):(n.value=r.issues.length===0,n)}}),IT=$("$ZodCatch",(e,t)=>{pe.init(e,t),Ee(e._zod,"optin",()=>t.innerType._zod.optin),Ee(e._zod,"optout",()=>t.innerType._zod.optout),Ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>wn(s,i,It()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>wn(o,i,It()))},input:n.value}),n.issues=[]),n)}}),TT=$("$ZodNaN",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),kT=$("$ZodPipe",(e,t)=>{pe.init(e,t),Ee(e._zod,"values",()=>t.in._zod.values),Ee(e._zod,"optin",()=>t.in._zod.optin),Ee(e._zod,"optout",()=>t.out._zod.optout),Ee(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const o=t.out._zod.run(n,i);return o instanceof Promise?o.then(s=>Pu(s,t.in,i)):Pu(o,t.in,i)}const r=t.in._zod.run(n,i);return r instanceof Promise?r.then(o=>Pu(o,t.out,i)):Pu(r,t.out,i)}});function Pu(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Sm=$("$ZodCodec",(e,t)=>{pe.init(e,t),Ee(e._zod,"values",()=>t.in._zod.values),Ee(e._zod,"optin",()=>t.in._zod.optin),Ee(e._zod,"optout",()=>t.out._zod.optout),Ee(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if((i.direction||"forward")==="forward"){const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(s=>Mu(s,t,i)):Mu(o,t,i)}else{const o=t.out._zod.run(n,i);return o instanceof Promise?o.then(s=>Mu(s,t,i)):Mu(o,t,i)}}});function Mu(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){const r=t.transform(e.value,e);return r instanceof Promise?r.then(o=>ju(e,o,t.out,n)):ju(e,r,t.out,n)}else{const r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(o=>ju(e,o,t.in,n)):ju(e,r,t.in,n)}}function ju(e,t,n,i){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},i)}const CT=$("$ZodReadonly",(e,t)=>{pe.init(e,t),Ee(e._zod,"propValues",()=>t.innerType._zod.propValues),Ee(e._zod,"values",()=>t.innerType._zod.values),Ee(e._zod,"optin",()=>t.innerType?._zod?.optin),Ee(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(ab):ab(r)}});function ab(e){return e.value=Object.freeze(e.value),e}const AT=$("$ZodTemplateLiteral",(e,t)=>{pe.init(e,t);const n=[];for(const i of t.parts)if(typeof i=="object"&&i!==null){if(!i._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);const r=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!r)throw new Error(`Invalid template literal part: ${i._zod.traits}`);const o=r.startsWith("^")?1:0,s=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(o,s))}else if(i===null||QS.has(typeof i))n.push(br(`${i}`));else throw new Error(`Invalid template literal part: ${i}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(i,r)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:e,expected:"template_literal",code:"invalid_type"}),i):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),i)}),RT=$("$ZodFunction",(e,t)=>(pe.init(e,t),e._def=t,e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...i){const r=e._def.input?Lp(e._def.input,i):i,o=Reflect.apply(n,this,r);return e._def.output?Lp(e._def.output,o):o}},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...i){const r=e._def.input?await Up(e._def.input,i):i,o=await Reflect.apply(n,this,r);return e._def.output?await Up(e._def.output,o):o}},e._zod.parse=(n,i)=>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 i=e.constructor;return Array.isArray(n[0])?new i({type:"function",input:new xm({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new i({type:"function",input:n[0],output:e._def.output})},e.output=n=>{const i=e.constructor;return new i({type:"function",input:e._def.input,output:n})},e)),$T=$("$ZodPromise",(e,t)=>{pe.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then(r=>t.innerType._zod.run({value:r,issues:[]},i))}),OT=$("$ZodLazy",(e,t)=>{pe.init(e,t),Ee(e._zod,"innerType",()=>t.getter()),Ee(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ee(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ee(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ee(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,i)=>e._zod.innerType._zod.run(n,i)}),NT=$("$ZodCustom",(e,t)=>{Ye.init(e,t),pe.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then(o=>ub(o,n,i,e));ub(r,n,i,e)}});function ub(e,t,n,i){if(!e){const r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(r.params=i._zod.def.params),t.issues.push(Ro(r))}}const gz=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return r=>{switch(r.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${r.expected}، ولكن تم إدخال ${n(r.input)}`;case"invalid_value":return r.values.length===1?`مدخلات غير مقبولة: يفترض إدخال ${ue(r.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?` أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()} ${s.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`أصغر من اللازم: يفترض لـ ${r.origin} أن يكون ${o} ${r.minimum.toString()} ${s.unit}`:`أصغر من اللازم: يفترض لـ ${r.origin} أن يكون ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`نَص غير مقبول: يجب أن يبدأ بـ "${r.prefix}"`:o.format==="ends_with"?`نَص غير مقبول: يجب أن ينتهي بـ "${o.suffix}"`:o.format==="includes"?`نَص غير مقبول: يجب أن يتضمَّن "${o.includes}"`:o.format==="regex"?`نَص غير مقبول: يجب أن يطابق النمط ${o.pattern}`:`${i[o.format]??r.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${r.divisor}`;case"unrecognized_keys":return`معرف${r.keys.length>1?"ات":""} غريب${r.keys.length>1?"ة":""}: ${q(r.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${r.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${r.origin}`;default:return"مدخل غير مقبول"}}};function vz(){return{localeError:gz()}}const yz=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={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",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${r.expected}, daxil olan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Yanlış dəyər: gözlənilən ${ue(r.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Çox böyük: gözlənilən ${r.origin??"dəyər"} ${o}${r.maximum.toString()} ${s.unit??"element"}`:`Çox böyük: gözlənilən ${r.origin??"dəyər"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Çox kiçik: gözlənilən ${r.origin} ${o}${r.minimum.toString()} ${s.unit}`:`Çox kiçik: gözlənilən ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Yanlış mətn: "${o.prefix}" ilə başlamalıdır`:o.format==="ends_with"?`Yanlış mətn: "${o.suffix}" ilə bitməlidir`:o.format==="includes"?`Yanlış mətn: "${o.includes}" daxil olmalıdır`:o.format==="regex"?`Yanlış mətn: ${o.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${i[o.format]??r.format}`}case"not_multiple_of":return`Yanlış ədəd: ${r.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${r.keys.length>1?"lar":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${r.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function bz(){return{localeError:yz()}}function lb(e,t,n,i){const r=Math.abs(e),o=r%10,s=r%100;return s>=11&&s<=19?i:o===1?t:o>=2&&o<=4?n:i}const _z=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"лік";case"object":{if(Array.isArray(r))return"масіў";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return r=>{switch(r.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${r.expected}, атрымана ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Няправільны ўвод: чакалася ${ue(r.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);if(s){const a=Number(r.maximum),l=lb(a,s.unit.one,s.unit.few,s.unit.many);return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна ${s.verb} ${o}${r.maximum.toString()} ${l}`}return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна быць ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);if(s){const a=Number(r.minimum),l=lb(a,s.unit.one,s.unit.few,s.unit.many);return`Занадта малы: чакалася, што ${r.origin} павінна ${s.verb} ${o}${r.minimum.toString()} ${l}`}return`Занадта малы: чакалася, што ${r.origin} павінна быць ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Няправільны радок: павінен пачынацца з "${o.prefix}"`:o.format==="ends_with"?`Няправільны радок: павінен заканчвацца на "${o.suffix}"`:o.format==="includes"?`Няправільны радок: павінен змяшчаць "${o.includes}"`:o.format==="regex"?`Няправільны радок: павінен адпавядаць шаблону ${o.pattern}`:`Няправільны ${i[o.format]??r.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${r.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${r.keys.length>1?"ключы":"ключ"}: ${q(r.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${r.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${r.origin}`;default:return"Няправільны ўвод"}}};function wz(){return{localeError:_z()}}const xz=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":{if(Array.isArray(e))return"масив";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Sz=()=>{const e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function t(i){return e[i]??null}const n={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"};return i=>{switch(i.code){case"invalid_type":return`Невалиден вход: очакван ${i.expected}, получен ${xz(i.input)}`;case"invalid_value":return i.values.length===1?`Невалиден вход: очакван ${ue(i.values[0])}`:`Невалидна опция: очаквано едно от ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Твърде голямо: очаква се ${i.origin??"стойност"} да съдържа ${r}${i.maximum.toString()} ${o.unit??"елемента"}`:`Твърде голямо: очаква се ${i.origin??"стойност"} да бъде ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Твърде малко: очаква се ${i.origin} да съдържа ${r}${i.minimum.toString()} ${o.unit}`:`Твърде малко: очаква се ${i.origin} да бъде ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;if(r.format==="starts_with")return`Невалиден низ: трябва да започва с "${r.prefix}"`;if(r.format==="ends_with")return`Невалиден низ: трябва да завършва с "${r.suffix}"`;if(r.format==="includes")return`Невалиден низ: трябва да включва "${r.includes}"`;if(r.format==="regex")return`Невалиден низ: трябва да съвпада с ${r.pattern}`;let o="Невалиден";return r.format==="emoji"&&(o="Невалидно"),r.format==="datetime"&&(o="Невалидно"),r.format==="date"&&(o="Невалидна"),r.format==="time"&&(o="Невалидно"),r.format==="duration"&&(o="Невалидна"),`${o} ${n[r.format]??i.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${i.divisor}`;case"unrecognized_keys":return`Неразпознат${i.keys.length>1?"и":""} ключ${i.keys.length>1?"ове":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${i.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${i.origin}`;default:return"Невалиден вход"}}};function Ez(){return{localeError:Sz()}}const Iz=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrada",email:"adreça electrònica",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:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipus invàlid: s'esperava ${r.expected}, s'ha rebut ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Valor invàlid: s'esperava ${ue(r.values[0])}`:`Opció invàlida: s'esperava una de ${q(r.values," o ")}`;case"too_big":{const o=r.inclusive?"com a màxim":"menys de",s=t(r.origin);return s?`Massa gran: s'esperava que ${r.origin??"el valor"} contingués ${o} ${r.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${r.origin??"el valor"} fos ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"com a mínim":"més de",s=t(r.origin);return s?`Massa petit: s'esperava que ${r.origin} contingués ${o} ${r.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${r.origin} fos ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Format invàlid: ha de començar amb "${o.prefix}"`:o.format==="ends_with"?`Format invàlid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format invàlid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format invàlid: ha de coincidir amb el patró ${o.pattern}`:`Format invàlid per a ${i[o.format]??r.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${r.divisor}`;case"unrecognized_keys":return`Clau${r.keys.length>1?"s":""} no reconeguda${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${r.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${r.origin}`;default:return"Entrada invàlida"}}};function Tz(){return{localeError:Iz()}}const kz=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(r))return"pole";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"regulární výraz",email:"e-mailová adresa",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:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return r=>{switch(r.code){case"invalid_type":return`Neplatný vstup: očekáváno ${r.expected}, obdrženo ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neplatný vstup: očekáváno ${ue(r.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Hodnota je příliš velká: ${r.origin??"hodnota"} musí mít ${o}${r.maximum.toString()} ${s.unit??"prvků"}`:`Hodnota je příliš velká: ${r.origin??"hodnota"} musí být ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Hodnota je příliš malá: ${r.origin??"hodnota"} musí mít ${o}${r.minimum.toString()} ${s.unit??"prvků"}`:`Hodnota je příliš malá: ${r.origin??"hodnota"} musí být ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Neplatný řetězec: musí začínat na "${o.prefix}"`:o.format==="ends_with"?`Neplatný řetězec: musí končit na "${o.suffix}"`:o.format==="includes"?`Neplatný řetězec: musí obsahovat "${o.includes}"`:o.format==="regex"?`Neplatný řetězec: musí odpovídat vzoru ${o.pattern}`:`Neplatný formát ${i[o.format]??r.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${r.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${q(r.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${r.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${r.origin}`;default:return"Neplatný vstup"}}};function Cz(){return{localeError:kz()}}const Az=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(s){return e[s]??null}function i(s){return t[s]??s}const r=s=>{const a=typeof s;switch(a){case"number":return Number.isNaN(s)?"NaN":"tal";case"object":return Array.isArray(s)?"liste":s===null?"null":Object.getPrototypeOf(s)!==Object.prototype&&s.constructor?s.constructor.name:"objekt"}return a},o={regex:"input",email:"e-mailadresse",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 dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return s=>{switch(s.code){case"invalid_type":return`Ugyldigt input: forventede ${i(s.expected)}, fik ${i(r(s.input))}`;case"invalid_value":return s.values.length===1?`Ugyldig værdi: forventede ${ue(s.values[0])}`:`Ugyldigt valg: forventede en af følgende ${q(s.values,"|")}`;case"too_big":{const a=s.inclusive?"<=":"<",l=n(s.origin),u=i(s.origin);return l?`For stor: forventede ${u??"value"} ${l.verb} ${a} ${s.maximum.toString()} ${l.unit??"elementer"}`:`For stor: forventede ${u??"value"} havde ${a} ${s.maximum.toString()}`}case"too_small":{const a=s.inclusive?">=":">",l=n(s.origin),u=i(s.origin);return l?`For lille: forventede ${u} ${l.verb} ${a} ${s.minimum.toString()} ${l.unit}`:`For lille: forventede ${u} havde ${a} ${s.minimum.toString()}`}case"invalid_format":{const a=s;return a.format==="starts_with"?`Ugyldig streng: skal starte med "${a.prefix}"`:a.format==="ends_with"?`Ugyldig streng: skal ende med "${a.suffix}"`:a.format==="includes"?`Ugyldig streng: skal indeholde "${a.includes}"`:a.format==="regex"?`Ugyldig streng: skal matche mønsteret ${a.pattern}`:`Ugyldig ${o[a.format]??s.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${s.divisor}`;case"unrecognized_keys":return`${s.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${q(s.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${s.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${s.origin}`;default:return"Ugyldigt input"}}};function Rz(){return{localeError:Az()}}const $z=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"Zahl";case"object":{if(Array.isArray(r))return"Array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"Eingabe",email:"E-Mail-Adresse",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-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return r=>{switch(r.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${r.expected}, erhalten ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ungültige Eingabe: erwartet ${ue(r.values[0])}`:`Ungültige Option: erwartet eine von ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ist`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ist`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ungültiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ungültiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ungültiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ungültiger String: muss dem Muster ${o.pattern} entsprechen`:`Ungültig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${r.divisor} sein`;case"unrecognized_keys":return`${r.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${r.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${r.origin}`;default:return"Ungültige Eingabe"}}};function Oz(){return{localeError:$z()}}const Nz=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Pz=()=>{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"}};function t(i){return e[i]??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",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Invalid input: expected ${i.expected}, received ${Nz(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${ue(i.values[0])}`:`Invalid option: expected one of ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${r}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Too small: expected ${i.origin} to have ${r}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Invalid string: must start with "${r.prefix}"`:r.format==="ends_with"?`Invalid string: must end with "${r.suffix}"`:r.format==="includes"?`Invalid string: must include "${r.includes}"`:r.format==="regex"?`Invalid string: must match pattern ${r.pattern}`:`Invalid ${n[r.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function PT(){return{localeError:Pz()}}const Mz=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":{if(Array.isArray(e))return"tabelo";if(e===null)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},jz=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(i){return e[i]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return i=>{switch(i.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${i.expected}, riceviĝis ${Mz(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendiĝis ${ue(i.values[0])}`:`Nevalida opcio: atendiĝis unu el ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Tro granda: atendiĝis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()} ${o.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Tro malgranda: atendiĝis ke ${i.origin} havu ${r}${i.minimum.toString()} ${o.unit}`:`Tro malgranda: atendiĝis ke ${i.origin} estu ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Nevalida karaktraro: devas komenciĝi per "${r.prefix}"`:r.format==="ends_with"?`Nevalida karaktraro: devas finiĝi per "${r.suffix}"`:r.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${r.includes}"`:r.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${r.pattern}`:`Nevalida ${n[r.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} ŝlosilo${i.keys.length>1?"j":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}};function Dz(){return{localeError:jz()}}const zz=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},t={string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};function n(s){return e[s]??null}function i(s){return t[s]??s}const r=s=>{const a=typeof s;switch(a){case"number":return Number.isNaN(s)?"NaN":"number";case"object":return Array.isArray(s)?"array":s===null?"null":Object.getPrototypeOf(s)!==Object.prototype?s.constructor.name:"object"}return a},o={regex:"entrada",email:"dirección de correo electrónico",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:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return s=>{switch(s.code){case"invalid_type":return`Entrada inválida: se esperaba ${i(s.expected)}, recibido ${i(r(s.input))}`;case"invalid_value":return s.values.length===1?`Entrada inválida: se esperaba ${ue(s.values[0])}`:`Opción inválida: se esperaba una de ${q(s.values,"|")}`;case"too_big":{const a=s.inclusive?"<=":"<",l=n(s.origin),u=i(s.origin);return l?`Demasiado grande: se esperaba que ${u??"valor"} tuviera ${a}${s.maximum.toString()} ${l.unit??"elementos"}`:`Demasiado grande: se esperaba que ${u??"valor"} fuera ${a}${s.maximum.toString()}`}case"too_small":{const a=s.inclusive?">=":">",l=n(s.origin),u=i(s.origin);return l?`Demasiado pequeño: se esperaba que ${u} tuviera ${a}${s.minimum.toString()} ${l.unit}`:`Demasiado pequeño: se esperaba que ${u} fuera ${a}${s.minimum.toString()}`}case"invalid_format":{const a=s;return a.format==="starts_with"?`Cadena inválida: debe comenzar con "${a.prefix}"`:a.format==="ends_with"?`Cadena inválida: debe terminar en "${a.suffix}"`:a.format==="includes"?`Cadena inválida: debe incluir "${a.includes}"`:a.format==="regex"?`Cadena inválida: debe coincidir con el patrón ${a.pattern}`:`Inválido ${o[a.format]??s.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${s.divisor}`;case"unrecognized_keys":return`Llave${s.keys.length>1?"s":""} desconocida${s.keys.length>1?"s":""}: ${q(s.keys,", ")}`;case"invalid_key":return`Llave inválida en ${i(s.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${i(s.origin)}`;default:return"Entrada inválida"}}};function Lz(){return{localeError:zz()}}const Uz=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"عدد";case"object":{if(Array.isArray(r))return"آرایه";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return r=>{switch(r.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${r.expected} میبود، ${n(r.input)} دریافت شد`;case"invalid_value":return r.values.length===1?`ورودی نامعتبر: میبایست ${ue(r.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${q(r.values,"|")} میبود`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} ${s.unit??"عنصر"} باشد`:`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} باشد`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`خیلی کوچک: ${r.origin} باید ${o}${r.minimum.toString()} ${s.unit} باشد`:`خیلی کوچک: ${r.origin} باید ${o}${r.minimum.toString()} باشد`}case"invalid_format":{const o=r;return o.format==="starts_with"?`رشته نامعتبر: باید با "${o.prefix}" شروع شود`:o.format==="ends_with"?`رشته نامعتبر: باید با "${o.suffix}" تمام شود`:o.format==="includes"?`رشته نامعتبر: باید شامل "${o.includes}" باشد`:o.format==="regex"?`رشته نامعتبر: باید با الگوی ${o.pattern} مطابقت داشته باشد`:`${i[o.format]??r.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${r.divisor} باشد`;case"unrecognized_keys":return`کلید${r.keys.length>1?"های":""} ناشناس: ${q(r.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${r.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${r.origin}`;default:return"ورودی نامعتبر"}}};function Fz(){return{localeError:Uz()}}const Bz=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return r=>{switch(r.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${r.expected}, oli ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Virheellinen syöte: täytyy olla ${ue(r.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Liian suuri: ${s.subject} täytyy olla ${o}${r.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon täytyy olla ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Liian pieni: ${s.subject} täytyy olla ${o}${r.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon täytyy olla ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Virheellinen syöte: täytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen syöte: täytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen syöte: täytyy sisältää "${o.includes}"`:o.format==="regex"?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${o.pattern}`:`Virheellinen ${i[o.format]??r.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${r.divisor} monikerta`;case"unrecognized_keys":return`${r.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${q(r.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function Vz(){return{localeError:Bz()}}const qz=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombre";case"object":{if(Array.isArray(r))return"tableau";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrée",email:"adresse e-mail",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:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return r=>{switch(r.code){case"invalid_type":return`Entrée invalide : ${r.expected} attendu, ${n(r.input)} reçu`;case"invalid_value":return r.values.length===1?`Entrée invalide : ${ue(r.values[0])} attendu`:`Option invalide : une valeur parmi ${q(r.values,"|")} attendue`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Trop grand : ${r.origin??"valeur"} doit ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"élément(s)"}`:`Trop grand : ${r.origin??"valeur"} doit être ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Trop petit : ${r.origin} doit ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Trop petit : ${r.origin} doit être ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chaîne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Chaîne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Chaîne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Chaîne invalide : doit correspondre au modèle ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${r.divisor}`;case"unrecognized_keys":return`Clé${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${q(r.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${r.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entrée invalide"}}};function Zz(){return{localeError:qz()}}const Hz=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrée",email:"adresse courriel",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:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return r=>{switch(r.code){case"invalid_type":return`Entrée invalide : attendu ${r.expected}, reçu ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrée invalide : attendu ${ue(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"≤":"<",s=t(r.origin);return s?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${o}${r.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"≥":">",s=t(r.origin);return s?`Trop petit : attendu que ${r.origin} ait ${o}${r.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${r.origin} soit ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chaîne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Chaîne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Chaîne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Chaîne invalide : doit correspondre au motif ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${r.divisor}`;case"unrecognized_keys":return`Clé${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${q(r.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${r.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entrée invalide"}}};function Gz(){return{localeError:Hz()}}const Wz=()=>{const e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},n=u=>u?e[u]:void 0,i=u=>{const c=n(u);return c?c.label:u??e.unknown.label},r=u=>`ה${i(u)}`,o=u=>(n(u)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",s=u=>u?t[u]??null:null,a=u=>{const c=typeof u;switch(c){case"number":return Number.isNaN(u)?"NaN":"number";case"object":return Array.isArray(u)?"array":u===null?"null":Object.getPrototypeOf(u)!==Object.prototype&&u.constructor?u.constructor.name:"object";default:return c}},l={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}};return u=>{switch(u.code){case"invalid_type":{const c=u.expected,d=i(c),f=a(u.input),p=e[f]?.label??f;return`קלט לא תקין: צריך להיות ${d}, התקבל ${p}`}case"invalid_value":{if(u.values.length===1)return`ערך לא תקין: הערך חייב להיות ${ue(u.values[0])}`;const c=u.values.map(p=>ue(p));if(u.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${c[0]} או ${c[1]}`;const d=c[c.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${c.slice(0,-1).join(", ")} או ${d}`}case"too_big":{const c=s(u.origin),d=r(u.origin??"value");if(u.origin==="string")return`${c?.longLabel??"ארוך"} מדי: ${d} צריכה להכיל ${u.maximum.toString()} ${c?.unit??""} ${u.inclusive?"או פחות":"לכל היותר"}`.trim();if(u.origin==="number"){const m=u.inclusive?`קטן או שווה ל-${u.maximum}`:`קטן מ-${u.maximum}`;return`גדול מדי: ${d} צריך להיות ${m}`}if(u.origin==="array"||u.origin==="set"){const m=u.origin==="set"?"צריכה":"צריך",h=u.inclusive?`${u.maximum} ${c?.unit??""} או פחות`:`פחות מ-${u.maximum} ${c?.unit??""}`;return`גדול מדי: ${d} ${m} להכיל ${h}`.trim()}const f=u.inclusive?"<=":"<",p=o(u.origin??"value");return c?.unit?`${c.longLabel} מדי: ${d} ${p} ${f}${u.maximum.toString()} ${c.unit}`:`${c?.longLabel??"גדול"} מדי: ${d} ${p} ${f}${u.maximum.toString()}`}case"too_small":{const c=s(u.origin),d=r(u.origin??"value");if(u.origin==="string")return`${c?.shortLabel??"קצר"} מדי: ${d} צריכה להכיל ${u.minimum.toString()} ${c?.unit??""} ${u.inclusive?"או יותר":"לפחות"}`.trim();if(u.origin==="number"){const m=u.inclusive?`גדול או שווה ל-${u.minimum}`:`גדול מ-${u.minimum}`;return`קטן מדי: ${d} צריך להיות ${m}`}if(u.origin==="array"||u.origin==="set"){const m=u.origin==="set"?"צריכה":"צריך";if(u.minimum===1&&u.inclusive){const v=(u.origin==="set","לפחות פריט אחד");return`קטן מדי: ${d} ${m} להכיל ${v}`}const h=u.inclusive?`${u.minimum} ${c?.unit??""} או יותר`:`יותר מ-${u.minimum} ${c?.unit??""}`;return`קטן מדי: ${d} ${m} להכיל ${h}`.trim()}const f=u.inclusive?">=":">",p=o(u.origin??"value");return c?.unit?`${c.shortLabel} מדי: ${d} ${p} ${f}${u.minimum.toString()} ${c.unit}`:`${c?.shortLabel??"קטן"} מדי: ${d} ${p} ${f}${u.minimum.toString()}`}case"invalid_format":{const c=u;if(c.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${c.prefix}"`;if(c.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${c.suffix}"`;if(c.format==="includes")return`המחרוזת חייבת לכלול "${c.includes}"`;if(c.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${c.pattern}`;const d=l[c.format],f=d?.label??c.format,m=(d?.gender??"m")==="f"?"תקינה":"תקין";return`${f} לא ${m}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${u.divisor}`;case"unrecognized_keys":return`מפתח${u.keys.length>1?"ות":""} לא מזוה${u.keys.length>1?"ים":"ה"}: ${q(u.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${r(u.origin??"array")}`;default:return"קלט לא תקין"}}};function Jz(){return{localeError:Wz()}}const Kz=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"szám";case"object":{if(Array.isArray(r))return"tömb";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"bemenet",email:"email cím",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 időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return r=>{switch(r.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${r.expected}, a kapott érték ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Érvénytelen bemenet: a várt érték ${ue(r.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Túl nagy: ${r.origin??"érték"} mérete túl nagy ${o}${r.maximum.toString()} ${s.unit??"elem"}`:`Túl nagy: a bemeneti érték ${r.origin??"érték"} túl nagy: ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Túl kicsi: a bemeneti érték ${r.origin} mérete túl kicsi ${o}${r.minimum.toString()} ${s.unit}`:`Túl kicsi: a bemeneti érték ${r.origin} túl kicsi ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Érvénytelen string: "${o.prefix}" értékkel kell kezdődnie`:o.format==="ends_with"?`Érvénytelen string: "${o.suffix}" értékkel kell végződnie`:o.format==="includes"?`Érvénytelen string: "${o.includes}" értéket kell tartalmaznia`:o.format==="regex"?`Érvénytelen string: ${o.pattern} mintának kell megfelelnie`:`Érvénytelen ${i[o.format]??r.format}`}case"not_multiple_of":return`Érvénytelen szám: ${r.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${r.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${r.origin}`;default:return"Érvénytelen bemenet"}}};function Yz(){return{localeError:Kz()}}const Xz=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat email",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:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak valid: diharapkan ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak valid: diharapkan ${ue(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${o}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Terlalu kecil: diharapkan ${r.origin} memiliki ${o}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${r.origin} menjadi ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${i[o.format]??r.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${r.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${r.origin}`;default:return"Input tidak valid"}}};function Qz(){return{localeError:Xz()}}const eL=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":{if(Array.isArray(e))return"fylki";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},tL=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(i){return e[i]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return i=>{switch(i.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${eL(i.input)} þar sem á að vera ${i.expected}`;case"invalid_value":return i.values.length===1?`Rangt gildi: gert ráð fyrir ${ue(i.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Of stórt: gert er ráð fyrir að ${i.origin??"gildi"} hafi ${r}${i.maximum.toString()} ${o.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${i.origin??"gildi"} sé ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Of lítið: gert er ráð fyrir að ${i.origin} hafi ${r}${i.minimum.toString()} ${o.unit}`:`Of lítið: gert er ráð fyrir að ${i.origin} sé ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Ógildur strengur: verður að byrja á "${r.prefix}"`:r.format==="ends_with"?`Ógildur strengur: verður að enda á "${r.suffix}"`:r.format==="includes"?`Ógildur strengur: verður að innihalda "${r.includes}"`:r.format==="regex"?`Ógildur strengur: verður að fylgja mynstri ${r.pattern}`:`Rangt ${n[r.format]??i.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${i.divisor}`;case"unrecognized_keys":return`Óþekkt ${i.keys.length>1?"ir lyklar":"ur lykill"}: ${q(i.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${i.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${i.origin}`;default:return"Rangt gildi"}}};function nL(){return{localeError:tL()}}const rL=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numero";case"object":{if(Array.isArray(r))return"vettore";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"indirizzo email",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:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input non valido: atteso ${r.expected}, ricevuto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input non valido: atteso ${ue(r.values[0])}`:`Opzione non valida: atteso uno tra ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Troppo grande: ${r.origin??"valore"} deve avere ${o}${r.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Troppo piccolo: ${r.origin} deve avere ${o}${r.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${r.origin} deve essere ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${r.divisor}`;case"unrecognized_keys":return`Chiav${r.keys.length>1?"i":"e"} non riconosciut${r.keys.length>1?"e":"a"}: ${q(r.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${r.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${r.origin}`;default:return"Input non valido"}}};function iL(){return{localeError:rL()}}const oL=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"数値";case"object":{if(Array.isArray(r))return"配列";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return r=>{switch(r.code){case"invalid_type":return`無効な入力: ${r.expected}が期待されましたが、${n(r.input)}が入力されました`;case"invalid_value":return r.values.length===1?`無効な入力: ${ue(r.values[0])}が期待されました`:`無効な選択: ${q(r.values,"、")}のいずれかである必要があります`;case"too_big":{const o=r.inclusive?"以下である":"より小さい",s=t(r.origin);return s?`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${s.unit??"要素"}${o}必要があります`:`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${o}必要があります`}case"too_small":{const o=r.inclusive?"以上である":"より大きい",s=t(r.origin);return s?`小さすぎる値: ${r.origin}は${r.minimum.toString()}${s.unit}${o}必要があります`:`小さすぎる値: ${r.origin}は${r.minimum.toString()}${o}必要があります`}case"invalid_format":{const o=r;return o.format==="starts_with"?`無効な文字列: "${o.prefix}"で始まる必要があります`:o.format==="ends_with"?`無効な文字列: "${o.suffix}"で終わる必要があります`:o.format==="includes"?`無効な文字列: "${o.includes}"を含む必要があります`:o.format==="regex"?`無効な文字列: パターン${o.pattern}に一致する必要があります`:`無効な${i[o.format]??r.format}`}case"not_multiple_of":return`無効な数値: ${r.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${r.keys.length>1?"群":""}: ${q(r.keys,"、")}`;case"invalid_key":return`${r.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${r.origin}内の無効な値`;default:return"無効な入力"}}};function sL(){return{localeError:oL()}}const aL=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"რიცხვი";case"object":{if(Array.isArray(e))return"მასივი";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return{string:"სტრინგი",boolean:"ბულეანი",undefined:"undefined",bigint:"bigint",symbol:"symbol",function:"ფუნქცია"}[t]??t},uL=()=>{const e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function t(i){return e[i]??null}const n={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"};return i=>{switch(i.code){case"invalid_type":return`არასწორი შეყვანა: მოსალოდნელი ${i.expected}, მიღებული ${aL(i.input)}`;case"invalid_value":return i.values.length===1?`არასწორი შეყვანა: მოსალოდნელი ${ue(i.values[0])}`:`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${q(i.values,"|")}-დან`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`ზედმეტად დიდი: მოსალოდნელი ${i.origin??"მნიშვნელობა"} ${o.verb} ${r}${i.maximum.toString()} ${o.unit}`:`ზედმეტად დიდი: მოსალოდნელი ${i.origin??"მნიშვნელობა"} იყოს ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`ზედმეტად პატარა: მოსალოდნელი ${i.origin} ${o.verb} ${r}${i.minimum.toString()} ${o.unit}`:`ზედმეტად პატარა: მოსალოდნელი ${i.origin} იყოს ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`არასწორი სტრინგი: უნდა იწყებოდეს "${r.prefix}"-ით`:r.format==="ends_with"?`არასწორი სტრინგი: უნდა მთავრდებოდეს "${r.suffix}"-ით`:r.format==="includes"?`არასწორი სტრინგი: უნდა შეიცავდეს "${r.includes}"-ს`:r.format==="regex"?`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${r.pattern}`:`არასწორი ${n[r.format]??i.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${i.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${i.keys.length>1?"ები":"ი"}: ${q(i.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${i.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${i.origin}-ში`;default:return"არასწორი შეყვანა"}}};function lL(){return{localeError:uL()}}const cL=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":{if(Array.isArray(r))return"អារេ (Array)";if(r===null)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return r=>{switch(r.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${r.expected} ប៉ុន្តែទទួលបាន ${n(r.input)}`;case"invalid_value":return r.values.length===1?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${ue(r.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()} ${s.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`តូចពេក៖ ត្រូវការ ${r.origin} ${o} ${r.minimum.toString()} ${s.unit}`:`តូចពេក៖ ត្រូវការ ${r.origin} ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${o.prefix}"`:o.format==="ends_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${o.suffix}"`:o.format==="includes"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${o.includes}"`:o.format==="regex"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${o.pattern}`:`មិនត្រឹមត្រូវ៖ ${i[o.format]??r.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${r.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${q(r.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${r.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${r.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function MT(){return{localeError:cL()}}function dL(){return MT()}const fL=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return r=>{switch(r.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${r.expected}, 받은 타입은 ${n(r.input)}입니다`;case"invalid_value":return r.values.length===1?`잘못된 입력: 값은 ${ue(r.values[0])} 이어야 합니다`:`잘못된 옵션: ${q(r.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const o=r.inclusive?"이하":"미만",s=o==="미만"?"이어야 합니다":"여야 합니다",a=t(r.origin),l=a?.unit??"요소";return a?`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()}${l} ${o}${s}`:`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()} ${o}${s}`}case"too_small":{const o=r.inclusive?"이상":"초과",s=o==="이상"?"이어야 합니다":"여야 합니다",a=t(r.origin),l=a?.unit??"요소";return a?`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()}${l} ${o}${s}`:`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()} ${o}${s}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`잘못된 문자열: "${o.prefix}"(으)로 시작해야 합니다`:o.format==="ends_with"?`잘못된 문자열: "${o.suffix}"(으)로 끝나야 합니다`:o.format==="includes"?`잘못된 문자열: "${o.includes}"을(를) 포함해야 합니다`:o.format==="regex"?`잘못된 문자열: 정규식 ${o.pattern} 패턴과 일치해야 합니다`:`잘못된 ${i[o.format]??r.format}`}case"not_multiple_of":return`잘못된 숫자: ${r.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${q(r.keys,", ")}`;case"invalid_key":return`잘못된 키: ${r.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${r.origin}`;default:return"잘못된 입력"}}};function pL(){return{localeError:fL()}}const hL=e=>Cs(typeof e,e),Cs=(e,t=void 0)=>{switch(e){case"number":return Number.isNaN(t)?"NaN":"skaičius";case"bigint":return"sveikasis skaičius";case"string":return"eilutė";case"boolean":return"loginė reikšmė";case"undefined":case"void":return"neapibrėžta reikšmė";case"function":return"funkcija";case"symbol":return"simbolis";case"object":return t===void 0?"nežinomas objektas":t===null?"nulinė reikšmė":Array.isArray(t)?"masyvas":Object.getPrototypeOf(t)!==Object.prototype&&t.constructor?t.constructor.name:"objektas";case"null":return"nulinė reikšmė"}return e},hs=e=>e.charAt(0).toUpperCase()+e.slice(1);function cb(e){const t=Math.abs(e),n=t%10,i=t%100;return i>=11&&i<=19||n===0?"many":n===1?"one":"few"}const mL=()=>{const e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(i,r,o,s){const a=e[i]??null;return a===null?a:{unit:a.unit[r],verb:a.verb[s][o?"inclusive":"notInclusive"]}}const n={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"};return i=>{switch(i.code){case"invalid_type":return`Gautas tipas ${hL(i.input)}, o tikėtasi - ${Cs(i.expected)}`;case"invalid_value":return i.values.length===1?`Privalo būti ${ue(i.values[0])}`:`Privalo būti vienas iš ${q(i.values,"|")} pasirinkimų`;case"too_big":{const r=Cs(i.origin),o=t(i.origin,cb(Number(i.maximum)),i.inclusive??!1,"smaller");if(o?.verb)return`${hs(r??i.origin??"reikšmė")} ${o.verb} ${i.maximum.toString()} ${o.unit??"elementų"}`;const s=i.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${hs(r??i.origin??"reikšmė")} turi būti ${s} ${i.maximum.toString()} ${o?.unit}`}case"too_small":{const r=Cs(i.origin),o=t(i.origin,cb(Number(i.minimum)),i.inclusive??!1,"bigger");if(o?.verb)return`${hs(r??i.origin??"reikšmė")} ${o.verb} ${i.minimum.toString()} ${o.unit??"elementų"}`;const s=i.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${hs(r??i.origin??"reikšmė")} turi būti ${s} ${i.minimum.toString()} ${o?.unit}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Eilutė privalo prasidėti "${r.prefix}"`:r.format==="ends_with"?`Eilutė privalo pasibaigti "${r.suffix}"`:r.format==="includes"?`Eilutė privalo įtraukti "${r.includes}"`:r.format==="regex"?`Eilutė privalo atitikti ${r.pattern}`:`Neteisingas ${n[r.format]??i.format}`}case"not_multiple_of":return`Skaičius privalo būti ${i.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${i.keys.length>1?"i":"as"} rakt${i.keys.length>1?"ai":"as"}: ${q(i.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{const r=Cs(i.origin);return`${hs(r??i.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function gL(){return{localeError:mL()}}const vL=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"број";case"object":{if(Array.isArray(r))return"низа";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return r=>{switch(r.code){case"invalid_type":return`Грешен внес: се очекува ${r.expected}, примено ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${ue(r.values[0])}`:`Грешана опција: се очекува една ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Премногу голем: се очекува ${r.origin??"вредноста"} да има ${o}${r.maximum.toString()} ${s.unit??"елементи"}`:`Премногу голем: се очекува ${r.origin??"вредноста"} да биде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Премногу мал: се очекува ${r.origin} да има ${o}${r.minimum.toString()} ${s.unit}`:`Премногу мал: се очекува ${r.origin} да биде ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неважечка низа: мора да започнува со "${o.prefix}"`:o.format==="ends_with"?`Неважечка низа: мора да завршува со "${o.suffix}"`:o.format==="includes"?`Неважечка низа: мора да вклучува "${o.includes}"`:o.format==="regex"?`Неважечка низа: мора да одгоара на патернот ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${q(r.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${r.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${r.origin}`;default:return"Грешен внес"}}};function yL(){return{localeError:vL()}}const bL=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombor";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat e-mel",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:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak sah: dijangka ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak sah: dijangka ${ue(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Terlalu besar: dijangka ${r.origin??"nilai"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Terlalu kecil: dijangka ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${r.origin} adalah ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${i[o.format]??r.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${q(r.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${r.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${r.origin}`;default:return"Input tidak sah"}}};function _L(){return{localeError:bL()}}const wL=()=>{const e={string:{unit:"tekens",verb:"te hebben"},file:{unit:"bytes",verb:"te hebben"},array:{unit:"elementen",verb:"te hebben"},set:{unit:"elementen",verb:"te hebben"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"getal";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"invoer",email:"emailadres",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 datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return r=>{switch(r.code){case"invalid_type":return`Ongeldige invoer: verwacht ${r.expected}, ontving ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ongeldige invoer: verwacht ${ue(r.values[0])}`:`Ongeldige optie: verwacht één van ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Te groot: verwacht dat ${r.origin??"waarde"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"elementen"}`:`Te groot: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} is`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Te klein: verwacht dat ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Te klein: verwacht dat ${r.origin} ${o}${r.minimum.toString()} is`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${r.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${r.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${r.origin}`;default:return"Ongeldige invoer"}}};function xL(){return{localeError:wL()}}const SL=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"tall";case"object":{if(Array.isArray(r))return"liste";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"e-postadresse",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 dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Ugyldig input: forventet ${r.expected}, fikk ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ugyldig verdi: forventet ${ue(r.values[0])}`:`Ugyldig valg: forventet en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`For lite(n): forventet ${r.origin} til å ha ${o}${r.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${r.origin} til å ha ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ugyldig streng: må starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: må ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: må inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: må matche mønsteret ${o.pattern}`:`Ugyldig ${i[o.format]??r.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${r.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${r.origin}`;default:return"Ugyldig input"}}};function EL(){return{localeError:SL()}}const IL=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numara";case"object":{if(Array.isArray(r))return"saf";if(r===null)return"gayb";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"giren",email:"epostagâh",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 hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return r=>{switch(r.code){case"invalid_type":return`Fâsit giren: umulan ${r.expected}, alınan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Fâsit giren: umulan ${ue(r.values[0])}`:`Fâsit tercih: mûteberler ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Fazla büyük: ${r.origin??"value"}, ${o}${r.maximum.toString()} ${s.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${r.origin??"value"}, ${o}${r.maximum.toString()} olmalıydı.`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Fazla küçük: ${r.origin}, ${o}${r.minimum.toString()} ${s.unit} sahip olmalıydı.`:`Fazla küçük: ${r.origin}, ${o}${r.minimum.toString()} olmalıydı.`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Fâsit metin: "${o.prefix}" ile başlamalı.`:o.format==="ends_with"?`Fâsit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`Fâsit metin: "${o.includes}" ihtivâ etmeli.`:o.format==="regex"?`Fâsit metin: ${o.pattern} nakşına uymalı.`:`Fâsit ${i[o.format]??r.format}`}case"not_multiple_of":return`Fâsit sayı: ${r.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${r.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function TL(){return{localeError:IL()}}const kL=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"عدد";case"object":{if(Array.isArray(r))return"ارې";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return r=>{switch(r.code){case"invalid_type":return`ناسم ورودي: باید ${r.expected} وای, مګر ${n(r.input)} ترلاسه شو`;case"invalid_value":return r.values.length===1?`ناسم ورودي: باید ${ue(r.values[0])} وای`:`ناسم انتخاب: باید یو له ${q(r.values,"|")} څخه وای`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} ${s.unit??"عنصرونه"} ولري`:`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} وي`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`ډیر کوچنی: ${r.origin} باید ${o}${r.minimum.toString()} ${s.unit} ولري`:`ډیر کوچنی: ${r.origin} باید ${o}${r.minimum.toString()} وي`}case"invalid_format":{const o=r;return o.format==="starts_with"?`ناسم متن: باید د "${o.prefix}" سره پیل شي`:o.format==="ends_with"?`ناسم متن: باید د "${o.suffix}" سره پای ته ورسيږي`:o.format==="includes"?`ناسم متن: باید "${o.includes}" ولري`:o.format==="regex"?`ناسم متن: باید د ${o.pattern} سره مطابقت ولري`:`${i[o.format]??r.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${r.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${r.keys.length>1?"کلیډونه":"کلیډ"}: ${q(r.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${r.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${r.origin} کې`;default:return"ناسمه ورودي"}}};function CL(){return{localeError:kL()}}const AL=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"liczba";case"object":{if(Array.isArray(r))return"tablica";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"wyrażenie",email:"adres email",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:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return r=>{switch(r.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${r.expected}, otrzymano ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Nieprawidłowe dane wejściowe: oczekiwano ${ue(r.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Za duża wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.maximum.toString()} ${s.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${r.origin??"wartość"} będzie wynosić ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Za mała wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.minimum.toString()} ${s.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${r.origin??"wartość"} będzie wynosić ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${o.prefix}"`:o.format==="ends_with"?`Nieprawidłowy ciąg znaków: musi kończyć się na "${o.suffix}"`:o.format==="includes"?`Nieprawidłowy ciąg znaków: musi zawierać "${o.includes}"`:o.format==="regex"?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${o.pattern}`:`Nieprawidłow(y/a/e) ${i[o.format]??r.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${r.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${r.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${r.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function RL(){return{localeError:AL()}}const $L=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"número";case"object":{if(Array.isArray(r))return"array";if(r===null)return"nulo";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"padrão",email:"endereço de e-mail",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:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipo inválido: esperado ${r.expected}, recebido ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrada inválida: esperado ${ue(r.values[0])}`:`Opção inválida: esperada uma das ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${o}${r.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Muito pequeno: esperado que ${r.origin} tivesse ${o}${r.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${r.origin} fosse ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Texto inválido: deve começar com "${o.prefix}"`:o.format==="ends_with"?`Texto inválido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inválido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inválido: deve corresponder ao padrão ${o.pattern}`:`${i[o.format]??r.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${r.divisor}`;case"unrecognized_keys":return`Chave${r.keys.length>1?"s":""} desconhecida${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Chave inválida em ${r.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${r.origin}`;default:return"Campo inválido"}}};function OL(){return{localeError:$L()}}function db(e,t,n,i){const r=Math.abs(e),o=r%10,s=r%100;return s>=11&&s<=19?i:o===1?t:o>=2&&o<=4?n:i}const NL=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"число";case"object":{if(Array.isArray(r))return"массив";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return r=>{switch(r.code){case"invalid_type":return`Неверный ввод: ожидалось ${r.expected}, получено ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Неверный ввод: ожидалось ${ue(r.values[0])}`:`Неверный вариант: ожидалось одно из ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);if(s){const a=Number(r.maximum),l=db(a,s.unit.one,s.unit.few,s.unit.many);return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет иметь ${o}${r.maximum.toString()} ${l}`}return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);if(s){const a=Number(r.minimum),l=db(a,s.unit.one,s.unit.few,s.unit.many);return`Слишком маленькое значение: ожидалось, что ${r.origin} будет иметь ${o}${r.minimum.toString()} ${l}`}return`Слишком маленькое значение: ожидалось, что ${r.origin} будет ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неверная строка: должна начинаться с "${o.prefix}"`:o.format==="ends_with"?`Неверная строка: должна заканчиваться на "${o.suffix}"`:o.format==="includes"?`Неверная строка: должна содержать "${o.includes}"`:o.format==="regex"?`Неверная строка: должна соответствовать шаблону ${o.pattern}`:`Неверный ${i[o.format]??r.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${r.divisor}`;case"unrecognized_keys":return`Нераспознанн${r.keys.length>1?"ые":"ый"} ключ${r.keys.length>1?"и":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${r.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${r.origin}`;default:return"Неверные входные данные"}}};function PL(){return{localeError:NL()}}const ML=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"število";case"object":{if(Array.isArray(r))return"tabela";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"vnos",email:"e-poštni naslov",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 datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return r=>{switch(r.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${r.expected}, prejeto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neveljaven vnos: pričakovano ${ue(r.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} imelo ${o}${r.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Premajhno: pričakovano, da bo ${r.origin} imelo ${o}${r.minimum.toString()} ${s.unit}`:`Premajhno: pričakovano, da bo ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Neveljaven niz: mora se začeti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se končati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${i[o.format]??r.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${r.divisor}`;case"unrecognized_keys":return`Neprepoznan${r.keys.length>1?"i ključi":" ključ"}: ${q(r.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${r.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${r.origin}`;default:return"Neveljaven vnos"}}};function jL(){return{localeError:ML()}}const DL=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"antal";case"object":{if(Array.isArray(r))return"lista";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"reguljärt uttryck",email:"e-postadress",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-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return r=>{switch(r.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${r.expected}, fick ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ogiltig inmatning: förväntat ${ue(r.values[0])}`:`Ogiltigt val: förväntade en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`För stor(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.maximum.toString()} ${s.unit??"element"}`:`För stor(t): förväntat ${r.origin??"värdet"} att ha ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`För lite(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.minimum.toString()} ${s.unit}`:`För lite(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ogiltig sträng: måste börja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig sträng: måste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig sträng: måste innehålla "${o.includes}"`:o.format==="regex"?`Ogiltig sträng: måste matcha mönstret "${o.pattern}"`:`Ogiltig(t) ${i[o.format]??r.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${r.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${r.origin??"värdet"}`;default:return"Ogiltig input"}}};function zL(){return{localeError:DL()}}const LL=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"எண் அல்லாதது":"எண்";case"object":{if(Array.isArray(r))return"அணி";if(r===null)return"வெறுமை";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",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 தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${r.expected}, பெறப்பட்டது ${n(r.input)}`;case"invalid_value":return r.values.length===1?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${ue(r.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${q(r.values,"|")} இல் ஒன்று`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ${s.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${r.origin} ${o}${r.minimum.toString()} ${s.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${r.origin} ${o}${r.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const o=r;return o.format==="starts_with"?`தவறான சரம்: "${o.prefix}" இல் தொடங்க வேண்டும்`:o.format==="ends_with"?`தவறான சரம்: "${o.suffix}" இல் முடிவடைய வேண்டும்`:o.format==="includes"?`தவறான சரம்: "${o.includes}" ஐ உள்ளடக்க வேண்டும்`:o.format==="regex"?`தவறான சரம்: ${o.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${i[o.format]??r.format}`}case"not_multiple_of":return`தவறான எண்: ${r.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${r.keys.length>1?"கள்":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${r.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function UL(){return{localeError:LL()}}const FL=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":{if(Array.isArray(r))return"อาร์เรย์ (Array)";if(r===null)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return r=>{switch(r.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${r.expected} แต่ได้รับ ${n(r.input)}`;case"invalid_value":return r.values.length===1?`ค่าไม่ถูกต้อง: ควรเป็น ${ue(r.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"ไม่เกิน":"น้อยกว่า",s=t(r.origin);return s?`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()} ${s.unit??"รายการ"}`:`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"อย่างน้อย":"มากกว่า",s=t(r.origin);return s?`น้อยกว่ากำหนด: ${r.origin} ควรมี${o} ${r.minimum.toString()} ${s.unit}`:`น้อยกว่ากำหนด: ${r.origin} ควรมี${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${o.prefix}"`:o.format==="ends_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${o.suffix}"`:o.format==="includes"?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${o.includes}" อยู่ในข้อความ`:o.format==="regex"?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${o.pattern}`:`รูปแบบไม่ถูกต้อง: ${i[o.format]??r.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${r.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${q(r.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${r.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${r.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function BL(){return{localeError:FL()}}const VL=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},qL=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(i){return e[i]??null}const n={regex:"girdi",email:"e-posta adresi",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 tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return i=>{switch(i.code){case"invalid_type":return`Geçersiz değer: beklenen ${i.expected}, alınan ${VL(i.input)}`;case"invalid_value":return i.values.length===1?`Geçersiz değer: beklenen ${ue(i.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Çok büyük: beklenen ${i.origin??"değer"} ${r}${i.maximum.toString()} ${o.unit??"öğe"}`:`Çok büyük: beklenen ${i.origin??"değer"} ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Çok küçük: beklenen ${i.origin} ${r}${i.minimum.toString()} ${o.unit}`:`Çok küçük: beklenen ${i.origin} ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Geçersiz metin: "${r.prefix}" ile başlamalı`:r.format==="ends_with"?`Geçersiz metin: "${r.suffix}" ile bitmeli`:r.format==="includes"?`Geçersiz metin: "${r.includes}" içermeli`:r.format==="regex"?`Geçersiz metin: ${r.pattern} desenine uymalı`:`Geçersiz ${n[r.format]??i.format}`}case"not_multiple_of":return`Geçersiz sayı: ${i.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${i.keys.length>1?"lar":""}: ${q(i.keys,", ")}`;case"invalid_key":return`${i.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${i.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function ZL(){return{localeError:qL()}}const HL=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"число";case"object":{if(Array.isArray(r))return"масив";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return r=>{switch(r.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${r.expected}, отримано ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Неправильні вхідні дані: очікується ${ue(r.values[0])}`:`Неправильна опція: очікується одне з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Занадто велике: очікується, що ${r.origin??"значення"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"елементів"}`:`Занадто велике: очікується, що ${r.origin??"значення"} буде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Занадто мале: очікується, що ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Занадто мале: очікується, що ${r.origin} буде ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неправильний рядок: повинен починатися з "${o.prefix}"`:o.format==="ends_with"?`Неправильний рядок: повинен закінчуватися на "${o.suffix}"`:o.format==="includes"?`Неправильний рядок: повинен містити "${o.includes}"`:o.format==="regex"?`Неправильний рядок: повинен відповідати шаблону ${o.pattern}`:`Неправильний ${i[o.format]??r.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${r.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${r.keys.length>1?"і":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${r.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${r.origin}`;default:return"Неправильні вхідні дані"}}};function jT(){return{localeError:HL()}}function GL(){return jT()}const WL=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"نمبر";case"object":{if(Array.isArray(r))return"آرے";if(r===null)return"نل";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return r=>{switch(r.code){case"invalid_type":return`غلط ان پٹ: ${r.expected} متوقع تھا، ${n(r.input)} موصول ہوا`;case"invalid_value":return r.values.length===1?`غلط ان پٹ: ${ue(r.values[0])} متوقع تھا`:`غلط آپشن: ${q(r.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`بہت بڑا: ${r.origin??"ویلیو"} کے ${o}${r.maximum.toString()} ${s.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${r.origin??"ویلیو"} کا ${o}${r.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`بہت چھوٹا: ${r.origin} کے ${o}${r.minimum.toString()} ${s.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${r.origin} کا ${o}${r.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const o=r;return o.format==="starts_with"?`غلط سٹرنگ: "${o.prefix}" سے شروع ہونا چاہیے`:o.format==="ends_with"?`غلط سٹرنگ: "${o.suffix}" پر ختم ہونا چاہیے`:o.format==="includes"?`غلط سٹرنگ: "${o.includes}" شامل ہونا چاہیے`:o.format==="regex"?`غلط سٹرنگ: پیٹرن ${o.pattern} سے میچ ہونا چاہیے`:`غلط ${i[o.format]??r.format}`}case"not_multiple_of":return`غلط نمبر: ${r.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${r.keys.length>1?"ز":""}: ${q(r.keys,"، ")}`;case"invalid_key":return`${r.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${r.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function JL(){return{localeError:WL()}}const KL=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"số";case"object":{if(Array.isArray(r))return"mảng";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"đầu vào",email:"địa chỉ email",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:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return r=>{switch(r.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${r.expected}, nhận được ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Đầu vào không hợp lệ: mong đợi ${ue(r.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Quá lớn: mong đợi ${r.origin??"giá trị"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"phần tử"}`:`Quá lớn: mong đợi ${r.origin??"giá trị"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Quá nhỏ: mong đợi ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Quá nhỏ: mong đợi ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chuỗi không hợp lệ: phải bắt đầu bằng "${o.prefix}"`:o.format==="ends_with"?`Chuỗi không hợp lệ: phải kết thúc bằng "${o.suffix}"`:o.format==="includes"?`Chuỗi không hợp lệ: phải bao gồm "${o.includes}"`:o.format==="regex"?`Chuỗi không hợp lệ: phải khớp với mẫu ${o.pattern}`:`${i[o.format]??r.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${r.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${q(r.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${r.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${r.origin}`;default:return"Đầu vào không hợp lệ"}}};function YL(){return{localeError:KL()}}const XL=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"非数字(NaN)":"数字";case"object":{if(Array.isArray(r))return"数组";if(r===null)return"空值(null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return r=>{switch(r.code){case"invalid_type":return`无效输入:期望 ${r.expected},实际接收 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`无效输入:期望 ${ue(r.values[0])}`:`无效选项:期望以下之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()} ${s.unit??"个元素"}`:`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`数值过小:期望 ${r.origin} ${o}${r.minimum.toString()} ${s.unit}`:`数值过小:期望 ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`无效字符串:必须以 "${o.prefix}" 开头`:o.format==="ends_with"?`无效字符串:必须以 "${o.suffix}" 结尾`:o.format==="includes"?`无效字符串:必须包含 "${o.includes}"`:o.format==="regex"?`无效字符串:必须满足正则表达式 ${o.pattern}`:`无效${i[o.format]??r.format}`}case"not_multiple_of":return`无效数字:必须是 ${r.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${r.origin} 中包含无效值(value)`;default:return"无效输入"}}};function QL(){return{localeError:XL()}}const eU=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"輸入",email:"郵件地址",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 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return r=>{switch(r.code){case"invalid_type":return`無效的輸入值:預期為 ${r.expected},但收到 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`無效的輸入值:預期為 ${ue(r.values[0])}`:`無效的選項:預期為以下其中之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()} ${s.unit??"個元素"}`:`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`數值過小:預期 ${r.origin} 應為 ${o}${r.minimum.toString()} ${s.unit}`:`數值過小:預期 ${r.origin} 應為 ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`無效的字串:必須以 "${o.prefix}" 開頭`:o.format==="ends_with"?`無效的字串:必須以 "${o.suffix}" 結尾`:o.format==="includes"?`無效的字串:必須包含 "${o.includes}"`:o.format==="regex"?`無效的字串:必須符合格式 ${o.pattern}`:`無效的 ${i[o.format]??r.format}`}case"not_multiple_of":return`無效的數字:必須為 ${r.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${r.keys.length>1?"們":""}:${q(r.keys,"、")}`;case"invalid_key":return`${r.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${r.origin} 中有無效的值`;default:return"無效的輸入值"}}};function tU(){return{localeError:eU()}}const nU=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nọ́mbà";case"object":{if(Array.isArray(r))return"akopọ";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",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:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return r=>{switch(r.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${r.expected}, àmọ̀ a rí ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ìbáwọlé aṣìṣe: a ní láti fi ${ue(r.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",s=t(r.origin);return s?`Tó pọ̀ jù: a ní láti jẹ́ pé ${r.origin??"iye"} ${s.verb} ${o}${r.maximum} ${s.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${o}${r.maximum}`}case"too_small":{const o=r.inclusive?">=":">",s=t(r.origin);return s?`Kéré ju: a ní láti jẹ́ pé ${r.origin} ${s.verb} ${o}${r.minimum} ${s.unit}`:`Kéré ju: a ní láti jẹ́ ${o}${r.minimum}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${o.prefix}"`:o.format==="ends_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${o.suffix}"`:o.format==="includes"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${o.includes}"`:o.format==="regex"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${o.pattern}`:`Aṣìṣe: ${i[o.format]??r.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${r.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${q(r.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${r.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${r.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function rU(){return{localeError:nU()}}const DT=Object.freeze(Object.defineProperty({__proto__:null,ar:vz,az:bz,be:wz,bg:Ez,ca:Tz,cs:Cz,da:Rz,de:Oz,en:PT,eo:Dz,es:Lz,fa:Fz,fi:Vz,fr:Zz,frCA:Gz,he:Jz,hu:Yz,id:Qz,is:nL,it:iL,ja:sL,ka:lL,kh:dL,km:MT,ko:pL,lt:gL,mk:yL,ms:_L,nl:xL,no:EL,ota:TL,pl:RL,ps:CL,pt:OL,ru:PL,sl:jL,sv:zL,ta:UL,th:BL,tr:ZL,ua:GL,uk:jT,ur:JL,vi:YL,yo:rU,zhCN:QL,zhTW:tU},Symbol.toStringTag,{value:"Module"}));var fb;const zT=Symbol("ZodOutput"),LT=Symbol("ZodInput");class UT{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];if(this._map.set(t,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return 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 i={...this.get(n)??{}};delete i.id;const r={...i,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Em(){return new UT}(fb=globalThis).__zod_globalRegistry??(fb.__zod_globalRegistry=Em());const On=globalThis.__zod_globalRegistry;function FT(e,t){return new e({type:"string",...D(t)})}function BT(e,t){return new e({type:"string",coerce:!0,...D(t)})}function Im(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...D(t)})}function Nl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...D(t)})}function Tm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...D(t)})}function km(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(t)})}function Cm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(t)})}function Am(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(t)})}function Ac(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...D(t)})}function Rm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...D(t)})}function $m(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(t)})}function Om(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...D(t)})}function Nm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(t)})}function Pm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...D(t)})}function Mm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...D(t)})}function jm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(t)})}function Dm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(t)})}function zm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(t)})}function VT(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...D(t)})}function Lm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(t)})}function Um(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(t)})}function Fm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...D(t)})}function Bm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...D(t)})}function Vm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...D(t)})}function qm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...D(t)})}const qT={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ZT(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(t)})}function HT(e,t){return new e({type:"string",format:"date",check:"string_format",...D(t)})}function GT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...D(t)})}function WT(e,t){return new e({type:"string",format:"duration",check:"string_format",...D(t)})}function JT(e,t){return new e({type:"number",checks:[],...D(t)})}function KT(e,t){return new e({type:"number",coerce:!0,checks:[],...D(t)})}function YT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...D(t)})}function XT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...D(t)})}function QT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...D(t)})}function e0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...D(t)})}function t0(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...D(t)})}function n0(e,t){return new e({type:"boolean",...D(t)})}function r0(e,t){return new e({type:"boolean",coerce:!0,...D(t)})}function i0(e,t){return new e({type:"bigint",...D(t)})}function o0(e,t){return new e({type:"bigint",coerce:!0,...D(t)})}function s0(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...D(t)})}function a0(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...D(t)})}function u0(e,t){return new e({type:"symbol",...D(t)})}function l0(e,t){return new e({type:"undefined",...D(t)})}function c0(e,t){return new e({type:"null",...D(t)})}function d0(e){return new e({type:"any"})}function f0(e){return new e({type:"unknown"})}function p0(e,t){return new e({type:"never",...D(t)})}function h0(e,t){return new e({type:"void",...D(t)})}function m0(e,t){return new e({type:"date",...D(t)})}function g0(e,t){return new e({type:"date",coerce:!0,...D(t)})}function v0(e,t){return new e({type:"nan",...D(t)})}function Hr(e,t){return new gm({check:"less_than",...D(t),value:e,inclusive:!1})}function _n(e,t){return new gm({check:"less_than",...D(t),value:e,inclusive:!0})}function Gr(e,t){return new vm({check:"greater_than",...D(t),value:e,inclusive:!1})}function Vt(e,t){return new vm({check:"greater_than",...D(t),value:e,inclusive:!0})}function Zm(e){return Gr(0,e)}function Hm(e){return Hr(0,e)}function Gm(e){return _n(0,e)}function Wm(e){return Vt(0,e)}function Oo(e,t){return new tI({check:"multiple_of",...D(t),value:e})}function za(e,t){return new iI({check:"max_size",...D(t),maximum:e})}function No(e,t){return new oI({check:"min_size",...D(t),minimum:e})}function Rc(e,t){return new sI({check:"size_equals",...D(t),size:e})}function La(e,t){return new aI({check:"max_length",...D(t),maximum:e})}function Ai(e,t){return new uI({check:"min_length",...D(t),minimum:e})}function Ua(e,t){return new lI({check:"length_equals",...D(t),length:e})}function $c(e,t){return new cI({check:"string_format",format:"regex",...D(t),pattern:e})}function Oc(e){return new dI({check:"string_format",format:"lowercase",...D(e)})}function Nc(e){return new fI({check:"string_format",format:"uppercase",...D(e)})}function Pc(e,t){return new pI({check:"string_format",format:"includes",...D(t),includes:e})}function Mc(e,t){return new hI({check:"string_format",format:"starts_with",...D(t),prefix:e})}function jc(e,t){return new mI({check:"string_format",format:"ends_with",...D(t),suffix:e})}function Jm(e,t,n){return new gI({check:"property",property:e,schema:t,...D(n)})}function Dc(e,t){return new vI({check:"mime_type",mime:e,...D(t)})}function Ar(e){return new yI({check:"overwrite",tx:e})}function zc(e){return Ar(t=>t.normalize(e))}function Lc(){return Ar(e=>e.trim())}function Uc(){return Ar(e=>e.toLowerCase())}function Fc(){return Ar(e=>e.toUpperCase())}function Bc(){return Ar(e=>YS(e))}function y0(e,t,n){return new e({type:"array",element:t,...D(n)})}function iU(e,t,n){return new e({type:"union",options:t,...D(n)})}function oU(e,t,n){return new e({type:"union",options:t,inclusive:!1,...D(n)})}function sU(e,t,n,i){return new e({type:"union",options:n,discriminator:t,...D(i)})}function aU(e,t,n){return new e({type:"intersection",left:t,right:n})}function uU(e,t,n,i){const r=n instanceof pe,o=r?i:n,s=r?n:null;return new e({type:"tuple",items:t,rest:s,...D(o)})}function lU(e,t,n,i){return new e({type:"record",keyType:t,valueType:n,...D(i)})}function cU(e,t,n,i){return new e({type:"map",keyType:t,valueType:n,...D(i)})}function dU(e,t,n){return new e({type:"set",valueType:t,...D(n)})}function fU(e,t,n){const i=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new e({type:"enum",entries:i,...D(n)})}function pU(e,t,n){return new e({type:"enum",entries:t,...D(n)})}function hU(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...D(n)})}function b0(e,t){return new e({type:"file",...D(t)})}function mU(e,t){return new e({type:"transform",transform:t})}function gU(e,t){return new e({type:"optional",innerType:t})}function vU(e,t){return new e({type:"nullable",innerType:t})}function yU(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Ic(n)}})}function bU(e,t,n){return new e({type:"nonoptional",innerType:t,...D(n)})}function _U(e,t){return new e({type:"success",innerType:t})}function wU(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:()=>n})}function xU(e,t,n){return new e({type:"pipe",in:t,out:n})}function SU(e,t){return new e({type:"readonly",innerType:t})}function EU(e,t,n){return new e({type:"template_literal",parts:t,...D(n)})}function IU(e,t){return new e({type:"lazy",getter:t})}function TU(e,t){return new e({type:"promise",innerType:t})}function _0(e,t,n){const i=D(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function w0(e,t,n){return new e({type:"custom",check:"custom",fn:t,...D(n)})}function x0(e){const t=S0(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(Ro(i,n.value,t._zod.def));else{const r=i;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Ro(r))}},e(n.value,n)));return t}function S0(e,t){const n=new Ye({check:"custom",...D(t)});return n._zod.check=e,n}function E0(e){const t=new Ye({check:"describe"});return t._zod.onattach=[n=>{const i=On.get(n)??{};On.add(n,{...i,description:e})}],t._zod.check=()=>{},t}function I0(e){const t=new Ye({check:"meta"});return t._zod.onattach=[n=>{const i=On.get(n)??{};On.add(n,{...i,...e})}],t._zod.check=()=>{},t}function T0(e,t){const n=D(t);let i=n.truthy??["true","1","yes","on","y","enabled"],r=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),r=r.map(p=>typeof p=="string"?p.toLowerCase():p));const o=new Set(i),s=new Set(r),a=e.Codec??Sm,l=e.Boolean??_m,u=e.String??Da,c=new u({type:"string",error:n.error}),d=new l({type:"boolean",error:n.error}),f=new a({type:"pipe",in:c,out:d,transform:((p,m)=>{let h=p;return n.case!=="sensitive"&&(h=h.toLowerCase()),o.has(h)?!0:s.has(h)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:m.value,inst:f,continue:!1}),{})}),reverseTransform:((p,m)=>p===!0?i[0]||"true":r[0]||"false"),error:n.error});return f}function Fa(e,t,n,i={}){const r=D(i),o={...D(i),check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...r};return n instanceof RegExp&&(o.pattern=n),new e(o)}function Po(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??On,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ue(e,t,n={path:[],schemaPath:[]}){var i;const r=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);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const c={...n,schemaPath:[...n.schemaPath,e],path:n.path},d=e._zod.parent;if(d)s.ref=d,Ue(d,t,c),t.seen.get(d).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,c);else{const f=s.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,f,c)}}const l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),t.io==="input"&&Mt(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&s.schema._prefault&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Mo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=o=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const c=e.external.registry.get(o[0])?.id,d=e.external.uri??(p=>p);if(c)return{ref:d(c)};const f=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=f,{defId:f,ref:`${d("__shared")}#/${s}/${f}`}}if(o[1]===n)return{ref:"#"};const l=`#/${s}/`,u=o[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+u}},r=o=>{if(o[1].schema.$ref)return;const s=o[1],{ref:a,defId:l}=i(o);s.def={...s.schema},l&&(s.defId=l);const u=s.schema;for(const c in u)delete u[c];u.$ref=a};if(e.cycles==="throw")for(const o of e.seen.entries()){const s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
28
|
+
|
|
29
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){r(o);continue}if(e.external){const l=e.external.registry.get(o[0])?.id;if(t!==o[0]&&l){r(o);continue}}if(e.metadataRegistry.get(o[0])?.id){r(o);continue}if(s.cycle){r(o);continue}if(s.count>1&&e.reused==="ref"){r(o);continue}}}function jo(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=s=>{const a=e.seen.get(s),l=a.def??a.schema,u={...l};if(a.ref===null)return;const c=a.ref;if(a.ref=null,c){i(c);const d=e.seen.get(c).schema;d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(d)):(Object.assign(l,d),Object.assign(l,u))}a.isParent||e.override({zodSchema:s,jsonSchema:l,path:a.path??[]})};for(const s of[...e.seen.entries()].reverse())i(s[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(s)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const s of e.seen.entries()){const a=s[1];a.def&&a.defId&&(o[a.defId]=a.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const s=JSON.parse(JSON.stringify(r));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ws(t,"input"),output:Ws(t,"output")}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Mt(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Mt(i.element,n);if(i.type==="set")return Mt(i.valueType,n);if(i.type==="lazy")return Mt(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Mt(i.innerType,n);if(i.type==="intersection")return Mt(i.left,n)||Mt(i.right,n);if(i.type==="record"||i.type==="map")return Mt(i.keyType,n)||Mt(i.valueType,n);if(i.type==="pipe")return Mt(i.in,n)||Mt(i.out,n);if(i.type==="object"){for(const r in i.shape)if(Mt(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(const r of i.options)if(Mt(r,n))return!0;return!1}if(i.type==="tuple"){for(const r of i.items)if(Mt(r,n))return!0;return!!(i.rest&&Mt(i.rest,n))}return!1}const k0=(e,t={})=>n=>{const i=Po({...n,processors:t});return Ue(e,i),Mo(i,e),jo(i,e)},Ws=(e,t)=>n=>{const{libraryOptions:i,target:r}=n??{},o=Po({...i??{},target:r,io:t,processors:{}});return Ue(e,o),Mo(o,e),jo(o,e)},kU={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},C0=(e,t,n,i)=>{const r=n;r.type="string";const{minimum:o,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof s=="number"&&(r.maxLength=s),a&&(r.format=kU[a]??a,r.format===""&&delete r.format),u&&(r.contentEncoding=u),l&&l.size>0){const c=[...l];c.length===1?r.pattern=c[0].source:c.length>1&&(r.allOf=[...c.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},A0=(e,t,n,i)=>{const r=n,{minimum:o,maximum:s,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:c}=e._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number",typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),typeof o=="number"&&(r.minimum=o,typeof c=="number"&&t.target!=="draft-04"&&(c>=o?delete r.minimum:delete r.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u),typeof s=="number"&&(r.maximum=s,typeof u=="number"&&t.target!=="draft-04"&&(u<=s?delete r.maximum:delete r.exclusiveMaximum)),typeof l=="number"&&(r.multipleOf=l)},R0=(e,t,n,i)=>{n.type="boolean"},$0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},O0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},N0=(e,t,n,i)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},P0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},M0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},j0=(e,t,n,i)=>{n.not={}},D0=(e,t,n,i)=>{},z0=(e,t,n,i)=>{},L0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},U0=(e,t,n,i)=>{const r=e._zod.def,o=tm(r.entries);o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),n.enum=o},F0=(e,t,n,i)=>{const r=e._zod.def,o=[];for(const s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");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},B0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},V0=(e,t,n,i)=>{const r=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},q0=(e,t,n,i)=>{const r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;s!==void 0&&(o.minLength=s),a!==void 0&&(o.maxLength=a),l?l.length===1?(o.contentMediaType=l[0],Object.assign(r,o)):r.anyOf=l.map(u=>({...o,contentMediaType:u})):Object.assign(r,o)},Z0=(e,t,n,i)=>{n.type="boolean"},H0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},G0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},W0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},J0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},K0=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Y0=(e,t,n,i)=>{const r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=Ue(o.element,t,{...i,path:[...i.path,"items"]})},X0=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const s=o.shape;for(const u in s)r.properties[u]=Ue(s[u],t,{...i,path:[...i.path,"properties",u]});const a=new Set(Object.keys(s)),l=new Set([...a].filter(u=>{const c=o.shape[u]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));l.size>0&&(r.required=Array.from(l)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=Ue(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Km=(e,t,n,i)=>{const r=e._zod.def,o=r.inclusive===!1,s=r.options.map((a,l)=>Ue(a,t,{...i,path:[...i.path,o?"oneOf":"anyOf",l]}));o?n.oneOf=s:n.anyOf=s},Q0=(e,t,n,i)=>{const r=e._zod.def,o=Ue(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=Ue(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,l=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=l},ek=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=o.items.map((f,p)=>Ue(f,t,{...i,path:[...i.path,s,p]})),u=o.rest?Ue(o.rest,t,{...i,path:[...i.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=l,u&&(r.items=u)):t.target==="openapi-3.0"?(r.items={anyOf:l},u&&r.items.anyOf.push(u),r.minItems=l.length,u||(r.maxItems=l.length)):(r.items=l,u&&(r.additionalItems=u));const{minimum:c,maximum:d}=e._zod.bag;typeof c=="number"&&(r.minItems=c),typeof d=="number"&&(r.maxItems=d)},tk=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=Ue(o.keyType,t,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=Ue(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})},nk=(e,t,n,i)=>{const r=e._zod.def,o=Ue(r.innerType,t,i),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},rk=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},ik=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},ok=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},sk=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ak=(e,t,n,i)=>{const r=e._zod.def,o=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;Ue(o,t,i);const s=t.seen.get(e);s.ref=o},uk=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},lk=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},ck=(e,t,n,i)=>{const r=e._zod.def;Ue(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},dk=(e,t,n,i)=>{const r=e._zod.innerType;Ue(r,t,i);const o=t.seen.get(e);o.ref=r},Bp={string:C0,number:A0,boolean:R0,bigint:$0,symbol:O0,null:N0,undefined:P0,void:M0,never:j0,any:D0,unknown:z0,date:L0,enum:U0,literal:F0,nan:B0,template_literal:V0,file:q0,success:Z0,custom:H0,function:G0,transform:W0,map:J0,set:K0,array:Y0,object:X0,union:Km,intersection:Q0,tuple:ek,record:tk,nullable:nk,nonoptional:rk,default:ik,prefault:ok,catch:sk,pipe:ak,readonly:uk,promise:lk,optional:ck,lazy:dk};function Vc(e,t){if("_idmap"in e){const i=e,r=Po({...t,processors:Bp}),o={};for(const l of i._idmap.entries()){const[u,c]=l;Ue(c,r)}const s={},a={registry:i,uri:t?.uri,defs:o};r.external=a;for(const l of i._idmap.entries()){const[u,c]=l;Mo(r,c),s[u]=jo(r,c)}if(Object.keys(o).length>0){const l=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:o}}return{schemas:s}}const n=Po({...t,processors:Bp});return Ue(e,n),Mo(n,e),jo(n,e)}class CU{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=Po({processors:Bp,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 Ue(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)),Mo(this.ctx,t);const i=jo(this.ctx,t),{"~standard":r,...o}=i;return o}}const AU=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),RU=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:QI,$ZodArray:iT,$ZodAsyncError:Ei,$ZodBase64:FI,$ZodBase64URL:VI,$ZodBigInt:wm,$ZodBigIntFormat:JI,$ZodBoolean:_m,$ZodCIDRv4:LI,$ZodCIDRv6:UI,$ZodCUID:kI,$ZodCUID2:CI,$ZodCatch:IT,$ZodCheck:Ye,$ZodCheckBigIntFormat:rI,$ZodCheckEndsWith:mI,$ZodCheckGreaterThan:vm,$ZodCheckIncludes:pI,$ZodCheckLengthEquals:lI,$ZodCheckLessThan:gm,$ZodCheckLowerCase:dI,$ZodCheckMaxLength:aI,$ZodCheckMaxSize:iI,$ZodCheckMimeType:vI,$ZodCheckMinLength:uI,$ZodCheckMinSize:oI,$ZodCheckMultipleOf:tI,$ZodCheckNumberFormat:nI,$ZodCheckOverwrite:yI,$ZodCheckProperty:gI,$ZodCheckRegex:cI,$ZodCheckSizeEquals:sI,$ZodCheckStartsWith:hI,$ZodCheckStringFormat:ja,$ZodCheckUpperCase:fI,$ZodCodec:Sm,$ZodCustom:NT,$ZodCustomStringFormat:GI,$ZodDate:rT,$ZodDefault:wT,$ZodDiscriminatedUnion:cT,$ZodE164:qI,$ZodEmail:SI,$ZodEmoji:II,$ZodEncodeError:Sc,$ZodEnum:mT,$ZodError:rm,$ZodFile:vT,$ZodFunction:RT,$ZodGUID:wI,$ZodIPv4:jI,$ZodIPv6:DI,$ZodISODate:NI,$ZodISODateTime:OI,$ZodISODuration:MI,$ZodISOTime:PI,$ZodIntersection:dT,$ZodJWT:HI,$ZodKSUID:$I,$ZodLazy:OT,$ZodLiteral:gT,$ZodMAC:zI,$ZodMap:pT,$ZodNaN:TT,$ZodNanoID:TI,$ZodNever:tT,$ZodNonOptional:ST,$ZodNull:XI,$ZodNullable:_T,$ZodNumber:bm,$ZodNumberFormat:WI,$ZodObject:aT,$ZodObjectJIT:uT,$ZodOptional:bT,$ZodPipe:kT,$ZodPrefault:xT,$ZodPromise:$T,$ZodReadonly:CT,$ZodRealError:cn,$ZodRecord:fT,$ZodRegistry:UT,$ZodSet:hT,$ZodString:Da,$ZodStringFormat:Fe,$ZodSuccess:ET,$ZodSymbol:KI,$ZodTemplateLiteral:AT,$ZodTransform:yT,$ZodTuple:xm,$ZodType:pe,$ZodULID:AI,$ZodURL:EI,$ZodUUID:xI,$ZodUndefined:YI,$ZodUnion:Cc,$ZodUnknown:eT,$ZodVoid:nT,$ZodXID:RI,$ZodXor:lT,$brand:JS,$constructor:$,$input:LT,$output:zT,Doc:bI,JSONSchema:AU,JSONSchemaGenerator:CU,NEVER:em,TimePrecision:qT,_any:d0,_array:y0,_base64:Fm,_base64url:Bm,_bigint:i0,_boolean:n0,_catch:wU,_check:S0,_cidrv4:Lm,_cidrv6:Um,_coercedBigint:o0,_coercedBoolean:r0,_coercedDate:g0,_coercedNumber:KT,_coercedString:BT,_cuid:Om,_cuid2:Nm,_custom:_0,_date:m0,_decode:am,_decodeAsync:lm,_default:yU,_discriminatedUnion:sU,_e164:Vm,_email:Im,_emoji:Rm,_encode:sm,_encodeAsync:um,_endsWith:jc,_enum:fU,_file:b0,_float32:XT,_float64:QT,_gt:Gr,_gte:Vt,_guid:Nl,_includes:Pc,_int:YT,_int32:e0,_int64:s0,_intersection:aU,_ipv4:Dm,_ipv6:zm,_isoDate:HT,_isoDateTime:ZT,_isoDuration:WT,_isoTime:GT,_jwt:qm,_ksuid:jm,_lazy:IU,_length:Ua,_literal:hU,_lowercase:Oc,_lt:Hr,_lte:_n,_mac:VT,_map:cU,_max:_n,_maxLength:La,_maxSize:za,_mime:Dc,_min:Vt,_minLength:Ai,_minSize:No,_multipleOf:Oo,_nan:v0,_nanoid:$m,_nativeEnum:pU,_negative:Hm,_never:p0,_nonnegative:Wm,_nonoptional:bU,_nonpositive:Gm,_normalize:zc,_null:c0,_nullable:vU,_number:JT,_optional:gU,_overwrite:Ar,_parse:Ra,_parseAsync:$a,_pipe:xU,_positive:Zm,_promise:TU,_property:Jm,_readonly:SU,_record:lU,_refine:w0,_regex:$c,_safeDecode:dm,_safeDecodeAsync:pm,_safeEncode:cm,_safeEncodeAsync:fm,_safeParse:Oa,_safeParseAsync:Na,_set:dU,_size:Rc,_slugify:Bc,_startsWith:Mc,_string:FT,_stringFormat:Fa,_stringbool:T0,_success:_U,_superRefine:x0,_symbol:u0,_templateLiteral:EU,_toLowerCase:Uc,_toUpperCase:Fc,_transform:mU,_trim:Lc,_tuple:uU,_uint32:t0,_uint64:a0,_ulid:Pm,_undefined:l0,_union:iU,_unknown:f0,_uppercase:Nc,_url:Ac,_uuid:Tm,_uuidv4:km,_uuidv6:Cm,_uuidv7:Am,_void:h0,_xid:Mm,_xor:oU,clone:Sn,config:It,createStandardJSONSchemaMethod:Ws,createToJSONSchemaMethod:k0,decode:LD,decodeAsync:FD,describe:E0,encode:zD,encodeAsync:UD,extractDefs:Mo,finalize:jo,flattenError:im,formatError:om,globalConfig:Al,globalRegistry:On,initializeContext:Po,isValidBase64:ym,isValidBase64URL:BI,isValidJWT:ZI,locales:DT,meta:I0,parse:Lp,parseAsync:Up,prettifyError:gE,process:Ue,regexes:mm,registry:Em,safeDecode:VD,safeDecodeAsync:ZD,safeEncode:BD,safeEncodeAsync:qD,safeParse:vE,safeParseAsync:yE,toDotPath:mE,toJSONSchema:Vc,treeifyError:hE,util:fE,version:_I},Symbol.toStringTag,{value:"Module"})),$U=Object.freeze(Object.defineProperty({__proto__:null,endsWith:jc,gt:Gr,gte:Vt,includes:Pc,length:Ua,lowercase:Oc,lt:Hr,lte:_n,maxLength:La,maxSize:za,mime:Dc,minLength:Ai,minSize:No,multipleOf:Oo,negative:Hm,nonnegative:Wm,nonpositive:Gm,normalize:zc,overwrite:Ar,positive:Zm,property:Jm,regex:$c,size:Rc,slugify:Bc,startsWith:Mc,toLowerCase:Uc,toUpperCase:Fc,trim:Lc,uppercase:Nc},Symbol.toStringTag,{value:"Module"})),Ym=$("ZodISODateTime",(e,t)=>{OI.init(e,t),Be.init(e,t)});function fk(e){return ZT(Ym,e)}const Xm=$("ZodISODate",(e,t)=>{NI.init(e,t),Be.init(e,t)});function pk(e){return HT(Xm,e)}const Qm=$("ZodISOTime",(e,t)=>{PI.init(e,t),Be.init(e,t)});function hk(e){return GT(Qm,e)}const eg=$("ZodISODuration",(e,t)=>{MI.init(e,t),Be.init(e,t)});function mk(e){return WT(eg,e)}const gk=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:Xm,ZodISODateTime:Ym,ZodISODuration:eg,ZodISOTime:Qm,date:pk,datetime:fk,duration:mk,time:hk},Symbol.toStringTag,{value:"Module"})),vk=(e,t)=>{rm.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>om(e,n)},flatten:{value:n=>im(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Rl,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Rl,2)}},isEmpty:{get(){return e.issues.length===0}}})},OU=$("ZodError",vk),dn=$("ZodError",vk,{Parent:Error}),yk=Ra(dn),bk=$a(dn),_k=Oa(dn),qc=Na(dn),wk=sm(dn),xk=am(dn),Sk=um(dn),Ek=lm(dn),Ik=cm(dn),Tk=dm(dn),kk=fm(dn),Ck=pm(dn),_e=$("ZodType",(e,t)=>(pe.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ws(e,"input"),output:Ws(e,"output")}}),e.toJSONSchema=k0(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Cr(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]})),e.clone=(n,i)=>Sn(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>yk(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>_k(e,n,i),e.parseAsync=async(n,i)=>bk(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>qc(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>wk(e,n,i),e.decode=(n,i)=>xk(e,n,i),e.encodeAsync=async(n,i)=>Sk(e,n,i),e.decodeAsync=async(n,i)=>Ek(e,n,i),e.safeEncode=(n,i)=>Ik(e,n,i),e.safeDecode=(n,i)=>Tk(e,n,i),e.safeEncodeAsync=async(n,i)=>kk(e,n,i),e.safeDecodeAsync=async(n,i)=>Ck(e,n,i),e.refine=(n,i)=>e.check(Dg(n,i)),e.superRefine=n=>e.check(zg(n)),e.overwrite=n=>e.check(Ar(n)),e.optional=()=>ge(e),e.nullable=()=>Ks(e),e.nullish=()=>ge(Ks(e)),e.nonoptional=n=>Tg(e,n),e.array=()=>J(e),e.or=n=>le([e,n]),e.and=n=>pg(e,n),e.transform=n=>Ys(e,pd(n)),e.default=n=>Sg(e,n),e.prefault=n=>Ig(e,n),e.catch=n=>Ag(e,n),e.pipe=n=>Ys(e,n),e.readonly=()=>Og(e),e.describe=n=>{const i=e.clone();return On.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return On.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return On.get(e);const i=e.clone();return On.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Zc=$("_ZodString",(e,t)=>{Da.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(i,r,o)=>C0(e,i,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check($c(...i)),e.includes=(...i)=>e.check(Pc(...i)),e.startsWith=(...i)=>e.check(Mc(...i)),e.endsWith=(...i)=>e.check(jc(...i)),e.min=(...i)=>e.check(Ai(...i)),e.max=(...i)=>e.check(La(...i)),e.length=(...i)=>e.check(Ua(...i)),e.nonempty=(...i)=>e.check(Ai(1,...i)),e.lowercase=i=>e.check(Oc(i)),e.uppercase=i=>e.check(Nc(i)),e.trim=()=>e.check(Lc()),e.normalize=(...i)=>e.check(zc(...i)),e.toLowerCase=()=>e.check(Uc()),e.toUpperCase=()=>e.check(Fc()),e.slugify=()=>e.check(Bc())}),Ba=$("ZodString",(e,t)=>{Da.init(e,t),Zc.init(e,t),e.email=n=>e.check(Im(Hc,n)),e.url=n=>e.check(Ac(Va,n)),e.jwt=n=>e.check(qm(ud,n)),e.emoji=n=>e.check(Rm(Gc,n)),e.guid=n=>e.check(Nl(Js,n)),e.uuid=n=>e.check(Tm(Kn,n)),e.uuidv4=n=>e.check(km(Kn,n)),e.uuidv6=n=>e.check(Cm(Kn,n)),e.uuidv7=n=>e.check(Am(Kn,n)),e.nanoid=n=>e.check($m(Wc,n)),e.guid=n=>e.check(Nl(Js,n)),e.cuid=n=>e.check(Om(Jc,n)),e.cuid2=n=>e.check(Nm(Kc,n)),e.ulid=n=>e.check(Pm(Yc,n)),e.base64=n=>e.check(Fm(id,n)),e.base64url=n=>e.check(Bm(sd,n)),e.xid=n=>e.check(Mm(Xc,n)),e.ksuid=n=>e.check(jm(Qc,n)),e.ipv4=n=>e.check(Dm(ed,n)),e.ipv6=n=>e.check(zm(td,n)),e.cidrv4=n=>e.check(Lm(nd,n)),e.cidrv6=n=>e.check(Um(rd,n)),e.e164=n=>e.check(Vm(ad,n)),e.datetime=n=>e.check(fk(n)),e.date=n=>e.check(pk(n)),e.time=n=>e.check(hk(n)),e.duration=n=>e.check(mk(n))});function T(e){return FT(Ba,e)}const Be=$("ZodStringFormat",(e,t)=>{Fe.init(e,t),Zc.init(e,t)}),Hc=$("ZodEmail",(e,t)=>{SI.init(e,t),Be.init(e,t)});function Ak(e){return Im(Hc,e)}const Js=$("ZodGUID",(e,t)=>{wI.init(e,t),Be.init(e,t)});function Rk(e){return Nl(Js,e)}const Kn=$("ZodUUID",(e,t)=>{xI.init(e,t),Be.init(e,t)});function $k(e){return Tm(Kn,e)}function Ok(e){return km(Kn,e)}function Nk(e){return Cm(Kn,e)}function Pk(e){return Am(Kn,e)}const Va=$("ZodURL",(e,t)=>{EI.init(e,t),Be.init(e,t)});function Mk(e){return Ac(Va,e)}function jk(e){return Ac(Va,{protocol:/^https?$/,hostname:DE,...D(e)})}const Gc=$("ZodEmoji",(e,t)=>{II.init(e,t),Be.init(e,t)});function Dk(e){return Rm(Gc,e)}const Wc=$("ZodNanoID",(e,t)=>{TI.init(e,t),Be.init(e,t)});function zk(e){return $m(Wc,e)}const Jc=$("ZodCUID",(e,t)=>{kI.init(e,t),Be.init(e,t)});function Lk(e){return Om(Jc,e)}const Kc=$("ZodCUID2",(e,t)=>{CI.init(e,t),Be.init(e,t)});function Uk(e){return Nm(Kc,e)}const Yc=$("ZodULID",(e,t)=>{AI.init(e,t),Be.init(e,t)});function Fk(e){return Pm(Yc,e)}const Xc=$("ZodXID",(e,t)=>{RI.init(e,t),Be.init(e,t)});function Bk(e){return Mm(Xc,e)}const Qc=$("ZodKSUID",(e,t)=>{$I.init(e,t),Be.init(e,t)});function Vk(e){return jm(Qc,e)}const ed=$("ZodIPv4",(e,t)=>{jI.init(e,t),Be.init(e,t)});function qk(e){return Dm(ed,e)}const tg=$("ZodMAC",(e,t)=>{zI.init(e,t),Be.init(e,t)});function Zk(e){return VT(tg,e)}const td=$("ZodIPv6",(e,t)=>{DI.init(e,t),Be.init(e,t)});function Hk(e){return zm(td,e)}const nd=$("ZodCIDRv4",(e,t)=>{LI.init(e,t),Be.init(e,t)});function Gk(e){return Lm(nd,e)}const rd=$("ZodCIDRv6",(e,t)=>{UI.init(e,t),Be.init(e,t)});function Wk(e){return Um(rd,e)}const id=$("ZodBase64",(e,t)=>{FI.init(e,t),Be.init(e,t)});function od(e){return Fm(id,e)}const sd=$("ZodBase64URL",(e,t)=>{VI.init(e,t),Be.init(e,t)});function Jk(e){return Bm(sd,e)}const ad=$("ZodE164",(e,t)=>{qI.init(e,t),Be.init(e,t)});function Kk(e){return Vm(ad,e)}const ud=$("ZodJWT",(e,t)=>{HI.init(e,t),Be.init(e,t)});function Yk(e){return qm(ud,e)}const Jo=$("ZodCustomStringFormat",(e,t)=>{GI.init(e,t),Be.init(e,t)});function Xk(e,t,n={}){return Fa(Jo,e,t,n)}function Qk(e){return Fa(Jo,"hostname",jE,e)}function eC(e){return Fa(Jo,"hex",QE,e)}function tC(e,t){const n=t?.enc??"hex",i=`${e}_${n}`,r=mm[i];if(!r)throw new Error(`Unrecognized hash format: ${i}`);return Fa(Jo,i,r,t)}const qa=$("ZodNumber",(e,t)=>{bm.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(i,r,o)=>A0(e,i,r),e.gt=(i,r)=>e.check(Gr(i,r)),e.gte=(i,r)=>e.check(Vt(i,r)),e.min=(i,r)=>e.check(Vt(i,r)),e.lt=(i,r)=>e.check(Hr(i,r)),e.lte=(i,r)=>e.check(_n(i,r)),e.max=(i,r)=>e.check(_n(i,r)),e.int=i=>e.check(Pl(i)),e.safe=i=>e.check(Pl(i)),e.positive=i=>e.check(Gr(0,i)),e.nonnegative=i=>e.check(Vt(0,i)),e.negative=i=>e.check(Hr(0,i)),e.nonpositive=i=>e.check(_n(0,i)),e.multipleOf=(i,r)=>e.check(Oo(i,r)),e.step=(i,r)=>e.check(Oo(i,r)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ee(e){return JT(qa,e)}const zi=$("ZodNumberFormat",(e,t)=>{WI.init(e,t),qa.init(e,t)});function Pl(e){return YT(zi,e)}function nC(e){return XT(zi,e)}function rC(e){return QT(zi,e)}function iC(e){return e0(zi,e)}function oC(e){return t0(zi,e)}const Za=$("ZodBoolean",(e,t)=>{_m.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>R0(e,n,i)});function De(e){return n0(Za,e)}const Ha=$("ZodBigInt",(e,t)=>{wm.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(i,r,o)=>$0(e,i),e.gte=(i,r)=>e.check(Vt(i,r)),e.min=(i,r)=>e.check(Vt(i,r)),e.gt=(i,r)=>e.check(Gr(i,r)),e.gte=(i,r)=>e.check(Vt(i,r)),e.min=(i,r)=>e.check(Vt(i,r)),e.lt=(i,r)=>e.check(Hr(i,r)),e.lte=(i,r)=>e.check(_n(i,r)),e.max=(i,r)=>e.check(_n(i,r)),e.positive=i=>e.check(Gr(BigInt(0),i)),e.negative=i=>e.check(Hr(BigInt(0),i)),e.nonpositive=i=>e.check(_n(BigInt(0),i)),e.nonnegative=i=>e.check(Vt(BigInt(0),i)),e.multipleOf=(i,r)=>e.check(Oo(i,r));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function sC(e){return i0(Ha,e)}const ld=$("ZodBigIntFormat",(e,t)=>{JI.init(e,t),Ha.init(e,t)});function aC(e){return s0(ld,e)}function uC(e){return a0(ld,e)}const ng=$("ZodSymbol",(e,t)=>{KI.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>O0(e,n)});function lC(e){return u0(ng,e)}const rg=$("ZodUndefined",(e,t)=>{YI.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>P0(e,n)});function cC(e){return l0(rg,e)}const ig=$("ZodNull",(e,t)=>{XI.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>N0(e,n,i)});function Ga(e){return c0(ig,e)}const og=$("ZodAny",(e,t)=>{QI.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>D0()});function lt(){return d0(og)}const sg=$("ZodUnknown",(e,t)=>{eT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>z0()});function Je(){return f0(sg)}const ag=$("ZodNever",(e,t)=>{tT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>j0(e,n,i)});function cd(e){return p0(ag,e)}const ug=$("ZodVoid",(e,t)=>{nT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>M0(e,n)});function dC(e){return h0(ug,e)}const dd=$("ZodDate",(e,t)=>{rT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(i,r,o)=>L0(e,i),e.min=(i,r)=>e.check(Vt(i,r)),e.max=(i,r)=>e.check(_n(i,r));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function fC(e){return m0(dd,e)}const lg=$("ZodArray",(e,t)=>{iT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Y0(e,n,i,r),e.element=t.element,e.min=(n,i)=>e.check(Ai(n,i)),e.nonempty=n=>e.check(Ai(1,n)),e.max=(n,i)=>e.check(La(n,i)),e.length=(n,i)=>e.check(Ua(n,i)),e.unwrap=()=>e.element});function J(e,t){return y0(lg,e,t)}function pC(e){const t=e._zod.def.shape;return ni(Object.keys(t))}const Wa=$("ZodObject",(e,t)=>{uT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>X0(e,n,i,r),Ee(e,"shape",()=>t.shape),e.keyof=()=>ni(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Je()}),e.loose=()=>e.clone({...e._zod.def,catchall:Je()}),e.strict=()=>e.clone({...e._zod.def,catchall:cd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>oE(e,n),e.safeExtend=n=>sE(e,n),e.merge=n=>aE(e,n),e.pick=n=>rE(e,n),e.omit=n=>iE(e,n),e.partial=(...n)=>uE(hd,e,n[0]),e.required=(...n)=>lE(md,e,n[0])});function N(e,t){const n={type:"object",shape:e??{},...D(t)};return new Wa(n)}function He(e,t){return new Wa({type:"object",shape:e,catchall:cd(),...D(t)})}function zr(e,t){return new Wa({type:"object",shape:e,catchall:Je(),...D(t)})}const Ja=$("ZodUnion",(e,t)=>{Cc.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Km(e,n,i,r),e.options=t.options});function le(e,t){return new Ja({type:"union",options:e,...D(t)})}const cg=$("ZodXor",(e,t)=>{Ja.init(e,t),lT.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Km(e,n,i,r),e.options=t.options});function hC(e,t){return new cg({type:"union",options:e,inclusive:!1,...D(t)})}const dg=$("ZodDiscriminatedUnion",(e,t)=>{Ja.init(e,t),cT.init(e,t)});function fd(e,t,n){return new dg({type:"union",options:t,discriminator:e,...D(n)})}const fg=$("ZodIntersection",(e,t)=>{dT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Q0(e,n,i,r)});function pg(e,t){return new fg({type:"intersection",left:e,right:t})}const hg=$("ZodTuple",(e,t)=>{xm.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ek(e,n,i,r),e.rest=n=>e.clone({...e._zod.def,rest:n})});function mg(e,t,n){const i=t instanceof pe,r=i?n:t,o=i?t:null;return new hg({type:"tuple",items:e,rest:o,...D(r)})}const Ka=$("ZodRecord",(e,t)=>{fT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>tk(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function nn(e,t,n){return new Ka({type:"record",keyType:e,valueType:t,...D(n)})}function mC(e,t,n){const i=Sn(e);return i._zod.values=void 0,new Ka({type:"record",keyType:i,valueType:t,...D(n)})}function gC(e,t,n){return new Ka({type:"record",keyType:e,valueType:t,mode:"loose",...D(n)})}const gg=$("ZodMap",(e,t)=>{pT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>J0(e,n),e.keyType=t.keyType,e.valueType=t.valueType});function vC(e,t,n){return new gg({type:"map",keyType:e,valueType:t,...D(n)})}const vg=$("ZodSet",(e,t)=>{hT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>K0(e,n),e.min=(...n)=>e.check(No(...n)),e.nonempty=n=>e.check(No(1,n)),e.max=(...n)=>e.check(za(...n)),e.size=(...n)=>e.check(Rc(...n))});function yC(e,t){return new vg({type:"set",valueType:e,...D(t)})}const Do=$("ZodEnum",(e,t)=>{mT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(i,r,o)=>U0(e,i,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{const o={};for(const s of i)if(n.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Do({...t,checks:[],...D(r),entries:o})},e.exclude=(i,r)=>{const o={...t.entries};for(const s of i)if(n.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Do({...t,checks:[],...D(r),entries:o})}});function ni(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new Do({type:"enum",entries:n,...D(t)})}function bC(e,t){return new Do({type:"enum",entries:e,...D(t)})}const yg=$("ZodLiteral",(e,t)=>{gT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>F0(e,n,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 F(e,t){return new yg({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}const bg=$("ZodFile",(e,t)=>{vT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>q0(e,n,i),e.min=(n,i)=>e.check(No(n,i)),e.max=(n,i)=>e.check(za(n,i)),e.mime=(n,i)=>e.check(Dc(Array.isArray(n)?n:[n],i))});function _C(e){return b0(bg,e)}const _g=$("ZodTransform",(e,t)=>{yT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>W0(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Sc(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(Ro(o,n.value,t));else{const s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Ro(s))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function pd(e){return new _g({type:"transform",transform:e})}const hd=$("ZodOptional",(e,t)=>{bT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ck(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function ge(e){return new hd({type:"optional",innerType:e})}const wg=$("ZodNullable",(e,t)=>{_T.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>nk(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Ks(e){return new wg({type:"nullable",innerType:e})}function wC(e){return ge(Ks(e))}const xg=$("ZodDefault",(e,t)=>{wT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ik(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Sg(e,t){return new xg({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ic(t)}})}const Eg=$("ZodPrefault",(e,t)=>{xT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ok(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Ig(e,t){return new Eg({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ic(t)}})}const md=$("ZodNonOptional",(e,t)=>{ST.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>rk(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Tg(e,t){return new md({type:"nonoptional",innerType:e,...D(t)})}const kg=$("ZodSuccess",(e,t)=>{ET.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Z0(e,n,i),e.unwrap=()=>e._zod.def.innerType});function xC(e){return new kg({type:"success",innerType:e})}const Cg=$("ZodCatch",(e,t)=>{IT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>sk(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ag(e,t){return new Cg({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Rg=$("ZodNaN",(e,t)=>{TT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>B0(e,n)});function SC(e){return v0(Rg,e)}const gd=$("ZodPipe",(e,t)=>{kT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ak(e,n,i,r),e.in=t.in,e.out=t.out});function Ys(e,t){return new gd({type:"pipe",in:e,out:t})}const vd=$("ZodCodec",(e,t)=>{gd.init(e,t),Sm.init(e,t)});function EC(e,t,n){return new vd({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const $g=$("ZodReadonly",(e,t)=>{CT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>uk(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Og(e){return new $g({type:"readonly",innerType:e})}const Ng=$("ZodTemplateLiteral",(e,t)=>{AT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>V0(e,n,i)});function IC(e,t){return new Ng({type:"template_literal",parts:e,...D(t)})}const Pg=$("ZodLazy",(e,t)=>{OT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>dk(e,n,i,r),e.unwrap=()=>e._zod.def.getter()});function Ya(e){return new Pg({type:"lazy",getter:e})}const Mg=$("ZodPromise",(e,t)=>{$T.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>lk(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function TC(e){return new Mg({type:"promise",innerType:e})}const jg=$("ZodFunction",(e,t)=>{RT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>G0(e,n)});function Ml(e){return new jg({type:"function",input:Array.isArray(e?.input)?mg(e?.input):e?.input??J(Je()),output:e?.output??Je()})}const Xa=$("ZodCustom",(e,t)=>{NT.init(e,t),_e.init(e,t),e._zod.processJSONSchema=(n,i,r)=>H0(e,n)});function kC(e){const t=new Ye({check:"custom"});return t._zod.check=e,t}function Qa(e,t){return _0(Xa,e??(()=>!0),t)}function Dg(e,t={}){return w0(Xa,e,t)}function zg(e){return x0(e)}const CC=E0,AC=I0;function er(e,t={error:`Input not instance of ${e.name}`}){const n=new Xa({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...D(t)});return n._zod.bag.Class=e,n}const RC=(...e)=>T0({Codec:vd,Boolean:Za,String:Ba},...e);function $C(e){const t=Ya(()=>le([T(e),ee(),De(),Ga(),J(t),nn(T(),t)]));return t}function OC(e,t){return Ys(pd(e),t)}const NU=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:og,ZodArray:lg,ZodBase64:id,ZodBase64URL:sd,ZodBigInt:Ha,ZodBigIntFormat:ld,ZodBoolean:Za,ZodCIDRv4:nd,ZodCIDRv6:rd,ZodCUID:Jc,ZodCUID2:Kc,ZodCatch:Cg,ZodCodec:vd,ZodCustom:Xa,ZodCustomStringFormat:Jo,ZodDate:dd,ZodDefault:xg,ZodDiscriminatedUnion:dg,ZodE164:ad,ZodEmail:Hc,ZodEmoji:Gc,ZodEnum:Do,ZodFile:bg,ZodFunction:jg,ZodGUID:Js,ZodIPv4:ed,ZodIPv6:td,ZodIntersection:fg,ZodJWT:ud,ZodKSUID:Qc,ZodLazy:Pg,ZodLiteral:yg,ZodMAC:tg,ZodMap:gg,ZodNaN:Rg,ZodNanoID:Wc,ZodNever:ag,ZodNonOptional:md,ZodNull:ig,ZodNullable:wg,ZodNumber:qa,ZodNumberFormat:zi,ZodObject:Wa,ZodOptional:hd,ZodPipe:gd,ZodPrefault:Eg,ZodPromise:Mg,ZodReadonly:$g,ZodRecord:Ka,ZodSet:vg,ZodString:Ba,ZodStringFormat:Be,ZodSuccess:kg,ZodSymbol:ng,ZodTemplateLiteral:Ng,ZodTransform:_g,ZodTuple:hg,ZodType:_e,ZodULID:Yc,ZodURL:Va,ZodUUID:Kn,ZodUndefined:rg,ZodUnion:Ja,ZodUnknown:sg,ZodVoid:ug,ZodXID:Xc,ZodXor:cg,_ZodString:Zc,_default:Sg,_function:Ml,any:lt,array:J,base64:od,base64url:Jk,bigint:sC,boolean:De,catch:Ag,check:kC,cidrv4:Gk,cidrv6:Wk,codec:EC,cuid:Lk,cuid2:Uk,custom:Qa,date:fC,describe:CC,discriminatedUnion:fd,e164:Kk,email:Ak,emoji:Dk,enum:ni,file:_C,float32:nC,float64:rC,function:Ml,guid:Rk,hash:tC,hex:eC,hostname:Qk,httpUrl:jk,instanceof:er,int:Pl,int32:iC,int64:aC,intersection:pg,ipv4:qk,ipv6:Hk,json:$C,jwt:Yk,keyof:pC,ksuid:Vk,lazy:Ya,literal:F,looseObject:zr,looseRecord:gC,mac:Zk,map:vC,meta:AC,nan:SC,nanoid:zk,nativeEnum:bC,never:cd,nonoptional:Tg,null:Ga,nullable:Ks,nullish:wC,number:ee,object:N,optional:ge,partialRecord:mC,pipe:Ys,prefault:Ig,preprocess:OC,promise:TC,readonly:Og,record:nn,refine:Dg,set:yC,strictObject:He,string:T,stringFormat:Xk,stringbool:RC,success:xC,superRefine:zg,symbol:lC,templateLiteral:IC,transform:pd,tuple:mg,uint32:oC,uint64:uC,ulid:Fk,undefined:cC,union:le,unknown:Je,url:Mk,uuid:$k,uuidv4:Ok,uuidv6:Nk,uuidv7:Pk,void:dC,xid:Bk,xor:hC},Symbol.toStringTag,{value:"Module"})),NC={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 PU(e){It({customError:e})}function MU(){return It().customError}var Vp;Vp||(Vp={});const K={...NU,...$U,iso:gk};function jU(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 DU(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 i=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===i){const r=n[1];if(!r||!t.defs[r])throw new Error(`Reference not found: ${e}`);return t.defs[r]}throw new Error(`Reference not found: ${e}`)}function PC(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return K.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 r=e.$ref;if(t.refs.has(r))return t.refs.get(r);if(t.processing.has(r))return K.lazy(()=>{if(!t.refs.has(r))throw new Error(`Circular reference not resolved: ${r}`);return t.refs.get(r)});t.processing.add(r);const o=DU(r,t),s=St(o,t);return t.refs.set(r,s),t.processing.delete(r),s}if(e.enum!==void 0){const r=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&r.length===1&&r[0]===null)return K.null();if(r.length===0)return K.never();if(r.length===1)return K.literal(r[0]);if(r.every(s=>typeof s=="string"))return K.enum(r);const o=r.map(s=>K.literal(s));return o.length<2?o[0]:K.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return K.literal(e.const);const n=e.type;if(Array.isArray(n)){const r=n.map(o=>{const s={...e,type:o};return PC(s,t)});return r.length===0?K.never():r.length===1?r[0]:K.union(r)}if(!n)return K.any();let i;switch(n){case"string":{let r=K.string();if(e.format){const o=e.format;o==="email"?r=r.check(K.email()):o==="uri"||o==="uri-reference"?r=r.check(K.url()):o==="uuid"||o==="guid"?r=r.check(K.uuid()):o==="date-time"?r=r.check(K.iso.datetime()):o==="date"?r=r.check(K.iso.date()):o==="time"?r=r.check(K.iso.time()):o==="duration"?r=r.check(K.iso.duration()):o==="ipv4"?r=r.check(K.ipv4()):o==="ipv6"?r=r.check(K.ipv6()):o==="mac"?r=r.check(K.mac()):o==="cidr"?r=r.check(K.cidrv4()):o==="cidr-v6"?r=r.check(K.cidrv6()):o==="base64"?r=r.check(K.base64()):o==="base64url"?r=r.check(K.base64url()):o==="e164"?r=r.check(K.e164()):o==="jwt"?r=r.check(K.jwt()):o==="emoji"?r=r.check(K.emoji()):o==="nanoid"?r=r.check(K.nanoid()):o==="cuid"?r=r.check(K.cuid()):o==="cuid2"?r=r.check(K.cuid2()):o==="ulid"?r=r.check(K.ulid()):o==="xid"?r=r.check(K.xid()):o==="ksuid"&&(r=r.check(K.ksuid()))}typeof e.minLength=="number"&&(r=r.min(e.minLength)),typeof e.maxLength=="number"&&(r=r.max(e.maxLength)),e.pattern&&(r=r.regex(new RegExp(e.pattern))),i=r;break}case"number":case"integer":{let r=n==="integer"?K.number().int():K.number();typeof e.minimum=="number"&&(r=r.min(e.minimum)),typeof e.maximum=="number"&&(r=r.max(e.maximum)),typeof e.exclusiveMinimum=="number"?r=r.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(r=r.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?r=r.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(r=r.lt(e.maximum)),typeof e.multipleOf=="number"&&(r=r.multipleOf(e.multipleOf)),i=r;break}case"boolean":{i=K.boolean();break}case"null":{i=K.null();break}case"object":{const r={},o=e.properties||{},s=new Set(e.required||[]);for(const[l,u]of Object.entries(o)){const c=St(u,t);r[l]=s.has(l)?c:c.optional()}if(e.propertyNames){const l=St(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties=="object"?St(e.additionalProperties,t):K.any();if(Object.keys(r).length===0){i=K.record(l,u);break}const c=K.object(r).passthrough(),d=K.looseRecord(l,u);i=K.intersection(c,d);break}if(e.patternProperties){const l=e.patternProperties,u=Object.keys(l),c=[];for(const f of u){const p=St(l[f],t),m=K.string().regex(new RegExp(f));c.push(K.looseRecord(m,p))}const d=[];if(Object.keys(r).length>0&&d.push(K.object(r).passthrough()),d.push(...c),d.length===0)i=K.object({}).passthrough();else if(d.length===1)i=d[0];else{let f=K.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)f=K.intersection(f,d[p]);i=f}break}const a=K.object(r);e.additionalProperties===!1?i=a.strict():typeof e.additionalProperties=="object"?i=a.catchall(St(e.additionalProperties,t)):i=a.passthrough();break}case"array":{const r=e.prefixItems,o=e.items;if(r&&Array.isArray(r)){const s=r.map(l=>St(l,t)),a=o&&typeof o=="object"&&!Array.isArray(o)?St(o,t):void 0;a?i=K.tuple(s).rest(a):i=K.tuple(s),typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(Array.isArray(o)){const s=o.map(l=>St(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?St(e.additionalItems,t):void 0;a?i=K.tuple(s).rest(a):i=K.tuple(s),typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(o!==void 0){const s=St(o,t);let a=K.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),i=a}else i=K.array(K.any());break}default:throw new Error(`Unsupported type: ${n}`)}return e.description&&(i=i.describe(e.description)),e.default!==void 0&&(i=i.default(e.default)),i}function St(e,t){if(typeof e=="boolean")return e?K.any():K.never();let n=PC(e,t);const i=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const r=e.anyOf.map(s=>St(s,t)),o=K.union(r);n=i?K.intersection(n,o):o}if(e.oneOf&&Array.isArray(e.oneOf)){const r=e.oneOf.map(s=>St(s,t)),o=K.xor(r);n=i?K.intersection(n,o):o}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=i?n:K.any();else{let r=i?n:St(e.allOf[0],t);const o=i?0:1;for(let s=o;s<e.allOf.length;s++)r=K.intersection(r,St(e.allOf[s],t));n=r}return e.nullable===!0&&t.version==="openapi-3.0"&&(n=K.nullable(n)),e.readOnly===!0&&(n=K.readonly(n)),n}function zU(e,t){if(typeof e=="boolean")return e?K.any():K.never();const n=jU(e,t?.defaultTarget),i=e.$defs||e.definitions||{};return St(e,{version:n,defs:i,refs:new Map,processing:new Set,rootSchema:e})}function LU(e){return BT(Ba,e)}function UU(e){return KT(qa,e)}function FU(e){return r0(Za,e)}function BU(e){return o0(Ha,e)}function VU(e){return g0(dd,e)}const qU=Object.freeze(Object.defineProperty({__proto__:null,bigint:BU,boolean:FU,date:VU,number:UU,string:LU},Symbol.toStringTag,{value:"Module"}));It(PT());const jl=Object.freeze(Object.defineProperty({__proto__:null,$brand:JS,$input:LT,$output:zT,NEVER:em,TimePrecision:qT,ZodAny:og,ZodArray:lg,ZodBase64:id,ZodBase64URL:sd,ZodBigInt:Ha,ZodBigIntFormat:ld,ZodBoolean:Za,ZodCIDRv4:nd,ZodCIDRv6:rd,ZodCUID:Jc,ZodCUID2:Kc,ZodCatch:Cg,ZodCodec:vd,ZodCustom:Xa,ZodCustomStringFormat:Jo,ZodDate:dd,ZodDefault:xg,ZodDiscriminatedUnion:dg,ZodE164:ad,ZodEmail:Hc,ZodEmoji:Gc,ZodEnum:Do,ZodError:OU,ZodFile:bg,get ZodFirstPartyTypeKind(){return Vp},ZodFunction:jg,ZodGUID:Js,ZodIPv4:ed,ZodIPv6:td,ZodISODate:Xm,ZodISODateTime:Ym,ZodISODuration:eg,ZodISOTime:Qm,ZodIntersection:fg,ZodIssueCode:NC,ZodJWT:ud,ZodKSUID:Qc,ZodLazy:Pg,ZodLiteral:yg,ZodMAC:tg,ZodMap:gg,ZodNaN:Rg,ZodNanoID:Wc,ZodNever:ag,ZodNonOptional:md,ZodNull:ig,ZodNullable:wg,ZodNumber:qa,ZodNumberFormat:zi,ZodObject:Wa,ZodOptional:hd,ZodPipe:gd,ZodPrefault:Eg,ZodPromise:Mg,ZodReadonly:$g,ZodRealError:dn,ZodRecord:Ka,ZodSet:vg,ZodString:Ba,ZodStringFormat:Be,ZodSuccess:kg,ZodSymbol:ng,ZodTemplateLiteral:Ng,ZodTransform:_g,ZodTuple:hg,ZodType:_e,ZodULID:Yc,ZodURL:Va,ZodUUID:Kn,ZodUndefined:rg,ZodUnion:Ja,ZodUnknown:sg,ZodVoid:ug,ZodXID:Xc,ZodXor:cg,_ZodString:Zc,_default:Sg,_function:Ml,any:lt,array:J,base64:od,base64url:Jk,bigint:sC,boolean:De,catch:Ag,check:kC,cidrv4:Gk,cidrv6:Wk,clone:Sn,codec:EC,coerce:qU,config:It,core:RU,cuid:Lk,cuid2:Uk,custom:Qa,date:fC,decode:xk,decodeAsync:Ek,describe:CC,discriminatedUnion:fd,e164:Kk,email:Ak,emoji:Dk,encode:wk,encodeAsync:Sk,endsWith:jc,enum:ni,file:_C,flattenError:im,float32:nC,float64:rC,formatError:om,fromJSONSchema:zU,function:Ml,getErrorMap:MU,globalRegistry:On,gt:Gr,gte:Vt,guid:Rk,hash:tC,hex:eC,hostname:Qk,httpUrl:jk,includes:Pc,instanceof:er,int:Pl,int32:iC,int64:aC,intersection:pg,ipv4:qk,ipv6:Hk,iso:gk,json:$C,jwt:Yk,keyof:pC,ksuid:Vk,lazy:Ya,length:Ua,literal:F,locales:DT,looseObject:zr,looseRecord:gC,lowercase:Oc,lt:Hr,lte:_n,mac:Zk,map:vC,maxLength:La,maxSize:za,meta:AC,mime:Dc,minLength:Ai,minSize:No,multipleOf:Oo,nan:SC,nanoid:zk,nativeEnum:bC,negative:Hm,never:cd,nonnegative:Wm,nonoptional:Tg,nonpositive:Gm,normalize:zc,null:Ga,nullable:Ks,nullish:wC,number:ee,object:N,optional:ge,overwrite:Ar,parse:yk,parseAsync:bk,partialRecord:mC,pipe:Ys,positive:Zm,prefault:Ig,preprocess:OC,prettifyError:gE,promise:TC,property:Jm,readonly:Og,record:nn,refine:Dg,regex:$c,regexes:mm,registry:Em,safeDecode:Tk,safeDecodeAsync:Ck,safeEncode:Ik,safeEncodeAsync:kk,safeParse:_k,safeParseAsync:qc,set:yC,setErrorMap:PU,size:Rc,slugify:Bc,startsWith:Mc,strictObject:He,string:T,stringFormat:Xk,stringbool:RC,success:xC,superRefine:zg,symbol:lC,templateLiteral:IC,toJSONSchema:Vc,toLowerCase:Uc,toUpperCase:Fc,transform:pd,treeifyError:hE,trim:Lc,tuple:mg,uint32:oC,uint64:uC,ulid:Fk,undefined:cC,union:le,unknown:Je,uppercase:Nc,url:Mk,util:fE,uuid:$k,uuidv4:Ok,uuidv6:Nk,uuidv7:Pk,void:dC,xid:Bk,xor:hC},Symbol.toStringTag,{value:"Module"}));var Xs;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function n(r){throw new Error}e.assertNever=n,e.arrayToEnum=r=>{const o={};for(const s of r)o[s]=s;return o},e.getValidEnumValues=r=>{const o=e.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),s={};for(const a of o)s[a]=r[a];return e.objectValues(s)},e.objectValues=r=>e.objectKeys(r).map(function(o){return r[o]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const o=[];for(const s in r)Object.prototype.hasOwnProperty.call(r,s)&&o.push(s);return o},e.find=(r,o)=>{for(const s of r)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,o=" | "){return r.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=i,e.jsonStringifyReplacer=(r,o)=>typeof o=="bigint"?o.toString():o})(Xs||(Xs={}));var pb;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pb||(pb={}));Xs.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);Xs.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Dl extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(o){return o.message},i={_errors:[]},r=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)i._errors.push(n(s));else{let a=i,l=0;for(;l<s.path.length;){const u=s.path[l];l===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(s))):a[u]=a[u]||{_errors:[]},a=a[u],l++}}};return r(this),i}static assert(t){if(!(t instanceof Dl))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xs.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n=Object.create(null),i=[];for(const r of this.issues)if(r.path.length>0){const o=r.path[0];n[o]=n[o]||[],n[o].push(t(r))}else i.push(t(r));return{formErrors:i,fieldErrors:n}}get formErrors(){return this.flatten()}}Dl.create=e=>new Dl(e);var hb;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(hb||(hb={}));var G;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(G||(G={}));var ZU=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,s=new Array(t);for(let a=0;a<t;a++)s[a]=n[Math.random()*o|0];return s.join("")};if(e==null)return r;if(n.includes(i))throw new xc({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`};ZU();function MC(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function HU(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function jC(e,...t){const n=new Headers(HU(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var GU=Symbol.for("vercel.ai.validator");function WU(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var JU=Symbol.for("vercel.ai.schema");function KU(e,{validate:t}={}){return{[JU]:!0,_type:void 0,[GU]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let Lg;Lg=globalThis.crypto;async function YU(e){return(await Lg).getRandomValues(new Uint8Array(e))}async function XU(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const i=await YU(e);for(let r=0;r<e;r++){const o=i[r]%t.length;n+=t[o]}return n}async function QU(e){return await XU(e)}async function e2(e){const t=await(await Lg).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function t2(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await QU(e),n=await e2(t);return{code_verifier:t,code_challenge:n}}var n2="AI_MCPClientError",DC=`vercel.ai.error.${n2}`,r2=Symbol.for(DC),mb,gb,Ne=class extends(gb=fe,mb=r2,gb){constructor({name:e="MCPClientError",message:t,cause:n,data:i,code:r}){super({name:e,message:t,cause:n}),this[mb]=!0,this.data=i,this.code=r}static isInstance(e){return fe.hasMarker(e,DC)}},Ko="2025-06-18",i2=[Ko,"2025-03-26","2024-11-05"],o2=zr({name:T(),version:T()}),yd=zr({_meta:ge(N({}).loose())}),_r=yd,zC=N({method:T(),params:ge(yd)}),LC=N({applyDefaults:ge(De())}).loose(),s2=zr({experimental:ge(N({}).loose()),logging:ge(N({}).loose()),prompts:ge(zr({listChanged:ge(De())})),resources:ge(zr({subscribe:ge(De()),listChanged:ge(De())})),tools:ge(zr({listChanged:ge(De())})),elicitation:ge(LC)});N({elicitation:ge(LC)}).loose();var a2=_r.extend({protocolVersion:T(),capabilities:s2,serverInfo:o2,instructions:ge(T())}),Ug=_r.extend({nextCursor:ge(T())}),u2=N({name:T(),description:ge(T()),inputSchema:N({type:F("object"),properties:ge(N({}).loose())}).loose()}).loose(),l2=Ug.extend({tools:J(u2)}),UC=N({type:F("text"),text:T()}).loose(),FC=N({type:F("image"),data:od(),mimeType:T()}).loose(),c2=N({uri:T(),name:T(),title:ge(T()),description:ge(T()),mimeType:ge(T()),size:ge(ee())}).loose(),d2=Ug.extend({resources:J(c2)}),BC=N({uri:T(),name:ge(T()),title:ge(T()),mimeType:ge(T())}).loose(),VC=BC.extend({text:T()}),qC=BC.extend({blob:od()}),ZC=N({type:F("resource"),resource:le([VC,qC])}).loose(),f2=_r.extend({content:J(le([UC,FC,ZC])),isError:De().default(!1).optional()}).or(_r.extend({toolResult:Je()})),p2=N({uriTemplate:T(),name:T(),title:ge(T()),description:ge(T()),mimeType:ge(T())}).loose(),h2=_r.extend({resourceTemplates:J(p2)}),m2=_r.extend({contents:J(le([VC,qC]))}),g2=N({name:T(),description:ge(T()),required:ge(De())}).loose(),v2=N({name:T(),title:ge(T()),description:ge(T()),arguments:ge(J(g2))}).loose(),y2=Ug.extend({prompts:J(v2)}),b2=N({role:le([F("user"),F("assistant")]),content:le([UC,FC,ZC])}).loose(),_2=_r.extend({description:ge(T()),messages:J(b2)}),w2=yd.extend({message:T(),requestedSchema:Je()}),vb=zC.extend({method:F("elicitation/create"),params:w2}),x2=_r.extend({action:le([F("accept"),F("decline"),F("cancel")]),content:ge(nn(T(),Je()))}),bd="2.0",S2=N({jsonrpc:F(bd),id:le([T(),ee().int()])}).merge(zC).strict(),E2=N({jsonrpc:F(bd),id:le([T(),ee().int()]),result:_r}).strict(),I2=N({jsonrpc:F(bd),id:le([T(),ee().int()]),error:N({code:ee().int(),message:T(),data:ge(Je())})}).strict(),T2=N({jsonrpc:F(bd)}).merge(N({method:T(),params:ge(yd)})).strict(),As=le([S2,T2,E2,I2]),HC=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",GC=N({access_token:T(),id_token:T().optional(),token_type:T(),expires_in:ee().optional(),scope:T().optional(),refresh_token:T().optional()}).strip(),qt=T().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:NC.custom,message:"URL must be parseable",fatal:!0}),em}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),k2=N({resource:T().url(),authorization_servers:J(qt).optional(),jwks_uri:T().url().optional(),scopes_supported:J(T()).optional(),bearer_methods_supported:J(T()).optional(),resource_signing_alg_values_supported:J(T()).optional(),resource_name:T().optional(),resource_documentation:T().optional(),resource_policy_uri:T().url().optional(),resource_tos_uri:T().url().optional(),tls_client_certificate_bound_access_tokens:De().optional(),authorization_details_types_supported:J(T()).optional(),dpop_signing_alg_values_supported:J(T()).optional(),dpop_bound_access_tokens_required:De().optional()}).passthrough(),WC=N({issuer:T(),authorization_endpoint:qt,token_endpoint:qt,registration_endpoint:qt.optional(),scopes_supported:J(T()).optional(),response_types_supported:J(T()),grant_types_supported:J(T()).optional(),code_challenge_methods_supported:J(T()),token_endpoint_auth_methods_supported:J(T()).optional(),token_endpoint_auth_signing_alg_values_supported:J(T()).optional()}).passthrough(),C2=N({issuer:T(),authorization_endpoint:qt,token_endpoint:qt,userinfo_endpoint:qt.optional(),jwks_uri:qt,registration_endpoint:qt.optional(),scopes_supported:J(T()).optional(),response_types_supported:J(T()),grant_types_supported:J(T()).optional(),subject_types_supported:J(T()),id_token_signing_alg_values_supported:J(T()),claims_supported:J(T()).optional(),token_endpoint_auth_methods_supported:J(T()).optional()}).passthrough(),A2=C2.merge(WC.pick({code_challenge_methods_supported:!0})),R2=N({client_id:T(),client_secret:T().optional(),client_id_issued_at:ee().optional(),client_secret_expires_at:ee().optional()}).strip(),$2=N({redirect_uris:J(qt),token_endpoint_auth_method:T().optional(),grant_types:J(T()).optional(),response_types:J(T()).optional(),client_name:T().optional(),client_uri:qt.optional(),logo_uri:qt.optional(),scope:T().optional(),contacts:J(T()).optional(),tos_uri:qt.optional(),policy_uri:T().optional(),jwks_uri:qt.optional(),jwks:lt().optional(),software_id:T().optional(),software_version:T().optional(),software_statement:T().optional()}).strip(),O2=N({error:T(),error_description:T().optional(),error_uri:T().optional()}),N2=$2.merge(R2),P2="AI_MCPClientOAuthError",JC=`vercel.ai.error.${P2}`,M2=Symbol.for(JC),yb,bb,eu=class extends(bb=fe,yb=M2,bb){constructor({name:e="MCPClientOAuthError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[yb]=!0}static isInstance(e){return fe.hasMarker(e,JC)}},zo=class extends eu{};zo.errorCode="server_error";var zl=class extends eu{};zl.errorCode="invalid_client";var Ll=class extends eu{};Ll.errorCode="invalid_grant";var Ul=class extends eu{};Ul.errorCode="unauthorized_client";var j2={[zo.errorCode]:zo,[zl.errorCode]:zl,[Ll.errorCode]:Ll,[Ul.errorCode]:Ul};function D2(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function z2({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),i=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==i.origin||n.pathname.length<i.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",o=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return r.startsWith(o)}var Fl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function Bl(e){var t;const n=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!n)return;const[i,r]=n.split(" ");if(i.toLowerCase()!=="bearer"||!r)return;const o=/resource_metadata="([^"]*)"/,s=n.match(o);if(s)try{return new URL(s[1])}catch{return}}function L2(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fg(e,t,n=fetch){try{return await n(e,{headers:t})}catch(i){if(i instanceof TypeError)return t?Fg(e,void 0,n):void 0;throw i}}async function _b(e,t,n=fetch){return await Fg(e,{"MCP-Protocol-Version":t},n)}function U2(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function F2(e,t,n,i){var r,o;const s=new URL(e),a=(r=i?.protocolVersion)!=null?r:Ko;let l;if(i?.metadataUrl)l=new URL(i.metadataUrl);else{const c=L2(t,s.pathname);l=new URL(c,(o=i?.metadataServerUrl)!=null?o:s),l.search=s.search}let u=await _b(l,a,n);if(!i?.metadataUrl&&U2(u,s.pathname)){const c=new URL(`/.well-known/${t}`,s);u=await _b(c,a,n)}return u}async function B2(e,t,n=fetch){const i=await F2(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||i.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw new Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return k2.parse(await i.json())}function V2(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",i=[];if(!n)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}async function q2(e,{fetchFn:t=fetch,protocolVersion:n=Ko}={}){var i;const r={"MCP-Protocol-Version":n},o=V2(e);for(const{url:s,type:a}of o){const l=await Fg(s,r,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}if(a==="oauth")return WC.parse(await l.json());{const u=A2.parse(await l.json());if(!((i=u.code_challenge_methods_supported)!=null&&i.includes("S256")))throw new Error(`Incompatible OIDC provider at ${s}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function Z2(e,{metadata:t,clientInformation:n,redirectUrl:i,scope:r,state:o,resource:s}){const a="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const c=await t2(),d=c.code_verifier,f=c.code_challenge;return u.searchParams.set("response_type",a),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",f),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(i)),o&&u.searchParams.set("state",o),r&&u.searchParams.set("scope",r),r?.includes("offline_access")&&u.searchParams.append("prompt","consent"),s&&u.searchParams.set("resource",s.href),{authorizationUrl:u,codeVerifier:d}}function KC(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function YC(e,t,n,i){const{client_id:r,client_secret:o}=t;switch(e){case"client_secret_basic":H2(r,o,n);return;case"client_secret_post":G2(r,o,i);return;case"none":W2(r,i);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function H2(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const i=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${i}`)}function G2(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function W2(e,t){t.set("client_id",e)}async function Bg(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const i=O2.parse(JSON.parse(n)),{error:r,error_description:o,error_uri:s}=i,a=j2[r]||zo;return new a({message:o||"",cause:s})}catch(i){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${i}. Raw body: ${n}`;return new zo({message:r})}}async function J2(e,{metadata:t,clientInformation:n,authorizationCode:i,codeVerifier:r,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:l}){var u;const c="authorization_code",d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:c,code:i,code_verifier:r,redirect_uri:String(o)});if(a)a(f,p,e,t);else{const h=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],v=KC(n,h);YC(v,n,f,p)}s&&p.set("resource",s.href);const m=await(l??fetch)(d,{method:"POST",headers:f,body:p});if(!m.ok)throw await Bg(m);return GC.parse(await m.json())}async function K2(e,{metadata:t,clientInformation:n,refreshToken:i,resource:r,addClientAuthentication:o,fetchFn:s}){var a;const l="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:l,refresh_token:i});if(o)o(c,d,e,t);else{const p=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],m=KC(n,p);YC(m,n,c,d)}r&&d.set("resource",r.href);const f=await(s??fetch)(u,{method:"POST",headers:c,body:d});if(!f.ok)throw await Bg(f);return GC.parse({refresh_token:i,...await f.json()})}async function Y2(e,{metadata:t,clientMetadata:n,fetchFn:i}){let r;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(t.registration_endpoint)}else r=new URL("/register",e);const o=await(i??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw await Bg(o);return N2.parse(await o.json())}async function Vl(e,t){var n,i;try{return await gf(e,t)}catch(r){if(r instanceof zl||r instanceof Ul)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await gf(e,t);if(r instanceof Ll)return await((i=e.invalidateCredentials)==null?void 0:i.call(e,"tokens")),await gf(e,t);throw r}}async function X2(e,t,n){const i=D2(e);if(t.validateResourceURL)return await t.validateResourceURL(i,n?.resource);if(n){if(!z2({requestedResource:i,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${i} (or origin)`);return new URL(n.resource)}}async function gf(e,{serverUrl:t,authorizationCode:n,scope:i,resourceMetadataUrl:r,fetchFn:o}){let s,a;try{s=await B2(t,{resourceMetadataUrl:r},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=t);const l=await X2(t,e,s),u=await q2(a,{fetchFn:o});let c=await Promise.resolve(e.clientInformation());if(!c){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await Y2(a,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(h),c=h}if(n!==void 0){const h=await e.codeVerifier(),v=await J2(a,{metadata:u,clientInformation:c,authorizationCode:n,codeVerifier:h,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(v),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const h=await K2(a,{metadata:u,clientInformation:c,refreshToken:d.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(h),"AUTHORIZED"}catch(h){if(!(!(h instanceof eu)||h instanceof zo))throw h}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await Z2(a,{metadata:u,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(p),"REDIRECT"}var Q2=class{constructor({url:e,headers:t,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Ko};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return jC(t,`ai-sdk/${HC}`,MC())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(i=!1)=>{var r,o,s,a,l;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:u,signal:(r=this.abortController)==null?void 0:r.signal});if(c.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=Bl(c);try{if(await Vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Fl;return(o=this.onerror)==null||o.call(this,h),t(h)}}catch(m){return(s=this.onerror)==null||s.call(this,m),t(m)}return n(!0)}if(!c.ok||!c.body){let m=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const h=new Ne({message:m});return(a=this.onerror)==null||a.call(this,h),t(h)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Gs).getReader(),p=async()=>{var m,h,v;try{for(;;){const{done:y,value:w}=await f.read();if(y){if(this.connected)throw this.connected=!1,new Ne({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:S,data:b}=w;if(S==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new Ne({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(S==="message")try{const C=As.parse(JSON.parse(b));(m=this.onmessage)==null||m.call(this,C)}catch(C){const _=new Ne({message:"MCP SSE Transport Error: Failed to parse message",cause:C});(h=this.onerror)==null||h.call(this,_)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(v=this.onerror)==null||v.call(this,y),t(y)}};this.sseConnection={close:()=>f.cancel()},p()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(l=this.onerror)==null||l.call(this,u),t(u)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Ne({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,n=async(i=!1)=>{var r,o,s,a,l;try{const c={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(r=this.abortController)==null?void 0:r.signal},d=await fetch(t,c);if(d.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=Bl(d);try{if(await Vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new Fl;(o=this.onerror)==null||o.call(this,p);return}}catch(f){(s=this.onerror)==null||s.call(this,f);return}return n(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new Ne({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(a=this.onerror)==null||a.call(this,p);return}}catch(u){(l=this.onerror)==null||l.call(this,u);return}};await n()}},e4=class{constructor({url:e,headers:t,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Ko};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return jC(t,`ai-sdk/${HC}`,MC())}async start(){if(this.abortController)throw new Ne({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const i=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:i,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const t=async(n=!1)=>{var i,r,o,s,a,l,u;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(i=this.abortController)==null?void 0:i.signal},f=await fetch(this.url,d),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Bl(f);try{if(await Vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Fl}catch(v){throw(r=this.onerror)==null||r.call(this,v),v}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const v=await f.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${v}`;f.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const w=new Ne({message:y});throw(o=this.onerror)==null||o.call(this,w),w}const m=f.headers.get("content-type")||"";if(m.includes("application/json")){const v=await f.json(),y=Array.isArray(v)?v.map(w=>As.parse(w)):[As.parse(v)];for(const w of y)(s=this.onmessage)==null||s.call(this,w);return}if(m.includes("text/event-stream")){if(!f.body){const S=new Ne({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(a=this.onerror)==null||a.call(this,S),S}const y=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Gs).getReader();(async()=>{var S,b,C;try{for(;;){const{done:_,value:k}=await y.read();if(_)return;const{event:R,data:M}=k;if(R==="message")try{const U=As.parse(JSON.parse(M));(S=this.onmessage)==null||S.call(this,U)}catch(U){const z=new Ne({message:"MCP HTTP Transport Error: Failed to parse message",cause:U});(b=this.onerror)==null||b.call(this,z)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(C=this.onerror)==null||C.call(this,_)}})();return}const h=new Ne({message:`MCP HTTP Transport Error: Unexpected content type: ${m}`});throw(l=this.onerror)==null||l.call(this,h),h}catch(c){throw(u=this.onerror)==null||u.call(this,c),c}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:i}=this.reconnectionOptions;return Math.min(t*Math.pow(n,e),i)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Ne({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var i;(i=this.abortController)!=null&&i.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,i,r,o,s,a;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const u=await fetch(this.url.href,{method:"GET",headers:l,signal:(n=this.abortController)==null?void 0:n.signal}),c=u.headers.get("mcp-session-id");if(c&&(this.sessionId=c),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Bl(u);try{if(await Vl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Fl;(i=this.onerror)==null||i.call(this,h);return}}catch(m){(r=this.onerror)==null||r.call(this,m);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const m=new Ne({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(o=this.onerror)==null||o.call(this,m);return}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Gs).getReader(),p=async()=>{var m,h,v,y;try{for(;;){const{done:w,value:S}=await f.read();if(w)return;const{event:b,data:C,id:_}=S;if(_&&(this.lastInboundEventId=_),b==="message")try{const k=As.parse(JSON.parse(C));(m=this.onmessage)==null||m.call(this,k)}catch(k){const R=new Ne({message:"MCP HTTP Transport Error: Failed to parse message",cause:k});(h=this.onerror)==null||h.call(this,R)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(v=this.onerror)==null||v.call(this,w),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(s=this.onerror)==null||s.call(this,l),(a=this.abortController)!=null&&a.signal.aborted||this.scheduleInboundSseReconnection()}}};function t4(e){switch(e.type){case"sse":return new Q2(e);case"http":return new e4(e);default:throw new Ne({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function n4(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var r4="1.0.0";async function i4(e){const t=new o4(e);return await t.init(),t}var o4=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:n=r4,onUncaughtError:i,capabilities:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=r??{},n4(e)?this.transport=e:this.transport=t4(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new Ne({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:t,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Ko,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:a2});if(e===void 0)throw new Ne({message:"Server sent invalid initialize result"});if(!i2.includes(e.protocolVersion))throw new Ne({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ne({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ne({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ne({message:"Server does not support prompts"});break;default:throw new Ne({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((i,r)=>{if(this.isClosed)return r(new Ne({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const o=n?.signal;o?.throwIfAborted();const s=this.requestMessageId++,a={...e,jsonrpc:"2.0",id:s},l=()=>{this.responseHandlers.delete(s)};this.responseHandlers.set(s,u=>{if(o?.aborted)return r(new Ne({message:"Request was aborted",cause:o.reason}));if(u instanceof Error)return r(u);try{const c=t.parse(u.result);i(c)}catch(c){const d=new Ne({message:"Failed to parse server response",cause:c});r(d)}}),this.transport.send(a).catch(u=>{l(),r(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:l2,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:f2,options:{signal:n?.abortSignal}})}catch(i){throw i}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:d2,options:t})}catch(n){throw n}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:m2,options:t})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:h2,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:y2,options:t})}catch(n){throw n}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:_2,options:n})}catch(i){throw i}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const i=await this.listTools();for(const{name:r,description:o,inputSchema:s}of i.tools){if(e!=="automatic"&&!(r in e))continue;const a=this,l=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),a.callTool({name:r,args:c,options:d})},u=e==="automatic"?WU({description:o,inputSchema:KU({...s,properties:(t=s.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:o,inputSchema:e[r].inputSchema,execute:l};n[r]=u}return n}catch(i){throw i}}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==vb)throw new Ne({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=vb.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const n=await this.elicitationRequestHandler(t.data),i=x2.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:i})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Ne({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new Ne({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new Ne({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},tu=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},s4={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},a4=class{#e=s4;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},bi=new a4;function u4(e){setTimeout(e,0)}var Ri=typeof window>"u"||"Deno"in globalThis;function Bt(){}function l4(e,t){return typeof e=="function"?e(t):e}function qp(e){return typeof e=="number"&&e>=0&&e!==1/0}function XC(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Fr(e,t){return typeof e=="function"?e(t):e}function vn(e,t){return typeof e=="function"?e(t):e}function wb(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:o,queryKey:s,stale:a}=e;if(s){if(i){if(t.queryHash!==Vg(s,t.options))return!1}else if(!ea(t.queryKey,s))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||o&&!o(t))}function xb(e,t){const{exact:n,status:i,predicate:r,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(Qs(t.options.mutationKey)!==Qs(o))return!1}else if(!ea(t.options.mutationKey,o))return!1}return!(i&&t.state.status!==i||r&&!r(t))}function Vg(e,t){return(t?.queryKeyHashFn||Qs)(e)}function Qs(e){return JSON.stringify(e,(t,n)=>Gp(n)?Object.keys(n).sort().reduce((i,r)=>(i[r]=n[r],i),{}):n)}function ea(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ea(e[n],t[n])):!1}var c4=Object.prototype.hasOwnProperty;function Zp(e,t){if(e===t)return e;const n=Sb(e)&&Sb(t);if(!n&&!(Gp(e)&&Gp(t)))return t;const r=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),s=o.length,a=n?new Array(s):{};let l=0;for(let u=0;u<s;u++){const c=n?u:o[u],d=e[c],f=t[c];if(d===f){a[c]=d,(n?u<r:c4.call(e,c))&&l++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){a[c]=f;continue}const p=Zp(d,f);a[c]=p,p===d&&l++}return r===s&&l===r?e:a}function Hp(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Sb(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Gp(e){if(!Eb(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Eb(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Eb(e){return Object.prototype.toString.call(e)==="[object Object]"}function d4(e){return new Promise(t=>{bi.setTimeout(t,e)})}function Wp(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Zp(e,t)}catch(i){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${i}`),i}return Zp(e,t)}return t}function f4(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function p4(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var ql=Symbol();function QC(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===ql&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ql?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function h4(e,t){return typeof e=="function"?e(...t):!!e}var m4=class extends tu{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!Ri&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},qg=new m4;function Jp(){let e,t;const n=new Promise((r,o)=>{e=r,t=o});n.status="pending",n.catch(()=>{});function i(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{i({status:"fulfilled",value:r}),e(r)},n.reject=r=>{i({status:"rejected",reason:r}),t(r)},n}var g4=u4;function v4(){let e=[],t=0,n=a=>{a()},i=a=>{a()},r=g4;const o=a=>{t?e.push(a):r(()=>{n(a)})},s=()=>{const a=e;e=[],a.length&&r(()=>{i(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||s()}return l},batchCalls:a=>(...l)=>{o(()=>{a(...l)})},schedule:o,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{i=a},setScheduler:a=>{r=a}}}var yt=v4(),y4=class extends tu{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!Ri&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},Zl=new y4;function b4(e){return Math.min(1e3*2**e,3e4)}function eA(e){return(e??"online")==="online"?Zl.isOnline():!0}var Kp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function tA(e){let t=!1,n=0,i;const r=Jp(),o=()=>r.status!=="pending",s=h=>{if(!o()){const v=new Kp(h);f(v),e.onCancel?.(v)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>qg.isFocused()&&(e.networkMode==="always"||Zl.isOnline())&&e.canRun(),c=()=>eA(e.networkMode)&&e.canRun(),d=h=>{o()||(i?.(),r.resolve(h))},f=h=>{o()||(i?.(),r.reject(h))},p=()=>new Promise(h=>{i=v=>{(o()||u())&&h(v)},e.onPause?.()}).then(()=>{i=void 0,o()||e.onContinue?.()}),m=()=>{if(o())return;let h;const v=n===0?e.initialPromise:void 0;try{h=v??e.fn()}catch(y){h=Promise.reject(y)}Promise.resolve(h).then(d).catch(y=>{if(o())return;const w=e.retry??(Ri?0:3),S=e.retryDelay??b4,b=typeof S=="function"?S(n,y):S,C=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,y);if(t||!C){f(y);return}n++,e.onFail?.(n,y),d4(b).then(()=>u()?void 0:p()).then(()=>{t?f(y):m()})})};return{promise:r,status:()=>r.status,cancel:s,continue:()=>(i?.(),r),cancelRetry:a,continueRetry:l,canStart:c,start:()=>(c()?m():p().then(m),r)}}var nA=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),qp(this.gcTime)&&(this.#e=bi.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ri?1/0:300*1e3))}clearGcTimeout(){this.#e&&(bi.clearTimeout(this.#e),this.#e=void 0)}},_4=class extends nA{#e;#t;#n;#i;#r;#a;#s;constructor(e){super(),this.#s=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Tb(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Tb(this.options);t.data!==void 0&&(this.setState(Ib(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Wp(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#o({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Bt).catch(Bt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>vn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ql||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Fr(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!XC(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#s?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#o({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const n=new AbortController,i=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},r=()=>{const a=QC(this.options,t),u=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return i(c),c})();return this.#s=!1,this.options.persister?this.options.persister(a,u,this):a(u)},s=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return i(a),a})();this.options.behavior?.onFetch(s,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#o({type:"fetch",meta:s.fetchOptions?.meta}),this.#r=tA({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:a=>{a instanceof Kp&&a.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(a,l)=>{this.#o({type:"failed",failureCount:a,error:l})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0});try{const a=await this.#r.start();if(a===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(a),this.#n.config.onSuccess?.(a,this),this.#n.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof Kp){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#o({type:"error",error:a}),this.#n.config.onError?.(a,this),this.#n.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#o(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...rA(n.data,this.options),fetchMeta:e.meta??null};case"success":const i={...n,...Ib(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?i:void 0,i;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),yt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function rA(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:eA(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ib(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Tb(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,i=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var w4=class extends tu{constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.#s=Jp(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#i=void 0;#r;#a;#s;#o;#m;#f;#p;#l;#c;#u;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),kb(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof vn(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),t._defaulted&&!Hp(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const i=this.hasListeners();i&&Cb(this.#t,n,this.options,t)&&this.#d(),this.updateResult(),i&&(this.#t!==n||vn(this.options.enabled,this.#t)!==vn(t.enabled,this.#t)||Fr(this.options.staleTime,this.#t)!==Fr(t.staleTime,this.#t))&&this.#g();const r=this.#v();i&&(this.#t!==n||vn(this.options.enabled,this.#t)!==vn(t.enabled,this.#t)||r!==this.#u)&&this.#y(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return S4(this,n)&&(this.#i=n,this.#a=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#i}trackResult(e,t){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),t?.(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#s.status==="pending"&&this.#s.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,i))})}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#i))}#d(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Bt)),t}#g(){this.#_();const e=Fr(this.options.staleTime,this.#t);if(Ri||this.#i.isStale||!qp(e))return;const n=XC(this.#i.dataUpdatedAt,e)+1;this.#l=bi.setTimeout(()=>{this.#i.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#u=e,!(Ri||vn(this.options.enabled,this.#t)===!1||!qp(this.#u)||this.#u===0)&&(this.#c=bi.setInterval(()=>{(this.options.refetchIntervalInBackground||qg.isFocused())&&this.#d()},this.#u))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#l&&(bi.clearTimeout(this.#l),this.#l=void 0)}#w(){this.#c&&(bi.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const n=this.#t,i=this.options,r=this.#i,o=this.#r,s=this.#a,l=e!==n?e.state:this.#n,{state:u}=e;let c={...u},d=!1,f;if(t._optimisticResults){const R=this.hasListeners(),M=!R&&kb(e,t),U=R&&Cb(e,n,t,i);(M||U)&&(c={...c,...rA(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:h}=c;f=c.data;let v=!1;if(t.placeholderData!==void 0&&f===void 0&&h==="pending"){let R;r?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(R=r.data,v=!0):R=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,R!==void 0&&(h="success",f=Wp(r?.data,R,t),d=!0)}if(t.select&&f!==void 0&&!v)if(r&&f===o?.data&&t.select===this.#m)f=this.#f;else try{this.#m=t.select,f=t.select(f),f=Wp(r?.data,f,t),this.#f=f,this.#o=null}catch(R){this.#o=R}this.#o&&(p=this.#o,f=this.#f,m=Date.now(),h="error");const y=c.fetchStatus==="fetching",w=h==="pending",S=h==="error",b=w&&y,C=f!==void 0,k={status:h,fetchStatus:c.fetchStatus,isPending:w,isSuccess:h==="success",isError:S,isInitialLoading:b,isLoading:b,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>l.dataUpdateCount||c.errorUpdateCount>l.errorUpdateCount,isFetching:y,isRefetching:y&&!w,isLoadingError:S&&!C,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:S&&C,isStale:Zg(e,t),refetch:this.refetch,promise:this.#s,isEnabled:vn(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=z=>{k.status==="error"?z.reject(k.error):k.data!==void 0&&z.resolve(k.data)},M=()=>{const z=this.#s=k.promise=Jp();R(z)},U=this.#s;switch(U.status){case"pending":e.queryHash===n.queryHash&&R(U);break;case"fulfilled":(k.status==="error"||k.data!==U.value)&&M();break;case"rejected":(k.status!=="error"||k.error!==U.reason)&&M();break}}return k}updateResult(){const e=this.#i,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#a=this.options,this.#r.data!==void 0&&(this.#p=this.#t),Hp(t,e))return;this.#i=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#h.size)return!0;const o=new Set(r??this.#h);return this.options.throwOnError&&o.add("error"),Object.keys(this.#i).some(s=>{const a=s;return this.#i[a]!==e[a]&&o.has(a)})};this.#S({listeners:n()})}#x(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#S(e){yt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#i)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function x4(e,t){return vn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function kb(e,t){return x4(e,t)||e.state.data!==void 0&&Yp(e,t,t.refetchOnMount)}function Yp(e,t,n){if(vn(t.enabled,e)!==!1&&Fr(t.staleTime,e)!=="static"){const i=typeof n=="function"?n(e):n;return i==="always"||i!==!1&&Zg(e,t)}return!1}function Cb(e,t,n,i){return(e!==t||vn(i.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Zg(e,n)}function Zg(e,t){return vn(t.enabled,e)!==!1&&e.isStaleByTime(Fr(t.staleTime,e))}function S4(e,t){return!Hp(e.getCurrentResult(),t)}function Ab(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=QC(t.options,t.fetchOptions),p=async(m,h,v)=>{if(c)return Promise.reject();if(h==null&&m.pages.length)return Promise.resolve(m);const w=(()=>{const _={client:t.client,queryKey:t.queryKey,pageParam:h,direction:v?"backward":"forward",meta:t.options.meta};return d(_),_})(),S=await f(w),{maxPages:b}=t.options,C=v?p4:f4;return{pages:C(m.pages,S,b),pageParams:C(m.pageParams,h,b)}};if(r&&o.length){const m=r==="backward",h=m?E4:Rb,v={pages:o,pageParams:s},y=h(i,v);a=await p(v,y,m)}else{const m=e??o.length;do{const h=l===0?s[0]??i.initialPageParam:Rb(i,a);if(l>0&&h==null)break;a=await p(a,h),l++}while(l<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function Rb(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function E4(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var I4=class extends nA{#e;#t;#n;#i;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||T4(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#i?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#i=tA({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,s)=>{this.#r({type:"failed",failureCount:o,error:s})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const i=this.state.status==="pending",r=!this.#i.canStart();try{if(i)t();else{this.#r({type:"pending",variables:e,isPaused:r}),await this.#n.config.onMutate?.(e,this,n);const s=await this.options.onMutate?.(e,n);s!==this.state.context&&this.#r({type:"pending",context:s,variables:e,isPaused:r})}const o=await this.#i.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#r({type:"success",data:o}),o}catch(o){try{throw await this.#n.config.onError?.(o,e,this.state.context,this,n),await this.options.onError?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(void 0,o,e,this.state.context,n),o}finally{this.#r({type:"error",error:o})}}finally{this.#n.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),yt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function T4(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var k4=class extends tu{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const i=new I4({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#e.add(e);const t=Du(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Du(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Du(e);if(typeof t=="string"){const i=this.#t.get(t)?.find(r=>r.state.status==="pending");return!i||i===e}else return!0}runNext(e){const t=Du(e);return typeof t=="string"?this.#t.get(t)?.find(i=>i!==e&&i.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){yt.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>xb(t,n))}findAll(e={}){return this.getAll().filter(t=>xb(e,t))}notify(e){yt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return yt.batch(()=>Promise.all(e.map(t=>t.continue().catch(Bt))))}};function Du(e){return e.options.scope?.id}var C4=class extends tu{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const i=t.queryKey,r=t.queryHash??Vg(i,t);let o=this.get(r);return o||(o=new _4({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){yt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>wb(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>wb(e,n)):t}notify(e){yt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){yt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){yt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},A4=class{#e;#t;#n;#i;#r;#a;#s;#o;constructor(e={}){this.#e=e.queryCache||new C4,this.#t=e.mutationCache||new k4,this.#n=e.defaultOptions||{},this.#i=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#s=qg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=Zl.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#s?.(),this.#s=void 0,this.#o?.(),this.#o=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),i=n.state.data;return i===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Fr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const i=n.data;return[t,i]})}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(i.queryHash)?.state.data,s=l4(t,o);if(s!==void 0)return this.#e.build(this,i).setData(s,{...n,manual:!0})}setQueriesData(e,t,n){return yt.batch(()=>this.#e.findAll(e).map(({queryKey:i})=>[i,this.setQueryData(i,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;yt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return yt.batch(()=>(n.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},i=yt.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(i).then(Bt).catch(Bt)}invalidateQueries(e,t={}){return yt.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=yt.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let o=r.fetch(void 0,n);return n.throwOnError||(o=o.catch(Bt)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(i).then(Bt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Fr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Bt).catch(Bt)}fetchInfiniteQuery(e){return e.behavior=Ab(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Bt).catch(Bt)}ensureInfiniteQueryData(e){return e.behavior=Ab(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Zl.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#i.set(Qs(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(i=>{ea(e,i.queryKey)&&Object.assign(n,i.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(Qs(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(i=>{ea(e,i.mutationKey)&&Object.assign(n,i.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Vg(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===ql&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},iA=x.createContext(void 0),oA=e=>{const t=x.useContext(iA);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},R4=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),g.jsx(iA.Provider,{value:e,children:t})),sA=x.createContext(!1),$4=()=>x.useContext(sA);sA.Provider;function O4(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var N4=x.createContext(O4()),P4=()=>x.useContext(N4),M4=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},j4=e=>{x.useEffect(()=>{e.clearReset()},[e])},D4=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&e.data===void 0||h4(n,[e.error,i])),z4=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),i=e.staleTime;e.staleTime=typeof i=="function"?(...r)=>n(i(...r)):n(i),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},L4=(e,t)=>e.isLoading&&e.isFetching&&!t,U4=(e,t)=>e?.suspense&&t.isPending,$b=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function F4(e,t,n){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const i=$4(),r=P4(),o=oA(),s=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(s),process.env.NODE_ENV!=="production"&&(s.queryFn||console.error(`[${s.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),s._optimisticResults=i?"isRestoring":"optimistic",z4(s),M4(s,r),j4(r);const a=!o.getQueryCache().get(s.queryHash),[l]=x.useState(()=>new t(o,s)),u=l.getOptimisticResult(s),c=!i&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(d=>{const f=c?l.subscribe(yt.batchCalls(d)):Bt;return l.updateResult(),f},[l,c]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(s)},[s,l]),U4(s,u))throw $b(s,l,r);if(D4({result:u,errorResetBoundary:r,throwOnError:s.throwOnError,query:o.getQueryCache().get(s.queryHash),suspense:s.suspense}))throw u.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(s,u),s.experimental_prefetchInRender&&!Ri&&L4(u,i)&&(a?$b(s,l,r):o.getQueryCache().get(s.queryHash)?.promise)?.catch(Bt).finally(()=>{l.updateResult()}),s.notifyOnChangeProps?u:l.trackResult(u)}function aA(e,t){return F4(e,w4)}function B4({auth:e,mcp:t,environment:n}){const i=Object.entries(e.headers??{}).map((o,s)=>`${o}:${s}`);return aA({queryKey:["mcpTools",t,...i],queryFn:async()=>(O.assert(!e.isLoading,"No auth found"),O.assert(t,"No MCP URL found"),await(await i4({name:"gram-elements-mcp-client",transport:{type:"http",url:t,headers:{...V4(n??{}),...e.headers}}})).tools()),enabled:!e.isLoading&&!!t,staleTime:1/0,gcTime:1/0})}const Ob="MCP-";function V4(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[n,i])=>{const r=n.replace(/_/g,"-"),o=r.startsWith(Ob)?r:`${Ob}${r}`;return t[o]=i,t},{})}const uA=()=>{const e=I.useContext(O.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e};function q4(e){return(e.api?.url||""||"https://app.getgram.ai").replace(/\/+$/,"")}const _d={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},hr=console,co={};Object.keys(_d).forEach(e=>{co[e]=hr[e]});const ms="Datadog Browser SDK:",he={debug:co.debug.bind(hr,ms),log:co.log.bind(hr,ms),info:co.info.bind(hr,ms),warn:co.warn.bind(hr,ms),error:co.error.bind(hr,ms)},wd="https://docs.datadoghq.com",Z4=`${wd}/real_user_monitoring/browser/troubleshooting`,Hg="More details:";function lA(e,t){return(...n)=>{try{return e(...n)}catch(i){he.error(t,i)}}}function _i(e){return e!==0&&Math.random()*100<=e}function Ns(e,t){return+e.toFixed(t)}function H4(e){return nu(e)&&e>=0&&e<=100}function nu(e){return typeof e=="number"}function ta(e){return{...e}}function Hl(e,t){return Object.keys(e).some(n=>e[n]===t)}function ri(e){return Object.keys(e).length===0}function cA(e,t){const n={};for(const i of Object.keys(e))n[i]=t(e[i]);return n}function fn(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}const tr=fn(),xd="WorkerGlobalScope"in tr;function Wr(e,t){const n=fn();let i;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(i=e[n.Zone.__symbol__(t)]),i||(i=e[t]),i}let Xp,dA=!1;function G4(e){Xp=e}function W4(e){dA=e}function ye(e){return function(){return Br(e,this,arguments)}}function Br(e,t,n){try{return e.apply(t,n)}catch(i){wr(i)}}function wr(e){if(Qp(e),Xp)try{Xp(e)}catch(t){Qp(t)}}function Qp(...e){dA&&he.error("[MONITOR]",...e)}function bt(e,t){return Wr(fn(),"setTimeout")(ye(e),t)}function Yt(e){Wr(fn(),"clearTimeout")(e)}function Yo(e,t){return Wr(fn(),"setInterval")(ye(e),t)}function Sd(e){Wr(fn(),"clearInterval")(e)}function Nb(e){var t;const n=(t=tr.queueMicrotask)===null||t===void 0?void 0:t.bind(tr);typeof n=="function"?n(ye(e)):Promise.resolve().then(ye(e))}class Ie{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.addObserver(t),{unsubscribe:()=>this.removeObserver(t)}}notify(t){this.observers.forEach(n=>n(t))}addObserver(t){this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0)}removeObserver(t){this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}function fA(...e){return new Ie(t=>{const n=e.map(i=>i.subscribe(r=>t.notify(r)));return()=>n.forEach(i=>i.unsubscribe())})}class pA extends Ie{constructor(t){super(),this.maxBufferSize=t,this.buffer=[]}notify(t){this.buffer.push(t),this.buffer.length>this.maxBufferSize&&this.buffer.shift(),super.notify(t)}subscribe(t){let n=!1;const i={unsubscribe:()=>{n=!0,this.removeObserver(t)}};return Nb(()=>{for(const r of this.buffer){if(n)return;t(r)}n||this.addObserver(t)}),i}unbuffer(){Nb(()=>{this.maxBufferSize=this.buffer.length=0})}}const _t=1e3,Ut=60*_t,hA=60*Ut,J4=24*hA,mA=365*J4;function ru(e){return{relative:e,timeStamp:Y4(e)}}function K4(e){return{relative:Wg(e),timeStamp:e}}function Y4(e){const t=zt()-performance.now();return t>iu()?Math.round(Xo(t,e)):X4(e)}function gA(){return Math.round(zt()-Xo(iu(),performance.now()))}function be(e){return nu(e)?Ns(e*1e6,0):e}function zt(){return new Date().getTime()}function ht(){return zt()}function rn(){return performance.now()}function ct(){return{relative:rn(),timeStamp:ht()}}function Gg(){return{relative:0,timeStamp:iu()}}function tt(e,t){return t-e}function Xo(e,t){return e+t}function Wg(e){return e-iu()}function X4(e){return Math.round(Xo(iu(),e))}function Q4(e){return e<mA}let vf;function iu(){var e,t;return vf===void 0&&(vf=(t=(e=performance.timing)===null||e===void 0?void 0:e.navigationStart)!==null&&t!==void 0?t:performance.timeOrigin),vf}function ou(e,t,n){const i=n&&n.leading!==void 0?n.leading:!0,r=n&&n.trailing!==void 0?n.trailing:!0;let o=!1,s,a;return{throttled:(...l)=>{if(o){s=l;return}i?e(...l):s=l,o=!0,a=bt(()=>{r&&s&&e(...s),o=!1,s=void 0},t)},cancel:()=>{Yt(a),o=!1,s=void 0}}}function $e(){}function Tt(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,Tt)}const Lo=/([\w-]+)\s*=\s*([^;]+)/g;function na(e,t){for(Lo.lastIndex=0;;){const n=Lo.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function eF(e){const t=new Map;for(Lo.lastIndex=0;;){const n=Lo.exec(e);if(n){const i=n[1],r=n[2];t.has(i)?t.get(i).push(r):t.set(i,[r])}else break}return t}function tF(e){const t=new Map;for(Lo.lastIndex=0;;){const n=Lo.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Jg(e,t,n=""){const i=e.charCodeAt(t-1),o=i>=55296&&i<=56319?t+1:t;return e.length<=o?e:`${e.slice(0,o)}${n}`}function nF(){return vA()===0}function rF(){return vA()===1}let zu;function vA(){return zu??(zu=iF())}function iF(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function Kg(e){return su(e,location.href).href}function oF(e){try{return!!su(e)}catch{return!1}}function sF(e){const t=su(e).pathname;return t[0]==="/"?t:`/${t}`}function su(e,t){const{URL:n}=aF();try{return t!==void 0?new n(e,t):new n(e)}catch(i){throw new Error(`Failed to construct URL: ${String(i)}`)}}let yf;function aF(){if(!yf){let e,t;try{e=document.createElement("iframe"),e.style.display="none",document.body.appendChild(e),t=e.contentWindow}catch{t=tr}yf={URL:t.URL},e?.remove()}return yf}function Ed(e,t,n=0,i){const r=new Date;r.setTime(r.getTime()+n);const o=`expires=${r.toUTCString()}`,s=i&&i.crossSite?"none":"strict",a=i&&i.domain?`;domain=${i.domain}`:"",l=i&&i.secure?";secure":"",u=i&&i.partitioned?";partitioned":"";document.cookie=`${e}=${t};${o};path=/;samesite=${s}${a}${l}${u}`}function Id(e){return na(document.cookie,e)}function uF(e){return eF(document.cookie).get(e)||[]}let bf;function Lr(e){return bf||(bf=tF(document.cookie)),bf.get(e)}function yA(e,t){Ed(e,"",0,t)}function lF(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${Tt()}`,n="test";Ed(t,n,Ut,e);const i=Id(t)===n;return yA(t,e),i}catch(t){return he.error(t),!1}}let _f;function bA(e=location.hostname,t=document.referrer){if(_f===void 0){const n=cF(e,t);if(n){const i=`dd_site_test_${Tt()}`,r="test",o=n.split(".");let s=o.pop();for(;o.length&&!Id(i);)s=`${o.pop()}.${s}`,Ed(i,r,_t,{domain:s});yA(i,{domain:s}),_f=s}}return _f}function cF(e,t){try{return e||su(t).hostname}catch{}}const xr="_dd_s";function _A(e,t){for(let n=e.length-1;n>=0;n-=1){const i=e[n];if(t(i,n,e))return i}}function wA(e){return Object.values(e)}function Td(e){return Object.entries(e)}const Li=4*hA,xA=15*Ut,dF=mA,SA="0",Uo={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},EA=/^([a-zA-Z]+)=([a-z0-9-]+)$/,Yg="&";function fF(e){return!!e&&(e.indexOf(Yg)!==-1||EA.test(e))}const pF="1";function pi(e,t){const n={isExpired:pF};return t.trackAnonymousUser&&e?.anonymousId&&(n.anonymousId=e?.anonymousId),n}function cl(e){return ri(e)}function IA(e){return!cl(e)}function Ps(e){return e.isExpired!==void 0||!hF(e)}function hF(e){return(e.created===void 0||zt()-Number(e.created)<Li)&&(e.expire===void 0||zt()<Number(e.expire))}function TA(e){e.expire=String(zt()+xA)}function eh(e){return Td(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(Yg)}function kd(e){const t={};return fF(e)&&e.split(Yg).forEach(n=>{const i=EA.exec(n);if(i!==null){const[,r,o]=i;r==="aid"?t.anonymousId=o:t[r]=o}}),t}const mF="_dd",gF="_dd_r",vF="_dd_l",yF="rum",bF="logs";function _F(e){if(!Lr(xr)){const n=Lr(mF),i=Lr(gF),r=Lr(vF),o={};n&&(o.id=n),r&&/^[01]$/.test(r)&&(o[bF]=r),i&&/^[012]$/.test(i)&&(o[yF]=i),IA(o)&&(TA(o),e.persistSession(o))}}const wF=0;function Pb(e){const t=SF(e);return t&&lF(t)?{type:Uo.COOKIE,cookieOptions:t}:void 0}function xF(e,t){const n={isLockEnabled:nF(),persistSession:i=>Mb(t,e,i,xA),retrieveSession:()=>kA(t,e),expireSession:i=>Mb(t,e,pi(i,e),Li)};return _F(n),n}function Mb(e,t,n,i){let r=eh(n);t.betaEncodeCookieOptions&&(r=eh({...n,...ri(n)?{}:{c:CA(e)}})),Ed(xr,r,t.trackAnonymousUser?dF:i,e)}function kA(e,t){if(t.betaEncodeCookieOptions)return EF(e);const n=Id(xr);return kd(n)}function SF(e){const t={};if(t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains){const n=bA();if(!n)return;t.domain=n}return t}function CA(e){const t=e.domain?e.domain.split(".").length-1:0;let n=0;return n|=wF<<5,n|=t<<1,n|=e.crossSite?1:0,n.toString(16)}function EF(e){const t=uF(xr),n=CA(e);let i;for(const r of t.reverse())if(i=kd(r),i.c===n)break;return i==null||delete i.c,i??{}}const IF="_dd_test_";function jb(){try{const e=Tt(),t=`${IF}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:Uo.LOCAL_STORAGE}:void 0}catch{return}}function TF(e){return{isLockEnabled:!1,persistSession:AA,retrieveSession:RA,expireSession:t=>kF(t,e)}}function AA(e){localStorage.setItem(xr,eh(e))}function RA(){const e=localStorage.getItem(xr);return kd(e)}function kF(e,t){AA(pi(e,t))}const CF=10,AF=100,RF=_t,$A="--",OA=[];let dl;function hi(e,t,n=0){var i;const{isLockEnabled:r,persistSession:o,expireSession:s}=t,a=f=>o({...f,lock:u}),l=()=>{const{lock:f,...p}=t.retrieveSession();return{session:p,lock:f&&!OF(f)?f:void 0}};if(dl||(dl=e),e!==dl){OA.push(e);return}if(r&&n>=AF){Db(t);return}let u,c=l();if(r){if(c.lock){Lu(e,t,n);return}if(u=$F(),a(c.session),c=l(),c.lock!==u){Lu(e,t,n);return}}let d=e.process(c.session);if(r&&(c=l(),c.lock!==u)){Lu(e,t,n);return}if(d&&(Ps(d)?s(d):(TA(d),r?a(d):o(d))),r&&!(d&&Ps(d))){if(c=l(),c.lock!==u){Lu(e,t,n);return}o(c.session),d=c.session}(i=e.after)===null||i===void 0||i.call(e,d||c.session),Db(t)}function Lu(e,t,n){bt(()=>{hi(e,t,n+1)},CF)}function Db(e){dl=void 0;const t=OA.shift();t&&hi(t,e)}function $F(){return Tt()+$A+ht()}function OF(e){const[,t]=e.split($A);return!t||tt(Number(t),ht())>RF}const zb=_t;function NF(e){switch(e.sessionPersistence){case Uo.COOKIE:return Pb(e);case Uo.LOCAL_STORAGE:return jb();case void 0:{let t=Pb(e);return!t&&e.allowFallbackToLocalStorage&&(t=jb()),t}default:he.error(`Invalid session persistence '${String(e.sessionPersistence)}'`)}}function PF(e,t){return e.type===Uo.COOKIE?xF(t,e.cookieOptions):TF(t)}function MF(e,t,n,i,r=PF(e,t)){const o=new Ie,s=new Ie,a=new Ie,l=Yo(p,zb);let u;h();const{throttled:c,cancel:d}=ou(()=>{hi({process:_=>{if(cl(_))return;const k=m(_);return v(k),k},after:_=>{IA(_)&&!y()&&b(_),u=_}},r)},zb);function f(){hi({process:_=>y()?m(_):void 0},r)}function p(){const _=r.retrieveSession();Ps(_)?hi({process:k=>Ps(k)?pi(k,t):void 0,after:m},r):m(_)}function m(_){return Ps(_)&&(_=pi(_,t)),y()&&(w(_)?S():(a.notify({previousState:u,newState:_}),u=_)),_}function h(){hi({process:_=>{if(cl(_))return _.anonymousId=Tt(),pi(_,t)},after:_=>{u=_}},r)}function v(_){if(cl(_))return!1;const k=i(_[n]);_[n]=k,delete _.isExpired,k!==SA&&!_.id&&(_.id=Tt(),_.created=String(zt()))}function y(){return u?.[n]!==void 0}function w(_){return u.id!==_.id||u[n]!==_[n]}function S(){u=pi(u,t),s.notify()}function b(_){u=_,o.notify()}function C(_){hi({process:k=>({...k,..._}),after:m},r)}return{expandOrRenewSession:c,expandSession:f,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:a,restartSession:h,expire:_=>{d(),_===!1&&u&&delete u.anonymousId,r.expireSession(u),m(pi(u,t))},stop:()=>{Sd(l)},updateSessionState:C}}const th={GRANTED:"granted",NOT_GRANTED:"not-granted"};function jF(e){const t=new Ie;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===th.GRANTED},observable:t}}function Ui(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function ra(e){const t=Ui(e);return t==="string"||t==="function"||e instanceof RegExp}function Cd(e,t,n=!1){return e.some(i=>{try{if(typeof i=="function")return i(t);if(i instanceof RegExp)return i.test(t);if(typeof i=="string")return n?t.startsWith(i):i===t}catch(r){he.error(r)}return!1})}const DF=["chrome-extension://","moz-extension://"];function Lb(e){return DF.some(t=>e.includes(t))}function zF(e,t=""){if(Lb(e))return!1;const i=t.split(`
|
|
30
|
+
`).filter(r=>{const o=r.trim();return o.length&&/^at\s+|@/.test(o)})[1]||"";return Lb(i)}const LF="Running the Browser SDK in a Web extension content script is forbidden unless the `allowedTrackingOrigins` option is provided.",UF="SDK initialized on a non-allowed domain.";function FF(e,t,n=typeof location<"u"?location.origin:""){const i=e.allowedTrackingOrigins;if(!i)return zF(n,t)?(he.error(LF),!1):!0;const r=Cd(i,n);return r||he.error(UF),r}const NA="datad0g.com",BF="dd0g-gov.com",wi="datadoghq.com",VF="datadoghq.eu",qF="ddog-gov.com",ZF="pci.browser-intake-datadoghq.com",HF=["ddsource","dd-api-key","dd-request-id"];function mi(e,t,n){const i=GF(e,t);return{build(r,o){const s=WF(e,t,r,o,n);return i(s)},trackType:t}}function GF(e,t){const n=`/api/v2/${t}`,i=e.proxy;if(typeof i=="string"){const o=Kg(i);return s=>`${o}?ddforward=${encodeURIComponent(`${n}?${s}`)}`}if(typeof i=="function")return o=>i({path:n,parameters:o});const r=PA(t,e);return o=>`https://${r}${n}?${o}`}function PA(e,t){const{site:n=wi,internalAnalyticsSubdomain:i}=t;if(e==="logs"&&t.usePciIntake&&n===wi)return ZF;if(i&&n===wi)return`${i}.${wi}`;if(n===BF)return`http-intake.logs.${n}`;const r=n.split("."),o=r.pop();return`browser-intake-${r.join("-")}.${o}`}function WF({clientToken:e,internalAnalyticsSubdomain:t,source:n="browser"},i,r,{retry:o,encoding:s},a=[]){const l=[`ddsource=${n}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.24.1")}`,"dd-evp-origin=browser",`dd-request-id=${Tt()}`].concat(a);return s&&l.push(`dd-evp-encoding=${s}`),i==="rum"&&(l.push(`batch_time=${ht()}`,`_dd.api=${r}`),o&&l.push(`_dd.retry_count=${o.count}`,`_dd.retry_after=${o.lastFailureStatus}`)),t&&l.reverse(),l.join("&")}function JF(e){const t=e.site||wi,n=KF(e.source),i=YF({...e,site:t,source:n});return{replica:XF({...e,site:t,source:n}),site:t,source:n,...i}}function KF(e){return e==="flutter"||e==="unity"?e:"browser"}function YF(e){return{logsEndpointBuilder:mi(e,"logs"),rumEndpointBuilder:mi(e,"rum"),profilingEndpointBuilder:mi(e,"profile"),sessionReplayEndpointBuilder:mi(e,"replay"),exposuresEndpointBuilder:mi(e,"exposures")}}function XF(e){if(!e.replica)return;const t={...e,site:wi,clientToken:e.replica.clientToken};return{logsEndpointBuilder:mi(t,"logs"),rumEndpointBuilder:mi(t,"rum",[`application.id=${e.replica.applicationId}`])}}function QF(e){return HF.every(t=>e.includes(t))}const ho={ALLOW:"allow",MASK:"mask",MASK_USER_INPUT:"mask-user-input",MASK_UNLESS_ALLOWLISTED:"mask-unless-allowlisted"},nh={ALL:"all",SAMPLED:"sampled"};function wf(e,t){return e!=null&&typeof e!="string"?(he.error(`${t} must be defined as a string`),!1):!0}function e6(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(he.error(`Site should be a valid Datadog site. ${Hg} ${wd}/getting_started/site/.`),!1):!0}function mo(e,t){return e!==void 0&&!H4(e)?(he.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function t6(e,t){var n,i,r,o,s,a,l,u,c,d;if(!e||!e.clientToken){he.error("Client Token is not configured, we will not send any data.");return}if(e.allowedTrackingOrigins!==void 0&&!Array.isArray(e.allowedTrackingOrigins)){he.error("Allowed Tracking Origins must be an array");return}if(!(!e6(e.site)||!mo(e.sessionSampleRate,"Session")||!mo(e.telemetrySampleRate,"Telemetry")||!mo(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!mo(e.telemetryUsageSampleRate,"Telemetry Usage")||!wf(e.version,"Version")||!wf(e.env,"Env")||!wf(e.service,"Service")||!FF(e,t??""))){if(e.trackingConsent!==void 0&&!Hl(th,e.trackingConsent)){he.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:e.beforeSend&&lA(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:xd?void 0:NF(e),sessionSampleRate:(n=e.sessionSampleRate)!==null&&n!==void 0?n:100,telemetrySampleRate:(i=e.telemetrySampleRate)!==null&&i!==void 0?i:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:(s=e.service)!==null&&s!==void 0?s:void 0,env:(a=e.env)!==null&&a!==void 0?a:void 0,version:(l=e.version)!==null&&l!==void 0?l:void 0,datacenter:(u=e.datacenter)!==null&&u!==void 0?u:void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(c=e.trackingConsent)!==null&&c!==void 0?c:th.GRANTED,trackAnonymousUser:(d=e.trackAnonymousUser)!==null&&d!==void 0?d:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,betaEncodeCookieOptions:!!e.betaEncodeCookieOptions,variant:e.variant,sdkVersion:e.sdkVersion,...JF(e)}}}function n6(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent,use_allowed_tracking_origins:Array.isArray(e.allowedTrackingOrigins),beta_encode_cookie_options:e.betaEncodeCookieOptions,source:e.source,sdk_version:e.sdkVersion,variant:e.variant}}var Jr;(function(e){e.TRACK_INTAKE_REQUESTS="track_intake_requests",e.USE_TREE_WALKER_FOR_ACTION_NAME="use_tree_walker_for_action_name",e.FEATURE_OPERATION_VITAL="feature_operation_vital",e.SHORT_SESSION_INVESTIGATION="short_session_investigation",e.AVOID_FETCH_KEEPALIVE="avoid_fetch_keepalive"})(Jr||(Jr={}));const Xg=new Set;function r6(e){Array.isArray(e)&&i6(e.filter(t=>Hl(Jr,t)))}function i6(e){e.forEach(t=>{Xg.add(t)})}function au(e){return Xg.has(e)}function o6(){return Xg}const Fo="?";function uu(e){var t,n;const i=[];let r=xf(e,"stack");const o=String(e);if(r&&r.startsWith(o)&&(r=r.slice(o.length)),r&&r.split(`
|
|
31
|
+
`).forEach(s=>{const a=u6(s)||c6(s)||f6(s)||m6(s);a&&(!a.func&&a.line&&(a.func=Fo),i.push(a))}),i.length>0&&b6()&&e instanceof Error){const s=[];let a=e;for(;(a=Object.getPrototypeOf(a))&&jA(a);){const l=((t=a.constructor)===null||t===void 0?void 0:t.name)||Fo;s.push(l)}for(let l=s.length-1;l>=0&&((n=i[0])===null||n===void 0?void 0:n.func)===s[l];l--)i.shift()}return{message:xf(e,"message"),name:xf(e,"name"),stack:i}}const MA="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",Bo="(?::(\\d+))",s6=new RegExp(`^\\s*at (.*?) ?\\(${MA}${Bo}?${Bo}?\\)?\\s*$`,"i"),a6=new RegExp(`\\((\\S*)${Bo}${Bo}\\)`);function u6(e){const t=s6.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,i=t[2]&&t[2].indexOf("eval")===0,r=a6.exec(t[2]);return i&&r&&(t[2]=r[1],t[3]=r[2],t[4]=r[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Fo,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const l6=new RegExp(`^\\s*at ?${MA}${Bo}?${Bo}??\\s*$`,"i");function c6(e){const t=l6.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Fo,line:t[2]?+t[2]:void 0,url:t[1]}}const d6=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function f6(e){const t=d6.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Fo,line:+t[3],url:t[2]}}const p6=/^\s*(.*?)(?:\((.*?)\))?(?:(?:(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle|\[wasm code\])(?::(\d+))?(?::(\d+))?)|@)\s*$/i,h6=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function m6(e){const t=p6.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,i=h6.exec(t[3]);return n&&i&&(t[3]=i[1],t[4]=i[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Fo,line:t[4]?+t[4]:void 0,url:t[3]}}function xf(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function g6(e,t,n,i){if(t===void 0)return;const{name:r,message:o}=y6(e);return{name:r,message:o,stack:[{url:t,column:i,line:n}]}}const v6=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function y6(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=v6.exec(e)),{name:t,message:n}}function jA(e){return String(e.constructor).startsWith("class ")}let Uu;function b6(){if(Uu!==void 0)return Uu;class e extends Error{constructor(){super(),this.name="Error"}}const[t,n]=[e,Error].map(i=>new i);return Uu=jA(Object.getPrototypeOf(t))&&n.stack!==t.stack,Uu}function Gl(e){const n=new Error(e);n.name="HandlingStack";let i;return Br(()=>{const r=uu(n);r.stack=r.stack.slice(2),i=lu(r)}),i}function lu(e){let t=DA(e);return e.stack.forEach(n=>{const i=n.func==="?"?"<anonymous>":n.func,r=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",o=n.line?`:${n.line}`:"",s=n.line&&n.column?`:${n.column}`:"";t+=`
|
|
32
|
+
at ${i}${r} @ ${n.url}${o}${s}`}),t}function DA(e){return`${e.name||"Error"}: ${e.message}`}function Mn(e,t,n,{computeHandlingStack:i}={}){let r=e[t];if(typeof r!="function")if(t in e&&t.startsWith("on"))r=$e;else return{stop:$e};let o=!1;const s=function(){if(o)return r.apply(this,arguments);const a=Array.from(arguments);let l;Br(n,null,[{target:this,parameters:a,onPostCall:c=>{l=c},handlingStack:i?Gl("instrumented method"):void 0}]);const u=r.apply(this,a);return l&&Br(l,null,[u]),u};return e[t]=s,{stop:()=>{o=!0,e[t]===s&&(e[t]=r)}}}function _6(e,t,n){const i=Object.getOwnPropertyDescriptor(e,t);if(!i||!i.set||!i.configurable)return{stop:$e};const r=$e;let o=(a,l)=>{bt(()=>{o!==r&&n(a,l)},0)};const s=function(a){i.set.call(this,a),o(this,a)};return Object.defineProperty(e,t,{set:s}),{stop:()=>{var a;((a=Object.getOwnPropertyDescriptor(e,t))===null||a===void 0?void 0:a.set)===s&&Object.defineProperty(e,t,i),o=r}}}const Fi=1024,zA=1024*Fi,w6=/[^\u0000-\u007F]/;function LA(e){return w6.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function UA(e){if(e.length===1)return e[0];const t=e.reduce((r,o)=>r+o.length,0),n=new Uint8Array(t);let i=0;for(const r of e)n.set(r,i),i+=r.length;return n}function Qo(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const i=go(Object.prototype),r=go(Array.prototype),o=go(Object.getPrototypeOf(e)),s=go(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{i(),r(),o(),s()}}function go(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):$e}const x6=220*Fi,S6="$",E6=3;function We(e,t=x6){const n=go(Object.prototype),i=go(Array.prototype),r=[],o=new WeakMap,s=Sf(e,S6,void 0,r,o),a=JSON.stringify(s);let l=a?a.length:0;if(l>t){Ef(t,"discarded",e);return}for(;r.length>0&&l<t;){const u=r.shift();let c=0;if(Array.isArray(u.source))for(let d=0;d<u.source.length;d++){const f=Sf(u.source[d],u.path,d,r,o);if(f!==void 0?l+=JSON.stringify(f).length:l+=4,l+=c,c=1,l>t){Ef(t,"truncated",e);break}u.target[d]=f}else for(const d in u.source)if(Object.prototype.hasOwnProperty.call(u.source,d)){const f=Sf(u.source[d],u.path,d,r,o);if(f!==void 0&&(l+=JSON.stringify(f).length+c+d.length+E6,c=1),l>t){Ef(t,"truncated",e);break}u.target[d]=f}}return n(),i(),s}function Sf(e,t,n,i,r){const o=k6(e);if(!o||typeof o!="object")return I6(o);const s=rh(o);if(s!=="[Object]"&&s!=="[Array]"&&s!=="[Error]")return s;const a=e;if(r.has(a))return`[Reference seen at ${r.get(a)}]`;const l=n!==void 0?`${t}.${n}`:t,u=Array.isArray(o)?[]:{};return r.set(a,l),i.push({source:o,target:u,path:l}),u}function I6(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function rh(e){try{if(e instanceof Event)return T6(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\[object (.*)\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function T6(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?rh(e.currentTarget):null,target:e.target?rh(e.target):null}}function k6(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function Ef(e,t,n){he.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const FA="No stack, consider using an instance of Error";function Qg({stackTrace:e,originalError:t,handlingStack:n,componentStack:i,startClocks:r,nonErrorPrefix:o,useFallbackStack:s=!0,source:a,handling:l}){const u=Bi(t);return!e&&u&&(e=uu(t)),{startClocks:r,source:a,handling:l,handlingStack:n,componentStack:i,originalError:t,type:e?e.name:void 0,message:C6(e,u,o,t),stack:e?lu(e):s?FA:void 0,causes:u?$6(t,a):void 0,fingerprint:A6(t),context:R6(t)}}function C6(e,t,n,i){return e?.message&&e?.name?e.message:t?"Empty message":`${n} ${Qo(We(i))}`}function A6(e){return Bi(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function R6(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Bi(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function $6(e,t){let n=e;const i=[];for(;Bi(n?.cause)&&i.length<10;){const r=uu(n.cause);i.push({message:n.cause.message,source:t,type:r?.name,stack:r&&lu(r)}),n=n.cause}return i.length?i:void 0}const es={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function O6(){return new Ie(e=>{const t=(r,o)=>{const s=Qg({stackTrace:o,originalError:r,startClocks:ct(),nonErrorPrefix:"Uncaught",source:es.SOURCE,handling:"unhandled"});e.notify(s)},{stop:n}=N6(t),{stop:i}=P6(t);return()=>{n(),i()}})}function N6(e){return Mn(fn(),"onerror",({parameters:[t,n,i,r,o]})=>{let s;Bi(o)||(s=g6(t,n,i,r)),e(o??t,s)})}function P6(e){return Mn(fn(),"onunhandledrejection",({parameters:[t]})=>{e(t.reason||"Empty reason")})}function M6(e){const t={version:"6.24.1",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return W4},enumerable:!1}),t}function j6(e,t,n){const i=e[t];i&&!i.q&&i.version&&he.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,i&&i.q&&i.q.forEach(r=>lA(r,"onReady callback threw an error:")())}function BA(e,t){t.silentMultipleInit||he.error(`${e} is already initialized.`)}function Ke(e,t,n,i,r){return Sr(e,t,[n],i,r)}function Sr(e,t,n,i,{once:r,capture:o,passive:s}={}){const a=ye(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(r&&d(),i(f))}),l=s?{capture:o,passive:s}:o,u=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,c=Wr(u,"addEventListener");n.forEach(f=>c.call(t,f,a,l));function d(){const f=Wr(u,"removeEventListener");n.forEach(p=>f.call(t,p,a,l))}return{stop:d}}const ia={intervention:"intervention",cspViolation:"csp_violation"};function D6(e,t){const n=[];t.includes(ia.cspViolation)&&n.push(L6(e));const i=t.filter(r=>r!==ia.cspViolation);return i.length&&n.push(z6(i)),fA(...n)}function z6(e){return new Ie(t=>{if(!window.ReportingObserver)return;const n=ye((r,o)=>r.forEach(s=>t.notify(U6(s)))),i=new window.ReportingObserver(n,{types:e,buffered:!0});return i.observe(),()=>{i.disconnect()}})}function L6(e){return new Ie(t=>{const{stop:n}=Ke(e,document,"securitypolicyviolation",i=>{t.notify(F6(i))});return n})}function U6(e){const{type:t,body:n}=e;return VA({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:qA(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function F6(e){const t=`'${e.blockedURI}' blocked by '${e.effectiveDirective}' directive`;return VA({type:e.effectiveDirective,message:`${ia.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:qA(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Jg(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function VA(e){return{startClocks:ct(),source:es.REPORT,handling:"unhandled",...e}}function qA(e,t,n,i,r){return n?lu({name:e,message:t,stack:[{func:"?",url:n,line:i??void 0,column:r??void 0}]}):void 0}const B6=200;function ev(e){const{env:t,service:n,version:i,datacenter:r,sdkVersion:o,variant:s}=e,a=[Xi("sdk_version",o??"6.24.1")];return t&&a.push(Xi("env",t)),n&&a.push(Xi("service",n)),i&&a.push(Xi("version",i)),r&&a.push(Xi("datacenter",r)),s&&a.push(Xi("variant",s)),a}function Xi(e,t){const n=t?`${e}:${t}`:e;return(n.length>B6||q6(n))&&he.warn(`Tag ${n} doesn't meet tag requirements and will be sanitized. ${Hg} ${wd}/getting_started/tagging/#defining-tags`),V6(n)}function V6(e){return e.replace(/,/g,"_")}function q6(e){return Z6()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(e):!1}function Z6(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function tv(e,t){const n=tr.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function Wl(e,t,n=H6()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const r=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,r)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const r=Array.isArray(e)?e:[];for(let o=0;o<t.length;++o)r[o]=Wl(r[o],t[o],n);return r}const i=Ui(e)==="object"?e:{};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[r]=Wl(i[r],t[r],n));return i}function nv(e){return Wl(void 0,e)}function Er(...e){let t;for(const n of e)n!=null&&(t=Wl(t,n));return t}function H6(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const i=t.has(n);return i||t.add(n),i}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function ZA(){var e;const t=tr.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function G6(e){return e>=500}function W6(e){try{return e.clone()}catch{return}}const J6=80*Fi,K6=32,HA=20*zA,Y6=Ut,GA=_t;function WA(e,t,n,i,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?KA(e,t,n,o,{onSuccess:()=>YA(0,t,n,i,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e)||o.notify({type:"queue-full",bandwidth:t.bandwidthMonitor.stats(),payload:e}),JA(t,n,i,r,o)}}):t.queuedPayloads.enqueue(e)||o.notify({type:"queue-full",bandwidth:t.bandwidthMonitor.stats(),payload:e})}function JA(e,t,n,i,r){e.transportStatus===2&&bt(()=>{const o=e.queuedPayloads.first();KA(o,e,t,r,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=GA,YA(1,e,t,n,i,r)},onFailure:()=>{e.currentBackoffTime=Math.min(Y6,e.currentBackoffTime*2),JA(e,t,n,i,r)}})},e.currentBackoffTime)}function KA(e,t,n,i,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),X6(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},i.notify({type:"failure",bandwidth:t.bandwidthMonitor.stats(),payload:e}),o()):(t.transportStatus=0,i.notify({type:"success",bandwidth:t.bandwidthMonitor.stats(),payload:e}),r())})}function YA(e,t,n,i,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(r({message:`Reached max ${i} events size queued for upload: ${HA/zA}MiB`,source:es.AGENT,startClocks:ct()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=XA();s.size()>0;)WA(s.dequeue(),t,n,i,r,o)}function X6(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||G6(e.status))}function Q6(){return{transportStatus:0,currentBackoffTime:GA,bandwidthMonitor:eB(),queuedPayloads:XA(),queueFullReported:!1}}function XA(){const e=[];return{bytesCount:0,enqueue(t){return this.isFull()?!1:(e.push(t),this.bytesCount+=t.bytesCount,!0)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=HA}}}function eB(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=J6&&this.ongoingRequestCount<K6},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount},stats(){return{ongoingByteCount:this.ongoingByteCount,ongoingRequestCount:this.ongoingRequestCount}}}}const ih=16*Fi;function rv(e,t,n=ih){const i=new Ie,r=Q6();return{observable:i,send:o=>{for(const s of e)WA(o,r,(a,l)=>{au(Jr.AVOID_FETCH_KEEPALIVE)?Jl(s,a,l):rB(s,n,a,l)},s.trackType,t,i)},sendOnExit:o=>{for(const s of e)tB(s,n,o)}}}function tB(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const r=e.build("beacon",n);if(navigator.sendBeacon(r,n.data))return}catch(r){nB(r)}Jl(e,n)}let Ub=!1;function nB(e){Ub||(Ub=!0,wr(e))}function rB(e,t,n,i){if(iB()&&n.bytesCount<t){const o=e.build("fetch-keepalive",n);fetch(o,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(ye(s=>i?.({status:s.status,type:s.type}))).catch(ye(()=>Jl(e,n,i)))}else Jl(e,n,i)}function Jl(e,t,n){const i=e.build("fetch",t);fetch(i,{method:"POST",body:t.data,mode:"cors"}).then(ye(r=>n?.({status:r.status,type:r.type}))).catch(ye(()=>n?.({status:0})))}function iB(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function ts(){const e=oB();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,i){const r=i?{id:i}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:r}))}}}function QA(e){const t=ts();return!!t&&t.getCapabilities().includes(e)}function $i(e){var t;e===void 0&&(e=(t=fn().location)===null||t===void 0?void 0:t.hostname);const n=ts();return!!n&&n.getAllowedWebViewHosts().some(i=>e===i||e.endsWith(`.${i}`))}function oB(){return fn().DatadogEventBridge}const yo={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function sB(e){return new Ie(t=>{const{stop:n}=Sr(e,window,["visibilitychange","freeze"],r=>{r.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:yo.HIDDEN}):r.type==="freeze"&&t.notify({reason:yo.FROZEN})},{capture:!0}),i=Ke(e,window,"beforeunload",()=>{t.notify({reason:yo.UNLOADING})}).stop;return()=>{n(),i()}})}function eR(e){return wA(yo).includes(e)}const Fb=256*Fi;function tR({encoder:e,request:t,flushController:n}){let i={};const r=n.flushObservable.subscribe(c=>u(c));function o(c,d,f){n.notifyBeforeAddMessage(d),f!==void 0?(i[f]=c,n.notifyAfterAddMessage()):e.write(e.isEmpty?c:`
|
|
33
|
+
${c}`,p=>{n.notifyAfterAddMessage(p-d)})}function s(c){return c!==void 0&&i[c]!==void 0}function a(c){const d=i[c];delete i[c];const f=e.estimateEncodedBytesCount(d);n.notifyAfterRemoveMessage(f)}function l(c,d){const f=Qo(c),p=e.estimateEncodedBytesCount(f);if(p>=Fb){he.warn(`Discarded a message whose size was bigger than the maximum allowed size ${Fb/Fi}KiB. ${Hg} ${Z4}/#technical-limitations`);return}s(d)&&a(d),o(f,p,d)}function u(c){const d=wA(i).join(`
|
|
34
|
+
`);i={};const f=eR(c.reason),p=f?t.sendOnExit:t.send;if(f&&e.isAsync){const m=e.finishSync();m.outputBytesCount&&p(Bb(m));const h=[m.pendingData,d].filter(Boolean).join(`
|
|
35
|
+
`);h&&p({data:h,bytesCount:LA(h)})}else d&&e.write(e.isEmpty?d:`
|
|
36
|
+
${d}`),e.finish(m=>{p(Bb(m))})}return{flushController:n,add:l,upsert:l,stop:r.unsubscribe}}function Bb(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}const aB=30*_t,uB=xd?1:50;function nR({pageMayExitObservable:e,sessionExpireObservable:t}){const n=e.subscribe(d=>a(d.reason)),i=t.subscribe(()=>a("session_expire")),r=new Ie(()=>()=>{n.unsubscribe(),i.unsubscribe()});let o=0,s=0;function a(d){if(s===0)return;const f=s,p=o;s=0,o=0,c(),r.notify({reason:d,messagesCount:f,bytesCount:p})}let l;function u(){l===void 0&&(l=bt(()=>{a("duration_limit")},aB))}function c(){Yt(l),l=void 0}return{flushObservable:r,get messagesCount(){return s},notifyBeforeAddMessage(d){o+d>=ih&&a("bytes_limit"),s+=1,o+=d,u()},notifyAfterAddMessage(d=0){o+=d,s>=uB?a("messages_limit"):o>=ih&&a("bytes_limit")},notifyAfterRemoveMessage(d){o-=d,s-=1,s===0&&c()}}}const Kr="DISCARDED",on="SKIPPED";function lB(){const e={};return{register(t,n){return e[t]||(e[t]=[]),e[t].push(n),{unregister:()=>{e[t]=e[t].filter(i=>i!==n)}}},triggerHook(t,n){const i=e[t]||[],r=[];for(const o of i){const s=o(n);if(s===Kr)return Kr;s!==on&&r.push(s)}return Er(...r)}}}const Vr={LOG:"log",CONFIGURATION:"configuration",USAGE:"usage"},cB=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],dB=1,fB=[qF],pB=15;let If;function ns(){return If||(If=new pA(100)),If}function hB(e,t,n,i,r,o){const s=new Ie,{stop:a}=gB(t,i,r,o,s),{enabled:l,metricsEnabled:u}=mB(e,t,n,s);return{stop:a,enabled:l,metricsEnabled:u}}function mB(e,t,n,i,r=dB,o=pB){const s={},a=!fB.includes(t.site)&&_i(t.telemetrySampleRate),l={[Vr.LOG]:a,[Vr.CONFIGURATION]:a&&_i(t.telemetryConfigurationSampleRate),[Vr.USAGE]:a&&_i(t.telemetryUsageSampleRate),metric:a&&_i(r)},u=vB(),c=ns();return c.subscribe(({rawEvent:f,metricName:p})=>{if(p&&!l.metric||!l[f.type])return;const m=p||f.status||f.type;let h=s[m];if(h||(h=s[m]=new Set),h.size>=o)return;const v=Qo(f);if(h.has(v))return;const y=n.triggerHook(1,{startTime:ct().relative});if(y===Kr)return;const w=d(y,e,f,u);i.notify(w),tv("telemetry",w),h.add(v)}),c.unbuffer(),G4(iv),{enabled:a,metricsEnabled:l.metric};function d(f,p,m,h){const y={type:"telemetry",date:ct().timeStamp,service:p,version:"6.24.1",source:"browser",_dd:{format_version:2},telemetry:Er(m,{runtime_env:h,connectivity:ZA(),sdk_setup:"npm"}),ddtags:ev(t).join(","),experimental_features:Array.from(o6())};return Er(y,f)}}function gB(e,t,n,i,r){const o=[];if($i()){const s=ts(),a=r.subscribe(l=>s.send("internal_telemetry",l));o.push(a.unsubscribe)}else{const s=[e.rumEndpointBuilder];e.replica&&yB(e)&&s.push(e.replica.rumEndpointBuilder);const a=tR({encoder:i(4),request:rv(s,t),flushController:nR({pageMayExitObservable:n,sessionExpireObservable:new Ie})});o.push(a.stop);const l=r.subscribe(a.add);o.push(l.unsubscribe)}return{stop:()=>o.forEach(s=>s())}}function vB(){var e;return{is_local_file:((e=tr.location)===null||e===void 0?void 0:e.protocol)==="file:",is_worker:xd}}function yB(e){return e.site===NA}function rs(e,t){Qp(_d.debug,e,t),ns().notify({rawEvent:{type:Vr.LOG,message:e,status:"debug",...t}})}function iv(e,t){ns().notify({rawEvent:{type:Vr.LOG,status:"error",..._B(e),...t}})}function bB(e){ns().notify({rawEvent:{type:Vr.CONFIGURATION,configuration:e}})}function cu(e,t){ns().notify({rawEvent:{type:Vr.LOG,message:e,status:"debug",...t},metricName:e})}function ft(e){ns().notify({rawEvent:{type:Vr.USAGE,usage:e}})}function _B(e){if(Bi(e)){const t=uu(e);return{error:{kind:t.name,stack:lu(wB(t))},message:t.message}}return{error:{stack:FA},message:`Uncaught ${Qo(e)}`}}function wB(e){return e.stack=e.stack.filter(t=>!t.url||cB.some(n=>t.url.startsWith(n))),e}function rR(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}function Ii(e){return Array.isArray(e)&&e.length>0}const Fu=1/0,xB=Ut;let gs=null;const fl=new Set;function SB(){fl.forEach(e=>e())}function is({expireDelay:e,maxEntries:t}){let n=[];gs||(gs=Yo(()=>SB(),xB));const i=()=>{const c=rn()-e;for(;n.length>0&&n[n.length-1].endTime<c;)n.pop()};fl.add(i);function r(c,d){const f={value:c,startTime:d,endTime:Fu,remove:()=>{rR(n,f)},close:p=>{f.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(f),f}function o(c=Fu,d={returnInactive:!1}){for(const f of n)if(f.startTime<=c){if(d.returnInactive||c<=f.endTime)return f.value;break}}function s(c){const d=n[0];d&&d.endTime===Fu&&d.close(c)}function a(c=Fu,d=0){const f=Xo(c,d);return n.filter(p=>p.startTime<=f&&c<=p.endTime).map(p=>p.value)}function l(){n=[]}function u(){fl.delete(i),fl.size===0&&gs&&(Sd(gs),gs=null)}return{add:r,find:o,closeActive:s,findAll:a,reset:l,stop:u}}const EB="datadog-synthetics-public-id",IB="datadog-synthetics-result-id",TB="datadog-synthetics-injects-rum";function iR(){return xd?!1:!!(tr._DATADOG_SYNTHETICS_INJECTS_RUM||Lr(TB))}function oR(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||Lr(EB);return typeof e=="string"?e:void 0}function sR(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||Lr(IB);return typeof e=="string"?e:void 0}function aR(){return!!(oR()&&sR())}const kB=Ut,CB=Li;function AB(e,t,n,i){const r=new Ie,o=new Ie,s=MF(e.sessionStoreStrategyType,e,t,n),a=is({expireDelay:CB});if(s.renewObservable.subscribe(()=>{a.add(l(),rn()),r.notify()}),s.expireObservable.subscribe(()=>{o.notify(),a.closeActive(rn())}),s.expandOrRenewSession(),a.add(l(),Gg().relative),au(Jr.SHORT_SESSION_INVESTIGATION)){const u=s.getSession();u&&PB(e,u)}i.observable.subscribe(()=>{i.isGranted()?s.expandOrRenewSession():s.expire(!1)}),RB(e,()=>{i.isGranted()&&s.expandOrRenewSession()}),$B(e,()=>s.expandSession()),OB(e,()=>s.restartSession());function l(){const u=s.getSession();return u?{id:u.id,trackingType:u[t],isReplayForced:!!u.forcedReplay,anonymousId:u.anonymousId}:(NB(e).catch(()=>{}),{id:"invalid",trackingType:SA,isReplayForced:!1,anonymousId:void 0})}return{findSession:(u,c)=>a.find(u,c),renewObservable:r,expireObservable:o,sessionStateUpdateObservable:s.sessionStateUpdateObservable,expire:s.expire,updateSessionState:s.updateSessionState}}function RB(e,t){const{stop:n}=Sr(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function $B(e,t){const n=()=>{document.visibilityState==="visible"&&t()},{stop:i}=Ke(e,document,"visibilitychange",n);Yo(n,kB)}function OB(e,t){const{stop:n}=Ke(e,window,"resume",t,{capture:!0})}async function NB(e){const t=e.sessionStoreStrategyType;if(!t)return;let n,i;t.type===Uo.COOKIE?(n=kA(t.cookieOptions,e),i={cookie:await uR(),currentDomain:`${window.location.protocol}//${window.location.hostname}`}):n=RA(),rs("Unexpected session state",{sessionStoreStrategyType:t.type,session:n,isSyntheticsTest:aR(),createdTimestamp:n?.created,expireTimestamp:n?.expire,...i})}function PB(e,t){if(!window.cookieStore||!t.created)return;const n=Number(t.created),i=zt(),{stop:r}=Ke(e,cookieStore,"change",o);function o(s){const a=_A(s.changed,u=>u.name===xr);if(!a)return;const l=zt()-n;if(l>14*Ut)r();else{const u=kd(a.value);if(u.id&&u.id!==t.id){r();const c=zt()-i;uR().then(d=>{rs("Session cookie changed",{time:c,session_age:l,old:t,new:u,cookie:d})}).catch(wr)}}}}async function uR(){let e;return"cookieStore"in window?e=await window.cookieStore.getAll(xr):e=document.cookie.split(/\s*;\s*/).filter(t=>t.startsWith(xr)),{count:e.length,domain:bA()||"undefined",...e}}function MB(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,i){const r=LA(n);t+=r,e+=n,i&&i(r)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class jB{constructor(){this.callbacks={}}notify(t,n){const i=this.callbacks[t];i&&i.forEach(r=>r(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(i=>n!==i)}}}}const DB=3e3;function Tf(e,t,n=DB){let i=0,r=!1;return{isLimitReached(){if(i===0&&bt(()=>{i=0},Ut),i+=1,i<=n||r)return r=!1,!1;if(i===n+1){r=!0;try{t({message:`Reached max number of ${e}s by minute: ${n}`,source:es.AGENT,startClocks:ct()})}finally{r=!1}}return!0}}}function ov(e,t,n){return document.readyState===t||document.readyState==="complete"?(n(),{stop:$e}):Ke(e,window,t==="complete"?"load":"DOMContentLoaded",n,{once:!0})}function zB(e,t){return new Promise(n=>{ov(e,t,n)})}let kf;const sv=new WeakMap;function LB(e){return kf||(kf=UB(e)),kf}function UB(e){return new Ie(t=>{const{stop:n}=Mn(XMLHttpRequest.prototype,"open",FB),{stop:i}=Mn(XMLHttpRequest.prototype,"send",o=>{BB(o,e,t)},{computeHandlingStack:!0}),{stop:r}=Mn(XMLHttpRequest.prototype,"abort",VB);return()=>{n(),i(),r()}})}function FB({target:e,parameters:[t,n]}){sv.set(e,{state:"open",method:String(t).toUpperCase(),url:Kg(String(n))})}function BB({target:e,parameters:[t],handlingStack:n},i,r){const o=sv.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=ct(),s.isAborted=!1,s.xhr=e,s.handlingStack=n,s.requestBody=t;let a=!1;const{stop:l}=Mn(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&u()}),u=()=>{if(c(),l(),a)return;a=!0;const d=o;d.state="complete",d.duration=tt(s.startClocks.timeStamp,ht()),d.status=e.status,typeof e.response=="string"&&(d.responseBody=e.response),r.notify(ta(d))},{stop:c}=Ke(i,e,"loadend",u);r.notify(s)}function VB({target:e}){const t=sv.get(e);t&&(t.isAborted=!0)}async function qB(e,t){const n=e.getReader(),i=[];for(;;){const r=await n.read();if(r.done)break;t.collectStreamBody&&i.push(r.value)}return n.cancel().catch($e),t.collectStreamBody?UA(i):void 0}let Cf;const lR=[];function cR({responseBodyAction:e}={}){return e&&lR.push(e),Cf||(Cf=ZB()),Cf}function ZB(){return new Ie(e=>{if(!tr.fetch)return;const{stop:t}=Mn(tr,"fetch",n=>HB(n,e),{computeHandlingStack:!0});return t})}function HB({parameters:e,onPostCall:t,handlingStack:n},i){const[r,o]=e;let s=o&&o.method;s===void 0&&r instanceof Request&&(s=r.method);const a=s!==void 0?String(s).toUpperCase():"GET",l=r instanceof Request?r.url:Kg(String(r)),u=ct(),c={state:"start",init:o,input:r,method:a,startClocks:u,url:l,handlingStack:n};i.notify(c),e[0]=c.input,e[1]=c.init,t(d=>{GB(i,d,c).catch(wr)})}async function GB(e,t,n){var i,r;const o=n;o.state="resolve";let s;try{s=await t}catch(l){o.status=0,o.isAborted=((r=(i=o.init)===null||i===void 0?void 0:i.signal)===null||r===void 0?void 0:r.aborted)||l instanceof DOMException&&l.code===DOMException.ABORT_ERR,o.error=l,e.notify(o);return}o.response=s,o.status=s.status,o.responseType=s.type,o.isAborted=!1;const a=lR.reduce((l,u)=>Math.max(l,u(o)),0);if(a!==0){const l=W6(s);if(l&&l.body)try{const u=await qB(l.body,{collectStreamBody:a===2});o.responseBody=u&&new TextDecoder().decode(u)}catch{}}e.notify(o)}function dR(e,t){if(window.requestIdleCallback&&window.cancelIdleCallback){const n=window.requestIdleCallback(ye(e),t);return()=>window.cancelIdleCallback(n)}return JB(e)}const WB=50;function JB(e){const t=zt(),n=bt(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,WB-(zt()-t))})},0);return()=>Yt(n)}const KB=_t,YB=30;function XB(){const e=[];function t(i){let r;if(i.didTimeout){const o=performance.now();r=()=>YB-(performance.now()-o)}else r=i.timeRemaining.bind(i);for(;r()>0&&e.length;)e.shift()();e.length&&n()}function n(){dR(t,{timeout:KB})}return{push(i){e.push(i)===1&&n()},stop(){e.length=0}}}let Af={};function QB(e){const t=e.map(n=>(Af[n]||(Af[n]=eV(n)),Af[n]));return fA(...t)}function eV(e){return new Ie(t=>{const n=hr[e];return hr[e]=(...i)=>{n.apply(console,i);const r=Gl("console error");Br(()=>{t.notify(tV(i,e,r))})},()=>{hr[e]=n}})}function tV(e,t,n){const i=e.map(r=>nV(r)).join(" ");if(t===_d.error){const r=e.find(Bi),o=Qg({originalError:r,handlingStack:n,startClocks:ct(),source:es.CONSOLE,handling:"handled",nonErrorPrefix:"Provided",useFallbackStack:!1});return o.message=i,{api:t,message:i,handlingStack:n,error:o}}return{api:t,message:i,error:void 0,handlingStack:n}}function nV(e){return typeof e=="string"?We(e):Bi(e)?DA(uu(e)):Qo(We(e),void 0,2)}const rV=500;function iV(){const e=[];return{add:r=>{e.push(r)>rV&&e.splice(0,1)},remove:r=>{rR(e,r)},drain:r=>{e.forEach(o=>o(r)),e.length=0}}}function oV(e){const t=Ui(e)==="object";return t||he.error("Unsupported context:",e),t}function Rf(e,t,n){const i={...e};for(const[r,{required:o,type:s}]of Object.entries(t))s==="string"&&!Vb(i[r])&&(i[r]=String(i[r])),o&&Vb(i[r])&&he.warn(`The property ${r} of ${n} is required; context will not be sent to the intake.`);return i}function Vb(e){return e==null||e===""}function Ad(e="",{propertiesConfig:t={}}={}){let n={};const i=new Ie,r={getContext:()=>nv(n),setContext:o=>{oV(o)?n=We(Rf(o,t,e)):r.clearContext(),i.notify()},setContextProperty:(o,s)=>{n=We(Rf({...n,[o]:s},t,e)),i.notify()},removeContextProperty:o=>{delete n[o],Rf(n,t,e),i.notify()},clearContext:()=>{n={},i.notify()},changeObservable:i};return r}function Rt(e,t,n,i){return ye((...r)=>(i&&ft({feature:i}),e()[t][n](...r)))}const sV="_dd_c",aV=[];function av(e,t,n,i){const r=uV(n,i);aV.push(Ke(e,window,"storage",({key:u})=>{r===u&&s()})),t.changeObservable.subscribe(a);const o=Er(l(),t.getContext());ri(o)||t.setContext(o);function s(){t.setContext(l())}function a(){localStorage.setItem(r,JSON.stringify(t.getContext()))}function l(){const u=localStorage.getItem(r);return u?JSON.parse(u):{}}}function uV(e,t){return`${sV}_${e}_${t}`}function lV(e,t,n){const i=fR();return t.storeContextsAcrossPages&&av(t,i,n,4),e.register(0,()=>{const r=i.getContext();return ri(r)||!r.id?on:{account:r}}),i}function fR(){return Ad("account",{propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}})}function cV(e,t,n,i){const r=pR();return t.storeContextsAcrossPages&&av(t,r,n,2),e.register(0,()=>({context:r.getContext()})),r}function pR(){return Ad("global context")}function dV(e,t,n,i){const r=hR();return t.storeContextsAcrossPages&&av(t,r,i,1),e.register(0,({eventType:o,startTime:s})=>{const a=r.getContext(),l=n.findTrackedSession(s);return l&&l.anonymousId&&!a.anonymous_id&&t.trackAnonymousUser&&(a.anonymous_id=l.anonymousId),ri(a)?on:{type:o,usr:a}}),e.register(1,({startTime:o})=>{var s;return{anonymous_id:(s=n.findTrackedSession(o))===null||s===void 0?void 0:s.anonymousId}}),r}function hR(){return Ad("user",{propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}})}const pt={userContext:"userContext",globalContext:"globalContext",accountContext:"accountContext"},$t={getContext:"getContext",setContext:"setContext",setContextProperty:"setContextProperty",removeContextProperty:"removeContextProperty",clearContext:"clearContext"},jt={DOCUMENT:"document",XHR:"xhr",BEACON:"beacon",FETCH:"fetch",CSS:"css",JS:"js",IMAGE:"image",FONT:"font",MEDIA:"media",OTHER:"other"},Rd={FETCH:jt.FETCH,XHR:jt.XHR},fV=500;function pV(e=O6){const t=new pA(fV),n=e().subscribe(i=>{t.notify({type:0,error:i})});return{observable:t,stop:()=>{n.unsubscribe()}}}function hV(){try{return new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}const me={ACTION:"action",ERROR:"error",LONG_TASK:"long_task",VIEW:"view",RESOURCE:"resource",VITAL:"vital"},mR={LONG_TASK:"long-task",LONG_ANIMATION_FRAME:"long-animation-frame"},mr={INITIAL_LOAD:"initial_load",ROUTE_CHANGE:"route_change",BF_CACHE:"bf_cache"},$d={CLICK:"click",CUSTOM:"custom"},vs={RAGE_CLICK:"rage_click",ERROR_CLICK:"error_click",DEAD_CLICK:"dead_click"},oa={DURATION:"duration",OPERATION_STEP:"operation_step"};function mV(){return{vitalsByName:new Map,vitalsByReference:new WeakMap}}function gV(e,t,n){function i(s){return!t.wasInPageStateDuringPeriod("frozen",s.startClocks.relative,s.duration)}function r(s){i(s)&&e.notify(12,qb(s))}function o(s,a,l,u){if(!au(Jr.FEATURE_OPERATION_VITAL))return;const{operationKey:c,context:d,description:f}=l||{},p={name:s,type:oa.OPERATION_STEP,operationKey:c,failureReason:u,stepType:a,startClocks:ct(),context:We(d),description:f};e.notify(12,qb(p))}return{addOperationStepVital:o,addDurationVital:r,startDurationVital:(s,a={})=>gR(n,s,a),stopDurationVital:(s,a={})=>{vR(r,n,s,a)}}}function gR({vitalsByName:e,vitalsByReference:t},n,i={}){const r={name:n,startClocks:ct(),...i},o={__dd_vital_reference:!0};return e.set(n,r),t.set(o,r),o}function vR(e,{vitalsByName:t,vitalsByReference:n},i,r={}){const o=typeof i=="string"?t.get(i):n.get(i);o&&(e(vV(o,o.startClocks,r,ct())),typeof i=="string"?t.delete(i):n.delete(i))}function vV(e,t,n,i){var r;return{name:e.name,type:oa.DURATION,startClocks:t,duration:tt(t.timeStamp,i.timeStamp),context:Er(e.context,n.context),description:(r=n.description)!==null&&r!==void 0?r:e.description}}function qb(e){const{startClocks:t,type:n,name:i,description:r,context:o}=e,s={id:Tt(),type:n,name:i,description:r,...n===oa.DURATION?{duration:be(e.duration)}:{step_type:e.stepType,operation_key:e.operationKey,failure_reason:e.failureReason}};return{rawRumEvent:{date:t.timeStamp,vital:s,type:me.VITAL,context:o},startTime:t.relative,duration:n===oa.DURATION?e.duration:void 0,domainContext:{}}}function yR(e,t,n){if(e)for(const i of e){const r=i[t];r&&r(n)}}const Zb=new Map;function bR(e,t){if(t===100)return!0;if(t===0)return!1;const n=Zb.get(t);if(n&&e===n.sessionId)return n.decision;let i;return window.BigInt?i=yV(BigInt(`0x${e.split("-")[4]}`),t):i=_i(t),Zb.set(t,{sessionId:e,decision:i}),i}function yV(e,t){const n=BigInt("1111111111111111111"),i=BigInt("0x10000000000000000"),r=e*n%i;return Number(r)<=t/100*Number(i)}function bV(){return wR(64)}function _R(){return wR(63)}function wR(e){const t=crypto.getRandomValues(new Uint32Array(2));return e===63&&(t[t.length-1]>>>=1),{toString(n=10){let i=t[1],r=t[0],o="";do{const s=i%n*4294967296+r;i=Math.floor(i/n),r=Math.floor(s/n),o=(s%n).toString(n)+o}while(i||r);return o}}}function Qi(e){return e.toString(16).padStart(16,"0")}function _V(e){const t=e;return Ui(t)==="object"&&ra(t.match)&&Array.isArray(t.propagatorTypes)}function wV(e){e.status===0&&!e.isAborted&&(e.traceId=void 0,e.spanId=void 0,e.traceSampled=void 0)}function xV(e,t,n,i){return{clearTracingIfNeeded:wV,traceFetch:r=>Hb(e,r,t,n,i,o=>{var s;if(r.input instanceof Request&&!(!((s=r.init)===null||s===void 0)&&s.headers))r.input=new Request(r.input),Object.keys(o).forEach(a=>{r.input.headers.append(a,o[a])});else{r.init=ta(r.init);const a=[];r.init.headers instanceof Headers?r.init.headers.forEach((l,u)=>{a.push([u,l])}):Array.isArray(r.init.headers)?r.init.headers.forEach(l=>{a.push(l)}):r.init.headers&&Object.keys(r.init.headers).forEach(l=>{a.push([l,r.init.headers[l]])}),r.init.headers=a.concat(Td(o))}}),traceXhr:(r,o)=>Hb(e,r,t,n,i,s=>{Object.keys(s).forEach(a=>{o.setRequestHeader(a,s[a])})})}}function Hb(e,t,n,i,r,o){const s=n.findTrackedSession();if(!s)return;const a=e.allowedTracingUrls.find(c=>Cd([c.match],t.url,!0));if(!a)return;const l=bR(s.id,e.traceSampleRate);(l||e.traceContextInjection===nh.ALL)&&(t.traceSampled=l,t.traceId=bV(),t.spanId=_R(),o(SV(t.traceId,t.spanId,t.traceSampled,s.id,a.propagatorTypes,i,r,e)))}function SV(e,t,n,i,r,o,s,a){const l={};if(r.forEach(u=>{switch(u){case"datadog":{Object.assign(l,{"x-datadog-origin":"rum","x-datadog-parent-id":t.toString(),"x-datadog-sampling-priority":n?"1":"0","x-datadog-trace-id":e.toString()});break}case"tracecontext":{Object.assign(l,{traceparent:`00-0000000000000000${Qi(e)}-${Qi(t)}-0${n?"1":"0"}`,tracestate:`dd=s:${n?"1":"0"};o:rum`});break}case"b3":{Object.assign(l,{b3:`${Qi(e)}-${Qi(t)}-${n?"1":"0"}`});break}case"b3multi":{Object.assign(l,{"X-B3-TraceId":Qi(e),"X-B3-SpanId":Qi(t),"X-B3-Sampled":n?"1":"0"});break}}}),a.propagateTraceBaggage){const u={"session.id":i},c=o.getContext().id;typeof c=="string"&&(u["user.id"]=c);const d=s.getContext().id;typeof d=="string"&&(u["account.id"]=d);const f=Object.entries(u).map(([p,m])=>`${p}=${encodeURIComponent(m)}`).join(",");f&&(l.baggage=f)}return l}const xR=["tracecontext","datadog"];function EV(e,t){var n,i,r,o,s,a,l;if(e.trackFeatureFlagsForEvents!==void 0&&!Array.isArray(e.trackFeatureFlagsForEvents)&&he.warn("trackFeatureFlagsForEvents should be an array"),!e.applicationId){he.error("Application ID is not configured, no RUM data will be collected.");return}if(!mo(e.sessionReplaySampleRate,"Session Replay")||!mo(e.traceSampleRate,"Trace"))return;if(e.excludedActivityUrls!==void 0&&!Array.isArray(e.excludedActivityUrls)){he.error("Excluded Activity Urls should be an array");return}const u=IV(e);if(!u)return;const c=t6(e,t),d=kV(e);if(!c)return;const f=(n=e.sessionReplaySampleRate)!==null&&n!==void 0?n:0;return{applicationId:e.applicationId,actionNameAttribute:e.actionNameAttribute,sessionReplaySampleRate:f,startSessionReplayRecordingManually:e.startSessionReplayRecordingManually!==void 0?!!e.startSessionReplayRecordingManually:f===0,traceSampleRate:(i=e.traceSampleRate)!==null&&i!==void 0?i:100,rulePsr:nu(e.traceSampleRate)?e.traceSampleRate/100:void 0,allowedTracingUrls:u,excludedActivityUrls:(r=e.excludedActivityUrls)!==null&&r!==void 0?r:[],workerUrl:e.workerUrl,compressIntakeRequests:!!e.compressIntakeRequests,trackUserInteractions:!!(!((o=e.trackUserInteractions)!==null&&o!==void 0)||o),trackViewsManually:!!e.trackViewsManually,trackResources:!!(!((s=e.trackResources)!==null&&s!==void 0)||s),trackLongTasks:!!(!((a=e.trackLongTasks)!==null&&a!==void 0)||a),trackBfcacheViews:!!e.trackBfcacheViews,trackEarlyRequests:!!e.trackEarlyRequests,subdomain:e.subdomain,defaultPrivacyLevel:Hl(ho,e.defaultPrivacyLevel)?e.defaultPrivacyLevel:ho.MASK,enablePrivacyForActionName:!!e.enablePrivacyForActionName,traceContextInjection:Hl(nh,e.traceContextInjection)?e.traceContextInjection:nh.SAMPLED,plugins:e.plugins||[],trackFeatureFlagsForEvents:e.trackFeatureFlagsForEvents||[],profilingSampleRate:(l=e.profilingSampleRate)!==null&&l!==void 0?l:0,propagateTraceBaggage:!!e.propagateTraceBaggage,allowedGraphQlUrls:d,...c}}function IV(e){if(e.allowedTracingUrls===void 0)return[];if(!Array.isArray(e.allowedTracingUrls)){he.error("Allowed Tracing URLs should be an array");return}if(e.allowedTracingUrls.length!==0&&e.service===void 0){he.error("Service needs to be configured when tracing is enabled");return}const t=[];return e.allowedTracingUrls.forEach(n=>{ra(n)?t.push({match:n,propagatorTypes:xR}):_V(n)?t.push(n):he.warn("Allowed Tracing Urls parameters should be a string, RegExp, function, or an object. Ignoring parameter",n)}),t}function TV(e){const t=new Set;return Ii(e.allowedTracingUrls)&&e.allowedTracingUrls.forEach(n=>{ra(n)?xR.forEach(i=>t.add(i)):Ui(n)==="object"&&Array.isArray(n.propagatorTypes)&&n.propagatorTypes.forEach(i=>t.add(i))}),Array.from(t)}function kV(e){if(!e.allowedGraphQlUrls)return[];if(!Array.isArray(e.allowedGraphQlUrls))return he.warn("allowedGraphQlUrls should be an array"),[];const t=[];return e.allowedGraphQlUrls.forEach(n=>{ra(n)?t.push({match:n,trackPayload:!1,trackResponseErrors:!1}):n&&typeof n=="object"&&"match"in n&&ra(n.match)&&t.push({match:n.match,trackPayload:!!n.trackPayload,trackResponseErrors:!!n.trackResponseErrors})}),t}function CV(e){return Ii(e)&&e.some(t=>typeof t=="object"&&"trackPayload"in t?!!t.trackPayload:!1)}function AV(e){return Ii(e)&&e.some(t=>typeof t=="object"&&"trackResponseErrors"in t?!!t.trackResponseErrors:!1)}function RV(e){var t;const n=n6(e);return{session_replay_sample_rate:e.sessionReplaySampleRate,start_session_replay_recording_manually:e.startSessionReplayRecordingManually,trace_sample_rate:e.traceSampleRate,trace_context_injection:e.traceContextInjection,propagate_trace_baggage:e.propagateTraceBaggage,action_name_attribute:e.actionNameAttribute,use_allowed_tracing_urls:Ii(e.allowedTracingUrls),use_allowed_graph_ql_urls:Ii(e.allowedGraphQlUrls),use_track_graph_ql_payload:CV(e.allowedGraphQlUrls),use_track_graph_ql_response_errors:AV(e.allowedGraphQlUrls),selected_tracing_propagators:TV(e),default_privacy_level:e.defaultPrivacyLevel,enable_privacy_for_action_name:e.enablePrivacyForActionName,use_excluded_activity_urls:Ii(e.excludedActivityUrls),use_worker_url:!!e.workerUrl,compress_intake_requests:e.compressIntakeRequests,track_views_manually:e.trackViewsManually,track_user_interactions:e.trackUserInteractions,track_resources:e.trackResources,track_long_task:e.trackLongTasks,track_bfcache_views:e.trackBfcacheViews,track_early_requests:e.trackEarlyRequests,plugins:(t=e.plugins)===null||t===void 0?void 0:t.map(i=>{var r;return{name:i.name,...(r=i.getConfigurationTelemetry)===null||r===void 0?void 0:r.call(i)}}),track_feature_flags_for_events:e.trackFeatureFlagsForEvents,remote_configuration_id:e.remoteConfigurationId,profiling_sample_rate:e.profilingSampleRate,use_remote_configuration_proxy:!!e.remoteConfigurationProxy,...n}}function $V(e){const t=[];let n=0,i;const r={quote:void 0,escapeSequence:void 0};let o="";for(const s of e){if(i=Gb[n].find(a=>DV[a](s,r)),!i)return[];if(r.escapeSequence!==void 0&&i!==12){if(!UV(r.escapeSequence))return[];o+=BV(r.escapeSequence),r.escapeSequence=void 0}zV.includes(i)?o+=s:LV.includes(i)&&o!==""?(t.push(o),o=""):i===12?r.escapeSequence=r.escapeSequence?`${r.escapeSequence}${s}`:s:i===8?r.quote=s:i===9&&(r.quote=void 0),n=i}return Gb[n].includes(1)?(o!==""&&t.push(o),t):[]}const OV=/[a-zA-Z_$]/,NV=/[a-zA-Z0-9_$]/,PV=/[0-9]/,MV=/[a-fA-F0-9]/,jV=`'"`,DV={0:()=>!1,1:()=>!1,2:e=>OV.test(e),3:e=>NV.test(e),4:e=>e===".",5:e=>e==="[",6:e=>e==="]",7:e=>PV.test(e),8:e=>jV.includes(e),9:(e,t)=>e===t.quote,10:()=>!0,11:e=>e==="\\",12:(e,t)=>t.escapeSequence===void 0?`${t.quote}/\\bfnrtu`.includes(e):t.escapeSequence.startsWith("u")&&t.escapeSequence.length<5?MV.test(e):!1},Gb={0:[2,5],1:[],2:[3,4,5,1],3:[3,4,5,1],4:[2],5:[8,7],6:[4,5,1],7:[7,6],8:[11,9,10],9:[6],10:[11,9,10],11:[12],12:[12,11,9,10]},zV=[2,3,7,10],LV=[4,5,6];function UV(e){return`"'/\\bfnrt`.includes(e)||e.startsWith("u")&&e.length===5}const FV={'"':'"',"'":"'","/":"/","\\":"\\",b:"\b",f:"\f",n:`
|
|
37
|
+
`,r:"\r",t:" "};function BV(e){return e.startsWith("u")?String.fromCharCode(parseInt(e.slice(1),16)):FV[e]}const VV="v1",qV=["applicationId","service","env","version","sessionSampleRate","sessionReplaySampleRate","defaultPrivacyLevel","enablePrivacyForActionName","traceSampleRate","trackSessionAcrossSubdomains","allowedTracingUrls","allowedTrackingOrigins"];async function ZV(e,t){let n;const i=GV(),r=await YV(e);return r.ok?(i.increment("fetch","success"),n=HV(e,r.value,t,i)):(i.increment("fetch","failure"),he.error(r.error)),cu("remote configuration metrics",{metrics:i.get()}),n}function HV(e,t,n,i){const r={...e};return qV.forEach(f=>{f in t&&(r[f]=o(t[f]))}),Object.keys(n).forEach(f=>{t[f]!==void 0&&s(n[f],t[f])}),r;function o(f){if(Array.isArray(f))return f.map(o);if(WV(f)){if(JV(f)){const p=f.rcSerializedType;switch(p){case"string":return f.value;case"regex":return SR(f.value);case"dynamic":return a(f);default:he.error(`Unsupported remote configuration: "rcSerializedType": "${p}"`);return}}return cA(f,o)}return f}function s(f,p){p.forEach(({key:m,value:h})=>{f.setContextProperty(m,o(h))})}function a(f){const p=f.strategy;let m;switch(p){case"cookie":m=l(f);break;case"dom":m=u(f);break;case"js":m=d(f);break;default:he.error(`Unsupported remote configuration: "strategy": "${p}"`);return}const h=f.extractor;return h!==void 0&&typeof m=="string"?KV(h,m):m}function l({name:f}){const p=Id(f);return i.increment("cookie",p!==void 0?"success":"missing"),p}function u({selector:f,attribute:p}){let m;try{m=document.querySelector(f)}catch{he.error(`Invalid selector in the remote configuration: '${f}'`),i.increment("dom","failure");return}if(!m){i.increment("dom","missing");return}if(c(m,p)){he.error(`Forbidden element selected by the remote configuration: '${f}'`),i.increment("dom","failure");return}const h=p!==void 0?m.getAttribute(p):m.textContent;if(h===null){i.increment("dom","missing");return}return i.increment("dom","success"),h}function c(f,p){return f.getAttribute("type")==="password"&&p==="value"}function d({path:f}){let p=window;const m=$V(f);if(m.length===0){he.error(`Invalid JSON path in the remote configuration: '${f}'`),i.increment("js","failure");return}for(const h of m){if(!(h in p)){i.increment("js","missing");return}try{p=p[h]}catch(v){he.error(`Error accessing: '${f}'`,v),i.increment("js","failure");return}}return i.increment("js","success"),p}}function GV(){const e={fetch:{}};return{get:()=>e,increment:(t,n)=>{e[t]||(e[t]={}),e[t][n]||(e[t][n]=0),e[t][n]=e[t][n]+1}}}function WV(e){return typeof e=="object"&&e!==null}function JV(e){return"rcSerializedType"in e}function SR(e){try{return new RegExp(e)}catch{he.error(`Invalid regex in the remote configuration: '${e}'`)}}function KV(e,t){const n=SR(e.value);if(n===void 0)return;const i=n.exec(t);if(i===null)return;const[r,o]=i;return o||r}async function YV(e){let t;try{t=await fetch(XV(e))}catch{t=void 0}if(!t||!t.ok)return{ok:!1,error:new Error("Error fetching the remote configuration.")};const n=await t.json();return n.rum?{ok:!0,value:n.rum}:{ok:!1,error:new Error("No remote configuration for RUM.")}}function XV(e){return e.remoteConfigurationProxy?e.remoteConfigurationProxy:`https://sdk-configuration.${PA("rum",e)}/${VV}/${encodeURIComponent(e.remoteConfigurationId)}.json`}function QV({ignoreInitIfSyntheticsWillInjectRum:e=!0,startDeflateWorker:t},n,i,r){const o=iV(),s=pR();$f(s,pt.globalContext,o);const a=hR();$f(a,pt.userContext,o);const l=fR();$f(l,pt.accountContext,o);let u,c,d,f;const p=n.observable.subscribe(h),m={};function h(){if(!d||!f||!n.isGranted())return;p.unsubscribe();let b;if(f.trackViewsManually){if(!u)return;o.remove(u.callback),b=u.options}const C=r(f,c,b);o.drain(C)}function v(b,C){const _=$i();if(_&&(b=eq(b)),d=b,bB(RV(b)),f){BA("DD_RUM",b);return}const k=EV(b,C);if(k){if(!_&&!k.sessionStoreStrategyType){he.warn("No storage available for session. We will not send any data.");return}k.compressIntakeRequests&&!_&&t&&(c=t(k,"Datadog RUM",$e),!c)||(f=k,cR().subscribe($e),n.tryToInit(k.trackingConsent),h())}}const y=b=>{o.add(C=>C.addDurationVital(b))};return{init(b,C,_){if(!b){he.error("Missing configuration");return}r6(b.enableExperimentalFeatures),d=b,!(e&&iR())&&(yR(b.plugins,"onInit",{initConfiguration:b,publicApi:C}),b.remoteConfigurationId?ZV(b,{user:a,context:s}).then(k=>{k&&v(k,_)}).catch(wr):v(b,_))},get initConfiguration(){return d},getInternalContext:$e,stopSession:$e,addTiming(b,C=ht()){o.add(_=>_.addTiming(b,C))},startView(b,C=ct()){const _=k=>{k.startView(b,C)};o.add(_),u||(u={options:b,callback:_},h())},setViewName(b){o.add(C=>C.setViewName(b))},setViewContext(b){o.add(C=>C.setViewContext(b))},setViewContextProperty(b,C){o.add(_=>_.setViewContextProperty(b,C))},getViewContext:()=>m,globalContext:s,userContext:a,accountContext:l,addAction(b){o.add(C=>C.addAction(b))},addError(b){o.add(C=>C.addError(b))},addFeatureFlagEvaluation(b,C){o.add(_=>_.addFeatureFlagEvaluation(b,C))},startDurationVital(b,C){return gR(i,b,C)},stopDurationVital(b,C){vR(y,i,b,C)},addDurationVital:y,addOperationStepVital:(b,C,_,k)=>{o.add(R=>R.addOperationStepVital(We(b),C,We(_),We(k)))}}}function eq(e){var t,n;return{...e,applicationId:"00000000-aaaa-0000-aaaa-000000000000",clientToken:"empty",sessionSampleRate:100,defaultPrivacyLevel:(t=e.defaultPrivacyLevel)!==null&&t!==void 0?t:(n=ts())===null||n===void 0?void 0:n.getPrivacyLevel()}}function $f(e,t,n){e.changeObservable.subscribe(()=>{const i=e.getContext();n.add(r=>r[t].setContext(i))})}function tq(e,t,n,i={}){const r=jF(),o=mV(),s=pV().observable;let a=QV(i,r,o,(d,f,p)=>{const m=f&&i.createDeflateEncoder?v=>i.createDeflateEncoder(d,f,v):MB,h=e(d,t,n,p,m,r,o,s,i.sdkName);return t.onRumStart(h.lifeCycle,d,h.session,h.viewHistory,f,h.telemetry),n.onRumStart(h.lifeCycle,h.hooks,d,h.session,h.viewHistory,m),a=nq(a,h),yR(d.plugins,"onRumStart",{strategy:a,addEvent:h.addEvent}),h});const l=()=>a,u=ye(d=>{const f=typeof d=="object"?d:{name:d};a.startView(f),ft({feature:"start-view"})}),c=M6({init:d=>{const f=new Error().stack;Br(()=>a.init(d,c,f))},setTrackingConsent:ye(d=>{r.update(d),ft({feature:"set-tracking-consent",tracking_consent:d})}),setViewName:ye(d=>{a.setViewName(d),ft({feature:"set-view-name"})}),setViewContext:ye(d=>{a.setViewContext(d),ft({feature:"set-view-context"})}),setViewContextProperty:ye((d,f)=>{a.setViewContextProperty(d,f),ft({feature:"set-view-context-property"})}),getViewContext:ye(()=>(ft({feature:"set-view-context-property"}),a.getViewContext())),getInternalContext:ye(d=>a.getInternalContext(d)),getInitConfiguration:ye(()=>nv(a.initConfiguration)),addAction:(d,f)=>{const p=Gl("action");Br(()=>{a.addAction({name:We(d),context:We(f),startClocks:ct(),type:$d.CUSTOM,handlingStack:p}),ft({feature:"add-action"})})},addError:(d,f)=>{const p=Gl("error");Br(()=>{a.addError({error:d,handlingStack:p,context:We(f),startClocks:ct()}),ft({feature:"add-error"})})},addTiming:ye((d,f)=>{a.addTiming(We(d),f)}),setGlobalContext:Rt(l,pt.globalContext,$t.setContext,"set-global-context"),getGlobalContext:Rt(l,pt.globalContext,$t.getContext,"get-global-context"),setGlobalContextProperty:Rt(l,pt.globalContext,$t.setContextProperty,"set-global-context-property"),removeGlobalContextProperty:Rt(l,pt.globalContext,$t.removeContextProperty,"remove-global-context-property"),clearGlobalContext:Rt(l,pt.globalContext,$t.clearContext,"clear-global-context"),setUser:Rt(l,pt.userContext,$t.setContext,"set-user"),getUser:Rt(l,pt.userContext,$t.getContext,"get-user"),setUserProperty:Rt(l,pt.userContext,$t.setContextProperty,"set-user-property"),removeUserProperty:Rt(l,pt.userContext,$t.removeContextProperty,"remove-user-property"),clearUser:Rt(l,pt.userContext,$t.clearContext,"clear-user"),setAccount:Rt(l,pt.accountContext,$t.setContext,"set-account"),getAccount:Rt(l,pt.accountContext,$t.getContext,"get-account"),setAccountProperty:Rt(l,pt.accountContext,$t.setContextProperty,"set-account-property"),removeAccountProperty:Rt(l,pt.accountContext,$t.removeContextProperty,"remove-account-property"),clearAccount:Rt(l,pt.accountContext,$t.clearContext,"clear-account"),startView:u,stopSession:ye(()=>{a.stopSession(),ft({feature:"stop-session"})}),addFeatureFlagEvaluation:ye((d,f)=>{a.addFeatureFlagEvaluation(We(d),We(f)),ft({feature:"add-feature-flag-evaluation"})}),getSessionReplayLink:ye(()=>t.getSessionReplayLink()),startSessionReplayRecording:ye(d=>{t.start(d),ft({feature:"start-session-replay-recording",force:d&&d.force})}),stopSessionReplayRecording:ye(()=>t.stop()),addDurationVital:ye((d,f)=>{ft({feature:"add-duration-vital"}),a.addDurationVital({name:We(d),type:oa.DURATION,startClocks:K4(f.startTime),duration:f.duration,context:We(f&&f.context),description:We(f&&f.description)})}),startDurationVital:ye((d,f)=>(ft({feature:"start-duration-vital"}),a.startDurationVital(We(d),{context:We(f&&f.context),description:We(f&&f.description)}))),stopDurationVital:ye((d,f)=>{ft({feature:"stop-duration-vital"}),a.stopDurationVital(typeof d=="string"?We(d):d,{context:We(f&&f.context),description:We(f&&f.description)})}),startFeatureOperation:ye((d,f)=>{ft({feature:"add-operation-step-vital",action_type:"start"}),a.addOperationStepVital(d,"start",f)}),succeedFeatureOperation:ye((d,f)=>{ft({feature:"add-operation-step-vital",action_type:"succeed"}),a.addOperationStepVital(d,"end",f)}),failFeatureOperation:ye((d,f,p)=>{ft({feature:"add-operation-step-vital",action_type:"fail"}),a.addOperationStepVital(d,"end",p,f)})});return c}function nq(e,t){return{init:n=>{BA("DD_RUM",n)},initConfiguration:e.initConfiguration,...t}}function rq(){const e=ER();return new Ie(t=>{if(!e)return;const n=new e(ye(i=>t.notify(i)));return n.observe(document,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),()=>n.disconnect()})}function ER(){let e;const t=window;if(t.Zone&&(e=Wr(t,"MutationObserver"),t.MutationObserver&&e===t.MutationObserver)){const n=new t.MutationObserver($e),i=Wr(n,"originalInstance");e=i&&i.constructor}return e||(e=t.MutationObserver),e}function iq(){const e=new Ie,{stop:t}=Mn(window,"open",()=>e.notify());return{observable:e,stop:t}}function oq(e,t,n,i,r){return{get:o=>{const s=n.findView(o),a=r.findUrl(o),l=t.findTrackedSession(o);if(l&&s&&a){const u=i.findActionId(o);return{application_id:e,session_id:l.id,user_action:u?{id:u}:void 0,view:{id:s.id,name:s.name,referrer:a.referrer,url:a.url}}}}}}const sq=jB,aq=Li;function uq(e){const t=is({expireDelay:aq});e.subscribe(1,i=>{t.add(n(i),i.startClocks.relative)}),e.subscribe(6,({endClocks:i})=>{t.closeActive(i.relative)}),e.subscribe(3,i=>{const r=t.find(i.startClocks.relative);r&&(i.name&&(r.name=i.name),i.context&&(r.context=i.context),r.sessionIsActive=i.sessionIsActive)}),e.subscribe(10,()=>{t.reset()});function n(i){return{service:i.service,version:i.version,context:i.context,id:i.id,name:i.name,startClocks:i.startClocks}}return{findView:i=>t.find(i),stop:()=>{t.stop()}}}const IR="initial_document",lq=[[jt.DOCUMENT,e=>IR===e],[jt.XHR,e=>e==="xmlhttprequest"],[jt.FETCH,e=>e==="fetch"],[jt.BEACON,e=>e==="beacon"],[jt.CSS,(e,t)=>/\.css$/i.test(t)],[jt.JS,(e,t)=>/\.js$/i.test(t)],[jt.IMAGE,(e,t)=>["image","img","icon"].includes(e)||/\.(gif|jpg|jpeg|tiff|png|svg|ico)$/i.exec(t)!==null],[jt.FONT,(e,t)=>/\.(woff|eot|woff2|ttf)$/i.exec(t)!==null],[jt.MEDIA,(e,t)=>["audio","video"].includes(e)||/\.(mp3|mp4)$/i.exec(t)!==null]];function cq(e){const t=e.name;if(!oF(t))return jt.OTHER;const n=sF(t);for(const[i,r]of lq)if(r(e.initiatorType,n))return i;return jt.OTHER}function Wb(...e){for(let t=1;t<e.length;t+=1)if(e[t-1]>e[t])return!1;return!0}function TR(e){return e.initiatorType==="xmlhttprequest"||e.initiatorType==="fetch"}function dq(e){const{duration:t,startTime:n,responseEnd:i}=e;return t===0&&n<i?tt(n,i):t}function fq(e){if(!CR(e))return;const{startTime:t,fetchStart:n,workerStart:i,redirectStart:r,redirectEnd:o,domainLookupStart:s,domainLookupEnd:a,connectStart:l,secureConnectionStart:u,connectEnd:c,requestStart:d,responseStart:f,responseEnd:p}=e,m={download:li(t,f,p),first_byte:li(t,d,f)};return 0<i&&i<n&&(m.worker=li(t,i,n)),n<c&&(m.connect=li(t,l,c),l<=u&&u<=c&&(m.ssl=li(t,u,c))),n<a&&(m.dns=li(t,s,a)),t<o&&(m.redirect=li(t,r,o)),m}function kR(e){return e.duration>=0}function CR(e){const t=Wb(e.startTime,e.fetchStart,e.domainLookupStart,e.domainLookupEnd,e.connectStart,e.connectEnd,e.requestStart,e.responseStart,e.responseEnd),n=pq(e)?Wb(e.startTime,e.redirectStart,e.redirectEnd,e.fetchStart):!0;return t&&n}function pq(e){return e.redirectEnd>e.startTime}function li(e,t,n){if(e<=t&&t<=n)return{duration:be(tt(t,n)),start:be(tt(e,t))}}function hq(e){return e.nextHopProtocol===""?void 0:e.nextHopProtocol}function mq(e){return e.deliveryType===""?"other":e.deliveryType}function gq(e){if(e.startTime<e.responseStart){const{encodedBodySize:t,decodedBodySize:n,transferSize:i}=e;return{size:n,encoded_body_size:t,decoded_body_size:n,transfer_size:i}}return{size:void 0,encoded_body_size:void 0,decoded_body_size:void 0,transfer_size:void 0}}function uv(e){return e&&(!QF(e)||au(Jr.TRACK_INTAKE_REQUESTS))}const vq=/data:(.+)?(;base64)?,/g,yq=24e3;function AR(e,t=yq){if(e.length<=t||!e.startsWith("data:"))return e;const n=e.substring(0,100).match(vq);return n?`${n[0]}[...]`:e}const bq=32*Fi;function _q(e,t){const n=xq(e.requestBody,t.trackPayload);if(n){if(t.trackResponseErrors&&e.responseBody){const i=wq(e.responseBody);i&&(n.errors_count=i.length,n.errors=i)}return n}}function wq(e){let t;try{t=JSON.parse(e)}catch{return}if(!t||typeof t!="object")return;const n=t;return Ii(n.errors)?n.errors.map(r=>{var o;return{message:r.message,path:r.path,locations:r.locations,code:(o=r.extensions)===null||o===void 0?void 0:o.code}}):void 0}function RR(e,t){return t.allowedGraphQlUrls.find(n=>Cd([n.match],e))}function xq(e,t=!1){if(!e||typeof e!="string")return;let n;try{n=JSON.parse(e)}catch{return}if(!n||!n.query)return;const i=n.query.trim(),r=Sq(i),o=n.operationName;if(!r)return;let s;return n.variables&&(s=JSON.stringify(n.variables)),{operationType:r,operationName:o,variables:s,payload:t?Jg(i,bq,"..."):void 0}}function Sq(e){var t;return(t=e.match(/^\s*(query|mutation|subscription)\b/i))===null||t===void 0?void 0:t[1]}let Jb=1;function Eq(e,t,n,i,r){const o=xV(t,n,i,r);Iq(e,t,o),Tq(e,t,o)}function Iq(e,t,n){const i=LB(t).subscribe(r=>{const o=r;if(uv(o.url))switch(o.state){case"start":n.traceXhr(o,o.xhr),o.requestIndex=$R(),e.notify(7,{requestIndex:o.requestIndex,url:o.url});break;case"complete":n.clearTracingIfNeeded(o),e.notify(8,{duration:o.duration,method:o.method,requestIndex:o.requestIndex,spanId:o.spanId,startClocks:o.startClocks,status:o.status,traceId:o.traceId,traceSampled:o.traceSampled,type:Rd.XHR,url:o.url,xhr:o.xhr,isAborted:o.isAborted,handlingStack:o.handlingStack,requestBody:o.requestBody,responseBody:o.responseBody});break}});return{stop:()=>i.unsubscribe()}}function Tq(e,t,n){const i=cR({responseBodyAction:r=>{var o;return!((o=RR(r.url,t))===null||o===void 0)&&o.trackResponseErrors?2:1}}).subscribe(r=>{var o;const s=r;if(uv(s.url))switch(s.state){case"start":n.traceFetch(s),s.requestIndex=$R(),e.notify(7,{requestIndex:s.requestIndex,url:s.url});break;case"resolve":n.clearTracingIfNeeded(s),e.notify(8,{duration:tt(s.startClocks.timeStamp,ht()),method:s.method,requestIndex:s.requestIndex,responseType:s.responseType,spanId:s.spanId,startClocks:s.startClocks,status:s.status,traceId:s.traceId,traceSampled:s.traceSampled,type:Rd.FETCH,url:s.url,response:s.response,init:s.init,input:s.input,isAborted:s.isAborted,handlingStack:s.handlingStack,requestBody:(o=s.init)===null||o===void 0?void 0:o.body,responseBody:s.responseBody});break}});return{stop:()=>i.unsubscribe()}}function $R(){const e=Jb;return Jb+=1,e}function OR(e){return nu(e)&&e<0?void 0:e}function NR({lifeCycle:e,isChildEvent:t,onChange:n=$e}){const i={errorCount:0,longTaskCount:0,resourceCount:0,actionCount:0,frustrationCount:0},r=e.subscribe(13,o=>{var s;if(!(o.type==="view"||o.type==="vital"||!t(o)))switch(o.type){case me.ERROR:i.errorCount+=1,n();break;case me.ACTION:i.actionCount+=1,o.action.frustration&&(i.frustrationCount+=o.action.frustration.type.length),n();break;case me.LONG_TASK:i.longTaskCount+=1,n();break;case me.RESOURCE:!((s=o._dd)===null||s===void 0)&&s.discarded||(i.resourceCount+=1,n());break}});return{stop:()=>{r.unsubscribe()},eventCounts:i}}function kq(e,t){const n=zt();let i=!1;const{stop:r}=Sr(e,window,["click","mousedown","keydown","touchstart","pointerdown"],a=>{if(!a.cancelable)return;const l={entryType:"first-input",processingStart:rn(),processingEnd:rn(),startTime:a.timeStamp,duration:0,name:"",cancelable:!1,target:null,toJSON:()=>({})};a.type==="pointerdown"?o(e,l):s(l)},{passive:!0,capture:!0});return{stop:r};function o(a,l){Sr(a,window,["pointerup","pointercancel"],u=>{u.type==="pointerup"&&s(l)},{once:!0})}function s(a){if(!i){i=!0,r();const l=a.processingStart-a.startTime;l>=0&&l<zt()-n&&t(a)}}}exports.RumPerformanceEntryType=void 0;(function(e){e.EVENT="event",e.FIRST_INPUT="first-input",e.LARGEST_CONTENTFUL_PAINT="largest-contentful-paint",e.LAYOUT_SHIFT="layout-shift",e.LONG_TASK="longtask",e.LONG_ANIMATION_FRAME="long-animation-frame",e.NAVIGATION="navigation",e.PAINT="paint",e.RESOURCE="resource",e.VISIBILITY_STATE="visibility-state"})(exports.RumPerformanceEntryType||(exports.RumPerformanceEntryType={}));function nr(e,t){return new Ie(n=>{if(!window.PerformanceObserver)return;const i=l=>{const u=Rq(l);u.length>0&&n.notify(u)};let r,o=!0;const s=new PerformanceObserver(ye(l=>{o?r=bt(()=>i(l.getEntries())):i(l.getEntries())}));try{s.observe(t)}catch{if([exports.RumPerformanceEntryType.RESOURCE,exports.RumPerformanceEntryType.NAVIGATION,exports.RumPerformanceEntryType.LONG_TASK,exports.RumPerformanceEntryType.PAINT].includes(t.type)){t.buffered&&(r=bt(()=>i(performance.getEntriesByType(t.type))));try{s.observe({entryTypes:[t.type]})}catch{return}}}o=!1,Cq(e);let a;return!ii(exports.RumPerformanceEntryType.FIRST_INPUT)&&t.type===exports.RumPerformanceEntryType.FIRST_INPUT&&({stop:a}=kq(e,l=>{i([l])})),()=>{s.disconnect(),a&&a(),Yt(r)}})}let ys;function Cq(e){return!ys&&Aq()&&"addEventListener"in performance&&(ys=Ke(e,performance,"resourcetimingbufferfull",()=>{performance.clearResourceTimings()})),()=>{ys?.stop()}}function Aq(){return window.performance!==void 0&&"getEntries"in performance}function ii(e){return window.PerformanceObserver&&PerformanceObserver.supportedEntryTypes!==void 0&&PerformanceObserver.supportedEntryTypes.includes(e)}function Rq(e){return e.filter(t=>!$q(t))}function $q(e){return e.entryType===exports.RumPerformanceEntryType.RESOURCE&&(!uv(e.name)||!kR(e))}function oh(e){return e.nodeType===Node.TEXT_NODE}function Oq(e){return e.nodeType===Node.COMMENT_NODE}function Ir(e){return e.nodeType===Node.ELEMENT_NODE}function lv(e){return Ir(e)&&!!e.shadowRoot}function PR(e){const t=e;return!!t.host&&t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&Ir(t.host)}function Nq(e){return e.childNodes.length>0||lv(e)}function Pq(e,t){let n=e.firstChild;for(;n;)t(n),n=n.nextSibling;lv(e)&&t(e.shadowRoot)}function MR(e){return PR(e)?e.host:e.parentNode}const jR=100,Mq=100,Kb="data-dd-excluded-activity-mutations";function cv(e,t,n,i,r,o){const s=Dq(e,t,n,i);return jq(s,r,o)}function jq(e,t,n){let i,r=!1;const o=bt(ye(()=>u({hadActivity:!1})),jR),s=n!==void 0?bt(ye(()=>u({hadActivity:!0,end:ht()})),n):void 0,a=e.subscribe(({isBusy:c})=>{Yt(o),Yt(i);const d=ht();c||(i=bt(ye(()=>u({hadActivity:!0,end:d})),Mq))}),l=()=>{r=!0,Yt(o),Yt(i),Yt(s),a.unsubscribe()};function u(c){r||(l(),t(c))}return{stop:l}}function Dq(e,t,n,i){return new Ie(r=>{const o=[];let s,a=0;return o.push(t.subscribe(u=>{u.every(zq)||l()}),n.subscribe(l),nr(i,{type:exports.RumPerformanceEntryType.RESOURCE}).subscribe(u=>{u.some(c=>!Of(i,c.name))&&l()}),e.subscribe(7,u=>{Of(i,u.url)||(s===void 0&&(s=u.requestIndex),a+=1,l())}),e.subscribe(8,u=>{Of(i,u.url)||s===void 0||u.requestIndex<s||(a-=1,l())})),()=>{o.forEach(u=>u.unsubscribe())};function l(){r.notify({isBusy:a>0})}})}function Of(e,t){return Cd(e.excludedActivityUrls,t)}function zq(e){const t=e.type==="characterData"?e.target.parentElement:e.target;return!!(t&&Ir(t)&&t.matches(`[${Kb}], [${Kb}] *`))}const Od="data-dd-action-name",DR="Masked Element",zR=[Od,"data-testid","data-test","data-qa","data-cy","data-test-id","data-qa-id","data-testing","data-component","data-element","data-source-file"],Lq=[UR,Fq],Uq=[UR,Bq,Vq];function du(e,t){if(!e.isConnected)return;let n,i=e;for(;i&&i.nodeName!=="HTML";){const r=Yb(i,Lq,Zq,t,n);if(r)return r;n=Yb(i,Uq,Hq,t,n)||Nd(qq(i),n),i=i.parentElement}return n}function LR(e){return/[0-9]/.test(e)}function Fq(e){if(e.id&&!LR(e.id))return`#${CSS.escape(e.id)}`}function Bq(e){if(e.tagName==="BODY")return;const t=e.classList;for(let n=0;n<t.length;n+=1){const i=t[n];if(!LR(i))return`${CSS.escape(e.tagName)}.${CSS.escape(i)}`}}function Vq(e){return CSS.escape(e.tagName)}function UR(e,t){if(t){const i=n(t);if(i)return i}for(const i of zR){const r=n(i);if(r)return r}function n(i){if(e.hasAttribute(i))return`${CSS.escape(e.tagName)}[${i}="${CSS.escape(e.getAttribute(i))}"]`}}function qq(e){let t=e.parentElement.firstElementChild,n=1;for(;t&&t!==e;)t.tagName===e.tagName&&(n+=1),t=t.nextElementSibling;return`${CSS.escape(e.tagName)}:nth-of-type(${n})`}function Yb(e,t,n,i,r){for(const o of t){const s=o(e,i);if(s&&n(e,s,r))return Nd(s,r)}}function Zq(e,t,n){return e.ownerDocument.querySelectorAll(Nd(t,n)).length===1}function Hq(e,t,n){let i;if(n===void 0)i=s=>s.matches(t);else{const s=Nd(`${t}:scope`,n);i=a=>a.querySelector(s)!==null}let o=e.parentElement.firstElementChild;for(;o;){if(o!==e&&i(o))return!1;o=o.nextElementSibling}return!0}function Nd(e,t){return t?`${e}>${t}`:e}const xe={IGNORE:"ignore",HIDDEN:"hidden",ALLOW:ho.ALLOW,MASK:ho.MASK,MASK_USER_INPUT:ho.MASK_USER_INPUT,MASK_UNLESS_ALLOWLISTED:ho.MASK_UNLESS_ALLOWLISTED},dv="data-dd-privacy",Gq="hidden",Wq="dd-privacy-",pl="***",Jq="data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",Kq={INPUT:!0,OUTPUT:!0,TEXTAREA:!0,SELECT:!0,OPTION:!0,DATALIST:!0,OPTGROUP:!0},Yq="x";function gi(e){return`[${dv}="${e}"], .${Wq}${e}`}function fu(e,t,n){if(n&&n.has(e))return n.get(e);const i=MR(e),r=i?fu(i,t,n):t,o=BR(e),s=FR(o,r);return n&&n.set(e,s),s}function FR(e,t){switch(t){case xe.HIDDEN:case xe.IGNORE:return t}switch(e){case xe.ALLOW:case xe.MASK:case xe.MASK_USER_INPUT:case xe.MASK_UNLESS_ALLOWLISTED:case xe.HIDDEN:case xe.IGNORE:return e;default:return t}}function BR(e){if(Ir(e)){if(e.tagName==="BASE")return xe.ALLOW;if(e.tagName==="INPUT"){const t=e;if(t.type==="password"||t.type==="email"||t.type==="tel"||t.type==="hidden")return xe.MASK;const n=t.getAttribute("autocomplete");if(n&&(n.startsWith("cc-")||n.endsWith("-password")))return xe.MASK}if(e.matches(gi(xe.HIDDEN)))return xe.HIDDEN;if(e.matches(gi(xe.MASK)))return xe.MASK;if(e.matches(gi(xe.MASK_UNLESS_ALLOWLISTED)))return xe.MASK_UNLESS_ALLOWLISTED;if(e.matches(gi(xe.MASK_USER_INPUT)))return xe.MASK_USER_INPUT;if(e.matches(gi(xe.ALLOW)))return xe.ALLOW;if(Qq(e))return xe.IGNORE}}function fv(e,t){switch(t){case xe.MASK:case xe.HIDDEN:case xe.IGNORE:return!0;case xe.MASK_UNLESS_ALLOWLISTED:return oh(e)?Bu(e.parentNode)?!0:!ZR(e.textContent||""):Bu(e);case xe.MASK_USER_INPUT:return oh(e)?Bu(e.parentNode):Bu(e);default:return!1}}function VR(e,t,n,i,r){if(i!==xe.MASK&&i!==xe.MASK_UNLESS_ALLOWLISTED||t===dv||zR.includes(t)||t===r.actionNameAttribute)return!1;switch(t){case"title":case"alt":case"placeholder":return!0}return!!(e==="A"&&t==="href"||e==="IFRAME"&&t==="srcdoc"||n&&t.startsWith("data-")||(e==="IMG"||e==="SOURCE")&&(t==="src"||t==="srcset"))}function Bu(e){if(!e||e.nodeType!==e.ELEMENT_NODE)return!1;const t=e;if(t.tagName==="INPUT")switch(t.type){case"button":case"color":case"reset":case"submit":return!1}return!!Kq[t.tagName]}const qR=e=>e.replace(/\S/g,Yq);function Xq(e,t){var n;const i=(n=e.parentElement)===null||n===void 0?void 0:n.tagName;let r=e.textContent||"";if(i==="HEAD"&&!r.trim())return;const s=t;if(i==="SCRIPT")r=pl;else if(s===xe.HIDDEN)r=pl;else if(fv(e,s))if(i==="DATALIST"||i==="SELECT"||i==="OPTGROUP"){if(!r.trim())return}else i==="OPTION"?r=pl:s===xe.MASK_UNLESS_ALLOWLISTED?r=HR(r):r=qR(r);return r}function Qq(e){if(e.nodeName==="SCRIPT")return!0;if(e.nodeName==="LINK"){const n=t("rel");return/preload|prefetch/i.test(n)&&t("as")==="script"||n==="shortcut icon"||n==="icon"}if(e.nodeName==="META"){const n=t("name"),i=t("rel"),r=t("property");return/^msapplication-tile(image|color)$/.test(n)||n==="application-name"||i==="icon"||i==="apple-touch-icon"||i==="shortcut icon"||n==="keywords"||n==="description"||/^(og|twitter|fb):/.test(r)||/^(og|twitter):/.test(n)||n==="pinterest"||n==="robots"||n==="googlebot"||n==="bingbot"||e.hasAttribute("http-equiv")||n==="author"||n==="generator"||n==="framework"||n==="publisher"||n==="progid"||/^article:/.test(r)||/^product:/.test(r)||n==="google-site-verification"||n==="yandex-verification"||n==="csrf-token"||n==="p:domain_verify"||n==="verify-v1"||n==="verification"||n==="shopify-checkout-api-token"}function t(n){return(e.getAttribute(n)||"").toLowerCase()}return!1}function ZR(e){var t;return!e||!e.trim()?!0:((t=window.$DD_ALLOW)===null||t===void 0?void 0:t.has(e.toLocaleLowerCase()))||!1}function HR(e,t){return ZR(e)?e:t||qR(e)}const GR=_t,e3=100;function t3(e,t){const n=[];let i=0,r;o(e);function o(l){l.stopObservable.subscribe(s),n.push(l),Yt(r),r=bt(a,GR)}function s(){i===1&&n.every(l=>l.isStopped())&&(i=2,t(n))}function a(){Yt(r),i===0&&(i=1,s())}return{tryAppend:l=>i!==0?!1:n.length>0&&!n3(n[n.length-1].event,l.event)?(a(),!1):(o(l),!0),stop:()=>{a()}}}function n3(e,t){return e.target===t.target&&r3(e,t)<=e3&&e.timeStamp-t.timeStamp<=GR}function r3(e,t){return Math.sqrt(Math.pow(e.clientX-t.clientX,2)+Math.pow(e.clientY-t.clientY,2))}function i3(e,t,n=xe.ALLOW){const i=new Map,{actionNameAttribute:r}=t,o=Xb(e,Od)||r&&Xb(e,r);return o?{name:o,nameSource:"custom_attribute"}:n===xe.MASK?{name:DR,nameSource:"mask_placeholder"}:Qb(e,o3,t,i)||Qb(e,s3,t,i)||{name:"",nameSource:"blank"}}function Xb(e,t){const n=e.closest(`[${t}]`);if(!n)return;const i=n.getAttribute(t);return JR(WR(i.trim()))}const o3=[(e,t,n)=>{if("labels"in e&&e.labels&&e.labels.length>0)return hl(e.labels[0],t,n)},e=>{if(e.nodeName==="INPUT"){const t=e,n=t.getAttribute("type");if(n==="button"||n==="submit"||n==="reset")return{name:t.value,nameSource:"text_content"}}},(e,t,n)=>{if(e.nodeName==="BUTTON"||e.nodeName==="LABEL"||e.getAttribute("role")==="button")return hl(e,t,n)},(e,t,n)=>bs(e,"aria-label",t,n),(e,t,n)=>{const i=e.getAttribute("aria-labelledby");if(i)return{name:i.split(/\s+/).map(r=>u3(e,r)).filter(r=>!!r).map(r=>KR(r,t,n)).join(" "),nameSource:"text_content"}},(e,t,n)=>bs(e,"alt",t,n),(e,t,n)=>bs(e,"name",t,n),(e,t,n)=>bs(e,"title",t,n),(e,t,n)=>bs(e,"placeholder",t,n),(e,t,n)=>{if("options"in e&&e.options.length>0)return hl(e.options[0],t,n)}],s3=[(e,t,n)=>hl(e,t,n)],a3=10;function Qb(e,t,n,i){let r=e,o=0;for(;o<=a3&&r&&r.nodeName!=="BODY"&&r.nodeName!=="HTML"&&r.nodeName!=="HEAD";){for(const s of t){const a=s(r,n,i);if(a){const{name:l,nameSource:u}=a,c=l&&l.trim();if(c)return{name:JR(WR(c)),nameSource:u}}}if(r.nodeName==="FORM")break;r=r.parentElement,o+=1}}function WR(e){return e.replace(/\s+/g," ")}function JR(e){return e.length>100?`${Jg(e,100)} [...]`:e}function u3(e,t){return e.ownerDocument?e.ownerDocument.getElementById(t):null}function bs(e,t,n,i){const{enablePrivacyForActionName:r,defaultPrivacyLevel:o}=n;let s=e.getAttribute(t);if(s&&r){const a=fu(e,o,i);VR(e.tagName,t,s,a,n)&&(s=HR(s,DR))}else s||(s="");return{name:s,nameSource:"standard_attribute"}}function hl(e,t,n){return{name:KR(e,t,n)||"",nameSource:"text_content"}}function KR(e,t,n){if(e.isContentEditable)return;const{enablePrivacyForActionName:i,actionNameAttribute:r,defaultPrivacyLevel:o}=t;if(au(Jr.USE_TREE_WALKER_FOR_ACTION_NAME))return l3(e,r,i,o,n);if("innerText"in e){let s=e.innerText;const a=l=>{const u=e.querySelectorAll(l);for(let c=0;c<u.length;c+=1){const d=u[c];if("innerText"in d){const f=d.innerText;f&&f.trim().length>0&&(s=s.replace(f,""))}}};return a(`[${Od}]`),r&&a(`[${r}]`),i&&a(`${gi(xe.HIDDEN)}, ${gi(xe.MASK)}`),s}return e.textContent}function l3(e,t,n,i,r){const o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,a);let s="";for(;o.nextNode();){const l=o.currentNode;if(Ir(l)){(l.nodeName==="BR"||l.nodeName==="P"||["block","flex","grid","list-item","table","table-caption"].includes(getComputedStyle(l).display))&&(s+=" ");continue}s+=l.textContent||""}return s.replace(/\s+/g," ").trim();function a(l){const u=fu(l,i,r);if(n&&u&&fv(l,u))return NodeFilter.FILTER_REJECT;if(Ir(l)){if(l.hasAttribute(Od)||t&&l.hasAttribute(t))return NodeFilter.FILTER_REJECT;const c=getComputedStyle(l);if(c.visibility!=="visible"||c.display==="none"||c.contentVisibility&&c.contentVisibility!=="visible")return NodeFilter.FILTER_REJECT}return NodeFilter.FILTER_ACCEPT}}function c3(e,{onPointerDown:t,onPointerUp:n}){let i,r={selection:!1,input:!1,scroll:!1},o;const s=[Ke(e,window,"pointerdown",a=>{t_(a)&&(i=e_(),r={selection:!1,input:!1,scroll:!1},o=t(a))},{capture:!0}),Ke(e,window,"selectionchange",()=>{(!i||!e_())&&(r.selection=!0)},{capture:!0}),Ke(e,window,"scroll",()=>{r.scroll=!0},{capture:!0,passive:!0}),Ke(e,window,"pointerup",a=>{if(t_(a)&&o){const l=r;n(o,a,()=>l),o=void 0}},{capture:!0}),Ke(e,window,"input",()=>{r.input=!0},{capture:!0})];return{stop:()=>{s.forEach(a=>a.stop())}}}function e_(){const e=window.getSelection();return!e||e.isCollapsed}function t_(e){return e.target instanceof Element&&e.isPrimary!==!1}const n_=3;function d3(e,t){if(f3(e))return t.addFrustration(vs.RAGE_CLICK),e.some(r_)&&t.addFrustration(vs.DEAD_CLICK),t.hasError&&t.addFrustration(vs.ERROR_CLICK),{isRage:!0};const n=e.some(i=>i.getUserActivity().selection);return e.forEach(i=>{i.hasError&&i.addFrustration(vs.ERROR_CLICK),r_(i)&&!n&&i.addFrustration(vs.DEAD_CLICK)}),{isRage:!1}}function f3(e){if(e.some(t=>t.getUserActivity().selection||t.getUserActivity().scroll))return!1;for(let t=0;t<e.length-(n_-1);t+=1)if(e[t+n_-1].event.timeStamp-e[t].event.timeStamp<=_t)return!0;return!1}const p3='input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="range"]),textarea,select,[contenteditable],[contenteditable] *,canvas,a[href],a[href] *';function r_(e){if(e.hasPageActivity||e.getUserActivity().input||e.getUserActivity().scroll)return!1;let t=e.event.target;return t.tagName==="LABEL"&&t.hasAttribute("for")&&(t=document.getElementById(t.getAttribute("for"))),!t||!t.matches(p3)}const YR=10*_t,Ms=new Map;function h3(e){const t=Ms.get(e);return Ms.delete(e),t}function XR(e,t){Ms.set(e,t),Ms.forEach((n,i)=>{tt(i,rn())>YR&&Ms.delete(i)})}const m3=5*Ut;function g3(e,t,n,i){const r=is({expireDelay:m3}),o=new Ie;let s;e.subscribe(10,()=>{r.reset()}),e.subscribe(5,c),e.subscribe(11,d=>{d.reason===yo.UNLOADING&&c()});const{stop:a}=c3(i,{onPointerDown:d=>v3(i,e,t,d,n),onPointerUp:({clickActionBase:d,hadActivityOnPointerDown:f},p,m)=>{y3(i,e,t,n,r,o,u,d,p,m,f)}});return{stop:()=>{c(),o.notify(),a()},actionContexts:{findActionId:d=>r.findAll(d)}};function u(d){if(!s||!s.tryAppend(d)){const f=d.clone();s=t3(d,p=>{_3(p,f)})}}function c(){s&&s.stop()}}function v3(e,t,n,i,r){let o;if(e.enablePrivacyForActionName?o=fu(i.target,e.defaultPrivacyLevel):o=xe.ALLOW,o===xe.HIDDEN)return;const s=b3(i,o,e);let a=!1;return cv(t,n,r,e,l=>{a=l.hadActivity},jR),{clickActionBase:s,hadActivityOnPointerDown:()=>a}}function y3(e,t,n,i,r,o,s,a,l,u,c){var d;const f=QR(t,r,u,a,l);s(f);const p=(d=a?.target)===null||d===void 0?void 0:d.selector;p&&XR(l.timeStamp,p);const{stop:m}=cv(t,n,i,e,y=>{y.hadActivity&&y.end<f.startClocks.timeStamp?f.discard():y.hadActivity?f.stop(y.end):c()?f.stop(f.startClocks.timeStamp):f.stop()},YR),h=t.subscribe(5,({endClocks:y})=>{f.stop(y.timeStamp)}),v=o.subscribe(()=>{f.stop()});f.stopObservable.subscribe(()=>{h.unsubscribe(),m(),v.unsubscribe()})}function b3(e,t,n){const i=e.target.getBoundingClientRect(),r=du(e.target,n.actionNameAttribute);r&&XR(e.timeStamp,r);const{name:o,nameSource:s}=i3(e.target,n,t);return{type:$d.CLICK,target:{width:Math.round(i.width),height:Math.round(i.height),selector:r},position:{x:Math.round(e.clientX-i.left),y:Math.round(e.clientY-i.top)},name:o,nameSource:s}}function QR(e,t,n,i,r){const o=Tt(),s=ct(),a=t.add(o,s.relative),l=NR({lifeCycle:e,isChildEvent:m=>m.action!==void 0&&(Array.isArray(m.action.id)?m.action.id.includes(o):m.action.id===o)});let u=0,c;const d=[],f=new Ie;function p(m){u===0&&(c=m,u=1,c?a.close(Wg(c)):a.remove(),l.stop(),f.notify())}return{event:r,stop:p,stopObservable:f,get hasError(){return l.eventCounts.errorCount>0},get hasPageActivity(){return c!==void 0},getUserActivity:n,addFrustration:m=>{d.push(m)},startClocks:s,isStopped:()=>u===1||u===2,clone:()=>QR(e,t,n,i,r),validate:m=>{if(p(),u!==1)return;const{resourceCount:h,errorCount:v,longTaskCount:y}=l.eventCounts,w={duration:c&&tt(s.timeStamp,c),startClocks:s,id:o,frustrationTypes:d,counts:{resourceCount:h,errorCount:v,longTaskCount:y},events:m??[r],event:r,...i};e.notify(0,w),u=2},discard:()=>{p(),u=2}}}function _3(e,t){const{isRage:n}=d3(e,t);n?(e.forEach(i=>i.discard()),t.stop(ht()),t.validate(e.map(i=>i.event))):(t.discard(),e.forEach(i=>i.validate()))}function w3(e,t,n,i,r){const{unsubscribe:o}=e.subscribe(0,l=>{e.notify(12,i_(l))});t.register(0,({startTime:l,eventType:u})=>{if(u!==me.ERROR&&u!==me.RESOURCE&&u!==me.LONG_TASK)return on;const c=s.findActionId(l);return c?{type:u,action:{id:c}}:on}),t.register(1,({startTime:l})=>({action:{id:s.findActionId(l)}}));let s={findActionId:$e},a=$e;return r.trackUserInteractions&&({actionContexts:s,stop:a}=g3(e,n,i,r)),{addAction:l=>{e.notify(12,i_(l))},actionContexts:s,stop:()=>{o(),a()}}}function i_(e){const t=Nf(e)?{action:{id:e.id,loading_time:OR(be(e.duration)),frustration:{type:e.frustrationTypes},error:{count:e.counts.errorCount},long_task:{count:e.counts.longTaskCount},resource:{count:e.counts.resourceCount}},_dd:{action:{target:e.target,position:e.position,name_source:e.nameSource}}}:{context:e.context},n=Er({action:{id:Tt(),target:{name:e.name},type:e.type},date:e.startClocks.timeStamp,type:me.ACTION},t),i=Nf(e)?e.duration:void 0,r=Nf(e)?{events:e.events}:{handlingStack:e.handlingStack};return{rawRumEvent:n,duration:i,startTime:e.startClocks.relative,domainContext:r}}function Nf(e){return e.type!==$d.CUSTOM}function x3(e){const t=QB([_d.error]).subscribe(n=>e.notify(n.error));return{stop:()=>{t.unsubscribe()}}}function S3(e,t){const n=D6(e,[ia.cspViolation,ia.intervention]).subscribe(i=>t.notify(i));return{stop:()=>{n.unsubscribe()}}}function E3(e,t,n){const i=new Ie;return n.subscribe(r=>{r.type===0&&i.notify(r.error)}),x3(i),S3(t,i),i.subscribe(r=>e.notify(14,{error:r})),I3(e)}function I3(e){return e.subscribe(14,({error:t})=>{e.notify(12,T3(t))}),{addError:({error:t,handlingStack:n,componentStack:i,startClocks:r,context:o})=>{const s=Qg({originalError:t,handlingStack:n,componentStack:i,startClocks:r,nonErrorPrefix:"Provided",source:es.CUSTOM,handling:"handled"});s.context=Er(s.context,o),e.notify(14,{error:s})}}}function T3(e){const t={date:e.startClocks.timeStamp,error:{id:Tt(),message:e.message,source:e.source,stack:e.stack,handling_stack:e.handlingStack,component_stack:e.componentStack,type:e.type,handling:e.handling,causes:e.causes,source_type:"browser",fingerprint:e.fingerprint,csp:e.csp},type:me.ERROR,context:e.context},n={error:e.originalError,handlingStack:e.handlingStack};return{rawRumEvent:t,startTime:e.startClocks.relative,domainContext:n}}const o_=new WeakSet;function k3(e){if(!performance||!("getEntriesByName"in performance))return;const t=performance.getEntriesByName(e.url,"resource");if(!t.length||!("toJSON"in t[0]))return;const n=t.filter(i=>!o_.has(i)).filter(i=>kR(i)&&CR(i)).filter(i=>C3(i,e.startClocks.relative,e$({startTime:e.startClocks.relative,duration:e.duration})));if(n.length===1)return o_.add(n[0]),n[0].toJSON()}function e$(e){return Xo(e.startTime,e.duration)}function C3(e,t,n){return e.startTime>=t-1&&e$(e)<=Xo(n,1)}const A3=2*Ut;function R3(e){const t=$3(e)||O3(e);if(!(!t||t.traceTime<=zt()-A3))return t.traceId}function $3(e){const t=e.querySelector("meta[name=dd-trace-id]"),n=e.querySelector("meta[name=dd-trace-time]");return t$(t&&t.content,n&&n.content)}function O3(e){const t=N3(e);if(t)return t$(na(t,"trace-id"),na(t,"trace-time"))}function t$(e,t){const n=t&&Number(t);if(!(!e||!n))return{traceId:e,traceTime:n}}function N3(e){for(let t=0;t<e.childNodes.length;t+=1){const n=s_(e.childNodes[t]);if(n)return n}if(e.body)for(let t=e.body.childNodes.length-1;t>=0;t-=1){const n=e.body.childNodes[t],i=s_(n);if(i)return i;if(!oh(n))break}}function s_(e){if(e&&Oq(e)){const t=/^\s*DATADOG;(.*?)\s*$/.exec(e.data);if(t)return t[1]}}function n$(){if(ii(exports.RumPerformanceEntryType.NAVIGATION)){const n=performance.getEntriesByType(exports.RumPerformanceEntryType.NAVIGATION)[0];if(n)return n}const e=P3(),t={entryType:exports.RumPerformanceEntryType.NAVIGATION,initiatorType:"navigation",name:window.location.href,startTime:0,duration:e.loadEventEnd,decodedBodySize:0,encodedBodySize:0,transferSize:0,workerStart:0,toJSON:()=>({...t,toJSON:void 0}),...e};return t}function P3(){const e={},t=performance.timing;for(const n in t)if(nu(t[n])){const i=n,r=t[i];e[i]=r===0?0:Wg(r)}return e}function M3(e,t,n=n$){ov(e,"interactive",()=>{const i=n(),r=Object.assign(i.toJSON(),{entryType:exports.RumPerformanceEntryType.RESOURCE,initiatorType:IR,duration:i.responseEnd,traceId:R3(document),toJSON:()=>({...r,toJSON:void 0})});t(r)})}const j3=1e3;function D3(e){const t=new Set,n=e.subscribe(8,i=>{t.add(i),t.size>j3&&(rs("Too many requests"),t.delete(t.values().next().value))});return{getMatchingRequest(i){let r=1/0,o;for(const s of t){const a=i.startTime-s.startClocks.relative;0<=a&&a<r&&s.url===i.name&&(r=Math.abs(a),o=s)}return o&&t.delete(o),o},stop(){n.unsubscribe()}}}function z3(e,t,n,i=XB(),r=M3){let o;const s=t.trackEarlyRequests;s?o=D3(e):e.subscribe(8,u=>{l(()=>L3(u,t,n))});const a=nr(t,{type:exports.RumPerformanceEntryType.RESOURCE,buffered:!0}).subscribe(u=>{for(const c of u)(s||!TR(c))&&l(()=>a_(c,t,n,o))});r(t,u=>{l(()=>a_(u,t,n,o))});function l(u){i.push(()=>{const c=u();c&&e.notify(12,c)})}return{stop:()=>{i.stop(),a.unsubscribe()}}}function L3(e,t,n){const i=k3(e);return r$(i,e,n,t)}function a_(e,t,n,i){const r=TR(e)&&i?i.getMatchingRequest(e):void 0;return r$(e,r,n,t)}function r$(e,t,n,i){if(!e&&!t)return;const r=t?V3(t,i):q3(e,i);if(!i.trackResources&&!r)return;const o=e?ru(e.startTime):t.startClocks,s=e?dq(e):Z3(n,o,t.duration),a=t&&U3(t,i),l=Er({date:o.timeStamp,resource:{id:Tt(),duration:be(s),type:t?t.type===Rd.XHR?jt.XHR:jt.FETCH:cq(e),method:t?t.method:void 0,status_code:t?t.status:H3(e.responseStatus),url:t?AR(t.url):e.name,protocol:e&&hq(e),delivery_type:e&&mq(e),graphql:a},type:me.RESOURCE,_dd:{discarded:!i.trackResources}},r,e&&B3(e));return{startTime:o.relative,duration:s,rawRumEvent:l,domainContext:F3(e,t)}}function U3(e,t){const n=RR(e.url,t);if(n)return _q(e,n)}function F3(e,t){if(t){const n={performanceEntry:e,isAborted:t.isAborted,handlingStack:t.handlingStack};return t.type===Rd.XHR?{xhr:t.xhr,...n}:{requestInput:t.input,requestInit:t.init,response:t.response,error:t.error,...n}}return{performanceEntry:e}}function B3(e){const{renderBlockingStatus:t}=e;return{resource:{render_blocking_status:t,...gq(e),...fq(e)}}}function V3(e,t){if(e.traceSampled&&e.traceId&&e.spanId)return{_dd:{span_id:e.spanId.toString(),trace_id:e.traceId.toString(),rule_psr:t.rulePsr}}}function q3(e,t){if(e.traceId)return{_dd:{trace_id:e.traceId,span_id:_R().toString(),rule_psr:t.rulePsr}}}function Z3(e,t,n){return e.wasInPageStateDuringPeriod("frozen",t.relative,n)?void 0:n}function H3(e){return e===0?void 0:e}function G3(e,t,n){const{stop:i,eventCounts:r}=NR({lifeCycle:e,isChildEvent:o=>o.view.id===t,onChange:n});return{stop:i,eventCounts:r}}const W3=10*Ut;function J3(e,t,n){return{stop:nr(e,{type:exports.RumPerformanceEntryType.PAINT,buffered:!0}).subscribe(r=>{const o=r.find(s=>s.name==="first-contentful-paint"&&s.startTime<t.timeStamp&&s.startTime<W3);o&&n(o.startTime)}).unsubscribe}}function K3(e,t){requestAnimationFrame(()=>{requestAnimationFrame(()=>{t(tt(e,rn()))})})}function Y3(e,t,n){const i=nr(e,{type:exports.RumPerformanceEntryType.FIRST_INPUT,buffered:!0}).subscribe(r=>{const o=r.find(s=>s.startTime<t.timeStamp);if(o){const s=tt(o.startTime,o.processingStart);let a;o.target&&Ir(o.target)&&(a=du(o.target,e.actionNameAttribute)),n({delay:s>=0?s:0,time:o.startTime,targetSelector:a})}});return{stop:()=>{i.unsubscribe()}}}function X3(e,t,n=n$){return t5(e,()=>{const i=n();e5(i)||t(Q3(i))})}function Q3(e){return{domComplete:e.domComplete,domContentLoaded:e.domContentLoadedEventEnd,domInteractive:e.domInteractive,loadEvent:e.loadEventEnd,firstByte:e.responseStart>=0&&e.responseStart<=rn()?e.responseStart:void 0}}function e5(e){return e.loadEventEnd<=0}function t5(e,t){let n;const{stop:i}=ov(e,"complete",()=>{n=bt(()=>t())});return{stop:()=>{i(),Yt(n)}}}const n5=10*Ut;function r5(e,t,n,i){let r=1/0;const{stop:o}=Sr(e,n,["pointerdown","keydown"],l=>{r=l.timeStamp},{capture:!0,once:!0});let s=0;const a=nr(e,{type:exports.RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT,buffered:!0}).subscribe(l=>{const u=_A(l,c=>c.entryType===exports.RumPerformanceEntryType.LARGEST_CONTENTFUL_PAINT&&c.startTime<r&&c.startTime<t.timeStamp&&c.startTime<n5&&c.size>s);if(u){let c;u.element&&(c=du(u.element,e.actionNameAttribute)),i({value:u.startTime,targetSelector:c,resourceUrl:i5(u)}),s=u.size}});return{stop:()=>{o(),a.unsubscribe()}}}function i5(e){return e.url===""?void 0:e.url}function i$(e,t,n=window){if(document.visibilityState==="hidden")return{timeStamp:0,stop:$e};if(ii(exports.RumPerformanceEntryType.VISIBILITY_STATE)){const o=performance.getEntriesByType(exports.RumPerformanceEntryType.VISIBILITY_STATE).filter(s=>s.name==="hidden").find(s=>s.startTime>=t.relative);if(o)return{timeStamp:o.startTime,stop:$e}}let i=1/0;const{stop:r}=Sr(e,n,["pagehide","visibilitychange"],o=>{(o.type==="pagehide"||document.visibilityState==="hidden")&&(i=o.timeStamp,r())},{capture:!0});return{get timeStamp(){return i},stop:r}}function o5(e,t,n,i){const r={},{stop:o}=X3(e,d=>{n(d.loadEvent),r.navigationTimings=d,i()}),s=i$(e,t),{stop:a}=J3(e,s,d=>{r.firstContentfulPaint=d,i()}),{stop:l}=r5(e,s,window,d=>{r.largestContentfulPaint=d,i()}),{stop:u}=Y3(e,s,d=>{r.firstInput=d,i()});function c(){o(),a(),l(),u(),s.stop()}return{stop:c,initialViewMetrics:r}}const sh=(e,t)=>e*t,s5=(e,t)=>{const n=Math.max(e.left,t.left),i=Math.max(e.top,t.top),r=Math.min(e.right,t.right),o=Math.min(e.bottom,t.bottom);return n>=r||i>=o?0:sh(r-n,o-i)},u_=e=>{const t=sh(e.previousRect.width,e.previousRect.height),n=sh(e.currentRect.width,e.currentRect.height),i=s5(e.previousRect,e.currentRect);return t+n-i};function a5(e,t,n){if(!f5())return{stop:$e};let i=0,r;n({value:0});const o=d5(),s=nr(e,{type:exports.RumPerformanceEntryType.LAYOUT_SHIFT,buffered:!0}).subscribe(a=>{var l;for(const u of a){if(u.hadRecentInput||u.startTime<t)continue;const{cumulatedValue:c,isMaxValue:d}=o.update(u);if(d){const f=u5(u.sources);r={target:f?.node?new WeakRef(f.node):void 0,time:tt(t,u.startTime),previousRect:f?.previousRect,currentRect:f?.currentRect,devicePixelRatio:window.devicePixelRatio}}if(c>i){i=c;const f=(l=r?.target)===null||l===void 0?void 0:l.deref();n({value:Ns(i,4),targetSelector:f&&du(f,e.actionNameAttribute),time:r?.time,previousRect:r?.previousRect?l_(r.previousRect):void 0,currentRect:r?.currentRect?l_(r.currentRect):void 0,devicePixelRatio:r?.devicePixelRatio})}}});return{stop:()=>{s.unsubscribe()}}}function u5(e){let t;for(const n of e)if(n.node&&Ir(n.node)){const i=u_(n);(!t||u_(t)<i)&&(t=n)}return t}function l_({x:e,y:t,width:n,height:i}){return{x:e,y:t,width:n,height:i}}const l5=5*_t,c5=_t;function d5(){let e=0,t,n,i=0;return{update:r=>{const o=t===void 0||r.startTime-n>=c5||r.startTime-t>=l5;let s;return o?(t=n=r.startTime,i=e=r.value,s=!0):(e+=r.value,n=r.startTime,s=r.value>i,s&&(i=r.value)),{cumulatedValue:e,isMaxValue:s}}}}function f5(){return ii(exports.RumPerformanceEntryType.LAYOUT_SHIFT)&&"WeakRef"in window}let ml,o$=0,Pf=1/0,Mf=0;function p5(){"interactionCount"in performance||ml||(ml=new window.PerformanceObserver(ye(e=>{e.getEntries().forEach(t=>{const n=t;n.interactionId&&(Pf=Math.min(Pf,n.interactionId),Mf=Math.max(Mf,n.interactionId),o$=(Mf-Pf)/7+1)})})),ml.observe({type:"event",buffered:!0,durationThreshold:0}))}const c_=()=>ml?o$:window.performance.interactionCount||0,d_=10,h5=1*Ut;function m5(e,t,n){if(!y5())return{getInteractionToNextPaint:()=>{},setViewEnd:$e,stop:$e};const{getViewInteractionCount:i,stopViewInteractionCount:r}=v5(n);let o=1/0;const s=g5(i);let a=-1,l,u;function c(p){for(const h of p)h.interactionId&&h.startTime>=t&&h.startTime<=o&&s.process(h);const m=s.estimateP98Interaction();m&&m.duration!==a&&(a=m.duration,u=tt(t,m.startTime),l=h3(m.startTime),!l&&m.target&&Ir(m.target)&&(l=du(m.target,e.actionNameAttribute)))}const d=nr(e,{type:exports.RumPerformanceEntryType.FIRST_INPUT,buffered:!0}).subscribe(c),f=nr(e,{type:exports.RumPerformanceEntryType.EVENT,durationThreshold:40,buffered:!0}).subscribe(c);return{getInteractionToNextPaint:()=>{if(a>=0)return{value:Math.min(a,h5),targetSelector:l,time:u};if(i())return{value:0}},setViewEnd:p=>{o=p,r()},stop:()=>{f.unsubscribe(),d.unsubscribe()}}}function g5(e){const t=[];function n(){t.sort((i,r)=>r.duration-i.duration).splice(d_)}return{process(i){const r=t.findIndex(s=>i.interactionId===s.interactionId),o=t[t.length-1];r!==-1?i.duration>t[r].duration&&(t[r]=i,n()):(t.length<d_||i.duration>o.duration)&&(t.push(i),n())},estimateP98Interaction(){const i=Math.min(t.length-1,Math.floor(e()/50));return t[i]}}}function v5(e){p5();const t=e===mr.INITIAL_LOAD?0:c_();let n={stopped:!1};function i(){return c_()-t}return{getViewInteractionCount:()=>n.stopped?n.interactionCount:i(),stopViewInteractionCount:()=>{n={stopped:!0,interactionCount:i()}}}}function y5(){return ii(exports.RumPerformanceEntryType.EVENT)&&window.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype}function b5(e,t,n,i,r,o,s){let a=r===mr.INITIAL_LOAD,l=!0;const u=[],c=i$(i,o);function d(){if(!l&&!a&&u.length>0){const p=Math.max(...u);p<c.timeStamp-o.relative&&s(p)}}const{stop:f}=cv(e,t,n,i,p=>{l&&(l=!1,p.hadActivity&&u.push(tt(o.timeStamp,p.end)),d())});return{stop:()=>{f(),c.stop()},setLoadEvent:p=>{a&&(a=!1,u.push(p),d())}}}function _5(){let e;const t=window.visualViewport;return t?e=t.pageLeft-t.offsetLeft:window.scrollX!==void 0?e=window.scrollX:e=window.pageXOffset||0,Math.round(e)}function s$(){let e;const t=window.visualViewport;return t?e=t.pageTop-t.offsetTop:window.scrollY!==void 0?e=window.scrollY:e=window.pageYOffset||0,Math.round(e)}let jf;function a$(e){return jf||(jf=w5(e)),jf}function w5(e){return new Ie(t=>{const{throttled:n}=ou(()=>{t.notify(Pd())},200);return Ke(e,window,"resize",n,{capture:!0,passive:!0}).stop})}function Pd(){const e=window.visualViewport;return e?{width:Number(e.width*e.scale),height:Number(e.height*e.scale)}:{width:Number(window.innerWidth||0),height:Number(window.innerHeight||0)}}const x5=_t;function S5(e,t,n,i=I5(e)){let r=0,o=0,s=0;const a=i.subscribe(({scrollDepth:l,scrollTop:u,scrollHeight:c})=>{let d=!1;if(l>r&&(r=l,d=!0),c>o){o=c;const f=rn();s=tt(t.relative,f),d=!0}d&&n({maxDepth:Math.min(r,o),maxDepthScrollTop:u,maxScrollHeight:o,maxScrollHeightTime:s})});return{stop:()=>a.unsubscribe()}}function E5(){const e=s$(),{height:t}=Pd(),n=Math.round((document.scrollingElement||document.documentElement).scrollHeight),i=Math.round(t+e);return{scrollHeight:n,scrollDepth:i,scrollTop:e}}function I5(e,t=x5){return new Ie(n=>{function i(){n.notify(E5())}if(window.ResizeObserver){const r=ou(i,t,{leading:!1,trailing:!0}),o=document.scrollingElement||document.documentElement,s=new ResizeObserver(ye(r.throttled));o&&s.observe(o);const a=Ke(e,window,"scroll",r.throttled,{passive:!0});return()=>{r.cancel(),s.disconnect(),a.stop()}}})}function T5(e,t,n,i,r,o,s){const a={},{stop:l,setLoadEvent:u}=b5(e,t,n,i,o,s,h=>{a.loadingTime=h,r()}),{stop:c}=S5(i,s,h=>{a.scroll=h}),{stop:d}=a5(i,s.relative,h=>{a.cumulativeLayoutShift=h,r()}),{stop:f,getInteractionToNextPaint:p,setViewEnd:m}=m5(i,s.relative,o);return{stop:()=>{l(),d(),c()},stopINPTracking:f,setLoadEvent:u,setViewEnd:m,getCommonViewMetrics:()=>(a.interactionToNextPaint=p(),a)}}function k5(e,t){const{stop:n}=Ke(e,window,"pageshow",i=>{i.persisted&&t(i)},{capture:!0});return n}function C5(e,t,n){K3(e.relative,i=>{t.firstContentfulPaint=i,t.largestContentfulPaint={value:i},n()})}const A5=3e3,R5=5*Ut,$5=5*Ut;function O5(e,t,n,i,r,o,s,a){const l=new Set;let u=f(mr.INITIAL_LOAD,Gg(),a),c;p();let d;s&&(d=m(o),r.trackBfcacheViews&&(c=k5(r,h=>{u.end();const v=ru(h.timeStamp);u=f(mr.BF_CACHE,v,void 0)})));function f(h,v,y){const w=N5(t,n,i,r,e,h,v,y);return l.add(w),w.stopObservable.subscribe(()=>{l.delete(w)}),w}function p(){t.subscribe(10,()=>{u=f(mr.ROUTE_CHANGE,void 0,{name:u.name,service:u.service,version:u.version,context:u.contextManager.getContext()})}),t.subscribe(9,()=>{u.end({sessionIsActive:!1})})}function m(h){return h.subscribe(({oldLocation:v,newLocation:y})=>{M5(v,y)&&(u.end(),u=f(mr.ROUTE_CHANGE))})}return{addTiming:(h,v=ht())=>{u.addTiming(h,v)},startView:(h,v)=>{u.end({endClocks:v}),u=f(mr.ROUTE_CHANGE,v,h)},setViewContext:h=>{u.contextManager.setContext(h)},setViewContextProperty:(h,v)=>{u.contextManager.setContextProperty(h,v)},setViewName:h=>{u.setViewName(h)},getViewContext:()=>u.contextManager.getContext(),stop:()=>{d&&d.unsubscribe(),c&&c(),u.end(),l.forEach(h=>h.stop())}}}function N5(e,t,n,i,r,o,s=ct(),a){const l=Tt(),u=new Ie,c={};let d=0,f;const p=ta(r),m=Ad();let h=!0,v=a?.name;const y=a?.service||i.service,w=a?.version||i.version,S=a?.context;S&&m.setContext(S);const b={id:l,name:v,startClocks:s,service:y,version:w,context:S};e.notify(1,b),e.notify(2,b);const{throttled:C,cancel:_}=ou(E,A5,{leading:!1}),{setLoadEvent:k,setViewEnd:R,stop:M,stopINPTracking:U,getCommonViewMetrics:z}=T5(e,t,n,i,se,o,s),{stop:Z,initialViewMetrics:W}=o===mr.INITIAL_LOAD?o5(i,s,k,se):{stop:$e,initialViewMetrics:{}};o===mr.BF_CACHE&&C5(s,W,se);const{stop:j,eventCounts:L}=G3(e,l,se),Y=Yo(E,R5),ne=e.subscribe(11,we=>{we.reason===yo.UNLOADING&&E()});E(),m.changeObservable.subscribe(se);function Q(){e.notify(3,{id:l,name:v,context:m.getContext(),startClocks:s,sessionIsActive:h})}function se(){Q(),C()}function E(){_(),Q(),d+=1;const we=f===void 0?ht():f.timeStamp;e.notify(4,{customTimings:c,documentVersion:d,id:l,name:v,service:y,version:w,context:m.getContext(),loadingType:o,location:p,startClocks:s,commonViewMetrics:z(),initialViewMetrics:W,duration:tt(s.timeStamp,we),isActive:f===void 0,sessionIsActive:h,eventCounts:L})}return{get name(){return v},service:y,version:w,contextManager:m,stopObservable:u,end(we={}){var de,A;f||(f=(de=we.endClocks)!==null&&de!==void 0?de:ct(),h=(A=we.sessionIsActive)!==null&&A!==void 0?A:!0,e.notify(5,{endClocks:f}),e.notify(6,{endClocks:f}),Sd(Y),R(f.relative),M(),ne.unsubscribe(),E(),bt(()=>{this.stop()},$5))},stop(){Z(),j(),U(),u.notify()},addTiming(we,de){if(f)return;const A=Q4(de)?de:tt(s.timeStamp,de);c[P5(we)]=A,se()},setViewName(we){v=we,E()}}}function P5(e){const t=e.replace(/[^a-zA-Z0-9-_.@$]/g,"_");return t!==e&&he.warn(`Invalid timing name: ${e}, sanitized to: ${t}`),t}function M5(e,t){return e.pathname!==t.pathname||!j5(t.hash)&&f_(t.hash)!==f_(e.hash)}function j5(e){const t=e.substring(1);return t!==""&&!!document.getElementById(t)}function f_(e){const t=e.indexOf("?");return t<0?e:e.slice(0,t)}function D5(e,t,n,i,r,o,s,a,l,u){return e.subscribe(4,c=>e.notify(12,z5(c,n,a))),t.register(0,({startTime:c,eventType:d})=>{const f=l.findView(c);return f?{type:d,service:f.service,version:f.version,context:f.context,view:{id:f.id,name:f.name}}:Kr}),t.register(1,({startTime:c})=>{var d;return{view:{id:(d=l.findView(c))===null||d===void 0?void 0:d.id}}}),O5(i,e,r,o,n,s,!n.trackViewsManually,u)}function z5(e,t,n){var i,r,o,s,a,l,u,c,d,f,p,m,h,v,y,w,S,b;const C=n.getReplayStats(e.id),_=(r=(i=e.commonViewMetrics)===null||i===void 0?void 0:i.cumulativeLayoutShift)===null||r===void 0?void 0:r.devicePixelRatio,k={_dd:{document_version:e.documentVersion,replay_stats:C,cls:_?{device_pixel_ratio:_}:void 0,configuration:{start_session_replay_recording_manually:t.startSessionReplayRecordingManually}},date:e.startClocks.timeStamp,type:me.VIEW,view:{action:{count:e.eventCounts.actionCount},frustration:{count:e.eventCounts.frustrationCount},cumulative_layout_shift:(o=e.commonViewMetrics.cumulativeLayoutShift)===null||o===void 0?void 0:o.value,cumulative_layout_shift_time:be((s=e.commonViewMetrics.cumulativeLayoutShift)===null||s===void 0?void 0:s.time),cumulative_layout_shift_target_selector:(a=e.commonViewMetrics.cumulativeLayoutShift)===null||a===void 0?void 0:a.targetSelector,first_byte:be((l=e.initialViewMetrics.navigationTimings)===null||l===void 0?void 0:l.firstByte),dom_complete:be((u=e.initialViewMetrics.navigationTimings)===null||u===void 0?void 0:u.domComplete),dom_content_loaded:be((c=e.initialViewMetrics.navigationTimings)===null||c===void 0?void 0:c.domContentLoaded),dom_interactive:be((d=e.initialViewMetrics.navigationTimings)===null||d===void 0?void 0:d.domInteractive),error:{count:e.eventCounts.errorCount},first_contentful_paint:be(e.initialViewMetrics.firstContentfulPaint),first_input_delay:be((f=e.initialViewMetrics.firstInput)===null||f===void 0?void 0:f.delay),first_input_time:be((p=e.initialViewMetrics.firstInput)===null||p===void 0?void 0:p.time),first_input_target_selector:(m=e.initialViewMetrics.firstInput)===null||m===void 0?void 0:m.targetSelector,interaction_to_next_paint:be((h=e.commonViewMetrics.interactionToNextPaint)===null||h===void 0?void 0:h.value),interaction_to_next_paint_time:be((v=e.commonViewMetrics.interactionToNextPaint)===null||v===void 0?void 0:v.time),interaction_to_next_paint_target_selector:(y=e.commonViewMetrics.interactionToNextPaint)===null||y===void 0?void 0:y.targetSelector,is_active:e.isActive,name:e.name,largest_contentful_paint:be((w=e.initialViewMetrics.largestContentfulPaint)===null||w===void 0?void 0:w.value),largest_contentful_paint_target_selector:(S=e.initialViewMetrics.largestContentfulPaint)===null||S===void 0?void 0:S.targetSelector,load_event:be((b=e.initialViewMetrics.navigationTimings)===null||b===void 0?void 0:b.loadEvent),loading_time:OR(be(e.commonViewMetrics.loadingTime)),loading_type:e.loadingType,long_task:{count:e.eventCounts.longTaskCount},performance:L5(e.commonViewMetrics,e.initialViewMetrics),resource:{count:e.eventCounts.resourceCount},time_spent:be(e.duration)},display:e.commonViewMetrics.scroll?{scroll:{max_depth:e.commonViewMetrics.scroll.maxDepth,max_depth_scroll_top:e.commonViewMetrics.scroll.maxDepthScrollTop,max_scroll_height:e.commonViewMetrics.scroll.maxScrollHeight,max_scroll_height_time:be(e.commonViewMetrics.scroll.maxScrollHeightTime)}}:void 0,privacy:{replay_level:t.defaultPrivacyLevel},device:{locale:navigator.language,locales:navigator.languages,time_zone:hV()}};return ri(e.customTimings)||(k.view.custom_timings=cA(e.customTimings,be)),{rawRumEvent:k,startTime:e.startClocks.relative,duration:e.duration,domainContext:{location:e.location}}}function L5({cumulativeLayoutShift:e,interactionToNextPaint:t},{firstContentfulPaint:n,firstInput:i,largestContentfulPaint:r}){return{cls:e&&{score:e.value,timestamp:be(e.time),target_selector:e.targetSelector,previous_rect:e.previousRect,current_rect:e.currentRect},fcp:n&&{timestamp:be(n)},fid:i&&{duration:be(i.delay),timestamp:be(i.time),target_selector:i.targetSelector},inp:t&&{duration:be(t.value),timestamp:be(t.time),target_selector:t.targetSelector},lcp:r&&{timestamp:be(r.value),target_selector:r.targetSelector,resource_url:r.resourceUrl}}}const U5="rum";function F5(e,t,n){const i=AB(e,U5,r=>V5(e,r),n);return i.expireObservable.subscribe(()=>{t.notify(9)}),i.renewObservable.subscribe(()=>{t.notify(10)}),i.sessionStateUpdateObservable.subscribe(({previousState:r,newState:o})=>{if(!r.forcedReplay&&o.forcedReplay){const s=i.findSession();s&&(s.isReplayForced=!0)}}),{findTrackedSession:r=>{const o=i.findSession(r);if(!(!o||o.trackingType==="0"))return{id:o.id,sessionReplay:o.trackingType==="1"?1:o.isReplayForced?2:0,anonymousId:o.anonymousId}},expire:i.expire,expireObservable:i.expireObservable,setForcedReplay:()=>i.updateSessionState({forcedReplay:"1"})}}function B5(){const e={id:"00000000-aaaa-0000-aaaa-000000000000",sessionReplay:QA("records")?1:0};return{findTrackedSession:()=>e,expire:$e,expireObservable:new Ie,setForcedReplay:$e}}function V5(e,t){return q5(t)?t:_i(e.sessionSampleRate)?_i(e.sessionReplaySampleRate)?"1":"2":"0"}function q5(e){return e==="0"||e==="1"||e==="2"}function Z5(e,t,n,i,r,o){const s=[e.rumEndpointBuilder];e.replica&&s.push(e.replica.rumEndpointBuilder);const a=tR({encoder:o(2),request:rv(s,n),flushController:nR({pageMayExitObservable:i,sessionExpireObservable:r})});return t.subscribe(13,l=>{l.type===me.VIEW?a.upsert(l,l.view.id):a.add(l)}),a}function H5(e){const t=ts();e.subscribe(13,n=>{t.send("rum",n)})}const G5=Li;function W5(e,t,n,i){const r=is({expireDelay:G5});let o;e.subscribe(1,({startClocks:l})=>{const u=i.href;r.add(a({url:u,referrer:o||document.referrer}),l.relative),o=u}),e.subscribe(6,({endClocks:l})=>{r.closeActive(l.relative)});const s=n.subscribe(({newLocation:l})=>{const u=r.find();if(u){const c=rn();r.closeActive(c),r.add(a({url:l.href,referrer:u.referrer}),c)}});function a({url:l,referrer:u}){return{url:l,referrer:u}}return t.register(0,({startTime:l,eventType:u})=>{const c=r.find(l);return c?{type:u,view:{url:c.url,referrer:c.referrer}}:Kr}),{findUrl:l=>r.find(l),stop:()=>{s.unsubscribe(),r.stop()}}}function J5(e,t){let n=ta(t);return new Ie(i=>{const{stop:r}=K5(e,s),{stop:o}=Y5(e,s);function s(){if(n.href===t.href)return;const a=ta(t);i.notify({newLocation:a,oldLocation:n}),n=a}return()=>{r(),o()}})}function K5(e,t){const{stop:n}=Mn(p_("pushState"),"pushState",({onPostCall:o})=>{o(t)}),{stop:i}=Mn(p_("replaceState"),"replaceState",({onPostCall:o})=>{o(t)}),{stop:r}=Ke(e,window,"popstate",t);return{stop:()=>{n(),i(),r()}}}function Y5(e,t){return Ke(e,window,"hashchange",t)}function p_(e){return Object.prototype.hasOwnProperty.call(history,e)?history:History.prototype}const X5=Li;function Q5(e,t,n){const i=is({expireDelay:X5});return e.subscribe(1,({startClocks:r})=>{i.add({},r.relative)}),e.subscribe(6,({endClocks:r})=>{i.closeActive(r.relative)}),t.register(0,({startTime:r,eventType:o})=>{if(!n.trackFeatureFlagsForEvents.concat([me.VIEW,me.ERROR]).includes(o))return on;const a=i.find(r);return!a||ri(a)?on:{type:o,feature_flags:a}}),{addFeatureFlagEvaluation:(r,o)=>{const s=i.find();s&&(s[r]=o)}}}const eZ=10*_t;let bo,Vu;function tZ(e,t,n){e.metricsEnabled&&(u$(),Vu=!1,t.subscribe(13,()=>{Vu=!0}),n.subscribe(({bytesCount:i,messagesCount:r})=>{Vu&&(Vu=!1,bo.batchCount+=1,m_(bo.batchBytesCount,i),m_(bo.batchMessagesCount,r))}),Yo(nZ,eZ))}function nZ(){bo.batchCount!==0&&(cu("Customer data measures",bo),u$())}function h_(){return{min:1/0,max:0,sum:0}}function m_(e,t){e.sum+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t)}function u$(){bo={batchCount:0,batchBytesCount:h_(),batchMessagesCount:h_()}}const rZ=4e3,iZ=500,oZ=Li;function sZ(e,t,n=iZ){const i=is({expireDelay:oZ,maxEntries:rZ});let r;ii(exports.RumPerformanceEntryType.VISIBILITY_STATE)&&performance.getEntriesByType(exports.RumPerformanceEntryType.VISIBILITY_STATE).forEach(u=>{const c=u.name==="hidden"?"hidden":"active";s(c,u.startTime)}),s(l$(),rn());const{stop:o}=Sr(t,window,["pageshow","focus","blur","visibilitychange","resume","freeze","pagehide"],l=>{s(uZ(l),l.timeStamp)},{capture:!0});function s(l,u=rn()){l!==r&&(r=l,i.closeActive(u),i.add({state:r,startTime:u},u))}function a(l,u,c){return i.findAll(u,c).some(d=>d.state===l)}return e.register(0,({startTime:l,duration:u=0,eventType:c})=>{if(c===me.VIEW){const d=i.findAll(l,u);return{type:c,_dd:{page_states:aZ(d,l,n)}}}return c===me.ACTION||c===me.ERROR?{type:c,view:{in_foreground:a("active",l,0)}}:on}),{wasInPageStateDuringPeriod:a,addPageState:s,stop:()=>{o(),i.stop()}}}function aZ(e,t,n){if(e.length!==0)return e.slice(-n).reverse().map(({state:i,startTime:r})=>({state:i,start:be(tt(t,r))}))}function uZ(e){return e.type==="freeze"?"frozen":e.type==="pagehide"?e.persisted?"frozen":"terminated":l$()}function l$(){return document.visibilityState==="hidden"?"hidden":document.hasFocus()?"active":"passive"}function lZ(e,t){let n;const i=requestAnimationFrame(ye(()=>{n=Pd()})),r=a$(t).subscribe(o=>{n=o}).unsubscribe;return e.register(0,({eventType:o})=>({type:o,display:n?{viewport:n}:void 0})),{stop:()=>{r(),i&&cancelAnimationFrame(i)}}}function cZ(e,t){const n=window.cookieStore?dZ(e):pZ;return new Ie(i=>n(t,r=>i.notify(r)))}function dZ(e){return(t,n)=>Ke(e,window.cookieStore,"change",r=>{const o=r.changed.find(s=>s.name===t)||r.deleted.find(s=>s.name===t);o&&n(o.value)}).stop}const fZ=_t;function pZ(e,t){const n=na(document.cookie,e),i=Yo(()=>{const r=na(document.cookie,e);r!==n&&t(r)},fZ);return()=>{Sd(i)}}const g_="datadog-ci-visibility-test-execution-id";function hZ(e,t,n=cZ(e,g_)){var i;let r=Lr(g_)||((i=window.Cypress)===null||i===void 0?void 0:i.env("traceId"));const o=n.subscribe(s=>{r=s});return t.register(0,({eventType:s})=>typeof r!="string"?on:{type:s,session:{type:"ci_test"},ci_test:{test_execution_id:r}}),{stop:()=>{o.unsubscribe()}}}function mZ(e,t){const n=nr(t,{type:exports.RumPerformanceEntryType.LONG_ANIMATION_FRAME,buffered:!0}).subscribe(i=>{for(const r of i){const o=ru(r.startTime),s={date:o.timeStamp,long_task:{id:Tt(),entry_type:mR.LONG_ANIMATION_FRAME,duration:be(r.duration),blocking_duration:be(r.blockingDuration),first_ui_event_timestamp:be(r.firstUIEventTimestamp),render_start:be(r.renderStart),style_and_layout_start:be(r.styleAndLayoutStart),start_time:be(r.startTime),scripts:r.scripts.map(a=>({duration:be(a.duration),pause_duration:be(a.pauseDuration),forced_style_and_layout_duration:be(a.forcedStyleAndLayoutDuration),start_time:be(a.startTime),execution_start:be(a.executionStart),source_url:a.sourceURL,source_function_name:a.sourceFunctionName,source_char_position:a.sourceCharPosition,invoker:a.invoker,invoker_type:a.invokerType,window_attribution:a.windowAttribution}))},type:me.LONG_TASK,_dd:{discarded:!1}};e.notify(12,{rawRumEvent:s,startTime:o.relative,duration:r.duration,domainContext:{performanceEntry:r}})}});return{stop:()=>n.unsubscribe()}}function gZ(e,t){const n=nr(t,{type:exports.RumPerformanceEntryType.LONG_TASK,buffered:!0}).subscribe(i=>{for(const r of i){if(r.entryType!==exports.RumPerformanceEntryType.LONG_TASK||!t.trackLongTasks)break;const o=ru(r.startTime),s={date:o.timeStamp,long_task:{id:Tt(),entry_type:mR.LONG_TASK,duration:be(r.duration)},type:me.LONG_TASK,_dd:{discarded:!1}};e.notify(12,{rawRumEvent:s,startTime:o.relative,duration:r.duration,domainContext:{performanceEntry:r}})}});return{stop(){n.unsubscribe()}}}function vZ(e){e.register(0,({eventType:t})=>{if(!aR())return on;const n=oR(),i=sR();return{type:t,session:{type:"synthetics"},synthetics:{test_id:n,result_id:i,injected:iR()}}})}function yZ(e,t,n){const i=nv(e),r=n(i);return Td(t).forEach(([o,s])=>ah(e,i,o.split(/\.|(?=\[\])/),s)),r}function ah(e,t,n,i){const[r,...o]=n;if(r==="[]"){Array.isArray(e)&&Array.isArray(t)&&e.forEach((s,a)=>ah(s,t[a],o,i));return}if(!(!v_(e)||!v_(t))){if(o.length>0)return ah(e[r],t[r],o,i);bZ(e,r,t[r],i)}}function bZ(e,t,n,i){const r=Ui(n);r===i?e[t]=We(n):i==="object"&&(r==="undefined"||r==="null")&&(e[t]={})}function v_(e){return Ui(e)==="object"}const eo={"view.name":"string","view.url":"string","view.referrer":"string"},to={context:"object"},no={service:"string",version:"string"};let c$;function _Z(e,t,n,i,r){c$={[me.VIEW]:{"view.performance.lcp.resource_url":"string",...to,...eo,...no},[me.ERROR]:{"error.message":"string","error.stack":"string","error.resource.url":"string","error.fingerprint":"string",...to,...eo,...no},[me.RESOURCE]:{"resource.url":"string","resource.graphql.variables":"string",...to,...eo,...no},[me.ACTION]:{"action.target.name":"string",...to,...eo,...no},[me.LONG_TASK]:{"long_task.scripts[].source_url":"string","long_task.scripts[].invoker":"string",...to,...eo,...no},[me.VITAL]:{...to,...eo,...no}};const o={[me.ERROR]:Tf(me.ERROR,i,r),[me.ACTION]:Tf(me.ACTION,i,r),[me.VITAL]:Tf(me.VITAL,i,r)};t.subscribe(12,({startTime:s,duration:a,rawRumEvent:l,domainContext:u})=>{const c=n.triggerHook(0,{eventType:l.type,startTime:s,duration:a});if(c===Kr)return;const d=Er(c,l,{ddtags:ev(e).join(",")});wZ(d,e.beforeSend,u,o)&&(ri(d.context)&&delete d.context,t.notify(13,d))})}function wZ(e,t,n,i){var r;if(t){const s=yZ(e,c$[e.type],a=>t(a,n));if(s===!1&&e.type!==me.VIEW)return!1;s===!1&&he.warn("Can't dismiss view events using beforeSend!")}return!((r=i[e.type])===null||r===void 0?void 0:r.isLimitReached())}function xZ(e,t,n,i){e.register(0,({eventType:r,startTime:o})=>{const s=t.findTrackedSession(o),a=i.findView(o);if(!s||!a)return Kr;let l,u,c;return r===me.VIEW?(l=n.getReplayStats(a.id)?!0:void 0,u=s.sessionReplay===1,c=a.sessionIsActive?void 0:!1):l=n.isRecording()?!0:void 0,{type:r,session:{id:s.id,type:"user",has_replay:l,sampled_for_replay:u,is_active:c}}}),e.register(1,({startTime:r})=>{const o=t.findTrackedSession(r);return o?{session:{id:o.id}}:on})}function SZ(e){e.register(0,({eventType:t})=>({type:t,connectivity:ZA()}))}function EZ(e,t,n){e.register(0,({eventType:i})=>{const r=t.source;return{type:i,_dd:{format_version:2,drift:gA(),configuration:{session_sample_rate:Ns(t.sessionSampleRate,3),session_replay_sample_rate:Ns(t.sessionReplaySampleRate,3),profiling_sample_rate:Ns(t.profilingSampleRate,3),beta_encode_cookie_options:t.betaEncodeCookieOptions},browser_sdk_version:$i()?"6.24.1":void 0,sdk_name:n},application:{id:t.applicationId},date:ht(),source:r}}),e.register(1,()=>({application:{id:t.applicationId}}))}function IZ(e,t){e.register(1,()=>t.isGranted()?on:Kr)}const TZ=lB,kZ=[me.ACTION,me.ERROR,me.LONG_TASK,me.RESOURCE,me.VITAL];function CZ(e){return{addEvent:(t,n,i,r)=>{kZ.includes(n.type)&&e.notify(12,{startTime:t,rawRumEvent:n,domainContext:i,duration:r})}}}function AZ(e,t){if(!t.metricsEnabled)return{stop:$e};const{unsubscribe:n}=e.subscribe(4,({initialViewMetrics:i})=>{!i.largestContentfulPaint||!i.navigationTimings||(cu("Initial view metrics",{metrics:RZ(i.largestContentfulPaint,i.navigationTimings)}),n())});return{stop:n}}function RZ(e,t){return{lcp:{value:e.value},navigation:{domComplete:t.domComplete,domContentLoaded:t.domContentLoaded,domInteractive:t.domInteractive,firstByte:t.firstByte,loadEvent:t.loadEvent}}}function $Z(e,t,n,i,r,o,s,a,l){const u=[],c=new sq,d=TZ();c.subscribe(13,ze=>tv("rum",ze));const f=ze=>{c.notify(14,{error:ze}),rs("Error reported to customer",{"error.message":ze.message})},p=sB(e),m=p.subscribe(ze=>{c.notify(11,ze)});u.push(()=>m.unsubscribe());const h=hB("browser-rum-sdk",e,d,f,p,r);u.push(h.stop);const v=$i()?B5():F5(e,c,o);if($i())H5(c);else{const ze=Z5(e,c,f,p,v.expireObservable,r);u.push(()=>ze.stop()),tZ(h,c,ze.flushController.flushObservable)}const y=rq(),w=J5(e,location),{observable:S,stop:b}=iq();u.push(b),EZ(d,e,l);const C=sZ(d,e),_=uq(c);u.push(()=>_.stop());const k=W5(c,d,w,location);u.push(()=>k.stop());const R=Q5(c,d,e);xZ(d,v,t,_),SZ(d),IZ(d,o);const M=cV(d,e,"rum"),U=dV(d,e,v,"rum"),z=lV(d,e,"rum"),{actionContexts:Z,addAction:W,addEvent:j,stop:L}=OZ(c,d,e,C,y,S,f);u.push(L);const{addTiming:Y,startView:ne,setViewName:Q,setViewContext:se,setViewContextProperty:E,getViewContext:we,stop:de}=D5(c,d,e,location,y,S,w,t,_,i);u.push(de);const{stop:A}=AZ(c,h);u.push(A);const{stop:H}=z3(c,e,C);if(u.push(H),e.trackLongTasks)if(ii(exports.RumPerformanceEntryType.LONG_ANIMATION_FRAME)){const{stop:ze}=mZ(c,e);u.push(ze)}else gZ(c,e);const{addError:re}=E3(c,e,a);a.unbuffer(),Eq(c,e,v,U,z);const ie=gV(c,C,s),ke=oq(e.applicationId,v,_,Z,k);return u.push(()=>n.stop()),{addAction:W,addEvent:j,addError:re,addTiming:Y,addFeatureFlagEvaluation:R.addFeatureFlagEvaluation,startView:ne,setViewContext:se,setViewContextProperty:E,getViewContext:we,setViewName:Q,lifeCycle:c,viewHistory:_,session:v,stopSession:()=>v.expire(),getInternalContext:ke.get,startDurationVital:ie.startDurationVital,stopDurationVital:ie.stopDurationVital,addDurationVital:ie.addDurationVital,addOperationStepVital:ie.addOperationStepVital,globalContext:M,userContext:U,accountContext:z,telemetry:h,stop:()=>{u.forEach(ze=>ze())},hooks:d}}function OZ(e,t,n,i,r,o,s){const a=w3(e,t,r,o,n),l=CZ(e),u=lZ(t,n),c=hZ(n,t);return vZ(t),_Z(n,e,t,s),{pageStateHistory:i,addAction:a.addAction,addEvent:l.addEvent,actionContexts:a.actionContexts,stop:()=>{a.stop(),c.stop(),u.stop(),i.stop()}}}function NZ(e,{session:t,viewContext:n,errorType:i}){const r=t?t.id:"no-session-id",o=[];i!==void 0&&o.push(`error-type=${i}`),n&&(o.push(`seed=${n.id}`),o.push(`from=${n.startClocks.timeStamp}`));const s=PZ(e),a=`/rum/replay/sessions/${r}`;return`${s}${a}?${o.join("&")}`}function PZ(e){const t=e.site,n=e.subdomain||MZ(e);return`https://${n?`${n}.`:""}${t}`}function MZ(e){switch(e.site){case wi:case VF:return"app";case NA:return"dd";default:return}}const jZ=1e3;let yn;function DZ(e){return Md(e).segments_count}function zZ(e){Md(e).segments_count+=1}function LZ(e){Md(e).records_count+=1}function UZ(e,t){Md(e).segments_total_raw_size+=t}function FZ(e){return yn?.get(e)}function Md(e){yn||(yn=new Map);let t;return yn.has(e)?t=yn.get(e):(t={records_count:0,segments_count:0,segments_total_raw_size:0},yn.set(e,t),yn.size>jZ&&BZ()),t}function BZ(){if(!yn)return;const e=yn.keys().next().value;e&&yn.delete(e)}function d$(e,t,n){let i=0,r=[],o,s=!0,a=0;const l=[],{stop:u}=Ke(e,t,"message",({data:f})=>{if(f.type!=="wrote"||f.streamId!==n)return;const p=l[0];p&&(p.id===f.id?(l.shift(),i+=f.additionalBytesCount,r.push(f.result),o=f.trailer,p.writeCallback?p.writeCallback(f.result.byteLength):p.finishCallback&&p.finishCallback()):p.id<f.id&&u())});function c(){const f=r.length===0?new Uint8Array(0):UA(r.concat(o)),p={rawBytesCount:i,output:f,outputBytesCount:f.byteLength,encoding:"deflate"};return i=0,r=[],p}function d(){s||(t.postMessage({action:"reset",streamId:n}),s=!0)}return{isAsync:!0,get isEmpty(){return s},write(f,p){t.postMessage({action:"write",id:a,data:f,streamId:n}),l.push({id:a,writeCallback:p,data:f}),s=!1,a+=1},finish(f){d(),l.length?(l.forEach(p=>{delete p.writeCallback}),l[l.length-1].finishCallback=()=>f(c())):f(c())},finishSync(){d();const f=l.map(p=>p.data).join("");return l.length=0,{...c(),pendingData:f}},estimateEncodedBytesCount(f){return f.length/8},stop(){u()}}}function pv({configuredUrl:e,error:t,source:n,scriptType:i}){if(he.error(`${n} failed to start: an error occurred while initializing the ${i}:`,t),t instanceof Event||t instanceof Error&&VZ(t.message)){let r;e?r=`Please make sure the ${i} URL ${e} is correct and CSP is correctly configured.`:r="Please make sure CSP is correctly configured.",he.error(`${r} See documentation at ${wd}/integrations/content_security_policy_logs/#use-csp-with-real-user-monitoring-and-session-replay`)}else i==="worker"&&iv(t)}function VZ(e){return e.includes("Content Security Policy")||e.includes("requires 'TrustedScriptURL'")}const qZ=30*_t;function f$(e){return new Worker(e.workerUrl||URL.createObjectURL(new Blob(['(()=>{function t(t){if(1===t.length)return t[0];const e=t.reduce((t,e)=>t+e.length,0),a=new Uint8Array(e);let n=0;for(const e of t)a.set(e,n),n+=e.length;return a}function e(t){for(var e=t.length;--e>=0;)t[e]=0}var a=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),n=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),i=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=Array(576);e(s);var h=Array(60);e(h);var l=Array(512);e(l);var _=Array(256);e(_);var o=Array(29);e(o);var d,u,f,c=Array(30);function p(t,e,a,n,r){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=n,this.max_length=r,this.has_stree=t&&t.length}function g(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}e(c);var v=function(t){return t<256?l[t]:l[256+(t>>>7)]},w=function(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},m=function(t,e,a){t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,w(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},b=function(t,e,a){m(t,a[2*e],a[2*e+1])},y=function(t,e){var a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},z=function(t,e,a){var n,r,i=Array(16),s=0;for(n=1;n<=15;n++)i[n]=s=s+a[n-1]<<1;for(r=0;r<=e;r++){var h=t[2*r+1];0!==h&&(t[2*r]=y(i[h]++,h))}},k=function(t){var e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0},x=function(t){t.bi_valid>8?w(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},A=function(t,e,a,n){var r=2*e,i=2*a;return t[r]<t[i]||t[r]===t[i]&&n[e]<=n[a]},U=function(t,e,a){for(var n=t.heap[a],r=a<<1;r<=t.heap_len&&(r<t.heap_len&&A(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!A(e,n,t.heap[r],t.depth));)t.heap[a]=t.heap[r],a=r,r<<=1;t.heap[a]=n},B=function(t,e,r){var i,s,h,l,d=0;if(0!==t.last_lit)do{i=t.pending_buf[t.d_buf+2*d]<<8|t.pending_buf[t.d_buf+2*d+1],s=t.pending_buf[t.l_buf+d],d++,0===i?b(t,s,e):(h=_[s],b(t,h+256+1,e),0!==(l=a[h])&&(s-=o[h],m(t,s,l)),i--,h=v(i),b(t,h,r),0!==(l=n[h])&&(i-=c[h],m(t,i,l)))}while(d<t.last_lit);b(t,256,e)},I=function(t,e){var a,n,r,i=e.dyn_tree,s=e.stat_desc.static_tree,h=e.stat_desc.has_stree,l=e.stat_desc.elems,_=-1;for(t.heap_len=0,t.heap_max=573,a=0;a<l;a++)0!==i[2*a]?(t.heap[++t.heap_len]=_=a,t.depth[a]=0):i[2*a+1]=0;for(;t.heap_len<2;)i[2*(r=t.heap[++t.heap_len]=_<2?++_:0)]=1,t.depth[r]=0,t.opt_len--,h&&(t.static_len-=s[2*r+1]);for(e.max_code=_,a=t.heap_len>>1;a>=1;a--)U(t,i,a);r=l;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],U(t,i,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,i[2*r]=i[2*a]+i[2*n],t.depth[r]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,i[2*a+1]=i[2*n+1]=r,t.heap[1]=r++,U(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a,n,r,i,s,h,l=e.dyn_tree,_=e.max_code,o=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,f=e.stat_desc.extra_base,c=e.stat_desc.max_length,p=0;for(i=0;i<=15;i++)t.bl_count[i]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;a<573;a++)(i=l[2*l[2*(n=t.heap[a])+1]+1]+1)>c&&(i=c,p++),l[2*n+1]=i,n>_||(t.bl_count[i]++,s=0,n>=f&&(s=u[n-f]),h=l[2*n],t.opt_len+=h*(i+s),d&&(t.static_len+=h*(o[2*n+1]+s)));if(0!==p){do{for(i=c-1;0===t.bl_count[i];)i--;t.bl_count[i]--,t.bl_count[i+1]+=2,t.bl_count[c]--,p-=2}while(p>0);for(i=c;0!==i;i--)for(n=t.bl_count[i];0!==n;)(r=t.heap[--a])>_||(l[2*r+1]!==i&&(t.opt_len+=(i-l[2*r+1])*l[2*r],l[2*r+1]=i),n--)}}(t,e),z(i,_,t.bl_count)},E=function(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,_=4;for(0===s&&(l=138,_=3),e[2*(a+1)+1]=65535,n=0;n<=a;n++)r=s,s=e[2*(n+1)+1],++h<l&&r===s||(h<_?t.bl_tree[2*r]+=h:0!==r?(r!==i&&t.bl_tree[2*r]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,i=r,0===s?(l=138,_=3):r===s?(l=6,_=3):(l=7,_=4))},C=function(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,_=4;for(0===s&&(l=138,_=3),n=0;n<=a;n++)if(r=s,s=e[2*(n+1)+1],!(++h<l&&r===s)){if(h<_)do{b(t,r,t.bl_tree)}while(0!==--h);else 0!==r?(r!==i&&(b(t,r,t.bl_tree),h--),b(t,16,t.bl_tree),m(t,h-3,2)):h<=10?(b(t,17,t.bl_tree),m(t,h-3,3)):(b(t,18,t.bl_tree),m(t,h-11,7));h=0,i=r,0===s?(l=138,_=3):r===s?(l=6,_=3):(l=7,_=4)}},D=!1,M=function(t,e,a,n){m(t,0+(n?1:0),3),function(t,e,a){x(t),w(t,a),w(t,~a),t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a}(t,e,a)},j=M,L=function(t,e,a,n){for(var r=65535&t,i=t>>>16&65535,s=0;0!==a;){a-=s=a>2e3?2e3:a;do{i=i+(r=r+e[n++]|0)|0}while(--s);r%=65521,i%=65521}return r|i<<16},S=new Uint32Array(function(){for(var t,e=[],a=0;a<256;a++){t=a;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}()),T=function(t,e,a,n){var r=S,i=n+a;t^=-1;for(var s=n;s<i;s++)t=t>>>8^r[255&(t^e[s])];return-1^t},O={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},q=j,F=function(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(_[a]+256+1)]++,t.dyn_dtree[2*v(e)]++),t.last_lit===t.lit_bufsize-1},G=-2,H=258,J=262,K=103,N=113,P=666,Q=function(t,e){return t.msg=O[e],e},R=function(t){return(t<<1)-(t>4?9:0)},V=function(t){for(var e=t.length;--e>=0;)t[e]=0},W=function(t,e,a){return(e<<t.hash_shift^a)&t.hash_mask},X=function(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},Y=function(t,e){(function(t,e,a,n){var r,l,_=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),I(t,t.l_desc),I(t,t.d_desc),_=function(t){var e;for(E(t,t.dyn_ltree,t.l_desc.max_code),E(t,t.dyn_dtree,t.d_desc.max_code),I(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*i[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),r=t.opt_len+3+7>>>3,(l=t.static_len+3+7>>>3)<=r&&(r=l)):r=l=a+5,a+4<=r&&-1!==e?M(t,e,a,n):4===t.strategy||l===r?(m(t,2+(n?1:0),3),B(t,s,h)):(m(t,4+(n?1:0),3),function(t,e,a,n){var r;for(m(t,e-257,5),m(t,a-1,5),m(t,n-4,4),r=0;r<n;r++)m(t,t.bl_tree[2*i[r]+1],3);C(t,t.dyn_ltree,e-1),C(t,t.dyn_dtree,a-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,_+1),B(t,t.dyn_ltree,t.dyn_dtree)),k(t),n&&x(t)})(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,X(t.strm)},Z=function(t,e){t.pending_buf[t.pending++]=e},$=function(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},tt=function(t,e,a,n){var r=t.avail_in;return r>n&&(r=n),0===r?0:(t.avail_in-=r,e.set(t.input.subarray(t.next_in,t.next_in+r),a),1===t.state.wrap?t.adler=L(t.adler,e,r,a):2===t.state.wrap&&(t.adler=T(t.adler,e,r,a)),t.next_in+=r,t.total_in+=r,r)},et=function(t,e){var a,n,r=t.max_chain_length,i=t.strstart,s=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-J?t.strstart-(t.w_size-J):0,_=t.window,o=t.w_mask,d=t.prev,u=t.strstart+H,f=_[i+s-1],c=_[i+s];t.prev_length>=t.good_match&&(r>>=2),h>t.lookahead&&(h=t.lookahead);do{if(_[(a=e)+s]===c&&_[a+s-1]===f&&_[a]===_[i]&&_[++a]===_[i+1]){i+=2,a++;do{}while(_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&_[++i]===_[++a]&&i<u);if(n=H-(u-i),i=u-H,n>s){if(t.match_start=e,s=n,n>=h)break;f=_[i+s-1],c=_[i+s]}}}while((e=d[e&o])>l&&0!==--r);return s<=t.lookahead?s:t.lookahead},at=function(t){var e,a,n,r,i,s=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-J)){t.window.set(t.window.subarray(s,s+s),0),t.match_start-=s,t.strstart-=s,t.block_start-=s,e=a=t.hash_size;do{n=t.head[--e],t.head[e]=n>=s?n-s:0}while(--a);e=a=s;do{n=t.prev[--e],t.prev[e]=n>=s?n-s:0}while(--a);r+=s}if(0===t.strm.avail_in)break;if(a=tt(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=a,t.lookahead+t.insert>=3)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=W(t,t.ins_h,t.window[i+1]);t.insert&&(t.ins_h=W(t,t.ins_h,t.window[i+3-1]),t.prev[i&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=i,i++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<J&&0!==t.strm.avail_in)},nt=function(t,e){for(var a,n;;){if(t.lookahead<J){if(at(t),t.lookahead<J&&0===e)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=W(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-J&&(t.match_length=et(t,a)),t.match_length>=3)if(n=F(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=W(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=W(t,t.ins_h,t.window[t.strstart+1]);else n=F(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(Y(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,4===e?(Y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Y(t,!1),0===t.strm.avail_out)?1:2},rt=function(t,e){for(var a,n,r;;){if(t.lookahead<J){if(at(t),t.lookahead<J&&0===e)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=W(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-J&&(t.match_length=et(t,a),t.match_length<=5&&(1===t.strategy||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-3,n=F(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=W(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,n&&(Y(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if((n=F(t,0,t.window[t.strstart-1]))&&Y(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=F(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,4===e?(Y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Y(t,!1),0===t.strm.avail_out)?1:2};function it(t,e,a,n,r){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=n,this.func=r}var st=[new it(0,0,0,0,function(t,e){var a=65535;for(a>t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(at(t),0===t.lookahead&&0===e)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,Y(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-J&&(Y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(Y(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(Y(t,!1),t.strm.avail_out),1)}),new it(4,4,8,4,nt),new it(4,5,16,8,nt),new it(4,6,32,32,nt),new it(4,4,16,16,rt),new it(8,16,32,32,rt),new it(8,16,128,128,rt),new it(8,32,128,256,rt),new it(32,128,258,1024,rt),new it(32,258,258,4096,rt)];function ht(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),V(this.dyn_ltree),V(this.dyn_dtree),V(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),V(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),V(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}for(var lt=function(t){var e,i=function(t){if(!t||!t.state)return Q(t,G);t.total_in=t.total_out=0,t.data_type=2;var e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:N,t.adler=2===e.wrap?0:1,e.last_flush=0,function(t){D||(function(){var t,e,i,g,v,w=Array(16);for(i=0,g=0;g<28;g++)for(o[g]=i,t=0;t<1<<a[g];t++)_[i++]=g;for(_[i-1]=g,v=0,g=0;g<16;g++)for(c[g]=v,t=0;t<1<<n[g];t++)l[v++]=g;for(v>>=7;g<30;g++)for(c[g]=v<<7,t=0;t<1<<n[g]-7;t++)l[256+v++]=g;for(e=0;e<=15;e++)w[e]=0;for(t=0;t<=143;)s[2*t+1]=8,t++,w[8]++;for(;t<=255;)s[2*t+1]=9,t++,w[9]++;for(;t<=279;)s[2*t+1]=7,t++,w[7]++;for(;t<=287;)s[2*t+1]=8,t++,w[8]++;for(z(s,287,w),t=0;t<30;t++)h[2*t+1]=5,h[2*t]=y(t,5);d=new p(s,a,257,286,15),u=new p(h,n,0,30,15),f=new p([],r,0,19,7)}(),D=!0),t.l_desc=new g(t.dyn_ltree,d),t.d_desc=new g(t.dyn_dtree,u),t.bl_desc=new g(t.bl_tree,f),t.bi_buf=0,t.bi_valid=0,k(t)}(e),0}(t);return 0===i&&((e=t.state).window_size=2*e.w_size,V(e.head),e.max_lazy_match=st[e.level].max_lazy,e.good_match=st[e.level].good_length,e.nice_match=st[e.level].nice_length,e.max_chain_length=st[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),i},_t=function(t,e){var a,n;if(!t||!t.state||e>5||e<0)return t?Q(t,G):G;var r=t.state;if(!t.output||!t.input&&0!==t.avail_in||r.status===P&&4!==e)return Q(t,0===t.avail_out?-5:G);r.strm=t;var i=r.last_flush;if(r.last_flush=e,42===r.status)if(2===r.wrap)t.adler=0,Z(r,31),Z(r,139),Z(r,8),r.gzhead?(Z(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Z(r,255&r.gzhead.time),Z(r,r.gzhead.time>>8&255),Z(r,r.gzhead.time>>16&255),Z(r,r.gzhead.time>>24&255),Z(r,9===r.level?2:r.strategy>=2||r.level<2?4:0),Z(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(Z(r,255&r.gzhead.extra.length),Z(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(t.adler=T(t.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(Z(r,0),Z(r,0),Z(r,0),Z(r,0),Z(r,0),Z(r,9===r.level?2:r.strategy>=2||r.level<2?4:0),Z(r,3),r.status=N);else{var h=8+(r.w_bits-8<<4)<<8;h|=(r.strategy>=2||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(h|=32),h+=31-h%31,r.status=N,$(r,h),0!==r.strstart&&($(r,t.adler>>>16),$(r,65535&t.adler)),t.adler=1}if(69===r.status)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),X(t),a=r.pending,r.pending!==r.pending_buf_size));)Z(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),X(t),a=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,Z(r,n)}while(0!==n);r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),0===n&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),X(t),a=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,Z(r,n)}while(0!==n);r.gzhead.hcrc&&r.pending>a&&(t.adler=T(t.adler,r.pending_buf,r.pending-a,a)),0===n&&(r.status=K)}else r.status=K;if(r.status===K&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&X(t),r.pending+2<=r.pending_buf_size&&(Z(r,255&t.adler),Z(r,t.adler>>8&255),t.adler=0,r.status=N)):r.status=N),0!==r.pending){if(X(t),0===t.avail_out)return r.last_flush=-1,0}else if(0===t.avail_in&&R(e)<=R(i)&&4!==e)return Q(t,-5);if(r.status===P&&0!==t.avail_in)return Q(t,-5);if(0!==t.avail_in||0!==r.lookahead||0!==e&&r.status!==P){var l=2===r.strategy?function(t,e){for(var a;;){if(0===t.lookahead&&(at(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,a=F(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(Y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(Y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Y(t,!1),0===t.strm.avail_out)?1:2}(r,e):3===r.strategy?function(t,e){for(var a,n,r,i,s=t.window;;){if(t.lookahead<=H){if(at(t),t.lookahead<=H&&0===e)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=s[r=t.strstart-1])===s[++r]&&n===s[++r]&&n===s[++r]){i=t.strstart+H;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<i);t.match_length=H-(i-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=F(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=F(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(Y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(Y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(Y(t,!1),0===t.strm.avail_out)?1:2}(r,e):st[r.level].func(r,e);if(3!==l&&4!==l||(r.status=P),1===l||3===l)return 0===t.avail_out&&(r.last_flush=-1),0;if(2===l&&(1===e?function(t){m(t,2,3),b(t,256,s),function(t){16===t.bi_valid?(w(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}(r):5!==e&&(q(r,0,0,!1),3===e&&(V(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),X(t),0===t.avail_out))return r.last_flush=-1,0}return 4!==e?0:r.wrap<=0?1:(2===r.wrap?(Z(r,255&t.adler),Z(r,t.adler>>8&255),Z(r,t.adler>>16&255),Z(r,t.adler>>24&255),Z(r,255&t.total_in),Z(r,t.total_in>>8&255),Z(r,t.total_in>>16&255),Z(r,t.total_in>>24&255)):($(r,t.adler>>>16),$(r,65535&t.adler)),X(t),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?0:1)},ot=function(t){if(!t||!t.state)return G;var e=t.state.status;return 42!==e&&69!==e&&73!==e&&91!==e&&e!==K&&e!==N&&e!==P?Q(t,G):(t.state=null,e===N?Q(t,-3):0)},dt=new Uint8Array(256),ut=0;ut<256;ut++)dt[ut]=ut>=252?6:ut>=248?5:ut>=240?4:ut>=224?3:ut>=192?2:1;dt[254]=dt[254]=1;var ft=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},ct=Object.prototype.toString;function pt(){this.options={level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0};var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ft,this.strm.avail_out=0;var e,a,n=function(t,e,a,n,r,i){if(!t)return G;var s=1;if(-1===e&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||8!==a||n<8||n>15||e<0||e>9||i<0||i>4)return Q(t,G);8===n&&(n=9);var h=new ht;return t.state=h,h.strm=t,h.wrap=s,h.gzhead=null,h.w_bits=n,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=r+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<r+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.d_buf=1*h.lit_bufsize,h.l_buf=3*h.lit_bufsize,h.level=e,h.strategy=i,h.method=a,lt(t)}(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==n)throw Error(O[n]);if(t.header&&(e=this.strm,a=t.header,e&&e.state&&(2!==e.state.wrap||(e.state.gzhead=a))),t.dictionary){var r;if(r="[object ArrayBuffer]"===ct.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(n=function(t,e){var a=e.length;if(!t||!t.state)return G;var n=t.state,r=n.wrap;if(2===r||1===r&&42!==n.status||n.lookahead)return G;if(1===r&&(t.adler=L(t.adler,e,a,0)),n.wrap=0,a>=n.w_size){0===r&&(V(n.head),n.strstart=0,n.block_start=0,n.insert=0);var i=new Uint8Array(n.w_size);i.set(e.subarray(a-n.w_size,a),0),e=i,a=n.w_size}var s=t.avail_in,h=t.next_in,l=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,at(n);n.lookahead>=3;){var _=n.strstart,o=n.lookahead-2;do{n.ins_h=W(n,n.ins_h,n.window[_+3-1]),n.prev[_&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=_,_++}while(--o);n.strstart=_,n.lookahead=2,at(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,t.next_in=h,t.input=l,t.avail_in=s,n.wrap=r,0}(this.strm,r)))throw Error(O[n]);this._dict_set=!0}}function gt(t,e,a){try{t.postMessage({type:"errored",error:e,streamId:a})}catch(n){t.postMessage({type:"errored",error:e+"",streamId:a})}}function vt(t){const e=t.strm.adler;return new Uint8Array([3,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e])}pt.prototype.push=function(t,e){var a,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;for(n=e===~~e?e:!0===e?4:0,"[object ArrayBuffer]"===ct.call(t)?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),(2===n||3===n)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if(1===(a=_t(r,n)))return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),a=ot(this.strm),this.onEnd(a),this.ended=!0,0===a;if(0!==r.avail_out){if(n>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},pt.prototype.onData=function(t){this.chunks.push(t)},pt.prototype.onEnd=function(t){0===t&&(this.result=function(t){for(var e=0,a=0,n=t.length;a<n;a++)e+=t[a].length;for(var r=new Uint8Array(e),i=0,s=0,h=t.length;i<h;i++){var l=t[i];r.set(l,s),s+=l.length}return r}(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},function(e=self){try{const a=new Map;e.addEventListener("message",n=>{try{const r=function(e,a){switch(a.action){case"init":return{type:"initialized",version:"6.24.1"};case"write":{let n=e.get(a.streamId);n||(n=new pt,e.set(a.streamId,n));const r=n.chunks.length,i=function(t){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,n,r,i,s=t.length,h=0;for(r=0;r<s;r++)a=t.charCodeAt(r),55296==(64512&a)&&r+1<s&&(n=t.charCodeAt(r+1),56320==(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),h+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(h),i=0,r=0;i<h;r++)a=t.charCodeAt(r),55296==(64512&a)&&r+1<s&&(n=t.charCodeAt(r+1),56320==(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),a<128?e[i++]=a:a<2048?(e[i++]=192|a>>>6,e[i++]=128|63&a):a<65536?(e[i++]=224|a>>>12,e[i++]=128|a>>>6&63,e[i++]=128|63&a):(e[i++]=240|a>>>18,e[i++]=128|a>>>12&63,e[i++]=128|a>>>6&63,e[i++]=128|63&a);return e}(a.data);return n.push(i,2),{type:"wrote",id:a.id,streamId:a.streamId,result:t(n.chunks.slice(r)),trailer:vt(n),additionalBytesCount:i.length}}case"reset":e.delete(a.streamId)}}(a,n.data);r&&e.postMessage(r)}catch(t){gt(e,t,n.data&&"streamId"in n.data?n.data.streamId:void 0)}})}catch(t){gt(e,t)}}()})();'])))}let rt={status:0};function p$(e,t,n,i=f$){switch(rt.status===0&&ZZ(e,t,i),rt.status){case 1:return rt.initializationFailureCallbacks.push(n),rt.worker;case 3:return rt.worker}}function y_(){return rt.status}function ZZ(e,t,n=f$){try{const i=n(e),{stop:r}=Ke(e,i,"error",a=>{Df(e,t,a)}),{stop:o}=Ke(e,i,"message",({data:a})=>{a.type==="errored"?Df(e,t,a.error,a.streamId):a.type==="initialized"&&GZ(a.version)});i.postMessage({action:"init"}),bt(()=>HZ(t),qZ),rt={status:1,worker:i,stop:()=>{r(),o()},initializationFailureCallbacks:[]}}catch(i){Df(e,t,i)}}function HZ(e){rt.status===1&&(he.error(`${e} failed to start: a timeout occurred while initializing the Worker`),rt.initializationFailureCallbacks.forEach(t=>t()),rt={status:2})}function GZ(e){rt.status===1&&(rt={status:3,worker:rt.worker,stop:rt.stop,version:e})}function Df(e,t,n,i){rt.status===1||rt.status===0?(pv({configuredUrl:e.workerUrl,error:n,source:t,scriptType:"worker"}),rt.status===1&&rt.initializationFailureCallbacks.forEach(r=>r()),rt={status:2}):iv(n,{worker_version:rt.status===3&&rt.version,stream_id:i})}function h$(){return typeof Array.from=="function"&&typeof CSSSupportsRule=="function"&&typeof URL.createObjectURL=="function"&&"forEach"in NodeList.prototype}function WZ(e,t,n,i){const r=t.findTrackedSession(),o=JZ(r,i),s=n.findView();return NZ(e,{viewContext:s,errorType:o,session:r})}function JZ(e,t){if(!h$())return"browser-not-supported";if(!e)return"rum-not-tracked";if(e.sessionReplay===0)return"incorrect-session-plan";if(!t)return"replay-not-started"}function KZ(e,t){if(!e.metricsEnabled)return{stop:$e};let n,i,r;const{unsubscribe:o}=t.subscribe(s=>{switch(s.type){case"start":n={forced:s.forced,timestamp:ht()},i=void 0,r=void 0;break;case"document-ready":n&&(i=tt(n.timestamp,ht()));break;case"recorder-settled":n&&(r=tt(n.timestamp,ht()));break;case"aborted":case"deflate-encoder-load-failed":case"recorder-load-failed":case"succeeded":o(),n&&cu("Recorder init metrics",{metrics:YZ(n.forced,r,tt(n.timestamp,ht()),s.type,i)});break}});return{stop:o}}function YZ(e,t,n,i,r){return{forced:e,loadRecorderModuleDuration:t,recorderInitDuration:n,result:i,waitForDocReadyDuration:r}}function XZ(e,t,n,i,r,o,s){let a=0,l;t.subscribe(9,()=>{(a===2||a===3)&&(f(),a=1)}),t.subscribe(10,()=>{a===1&&d()});const u=new Ie;KZ(s,u);const c=async p=>{u.notify({type:"start",forced:p});const[m]=await Promise.all([b_(u,{type:"recorder-settled"},r()),b_(u,{type:"document-ready"},zB(e,"interactive"))]);if(a!==2){u.notify({type:"aborted"});return}if(!m){a=0,u.notify({type:"recorder-load-failed"});return}const h=o();if(!h){a=0,u.notify({type:"deflate-encoder-load-failed"});return}({stop:l}=m(t,e,n,i,h,s)),a=3,u.notify({type:"succeeded"})};function d(p){const m=n.findTrackedSession();if(QZ(m,p)){a=1;return}if(eH(a))return;a=2;const h=tH(m,p)||!1;c(h).catch(wr),h&&n.setForcedReplay()}function f(){a===3&&l?.(),a=0}return{start:d,stop:f,getSessionReplayLink(){return WZ(e,n,i,a!==0)},isRecording:()=>a===3}}function QZ(e,t){return!e||e.sessionReplay===0&&(!t||!t.force)}function eH(e){return e===2||e===3}function tH(e,t){return t&&t.force&&e.sessionReplay===0}async function b_(e,t,n){try{return await n}finally{e.notify(t)}}function nH(){let e=0;return{strategy:{start(){e=1},stop(){e=2},isRecording:()=>!1,getSessionReplayLink:$e},shouldStartImmediately(t){return e===1||e===0&&!t.startSessionReplayRecordingManually}}}function rH(e,t){if($i()&&!QA("records")||!h$())return{start:$e,stop:$e,getReplayStats:()=>{},onRumStart:$e,isRecording:()=>!1,getSessionReplayLink:()=>{}};let{strategy:n,shouldStartImmediately:i}=nH();return{start:o=>n.start(o),stop:()=>n.stop(),getSessionReplayLink:()=>n.getSessionReplayLink(),onRumStart:r,isRecording:()=>y_()===3&&n.isRecording(),getReplayStats:o=>y_()===3?FZ(o):void 0};function r(o,s,a,l,u,c){let d;function f(){return d||(u??(u=p$(s,"Datadog Session Replay",()=>{n.stop()},t)),u&&(d=d$(s,u,1))),d}n=XZ(s,o,a,l,e,f,c),i(s)&&n.start()}}async function iH(e=oH){try{return await e()}catch(t){pv({error:t,source:"Recorder",scriptType:"module"})}}async function oH(){return(await Promise.resolve().then(()=>require("./startRecording-B97e4Mlu.cjs"))).startRecording}function sH(){return fn().Profiler!==void 0}const aH=e=>{let t={status:"starting"};return e.register(0,({eventType:n})=>n!==me.VIEW&&n!==me.LONG_TASK?on:{type:n,_dd:{profiling:t}}),{get:()=>t,set:n=>{t=n}}};async function uH(e=lH){try{return await e()}catch(t){pv({error:t,source:"Profiler",scriptType:"module"})}}async function lH(){return(await Promise.resolve().then(()=>require("./profiler-DPH9zydw.cjs"))).createRumProfiler}function cH(){let e;function t(n,i,r,o,s,a){const l=o.findTrackedSession();if(!l||!bR(l.id,r.profilingSampleRate))return;const u=aH(i);if(!sH()){u.set({status:"error",error_reason:"not-supported-by-browser"});return}uH().then(c=>{if(!c){rs("[DD_RUM] Failed to lazy load the RUM Profiler"),u.set({status:"error",error_reason:"failed-to-lazy-load"});return}e=c(r,n,o,u,a),e.start(s.findView())}).catch(wr)}return{onRumStart:t,stop:()=>{e?.stop().catch(wr)}}}const dH=rH(iH),fH=cH(),js=tq($Z,dH,fH,{startDeflateWorker:p$,createDeflateEncoder:d$,sdkName:"rum"});j6(fn(),"DD_RUM",js);const qu={applicationId:"0b0a19b9-099b-4812-b342-930518330975",clientToken:"puba92c09799d321f572535176e9fe08256",site:"datadoghq.com",service:"gram-elements"};let uh=!1,lh=!0;function pH(e={}){if(e.enabled===!1){lh=!1;return}if(!uh)try{js.init({applicationId:qu.applicationId,clientToken:qu.clientToken,site:qu.site,service:qu.service,env:process.env.NODE_ENV||"production",sessionSampleRate:100,sessionReplaySampleRate:100,trackUserInteractions:!0,trackResources:!0,trackLongTasks:!0,defaultPrivacyLevel:"mask"}),e.projectSlug&&js.setGlobalContextProperty("projectSlug",e.projectSlug),e.variant&&js.setGlobalContextProperty("variant",e.variant),uh=!0}catch(t){console.warn("[Elements] Failed to initialize Datadog RUM:",t),lh=!1}}function Kl(e,t){if(!lh||!uh)return;const n=e instanceof Error?e:new Error(String(e));try{js.addError(n,{...t,timestamp:new Date().toISOString()})}catch(i){console.warn("[Elements] Failed to track error:",i)}}const hv=["anthropic/claude-sonnet-4.5","anthropic/claude-haiku-4.5","anthropic/claude-sonnet-4","anthropic/claude-opus-4.5","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-5.1-codex","openai/gpt-5","openai/gpt-5.1","openai/gpt-4.1","anthropic/claude-3.7-sonnet","anthropic/claude-opus-4","google/gemini-2.5-pro-preview","google/gemini-3-pro-preview","moonshotai/kimi-k2","mistralai/mistral-medium-3","mistralai/mistral-medium-3.1","mistralai/codestral-2501"],hH=e=>Array.from(e).map(n=>n.getModelContext()).sort((n,i)=>(i.priority??0)-(n.priority??0)).reduce((n,i)=>{if(i.system&&(n.system?n.system+=`
|
|
38
|
+
|
|
39
|
+
${i.system}`:n.system=i.system),i.tools)for(const[r,o]of Object.entries(i.tools)){const s=n.tools?.[r];if(s&&s!==o)throw new Error(`You tried to define a tool with the name ${r}, but it already exists.`);n.tools||(n.tools={}),n.tools[r]=o}return i.config&&(n.config={...n.config,...i.config}),i.callSettings&&(n.callSettings={...n.callSettings,...i.callSettings}),n},{});class mv{_providers=new Set;getModelContext(){return hH(this._providers)}registerModelContextProvider(t){this._providers.add(t);const n=t.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),n?.(),this.notifySubscribers()}}_subscribers=new Set;notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}}class gv{_contextProvider=new mv;registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}getModelContextProvider(){return this._contextProvider}}class jd{_subscribers=new Set;subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const n=this.subscribe(()=>{n(),t()})})}_notifySubscribers(){const t=[];for(const n of this._subscribers)try{n()}catch(i){t.push(i)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}}const mH=e=>e.status.type==="complete";class m$ extends jd{isEditing=!0;get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}_attachments=[];get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text="";get text(){return this._text}_role="user";get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const t=this.getAttachmentAdapter();t&&await Promise.all(this._attachments.map(n=>t.remove(n)))}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),await t}async clearAttachments(){const t=this._onClearAttachments();this.setAttachments([]),await t}async send(){const t=this.getAttachmentAdapter(),n=t&&this.attachments.length>0?Promise.all(this.attachments.map(async o=>mH(o)?o:await t.send(o))):[],i=this.text;this._emptyTextAndAttachments();const r={createdAt:new Date,role:this.role,content:i?[{type:"text",text:i}]:[],attachments:await n,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(t){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const i=o=>{const s=this._attachments.findIndex(a=>a.id===o.id);s!==-1?this._attachments=[...this._attachments.slice(0,s),o,...this._attachments.slice(s+1)]:this._attachments=[...this._attachments,o],this._notifySubscribers()},r=n.add({file:t});if(Symbol.asyncIterator in r)for await(const o of r)i(o);else i(await r);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()}async removeAttachment(t){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const i=this._attachments.findIndex(o=>o.id===t);if(i===-1)throw new Error("Attachment not found");const r=this._attachments[i];await n.remove(r),this._attachments=[...this._attachments.slice(0,i),...this._attachments.slice(i+1)],this._notifySubscribers()}_eventSubscribers=new Map;_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const i of n)i()}unstable_on(t,n){const i=this._eventSubscribers.get(t);return i?i.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{const r=this._eventSubscribers.get(t);r&&r.delete(n)}}}class g$ extends m${runtime;_canCancel=!1;get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){return this.runtime.adapters?.attachments}constructor(t){super(),this.runtime=t,this.connect()}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(t){this.runtime.append({...t,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}}let v$=(e,t=21)=>(n=t)=>{let i="",r=n|0;for(;r--;)i+=e[Math.random()*e.length|0];return i};const pu=v$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),gH="__optimistic__",vH=()=>`${gH}${pu()}`,os=Symbol("autoStatus"),yH=Object.freeze(Object.assign({type:"running"},{[os]:!0})),bH=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[os]:!0})),_H=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[os]:!0})),wH=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[os]:!0})),y$=e=>e[os]===!0,hu=(e,t,n,i,r)=>e&&r?Object.assign({type:"incomplete",reason:"error",error:r},{[os]:!0}):e&&t?yH:n?wH:i?_H:bH;function mu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ci={exports:{}},__;function xH(){if(__)return ci.exports;__=1;const e=typeof Buffer<"u",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,n=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function i(a,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(a)&&(a=a.toString()),a&&a.charCodeAt(0)===65279&&(a=a.slice(1));const c=JSON.parse(a,l);if(c===null||typeof c!="object")return c;const d=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(d==="ignore"&&f==="ignore")return c;if(d!=="ignore"&&f!=="ignore"){if(t.test(a)===!1&&n.test(a)===!1)return c}else if(d!=="ignore"&&f==="ignore"){if(t.test(a)===!1)return c}else if(n.test(a)===!1)return c;return r(c,{protoAction:d,constructorAction:f,safe:u&&u.safe})}function r(a,{protoAction:l="error",constructorAction:u="error",safe:c}={}){let d=[a];for(;d.length;){const f=d;d=[];for(const p of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(p,"__proto__")){if(c===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(p,"constructor")&&p.constructor!==null&&typeof p.constructor=="object"&&Object.prototype.hasOwnProperty.call(p.constructor,"prototype")){if(c===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.constructor}for(const m in p){const h=p[m];h&&typeof h=="object"&&d.push(h)}}}return a}function o(a,l,u){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return i(a,l,u)}finally{Error.stackTraceLimit=c}}function s(a,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return i(a,l,{safe:!0})}catch{return}finally{Error.stackTraceLimit=u}}return ci.exports=o,ci.exports.default=o,ci.exports.parse=o,ci.exports.safeParse=s,ci.exports.scan=r,ci.exports}var SH=xH();const ch=mu(SH);function EH(e){const t=["ROOT"];let n=-1,i=null;const r=[];let o;function s(){o!==void 0&&(r.push(JSON.parse(`"${o}"`)),o=void 0)}function a(d,f,p){switch(d){case'"':{n=f,t.pop(),t.push(p),t.push("INSIDE_STRING"),s();break}case"f":case"t":case"n":{n=f,i=f,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER"),s();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=f,t.pop(),t.push(p),t.push("INSIDE_NUMBER"),s();break}case"{":{n=f,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START"),s();break}case"[":{n=f,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START"),s();break}}}function l(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=f,t.pop(),o=r.pop();break}}}function u(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),o=(Number(o)+1).toString();break}case"]":{n=f,t.pop(),o=r.pop();break}}}for(let d=0;d<e.length;d++){const f=e[d];switch(t[t.length-1]){case"ROOT":a(f,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),o="";break}case"}":{n=d,t.pop(),o=r.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),o="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),o+=f;break}default:{o+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{a(f,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,d);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),n=d,o=r.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=d}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{n=d,t.pop(),o=r.pop();break}default:{n=d,o="0",a(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),o=(Number(o)+1).toString();break}case"]":{n=d,t.pop(),o=r.pop();break}default:{n=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{a(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?n=d:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(o+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,d);break}case"}":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,d);break}case"]":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d);break}default:{t.pop(),o=r.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(i,d+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d)):n=d;break}}}let c=e.slice(0,n+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{c+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const p=e.substring(i,e.length);"true".startsWith(p)?c+="true".slice(p.length):"false".startsWith(p)?c+="false".slice(p.length):"null".startsWith(p)&&(c+="null".slice(p.length))}}return[c,r]}const gl=Symbol("aui.parse-partial-json-object.meta"),IH=e=>e?.[gl],Yl=e=>{if(e.length===0)return{[gl]:{state:"partial",partialPath:[]}};try{const t=ch.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[gl]={state:"complete",partialPath:[]},t}catch{try{const[t,n]=EH(e),i=ch.parse(t);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[gl]={state:"partial",partialPath:n},i}catch{return}}},b$=(e,t,n)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(n.length===0)return t.state;const[i,...r]=n;if(!Object.prototype.hasOwnProperty.call(e,i))return"partial";const[o,...s]=t.partialPath;if(i!==o)return"complete";const a=e[i];return b$(a,{state:"partial",partialPath:s},r)},Vo=(e,t)=>{const n=IH(e);if(!n)throw new Error("unable to determine object state");return b$(e,n,t.map(String))};async function*TH(){const e=this.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{e.releaseLock()}}function zf(e){return e[Symbol.asyncIterator]??=TH,e}const dh={toResponse(e,t){return new Response(dh.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return dh.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},vv=function(){let e,t;const n=new Promise((i,r)=>{e=i,t=r});if(!e||!t)throw new Error("Failed to create promise");return{promise:n,resolve:e,reject:t}},kH=()=>{const e=[];let t=!1,n,i;const r=s=>{s.promise||(s.promise=s.reader.read().then(({done:a,value:l})=>{s.promise=void 0,a?(e.splice(e.indexOf(s),1),t&&e.length===0&&n.close()):n.enqueue(l),i?.resolve(),i=void 0}).catch(a=>{console.error(a),e.forEach(l=>{l.reader.cancel()}),e.length=0,n.error(a),i?.reject(a),i=void 0}))};return{readable:new ReadableStream({start(s){n=s},pull(){return i=vv(),e.forEach(s=>{r(s)}),i.promise},cancel(){e.forEach(s=>{s.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(s){if(t)throw new Error("Cannot add streams after the run callback has settled.");const a={reader:s.getReader()};e.push(a),r(a)},enqueue(s){this.addStream(new ReadableStream({start(a){a.enqueue(s),a.close()}}))}}};class w_{_controller;_isClosed=!1;constructor(t){this._controller=t}append(t){return this._controller.enqueue({type:"text-delta",path:[],textDelta:t}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const _$=e=>new ReadableStream({start(t){return e.start?.(new w_(t))},pull(t){return e.pull?.(new w_(t))},cancel(t){return e.cancel?.(t)}}),x_=()=>{let e;return[_$({start(n){e=n}}),e]};class S_{_controller;_isClosed=!1;_mergeTask;constructor(t){this._controller=t;const n=_$({start:r=>{this._argsTextController=r}});let i=!1;this._mergeTask=n.pipeTo(new WritableStream({write:r=>{switch(r.type){case"text-delta":i=!0,this._controller.enqueue(r);break;case"part-finish":i||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${r.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(t){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const CH=e=>new ReadableStream({start(t){return e.start?.(new S_(t))},pull(t){return e.pull?.(new S_(t))},cancel(t){return e.cancel?.(t)}}),AH=()=>{let e;return[CH({start(n){e=n}}),e]};class w${value=-1;up(){return++this.value}}class RH extends TransformStream{constructor(t){super({transform(n,i){i.enqueue({...n,path:[t,...n.path]})}})}}class ufe extends TransformStream{constructor(t){super({transform(n,i){const{path:[r,...o]}=n;if(t!==r)throw new Error(`Path mismatch: expected ${t}, got ${r}`);i.enqueue({...n,path:o})}})}}class $H extends TransformStream{constructor(t){const n=new w$,i=new Map;super({transform(r,o){r.type==="part-start"&&r.path.length===0&&i.set(n.up(),t.up());const[s,...a]=r.path;if(s===void 0){o.enqueue(r);return}const l=i.get(s);if(l===void 0)throw new Error("Path not found");o.enqueue({...r,path:[l,...a]})}})}}class x$ extends TransformStream{constructor(t){super();const n=t(super.readable);Object.defineProperty(this,"readable",{value:n,writable:!1})}}class S$ extends TransformStream{constructor(){const t=[];super({transform(n,i){if(n.type==="part-start"){if(n.path.length!==0){i.error(new Error("Nested parts are not supported"));return}t.push(n.part),i.enqueue(n);return}if(n.type==="text-delta"||n.type==="result"||n.type==="part-finish"||n.type==="tool-call-args-text-finish"){if(n.path.length!==1){i.error(new Error(`${n.type} chunks must have a path of length 1`));return}const r=n.path[0];if(r<0||r>=t.length){i.error(new Error(`Invalid path index: ${r}`));return}const o=t[r];i.enqueue({...n,meta:o});return}i.enqueue(n)}})}}const E$=v$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class yv{_state;_parentId;constructor(t){this._state=t||{merger:kH(),contentCounter:new w$}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,n){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(n.pipeThrough(new RH(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new $H(this._state.contentCounter)))}appendText(t){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,n]=x_();return this._addPart({type:"text"},t),n}addReasoningPart(){const[t,n]=x_();return this._addPart({type:"reasoning"},t),n}addToolCallPart(t){const n=typeof t=="string"?{toolName:t}:t,i=n.toolName,r=n.toolCallId??E$(),[o,s]=AH();return this._addPart({type:"tool-call",toolName:i,toolCallId:r,...this._parentId&&{parentId:this._parentId}},o),n.argsText!==void 0&&(s.argsText.append(n.argsText),s.argsText.close()),n.args!==void 0&&(s.argsText.append(JSON.stringify(n.args)),s.argsText.close()),n.response!==void 0&&s.setResponse(n.response),s}appendSource(t){this._addPart({...t,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const n=new yv(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}function OH(e){const t=new yv;return(async()=>{try{await e(t)}catch(i){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(i)}),i}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}function I$(){const{resolve:e,promise:t}=vv();let n;return[OH(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}class NH extends TransformStream{constructor(t,n,i){const[r,o]=I$();let s;super({start(a){return s=r.pipeTo(new WritableStream({write(l){a.enqueue(l)},abort(l){a.error(l)},close(){a.terminate()}})).catch(l=>{a.error(l)}),t.start?.(o)},transform(a){return t.transform?.(a,o)},async flush(){await t.flush?.(o),o.close(),await s}},n,i)}}const Vi=(e,t,n)=>{const{role:i,id:r,createdAt:o,attachments:s,status:a,metadata:l}=e,u={id:r??t,createdAt:o??new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,d=({image:f,...p})=>f.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?{...p,image:f}:(console.warn("Invalid image data format detected"),null);if(i!=="user"&&s?.length)throw new Error("attachments are only supported for user messages");if(i!=="assistant"&&a)throw new Error("status is only supported for assistant messages");if(i!=="assistant"&&l?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(i){case"assistant":return{...u,role:i,content:c.map(f=>{const p=f.type;switch(p){case"text":case"reasoning":return f.text.trim().length===0?null:f;case"file":case"source":return f;case"image":return d(f);case"data":return f;case"tool-call":{const{parentId:m,messages:h,...v}=f,y={...v,toolCallId:f.toolCallId??`tool-${pu()}`,...m!==void 0&&{parentId:m},...h!==void 0&&{messages:h}};return f.args?{...y,args:f.args,argsText:f.argsText??JSON.stringify(f.args)}:{...y,args:Yl(f.argsText??"")??{},argsText:f.argsText??""}}default:{const m=p;throw new Error(`Unsupported assistant message part type: ${m}`)}}}).filter(f=>!!f),status:a??n,metadata:{unstable_state:l?.unstable_state??null,unstable_annotations:l?.unstable_annotations??[],unstable_data:l?.unstable_data??[],custom:l?.custom??{},steps:l?.steps??[],...l?.submittedFeedback&&{submittedFeedback:l.submittedFeedback}}};case"user":return{...u,role:i,content:c.map(f=>{const p=f.type;switch(p){case"text":case"image":case"audio":case"file":return f;default:{const m=p;throw new Error(`Unsupported user message part type: ${m}`)}}}),attachments:s??[],metadata:{custom:l?.custom??{}}};case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...u,role:i,content:c,metadata:{custom:l?.custom??{}}};default:{const f=i;throw new Error(`Unknown message role: ${f}`)}}},bv={fromArray:e=>{const t=e.map(n=>Vi(n,pu(),hu(!1,!1,!1,!1,void 0)));return{messages:t.map((n,i)=>({parentId:i>0?t[i-1].id:null,message:n}))}}},vl=e=>e.next?vl(e.next):"current"in e?e:null;class PH{func;_value=null;constructor(t){this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}}let _v=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(t,n){t.level=n;for(const i of t.children){const r=this.messages.get(i);r&&this.updateLevels(r,n+1)}}performOp(t,n,i){const r=n.prev??this.root,o=t??this.root;if(!(i==="relink"&&r===o)){if(i!=="link"&&(r.children=r.children.filter(s=>s!==n.current.id),r.next===n)){const s=r.children.at(-1),a=s?this.messages.get(s):null;if(a===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=a}if(i!=="cut"){for(let a=t;a;a=a.prev)if(a.current.id===n.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");o.children=[...o.children,n.current.id],(vl(n)===this.head||o.next===null)&&(o.next=n),n.prev=t;const s=t?t.level+1:0;this.updateLevels(n,s)}}}_messages=new PH(()=>{const t=new Array((this.head?.level??-1)+1);for(let n=this.head;n;n=n.prev)t[n.level]=n.current;return t});get headId(){return this.head?.current.id??null}getMessages(t){if(t===void 0||t===this.head?.current.id)return this._messages.value;const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const i=new Array(n.level+1);for(let r=n;r;r=r.prev)i[r.level]=r.current;return i}addOrUpdateMessage(t,n){const i=this.messages.get(n.id),r=t?this.messages.get(t):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(i){i.current=n,this.performOp(r,i,"relink"),this._messages.dirty();return}const o={prev:r,current:n,next:null,children:[],level:r?r.level+1:0};this.messages.set(n.id,o),this.performOp(r,o,"link"),this.head===r&&(this.head=o),this._messages.dirty()}getMessage(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:n.prev?.current.id??null,message:n.current,index:n.level}}appendOptimisticMessage(t,n){let i;do i=vH();while(this.messages.has(i));return this.addOrUpdateMessage(t,Vi(n,i,{type:"running"})),i}deleteMessage(t,n){const i=this.messages.get(t);if(!i)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=n===void 0?i.prev:n===null?null:this.messages.get(n);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const o of i.children){const s=this.messages.get(o);if(!s)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,s,"relink")}this.performOp(null,i,"cut"),this.messages.delete(t),this.head===i&&(this.head=vl(r??this.root)),this._messages.dirty()}getBranches(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:i}=n.prev??this.root;return i}switchToBranch(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const i=n.prev??this.root;i.next=n,this.head=vl(n),this._messages.dirty()}resetHead(t){if(t===null){this.clear();return}const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(n.children.length>0){const i=r=>{for(const o of r.children){const s=this.messages.get(o);s&&(i(s),this.messages.delete(o))}};i(n),n.children=[],n.next=null}this.head=n;for(let i=n;i;i=i.prev)i.prev&&(i.prev.next=i);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){const t=[];for(const[,n]of this.messages)t.push({message:n.current,parentId:n.prev?.current.id??null});return{headId:this.head?.current.id??null,messages:t}}import({headId:t,messages:n}){for(const{message:i,parentId:r}of n)this.addOrUpdateMessage(r,i);this.resetHead(t??n.at(-1)?.message.id??null)}};class Dd{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}}const Dn=Symbol("skip-update");class wv extends Dd{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Dn&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState};_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}}class Zu{_core;_threadListBinding;get path(){return this._core.path}constructor(t,n){this._core=t,this._threadListBinding=n,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const n=this._core.getState();return this._threadListBinding.rename(n.id,t)}archive(){const t=this._core.getState();return this._threadListBinding.archive(t.id)}unarchive(){const t=this._core.getState();return this._threadListBinding.unarchive(t.id)}delete(){const t=this._core.getState();return this._threadListBinding.delete(t.id)}initialize(){const t=this._core.getState();return this._threadListBinding.initialize(t.id)}generateTitle(){const t=this._core.getState();return this._threadListBinding.generateTitle(t.id)}unstable_on(t,n){let i=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const o=this._core.getState(),s=o.isMain,a=o.id;i===s&&r===a||(i=s,r=a,!(t==="switched-to"&&!s)&&(t==="switched-away"&&s||n()))})}subscribe(t){return this._core.subscribe(t)}detach(){const t=this._core.getState();this._threadListBinding.detach(t.id)}__internal_getRuntime(){return this}}function MH(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const n of Object.keys(e)){const i=e[n],r=t[n];if(!Object.is(i,r))return!1}return!0}class Nn extends Dd{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t;const n=t.getState();if(n===Dn)throw new Error("Entry not available in the store");this._previousState=n}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){const t=this.binding.getState();return t===Dn||MH(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}}const Qt=Symbol("innerMessage"),Lf=Symbol("innerMessages"),jH=e=>e[Qt],DH=[],Ti=e=>{const t="messages"in e?e.messages:e,n=t[Lf]||t[Qt];return n?Array.isArray(n)?n:(t[Lf]=[n],t[Lf]):DH},sa=e=>e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
40
|
+
|
|
41
|
+
`);class T${_core;get path(){return this._core.path}constructor(t){this._core=t,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}}class k$ extends T${_composerApi;constructor(t,n){super(t),this._composerApi=n}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}}class zH extends k${get source(){return"thread-composer"}}class LH extends k${get source(){return"edit-composer"}}class UH extends T${get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}}class C$ extends Dd{config;constructor(t){super(),this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let n=this.config.binding.getState(),i=n?.unstable_on(this.config.event,t);const r=()=>{const s=this.config.binding.getState();s!==n&&(n=s,i?.(),i=this.config.binding.getState()?.unstable_on(this.config.event,t))},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const A$=Object.freeze([]),R$=Object.freeze({}),FH=e=>Object.freeze({type:"thread",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??A$,text:e?.text??"",role:e?.role??"user",runConfig:e?.runConfig??R$,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""}),BH=e=>Object.freeze({type:"edit",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,text:e?.text??"",role:e?.role??"user",attachments:e?.attachments??A$,runConfig:e?.runConfig??R$,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""});class $${_core;get path(){return this._core.path}constructor(t){this._core=t}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setText(t)}setRunConfig(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRunConfig(t)}addAttachment(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");return n.addAttachment(t)}reset(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.reset()}clearAttachments(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.clearAttachments()}send(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send()}cancel(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.cancel()}setRole(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRole(t)}subscribe(t){return this._core.subscribe(t)}_eventSubscriptionSubjects=new Map;unstable_on(t,n){let i=this._eventSubscriptionSubjects.get(t);return i||(i=new C$({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}class VH extends $${get path(){return this._core.path}get type(){return"thread"}_getState;constructor(t){const n=new wv({path:t.path,getState:()=>FH(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>n.subscribe(i)}),this._getState=n.getState.bind(n),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(t){return new zH(new Nn({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`},getState:()=>{const i=this.getState().attachments[t];return i?{...i,source:"thread-composer"}:Dn},subscribe:n=>this._core.subscribe(n)}),this._core)}}class qH extends $${_beginEdit;get path(){return this._core.path}get type(){return"edit"}_getState;constructor(t,n){const i=new wv({path:t.path,getState:()=>BH(t.getState()),subscribe:r=>t.subscribe(r)});super({path:t.path,getState:()=>t.getState(),subscribe:r=>i.subscribe(r)}),this._beginEdit=n,this._getState=i.getState.bind(i),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new LH(new Nn({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`},getState:()=>{const i=this.getState().attachments[t];return i?{...i,source:"edit-composer"}:Dn},subscribe:n=>this._core.subscribe(n)}),this._core)}}class Ds{_state;constructor(t=null){this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,i)=>Ds.apply(n,i),this._state)}static apply(t,n){const i=n.type;switch(i){case"set":return Ds.updatePath(t,n.path,()=>n.value);case"append-text":return Ds.updatePath(t,n.path,r=>{if(typeof r!="string")throw new Error(`Expected string at path [${n.path.join(", ")}]`);return r+n.value});default:{const r=i;throw new Error(`Invalid operation type: ${r}`)}}}static updatePath(t,n,i){if(n.length===0)return i(t);if(t??={},typeof t!="object")throw new Error(`Invalid path: [${n.join(", ")}]`);const[r,...o]=n;if(Array.isArray(t)){const a=Number(r);if(Number.isNaN(a))throw new Error(`Expected array index at [${n.join(", ")}]`);if(a>t.length||a<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[a]=this.updatePath(l[a],o,i),l}const s={...t};return s[r]=this.updatePath(s[r],o,i),s}}const ZH=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),zd=(e,t,n)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const i=t.path[0],r=n(e.parts[i]);return{...e,parts:[...e.parts.slice(0,i),r,...e.parts.slice(i+1)],get content(){return this.parts}}},HH=(e,t)=>{const n=t.part;if(n.type==="text"||n.type==="reasoning"){const i={type:n.type,text:"",status:{type:"running"},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="tool-call"){const i={type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:"",args:{},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="source"){const i={type:"source",sourceType:n.sourceType,id:n.id,url:n.url,...n.title?{title:n.title}:void 0,...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="file"){const i={type:"file",mimeType:n.mimeType,data:n.data};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else throw new Error(`Unsupported part type: ${n.type}`)},GH=(e,t)=>zd(e,t,n=>{if(n.type!=="tool-call")throw new Error("Last is not a tool call");return n.state!=="partial-call"?n:{...n,state:"call"}}),WH=(e,t)=>zd(e,t,n=>({...n,status:{type:"complete",reason:"unknown"}})),JH=(e,t)=>zd(e,t,n=>{if(n.type==="text"||n.type==="reasoning")return{...n,text:n.text+t.textDelta};if(n.type==="tool-call"){const i=n.argsText+t.textDelta,r=Yl(i)??n.args;return{...n,argsText:i,args:r}}else throw new Error("text-delta received but part is neither text nor tool-call")}),KH=(e,t)=>zd(e,t,n=>{if(n.type==="tool-call")return{...n,state:"result",...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.isError??!1,status:{type:"complete",reason:"stop"}};throw new Error("Result chunk received but part is not a tool-call")}),E_=(e,t)=>{if(e.status?.type==="incomplete"&&e.status?.reason==="error")return e;const n=YH(t);return{...e,status:n}},YH=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},XH=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),QH=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),e9=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]}}),t9=(e,t)=>{const n=e.metadata.steps.slice(),i=n.length-1;return n.length>0&&n[i]?.state==="started"?n[i]={...n[i],state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:"finished",messageId:E$(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},n9=(e,t)=>({...e,status:{type:"incomplete",reason:"error",error:t.error}}),r9=(e,t)=>{const n=new Ds(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},i9=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}};class o9 extends TransformStream{constructor({initialMessage:t,throttle:n,onError:i}={}){let r=t??ZH(),o;const s=n?i9(()=>{o?.enqueue(r)}):()=>{o?.enqueue(r)};super({start(a){o=a},transform(a){const l=a.type;switch(l){case"part-start":r=HH(r,a);break;case"tool-call-args-text-finish":r=GH(r,a);break;case"part-finish":r=WH(r,a);break;case"text-delta":r=JH(r,a);break;case"result":r=KH(r,a);break;case"message-finish":r=E_(r,a);break;case"annotations":r=XH(r,a);break;case"data":r=QH(r,a);break;case"step-start":r=e9(r,a);break;case"step-finish":r=t9(r,a);break;case"error":r=n9(r,a),i?.(a.error);break;case"update-state":r=r9(r,a);break;default:{const u=l;throw new Error(`Unsupported chunk type: ${u}`)}}s()},flush(a){if(r.status?.type==="running"){const l=r.parts?.some(u=>u.type==="tool-call"&&(u.state==="call"||u.state==="partial-call")&&u.result===void 0)??!1;r=E_(r,{finishReason:l?"tool-calls":"unknown"}),a.enqueue(r)}}})}}class s9 extends x${constructor(){super(t=>{const n=new NH({transform(i,r){r.appendText(i)}});return t.pipeThrough(new TextDecoderStream).pipeThrough(n)})}}class zs{readable;constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new zs(t.pipeThrough(new o9))}async unstable_result(){let t;for await(const n of this)t=n;return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){const t=this.readable.getReader();return{async next(){const{done:n,value:i}=await t.read();return n?{done:!0,value:void 0}:{done:!1,value:i}}}}tee(){const[t,n]=this.readable.tee();return[new zs(t),new zs(n)]}}const I_=Symbol.for("aui.tool-response");class jn{get[I_](){return!0}artifact;result;isError;constructor(t){t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=t.isError??!1}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&I_ in t}static toResponse(t){return t instanceof jn?t:new jn({result:t===void 0?"<no result>":t})}}function a9(e,t,n){try{const i=e();if(typeof i=="object"&&i!==null&&"then"in i)return i.then(t,n);t(i)}catch(i){n(i)}}function gu(e,t){let n=e;for(const i of t){if(n==null)return;n=n[i]}return n}class u9{resolve;reject;disposed=!1;fieldPath;constructor(t,n,i){this.resolve=t,this.reject=n,this.fieldPath=i}update(t){if(!this.disposed)try{if(Vo(t,this.fieldPath)==="complete"){const n=gu(t,this.fieldPath);n!==void 0&&(this.resolve(n),this.dispose())}}catch(n){this.reject(n),this.dispose()}}dispose(){this.disposed=!0}}class T_{controller;disposed=!1;fieldPath;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=gu(t,this.fieldPath);n!==void 0&&this.controller.enqueue(n),Vo(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class k_{controller;disposed=!1;fieldPath;lastValue=void 0;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=gu(t,this.fieldPath);if(n!==void 0&&typeof n=="string"){const i=n.substring(this.lastValue?.length||0);this.lastValue=n,this.controller.enqueue(i)}Vo(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class C_{controller;disposed=!1;fieldPath;processedIndexes=new Set;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=gu(t,this.fieldPath);if(!Array.isArray(n))return;for(let i=0;i<n.length;i++)if(!this.processedIndexes.has(i)){const r=[...this.fieldPath,i];Vo(t,r)==="complete"&&(this.controller.enqueue(n[i]),this.processedIndexes.add(i))}Vo(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class l9{argTextDeltas;handles=new Set;args=Yl("");constructor(t){this.argTextDeltas=t,this.processStream()}async processStream(){try{let t="";const n=this.argTextDeltas.getReader();for(;;){const{value:i,done:r}=await n.read();if(r)break;t+=i;const o=Yl(t);if(o!==void 0){this.args=o;for(const s of this.handles)s.update(o)}}}catch(t){console.error("Error processing argument stream:",t);for(const n of this.handles)n.dispose()}}get(...t){return new Promise((n,i)=>{const r=new u9(n,i,t);if(this.args&&Vo(this.args,t)==="complete"){const o=gu(this.args,t);if(o!==void 0){n(o);return}}this.handles.add(r),r.update(this.args)})}streamValues(...t){const n=t,i=new ReadableStream({start:r=>{const o=new T_(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof T_){r.dispose(),this.handles.delete(r);break}}});return zf(i)}streamText(...t){const n=t,i=new ReadableStream({start:r=>{const o=new k_(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof k_){r.dispose(),this.handles.delete(r);break}}});return zf(i)}forEach(...t){const n=t,i=new ReadableStream({start:r=>{const o=new C_(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof C_){r.dispose(),this.handles.delete(r);break}}});return zf(i)}}class c9{promise;constructor(t){this.promise=t}get(){return this.promise}}class d9{args;response;writable;resolve;argsText="";constructor(){const t=new TransformStream;this.writable=t.writable,this.args=new l9(t.readable);const{promise:n,resolve:i}=vv();this.resolve=i,this.response=new c9(n)}async appendArgsTextDelta(t){const n=this.writable.getWriter();try{await n.write(t)}catch(i){console.warn(i)}finally{n.releaseLock()}this.argsText+=t}setResponse(t){this.resolve(t)}result={get:async()=>(await this.response.get()).result}}class f9 extends x${constructor(t){const n=new Map,i=new Map;super(r=>{const o=new TransformStream({transform(s,a){switch((s.type!=="part-finish"||s.meta.type!=="tool-call")&&a.enqueue(s),s.type){case"part-start":if(s.part.type==="tool-call"){const u=new d9;i.set(s.part.toolCallId,u),t.streamCall({reader:u,toolCallId:s.part.toolCallId,toolName:s.part.toolName})}break;case"text-delta":{if(s.meta.type==="tool-call"){const u=s.meta.toolCallId,c=i.get(u);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,c=i.get(u);if(!c)throw new Error("No controller found for tool call");c.setResponse(new jn({result:s.result,artifact:s.artifact,isError:s.isError}));break}case"tool-call-args-text-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u,toolName:c}=s.meta,d=i.get(u);if(!d)throw new Error("No controller found for tool call");let f=!1;const p=a9(()=>{let m;try{m=ch.parse(d.argsText)}catch(v){throw new Error(`Function parameter parsing failed. ${JSON.stringify(v.message)}`)}const h=t.execute({toolCallId:u,toolName:c,args:m});return h!==void 0&&(f=!0,t.onExecutionStart?.(u,c)),h},m=>{if(f&&t.onExecutionEnd?.(u,c),m===void 0)return;const h=new jn({artifact:m.artifact,result:m.result,isError:m.isError});d.setResponse(h),a.enqueue({type:"result",path:s.path,...h})},m=>{f&&t.onExecutionEnd?.(u,c);const h=new jn({result:String(m),isError:!0});d.setResponse(h),a.enqueue({type:"result",path:s.path,...h})});p&&n.set(u,p);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,c=n.get(u);c?c.then(()=>{n.delete(u),i.delete(u),a.enqueue(s)}):a.enqueue(s)}}},async flush(){await Promise.all(n.values())}});return r.pipeThrough(new S$).pipeThrough(o)})}}const p9=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function h9(e,t,n,i){const r=e?.[n.toolName];return!r||!r.execute?void 0:(async s=>{if(t.aborted)return new jn({result:"Tool execution was cancelled.",isError:!0});let a=s;if(p9(r.parameters)){let c=r.parameters["~standard"].validate(n.args);c instanceof Promise&&(c=await c),c.issues&&(a=r.experimental_onSchemaValidationError??(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const d=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new jn({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?d():t.addEventListener("abort",d,{once:!0})}),u=(async()=>{const c=await a(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:d=>i(n.toolCallId,d)});return jn.toResponse(c)})();return Promise.race([u,l])})(r.execute)}function m9(e,t,n,i,r){e?.[i.toolName]?.streamCall?.(n,{toolCallId:i.toolCallId,abortSignal:t,human:o=>r(i.toolCallId,o)})}function g9(e,t,n,i){const r=typeof e=="function"?e:()=>e,o=typeof t=="function"?t:()=>t;return new f9({execute:s=>h9(r(),o(),s,n),streamCall:({reader:s,...a})=>m9(r(),o(),s,a,n),onExecutionStart:i?.onExecutionStart,onExecutionEnd:i?.onExecutionEnd})}class A_{contentBinding;messageApi;threadApi;get path(){return this.contentBinding.path}constructor(t,n,i){this.contentBinding=t,this.messageApi=n,this.threadApi=i,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const i=this.messageApi.getState();if(!i)throw new Error("Message is not available");const r=n.toolName,o=n.toolCallId,s=jn.toResponse(t);this.threadApi.getState().addToolResult({messageId:i.id,toolName:r,toolCallId:o,result:s.result,artifact:s.artifact,isError:s.isError})}resumeToolCall(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const i=n.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:i,payload:t})}subscribe(t){return this.contentBinding.subscribe(t)}}class Xl extends Dd{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let n=this.binding.getState(),i=n?.subscribe(t);const r=()=>{const s=this.binding.getState();s!==n&&(n=s,i?.(),i=this.binding.getState()?.subscribe(t),t())},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const Hu=Object.freeze({type:"complete"}),v9=(e,t,n)=>{if(e.role!=="assistant")return Hu;if(n.type==="tool-call")return n.result?Hu:e.status;const i=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Hu:i?e.status:Hu},R_=(e,t)=>{const n=e.content[t];if(!n)return Dn;const i=v9(e,t,n);return Object.freeze({...n,[Qt]:n[Qt],status:i})};class y9{_core;_threadBinding;get path(){return this._core.path}constructor(t,n){this._core=t,this._threadBinding=n,this.composer=new qH(new Xl({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:i=>this._threadBinding.subscribe(i)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}reload(t={}){const n=this._getEditComposerRuntimeCore(),i=n??this._threadBinding.getState().composer,r=n??i,{runConfig:o=r.runConfig}=t,s=this._core.getState();if(s.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:s.parentId,sourceId:s.id,runConfig:o})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){const t=this._core.getState();if(this._threadBinding.getState().speech?.messageId===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:t})}switchToBranch({position:t,branchId:n}){const i=this._core.getState();if(n&&t)throw new Error("May not specify both branchId and position");if(!n&&!t)throw new Error("Must specify either branchId or position");const o=this._threadBinding.getState().getBranches(i.id);let s=n;if(t==="previous"?s=o[i.branchNumber-2]:t==="next"&&(s=o[i.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return sa(this.getState())}subscribe(t){return this._core.subscribe(t)}getMessagePartByIndex(t){if(t<0)throw new Error("Message part index must be >= 0");return new A_(new Nn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${t}]`,messagePartSelector:{type:"index",index:t}},getState:()=>R_(this.getState(),t),subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getMessagePartByToolCallId(t){return new A_(new Nn({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,messagePartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const n=this._core.getState(),i=n.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return i===-1?Dn:R_(n,i)},subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new UH(new Nn({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const i=this.getState().attachments?.[t];return i?{...i,source:"message"}:Dn},subscribe:n=>this._core.subscribe(n)}))}}const b9=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),_9=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),w9=(e,t)=>typeof t=="string"?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??"user",content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},x9=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:n?.role!=="assistant"?!1:n.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})};class O${get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(t,n){const i=new Nn({path:t.path,getState:()=>x9(t.getState(),n.getState()),subscribe:r=>{const o=t.subscribe(r),s=n.subscribe(r);return()=>{o(),s()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>i.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new VH(new Xl({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(w9(this._threadBinding.getState().messages,t))}subscribe(t){return this._threadBinding.subscribe(t)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(t){const n=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(_9(n))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(b9(t))}unstable_loadExternalState(t){this._threadBinding.getState().unstable_loadExternalState(t)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(t){this._threadBinding.getState().import(t)}reset(t){this._threadBinding.getState().reset(t)}getMessageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}},()=>{const n=this._threadBinding.getState().messages,i=n[t];if(i)return{message:i,parentId:n[t-1]?.id??null,index:t}})}getMessageById(t){return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(t)}]`,messageSelector:{type:"messageId",messageId:t}},()=>this._threadBinding.getState().getMessageById(t))}_getMessageRuntime(t,n){return new y9(new Nn({path:t,getState:()=>{const{message:i,parentId:r,index:o}=n()??{},{messages:s,speech:a}=this._threadBinding.getState();if(!i||r===void 0||o===void 0)return Dn;const u=this._threadBinding.getState().getBranches(i.id),c=i.metadata.submittedFeedback;return{...i,[Qt]:i[Qt],index:o,isLast:s.at(-1)?.id===i.id,parentId:r,branchNumber:u.indexOf(i.id)+1,branchCount:u.length,speech:a?.messageId===i.id?a:void 0,submittedFeedback:c}},subscribe:i=>this._threadBinding.subscribe(i)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(t,n){let i=this._eventSubscriptionSubjects.get(t);return i||(i=new C$({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}const S9=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Gu=(e,t)=>{if(t===void 0)return Dn;const n=e.getItemById(t);return n?{id:n.id,threadId:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:Dn};class E9{_core;_runtimeFactory;_getState;constructor(t,n=O$){this._core=t,this._runtimeFactory=n;const i=new wv({path:{},getState:()=>S9(t),subscribe:r=>t.subscribe(r)});this._getState=i.getState.bind(i),this._mainThreadListItemRuntime=new Zu(new Nn({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Gu(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new n(new Xl({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(t){return this._core.switchToThread(t)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(t){return this._core.subscribe(t)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new Xl({path:{ref:`threads[threadId=${JSON.stringify(t)}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:n=>this._core.subscribe(n)}),this.mainItem)}getItemByIndex(t){return new Zu(new Nn({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>Gu(this._core,this._core.threadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getArchivedItemByIndex(t){return new Zu(new Nn({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>Gu(this._core,this._core.archivedThreadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getItemById(t){return new Zu(new Nn({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>Gu(this._core,t),subscribe:n=>this._core.subscribe(n)}),this._core)}}const I9=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file";class T9{cloud;accept="*";constructor(t){this.cloud=t}uploadedUrls=new Map;async*add({file:t}){const n=crypto.randomUUID(),i=I9(t.type);let r={id:n,type:i,name:t.name,contentType:t.type,file:t,status:{type:"running",reason:"uploading",progress:0}};yield r;try{const{signedUrl:o,publicUrl:s}=await this.cloud.files.generatePresignedUploadUrl({filename:t.name});await fetch(o,{method:"PUT",body:t,headers:{"Content-Type":t.type},mode:"cors"}),this.uploadedUrls.set(n,s),r={...r,status:{type:"requires-action",reason:"composer-send"}},yield r}catch{r={...r,status:{type:"incomplete",reason:"error"}},yield r}}async remove(t){this.uploadedUrls.delete(t.id)}async send(t){const n=this.uploadedUrls.get(t.id);if(!n)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(t.id);let i;return t.type==="image"?i=[{type:"image",image:n,filename:t.name}]:i=[{type:"file",data:n,mimeType:t.contentType,filename:t.name}],{...t,status:{type:"complete"},content:i}}}const fh=I.createContext(null),xv=({adapters:e,children:t})=>{const n=I.useContext(fh);return g.jsx(fh.Provider,{value:{...n,...e},children:t})},N$=()=>I.useContext(fh),di=Object.freeze([]),xi="DEFAULT_THREAD_ID",k9=Object.freeze([xi]),P$=Object.freeze({id:xi,remoteId:void 0,externalId:void 0,status:"regular"}),C9=Promise.resolve(),$_=Object.freeze({[xi]:P$});class A9{adapter;threadFactory;_mainThreadId=xi;_threads=k9;_archivedThreads=di;_threadData=$_;get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadData(){return this._threadData}getLoadThreadsPromise(){return C9}_mainThread;get mainThreadId(){return this._mainThreadId}constructor(t={},n){this.adapter=t,this.threadFactory=n,this._mainThread=this.threadFactory(),this.__internal_setAdapter(t,!0)}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const n of this.adapter.threads??[])if(n.id===t)return n;for(const n of this.adapter.archivedThreads??[])if(n.id===t)return n;if(t===xi)return P$}__internal_setAdapter(t,n=!1){const i=this.adapter;this.adapter=t;const r=t.threadId??xi,o=t.threads??di,s=t.archivedThreads??di,a=i.threadId??xi,l=i.threads??di,u=i.archivedThreads??di;!n&&a===r&&l===o&&u===s||(this._threadData={...$_,...Object.fromEntries(t.threads?.map(c=>[c.id,{...c,remoteId:c.remoteId,externalId:c.externalId,status:"regular"}])??[]),...Object.fromEntries(t.archivedThreads?.map(c=>[c.id,{...c,remoteId:c.remoteId,externalId:c.externalId,status:"archived"}])??[])},l!==o&&(this._threads=this.adapter.threads?.map(c=>c.id)??di),u!==s&&(this._archivedThreads=this.adapter.archivedThreads?.map(c=>c.id)??di),a!==r&&(this._mainThreadId=r,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const n=this.adapter.onSwitchToThread;if(!n)throw new Error("External store adapter does not support switching to thread");n(t)}async switchToNewThread(){const t=this.adapter.onSwitchToNewThread;if(!t)throw new Error("External store adapter does not support switching to new thread");t()}async rename(t,n){const i=this.adapter.onRename;if(!i)throw new Error("External store adapter does not support renaming");i(t,n)}async detach(){}async archive(t){const n=this.adapter.onArchive;if(!n)throw new Error("External store adapter does not support archiving");n(t)}async unarchive(t){const n=this.adapter.onUnarchive;if(!n)throw new Error("External store adapter does not support unarchiving");n(t)}async delete(t){const n=this.adapter.onDelete;if(!n)throw new Error("External store adapter does not support deleting");n(t)}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}_subscriptions=new Set;subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}}class ph{cache=new WeakMap;convertMessages(t,n){return t.map((i,r)=>{const o=this.cache.get(i),s=n(o,i,r);return this.cache.set(i,s),s})}}class R9 extends m${runtime;endEditCallback;get canCancel(){return!0}getAttachmentAdapter(){return this.runtime.adapters?.attachments}_nonTextParts;_previousText;_parentId;_sourceId;constructor(t,n,{parentId:i,message:r}){super(),this.runtime=t,this.endEditCallback=n,this._parentId=i,this._sourceId=r.id,this._previousText=sa(r),this.setText(this._previousText),this.setRole(r.role),this.setAttachments(r.attachments??[]),this._nonTextParts=r.content.filter(o=>o.type!=="text"),this.setRunConfig({...t.composer.runConfig})}async handleSend(t){sa(t)!==this._previousText&&this.runtime.append({...t,content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}}class $9{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new _v;get messages(){return this.repository.getMessages()}get state(){let t;for(const n of this.messages)if(n.role==="assistant"){t=n;break}return t?.metadata.unstable_state??null}composer=new g$(this);constructor(t){this._contextProvider=t}getModelContext(){return this._contextProvider.getModelContext()}_editComposers=new Map;getEditComposer(t){return this._editComposers.get(t)}beginEdit(t){if(this._editComposers.has(t))throw new Error("Edit already in progress");this._editComposers.set(t,new R9(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){try{return this.repository.getMessage(t)}catch{return}}getBranches(t){return this.repository.getBranches(t)}switchToBranch(t){this.repository.switchToBranch(t),this._notifySubscribers()}_notifySubscribers(){for(const t of this._subscriptions)t()}_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const i of n)i()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}submitFeedback({messageId:t,type:n}){const i=this.adapters?.feedback;if(!i)throw new Error("Feedback adapter not configured");const{message:r,parentId:o}=this.repository.getMessage(t);if(i.submit({message:r,type:n}),r.role==="assistant"){const s={...r,metadata:{...r.metadata,submittedFeedback:{type:n}}};this.repository.addOrUpdateMessage(o,s)}this._notifySubscribers()}_stopSpeaking;speech;speak(t){const n=this.adapters?.speech;if(!n)throw new Error("Speech adapter not configured");const{message:i}=this.repository.getMessage(t);this._stopSpeaking?.();const r=n.speak(sa(i)),o=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:r.status},this._notifySubscribers()});this.speech={messageId:t,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),o(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(t){this.ensureInitialized(),this.repository.clear(),this.repository.import(t),this._notifySubscribers()}reset(t){this.import(bv.fromArray(t??[]))}_eventSubscribers=new Map;unstable_on(t,n){if(t==="model-context-update")return this._contextProvider.subscribe?.(n)??(()=>{});const i=this._eventSubscribers.get(t);return i?i.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{this._eventSubscribers.get(t).delete(n)}}}const O9=Object.freeze([]),N9=(e,t)=>e&&t[t.length-1]?.role!=="assistant";class P9 extends $9{_assistantOptimisticId=null;_capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1};get capabilities(){return this._capabilities}_messages;isDisabled;get isLoading(){return this._store.isLoading??!1}get messages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}suggestions=[];extras=void 0;_converter=new ph;_store;beginEdit(t){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(t)}constructor(t,n){super(t),this.__internal_setAdapter(n)}__internal_setAdapter(t){if(this._store===t)return;const n=t.isRunning??!1;this.isDisabled=t.isDisabled??!1;const i=this._store;this._store=t,this.extras=t.extras,this.suggestions=t.suggestions??O9,this._capabilities={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback};let r;if(t.messageRepository){if(i&&i.isRunning===t.isRunning&&i.messageRepository===t.messageRepository){this._notifySubscribers();return}this.repository.clear(),this._assistantOptimisticId=null,this.repository.import(t.messageRepository),r=this.repository.getMessages()}else if(t.messages){if(i){if(i.convertMessage!==t.convertMessage)this._converter=new ph;else if(i.isRunning===t.isRunning&&i.messages===t.messages){this._notifySubscribers();return}}r=t.convertMessage?this._converter.convertMessages(t.messages,(o,s,a)=>{if(!t.convertMessage)return s;const l=a===t.messages.length-1,u=hu(l,n,!1,!1,void 0);if(o&&(o.role!=="assistant"||!y$(o.status)||o.status===u))return o;const c=t.convertMessage(s,a),d=Vi(c,a.toString(),u);return d[Qt]=s,d}):t.messages;for(let o=0;o<r.length;o++){const s=r[o],a=r[o-1];this.repository.addOrUpdateMessage(a?.id??null,s)}}else throw new Error("ExternalStoreAdapter must provide either 'messages' or 'messageRepository'");r.length>0&&this.ensureInitialized(),(i?.isRunning??!1)!==(t.isRunning??!1)&&(t.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end")),this._assistantOptimisticId&&(this.repository.deleteMessage(this._assistantOptimisticId),this._assistantOptimisticId=null),N9(n,r)&&(this._assistantOptimisticId=this.repository.appendOptimisticMessage(r.at(-1)?.id??null,{role:"assistant",content:[]})),this.repository.resetHead(this._assistantOptimisticId??r.at(-1)?.id??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(t){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this._store.isRunning||(this.repository.switchToBranch(t),this.updateMessages(this.repository.getMessages()))}async append(t){if(t.parentId!==(this.messages.at(-1)?.id??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(t)}else await this._store.onNew(t)}async startRun(t){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(t.parentId,t)}async resumeRun(t){if(!this._store.onResume)throw new Error("Runtime does not support resuming runs.");await this._store.onResume(t)}unstable_loadExternalState(t){if(!this._store.onLoadExternalState)throw new Error("Runtime does not support importing states.");this._store.onLoadExternalState(t)}cancelRun(){if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._store.onCancel(),this._assistantOptimisticId&&(this.repository.deleteMessage(this._assistantOptimisticId),this._assistantOptimisticId=null);let t=this.repository.getMessages();const n=t[t.length-1];n?.role==="user"&&n.id===t.at(-1)?.id?(this.repository.deleteMessage(n.id),this.composer.text.trim()||this.composer.setText(sa(n)),t=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(t)},0)}addToolResult(t){if(!this._store.onAddToolResult&&!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult?.(t)}resumeToolCall(t){if(!this._store.onResumeToolCall)throw new Error("Runtime does not support resuming tool calls.");this._store.onResumeToolCall(t)}reset(t){const n=new _v;n.import(bv.fromArray(t??[])),this.updateMessages(n.getMessages())}import(t){this._assistantOptimisticId=null,super.import(t),this._store.onImport&&this._store.onImport(this.repository.getMessages())}updateMessages=t=>{this._store.convertMessage!==void 0?this._store.setMessages?.(t.flatMap(jH).filter(i=>i!=null)):this._store.setMessages?.(t)}}const O_=e=>e.adapters?.threadList??{};class M9 extends gv{threads;constructor(t){super(),this.threads=new A9(O_(t),()=>new P9(this._contextProvider,t))}setAdapter(t){this.threads.__internal_setAdapter(O_(t)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(t)}}const j9=e=>{const[t]=I.useState(()=>new M9(e));I.useEffect(()=>{t.setAdapter(e)});const{modelContext:n}=N$()??{};return I.useEffect(()=>{if(n)return t.registerModelContextProvider(n)},[n,t]),I.useMemo(()=>new kv(t),[t])},D9=e=>{try{return JSON.parse(e),!0}catch{return!1}};function M$({state:e,getTools:t,onResult:n,setToolStatuses:i}){const r=I.useRef({}),o=I.useRef(new Map),s=I.useRef(new AbortController),a=I.useRef(0),l=I.useRef([]),[u]=I.useState(()=>{const[p,m]=I$(),h=g9(t,()=>s.current?.signal??new AbortController().signal,(v,y)=>new Promise((w,S)=>{const b=o.current.get(v);b&&b.reject(new Error("Human input request was superseded by a new request")),o.current.set(v,{resolve:w,reject:S}),i(C=>({...C,[v]:{type:"interrupt",payload:{type:"human",payload:y}}}))}),{onExecutionStart:v=>{a.current++,i(y=>({...y,[v]:{type:"executing"}}))},onExecutionEnd:v=>{a.current--,i(y=>{const w={...y};return delete w[v],w}),a.current===0&&(l.current.forEach(y=>y()),l.current=[])}});return p.pipeThrough(h).pipeThrough(new S$).pipeTo(new WritableStream({write(v){if(v.type==="result"){if(r.current[v.meta.toolCallId]?.hasResult)return;n({type:"add-tool-result",toolCallId:v.meta.toolCallId,toolName:v.meta.toolName,result:v.result,isError:v.isError,...v.artifact&&{artifact:v.artifact}})}}})),m}),c=I.useRef(new Set),d=I.useRef(!0);I.useEffect(()=>{const p=m=>{m.forEach(h=>{h.content.forEach(v=>{if(v.type==="tool-call"){if(d.current)c.current.add(v.toolCallId);else{if(c.current.has(v.toolCallId))return;let y=r.current[v.toolCallId];if(y||(y={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:v.toolName,toolCallId:v.toolCallId})},r.current[v.toolCallId]=y),v.argsText!==y.argsText)if(y.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:y.argsText,next:v.argsText});else{if(!v.argsText.startsWith(y.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${v.argsText} does not start with ${y.argsText}`);const w=v.argsText.slice(y.argsText.length);y.controller.argsText.append(w);const S=D9(v.argsText);S&&y.controller.argsText.close(),r.current[v.toolCallId]={argsText:v.argsText,hasResult:y.hasResult,argsComplete:S,controller:y.controller}}v.result!==void 0&&!y.hasResult&&(y.controller.setResponse(new jn({result:v.result,artifact:v.artifact,isError:v.isError})),y.controller.close(),r.current[v.toolCallId]={hasResult:!0,argsComplete:!0,argsText:y.argsText,controller:y.controller})}v.messages&&p(v.messages)}})})};p(e.messages),d.current&&(d.current=!1)},[e,u,n]);const f=()=>(o.current.forEach(({reject:p})=>{p(new Error("Tool execution aborted"))}),o.current.clear(),s.current.abort(),s.current=new AbortController,a.current===0?Promise.resolve():new Promise(p=>{l.current.push(p)}));return{reset:()=>{f(),d.current=!0},abort:f,resume:(p,m)=>{const h=o.current.get(p);if(h)o.current.delete(p),i(v=>({...v,[p]:{type:"executing"}})),h.resolve(m);else throw new Error(`Tool call ${p} is not waiting for human input`)}}}class z9{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(t){return Promise.reject(new Error("Thread not found"))}}function L9(e,t){e.commitTasks.forEach(n=>{const i=n.cellIndex,r=t.cells[i];if(r.type!=="effect")throw new Error("Cannot find effect cell");let o=!0;if(r.deps!==void 0&&n.deps!==void 0&&(o=r.deps.length!==n.deps.length||r.deps.some((s,a)=>!Object.is(s,n.deps[a]))),o){if(r.mounted){if(typeof r.deps!=typeof n.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{r.mounted&&r.cleanup&&r.cleanup()}finally{r.mounted=!1}}const s=n.effect();if(s!==void 0&&typeof s!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof s}`);r.mounted=!0,r.cleanup=typeof s=="function"?s:void 0,r.deps=n.deps}})}function U9(e){let t=null;for(let n=e.cells.length-1;n>=0;n--){const i=e.cells[n];if(i?.type==="effect"&&i.mounted&&i.cleanup)try{i.cleanup()}catch(r){t==null&&(t=r)}finally{i.mounted=!1}}if(t!=null)throw t}let Ls=null;function F9(e,t){e.currentIndex=0;const n=Ls;Ls=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{Ls=n}}function Sv(){if(!Ls)throw new Error("No resource fiber available");return Ls}function j$(e,t){const n=e[D$];if(!n)throw new Error("ResourceElement.type is not a valid Resource");return n(t)}const D$=Symbol("fnSymbol");function Ld(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function aa(e){e.isMounted=!1,U9(e)}function ua(e,t){const n={commitTasks:[],props:t,state:void 0};return F9(e,()=>{e.renderContext=n;try{n.state=j$(e.resource,t)}finally{e.renderContext=void 0}}),n}function la(e,t){e.isMounted=!0,e.isNeverMounted=!1,L9(t,e)}const B9=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,N_=B9?I.useEffect:I.useLayoutEffect;function Ev(e){const[,t]=I.useState({}),n=I.useMemo(()=>Ld(e.type,()=>t({})),[e.type]),i=ua(n,e.props);return N_(()=>()=>aa(n),[n]),N_(()=>{la(n,i)}),i.state}const ss=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},ki=(e,t,n)=>t===e;let ro;const Uf=()=>{if(ro)return ro;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window>"u")return ro=e(),ro;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return ro=t,t;const n=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=n,ro=n,n};class vi{static MAX_EVENT_LOGS_PER_API=200;static register(t){const n=Uf();for(const a of n.apis.values())if(a.api===t)return()=>{};const i=n.nextId++,r={api:t,logs:[]},o=t.on?.("*",a=>{const l=n.apis.get(i);l&&(l.logs.push({time:new Date,event:a.event,data:a.payload}),l.logs.length>vi.MAX_EVENT_LOGS_PER_API&&(l.logs=l.logs.slice(-200)),vi.notifyListeners(i))}),s=t.subscribe?.(()=>{vi.notifyListeners(i)});return n.apis.set(i,r),vi.notifyListeners(i),()=>{const a=Uf();a.apis.get(i)&&(o?.(),s?.(),a.apis.delete(i),vi.notifyListeners(i))}}static notifyListeners(t){Uf().listeners.forEach(i=>i(t))}}function Qe(e){const t=n=>({type:t,props:n});return t[D$]=e,t}const V9=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isMounted)e.scheduleRerender();else if(e.isNeverMounted)throw new Error("Resource updated before mount")};function q9(e){const t=Sv(),n=t.currentIndex++;if(!t.isFirstRender&&n>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[n]){const o={type:"state",value:typeof e=="function"?e():e,set:s=>{const a=o.value,l=typeof s=="function"?s(a):s;Object.is(a,l)||(o.value=l,V9(t))}};t.cells[n]=o}const i=t.cells[n];if(i.type!=="state")throw new Error("Hook order changed between renders");return i}function rr(e){const t=q9(e);return[t.value,t.set]}function Z9(){const e=Sv(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const i={type:"effect",mounted:!1};e.cells[t]=i}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function Lt(e,t){const n=Sv(),i=Z9();n.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:i})}function qo(e){const[t]=rr(()=>({current:e}));return t}const H9=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},Oe=(e,t)=>{const n=qo();return n.current||(n.current={value:e(),deps:t}),H9(n.current.deps,t)||(n.current.value=e(),n.current.deps=t),n.current.value},G9=(e,t)=>Oe(()=>e,t);function Us(e,t){const[n,i]=rr({}),r=Oe(()=>Ld(e.type,()=>i({})),[e.type]),o=t?Oe(()=>e.props,t):e.props,s=Oe(()=>ua(r,o),[r,o,n]);return Lt(()=>()=>aa(r),[r]),Lt(()=>{la(r,s)},[r,s]),s.state}function sr(e){return j$(e.type,e.props)}function z$(e,t,n){const[i,r]=rr(0),o=G9(()=>r(u=>u+1),[]),[s]=rr(()=>new Map),a=Oe(()=>t,n),l=Oe(()=>{const u={remove:[],add:[],commit:[],return:{}};for(const c in e){const d=e[c],f=a(d,c);let p=s.get(c);(!p||p.resource!==f.type)&&(p&&u.remove.push(c),p=Ld(f.type,o),u.add.push([c,p]));const m=ua(p,f.props);u.commit.push([c,m]),u.return[c]=m.state}if(s.size>u.commit.length-u.add.length+u.remove.length)for(const c of s.keys())c in e||u.remove.push(c);return u},[e,a,i]);return Lt(()=>()=>{for(const u of s.keys())aa(s.get(u)),s.delete(u)},[]),Lt(()=>{for(const u of l.remove)aa(s.get(u)),s.delete(u);for(const[u,c]of l.add)s.set(u,c);for(const[u,c]of l.commit)la(s.get(u),c)},[l]),l.return}const W9=50;let Yn={schedulers:new Set([]),isScheduled:!1};class J9{_task;_isDirty=!1;constructor(t){this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,Yn.schedulers.add(this),K9()}runTask(){this._isDirty=!1,this._task()}}const K9=()=>{Yn.isScheduled||(Yn.isScheduled=!0,queueMicrotask(L$))},L$=()=>{try{const e=[];let t=0;for(const n of Yn.schedulers)if(Yn.schedulers.delete(n),!!n.isDirty){if(t++,t>W9)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");try{n.runTask()}catch(i){e.push(i)}}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e,"Errors occurred during flushSync")}finally{Yn.schedulers.clear(),Yn.isScheduled=!1}},hh=e=>{const t=Yn;Yn={schedulers:new Set([]),isScheduled:!0};try{const n=e();return L$(),n}finally{Yn=t}},Y9=Qe(e=>{const[,t]=rr(e.element),n=Us(e.element),i=qo(new Set).current,r=qo(n);return Lt(()=>{n!==r.current&&(r.current=n,i.forEach(s=>s()))}),Oe(()=>({getState:()=>r.current,subscribe:s=>(i.add(s),()=>i.delete(s)),render:s=>{const a=e.element!==s;e.element=s,e.onRender(a)&&t(s)},unmount:e.onUnmount}),[])}),X9=(e,{mount:t=!0}={})=>{let n=t,i;const r={element:e,onRender:a=>n?a:(n=!0,hh(()=>{a&&(i=ua(s,r)),!o.isDirty&&la(s,i)}),!1),onUnmount:()=>{if(!n)throw new Error("Resource not mounted");n=!1,aa(s)}},o=new J9(()=>{i=ua(s,r),!(o.isDirty||!n)&&la(s,i)}),s=Ld(Y9,()=>o.markDirty());return hh(()=>{o.markDirty()}),i.state},Fs=Symbol("tap.Context"),U$=e=>({[Fs]:e}),F$=(e,t,n)=>{const i=e[Fs];e[Fs]=t;try{return n()}finally{e[Fs]=i}},B$=e=>e[Fs],Q9=e=>{const t=Re();I.useEffect(()=>{if(e.render)return t.tools().setToolUI(e.toolName,e.render)},[t,e.toolName,e.render]),I.useEffect(()=>{const{toolName:n,render:i,...r}=e,o={tools:{[n]:r}};return t.modelContext().register({getModelContext:()=>o})},[t,e])},eG=e=>{const t=()=>(Q9(e),null);return t.unstable_tool=e,t};function P_(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Iv(...e){return t=>{let n=!1;const i=e.map(r=>{const o=P_(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<i.length;r++){const o=i[r];typeof o=="function"?o():P_(e[r],null)}}}}function mt(...e){return x.useCallback(Iv(...e),e)}const V$=Qe(e=>{const t=Oe(()=>X9(e,{mount:!1}),[e.type]);return Lt(()=>{t.render(e)}),t});class tG{ref;constructor(t){this.ref=t}get(t,n){return this.ref.current[n]}ownKeys(){return Object.keys(this.ref.current)}has(t,n){return n in this.ref.current}getOwnPropertyDescriptor(t,n){return Object.getOwnPropertyDescriptor(this.ref.current,n)}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}}const Fn=(e,t)=>{const n=qo(e);Lt(()=>{n.current=e});const i=Oe(()=>new Proxy({},new tG(n)),[]),r=t?.key,o=e.getState();return Oe(()=>({key:r,state:o,api:i}),[o,r])},Yr=Qe(e=>{const t=qo(e.get);return Lt(()=>{t.current=e.get}),Oe(()=>Et({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),nG=Qe(e=>{const t=Us(e.scopeElement);return Oe(()=>[e.fieldName,t],[e.fieldName,t])}),rG=Qe(e=>{const{on:t,subscribe:n,...i}=e,r=qo({on:t,subscribe:n});Lt(()=>{r.current={on:t,subscribe:n}});const o=z$(i,(s,a)=>nG({fieldName:a,scopeElement:s}),[]);return Oe(()=>{const s=Object.fromEntries(Object.values(o)),{on:a,subscribe:l}=r.current;return a&&(s.on=(u,c)=>a(u,c)),l&&(s.subscribe=u=>l(u)),s},[o])}),q$=U$(null),iG=(e,t)=>F$(q$,e,t),Z$=()=>{const e=B$(q$);if(!e)throw new Error("Model context is not available in this context");return e},oG=Qe(({toolkit:e})=>{const[t,n]=rr(()=>({tools:{}})),i=Z$();Lt(()=>{if(!e)return;const o=[];for(const[l,u]of Object.entries(e))u.render&&o.push(r(l,u.render));const s=Object.entries(e).reduce((l,[u,c])=>{const{render:d,...f}=c;return l[u]=f,l},{}),a={getModelContext:()=>({tools:s})};return o.push(i.register(a)),()=>{o.forEach(l=>l())}},[e,i]);const r=(o,s)=>(n(a=>({...a,tools:{...a.tools,[o]:[...a.tools[o]??[],s]}})),()=>{n(a=>({...a,tools:{...a.tools,[o]:a.tools[o]?.filter(l=>l!==s)??[]}}))});return Fn({getState:()=>t,setToolUI:r})}),sG=Qe(()=>Oe(()=>{const t=new Map;return{on:(n,i)=>{t.has(n)||t.set(n,new Set);const r=t.get(n);return r.add(i),()=>{r.delete(i),r.size===0&&t.delete(n)}},emit:(n,i)=>{const r=t.get(n),o=t.get("*");!r&&!o||queueMicrotask(()=>{if(r)for(const s of r)s(i);if(o)for(const s of o)s({event:n,payload:i})})}}},[])),H$=U$(null),aG=(e,t)=>F$(H$,e,t),Tv=()=>{const e=B$(H$);if(!e)throw new Error("Events context is not available");return e},uG=Qe(()=>{const[e]=rr(()=>({})),t=new mv;return Fn({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:n=>t.subscribe(n),register:n=>t.registerModelContextProvider(n)})}),lG=Qe(({threads:e,modelContext:t,tools:n})=>{const i=sr(sG()),{threads:r,tools:o,modelContext:s}=aG(i,()=>{const l=Us(t??uG(),[t]);return iG(l.api,()=>({modelContext:l,tools:Us(n??oG({}),[n]),threads:Us(e,[e])}))}),a=Oe(()=>({threads:r.state,tools:o.state,modelContext:s.state}),[r.state,o.state,s.state]);return Fn({getState:()=>a,threads:r.api,tools:o.api,modelContext:s.api,on:i.on})}),cG=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Et({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Et({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Et({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Et({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Et({source:"threads",query:{type:"main"},get:()=>t()}),composer:Et({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(n,i){const{event:r,scope:o}=ss(n);if(o==="*")return e.getState().api.on(r,i);if(ki("thread",o)||ki("thread-list-item",o)||ki("composer",o))return e.getState().api.on(r,s=>{s.threadId===t().getState().id&&i(s)});throw new Error(`Event scope is not available in this component: ${o}`)},subscribe:e.subscribe}},dG=e=>{const t=Ud(),n=Ev(V$(lG(e))),i=I.useMemo(()=>cG(n),[n]);return I.useMemo(()=>W$(t,i),[t,i])},Et=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},Ql=()=>()=>{},G$=I.createContext({threads:Et({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Et({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Et({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Et({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Et({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Et({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Et({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Et({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Et({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:Ql,on:e=>{const{scope:t}=ss(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Ud=()=>I.useContext(G$),qi=e=>{const t=Ud(),n=Ev(rG(e));return I.useMemo(()=>W$(t,n),[t,n])},fG=e=>dG(e);function Re(e){return e?fG(e):Ud()}const pG=(e,t)=>e===Ql?t:t===Ql?e:(...n)=>{const i=e(...n),r=t(...n);return()=>{i(),r()}},W$=(e,t)=>{const n=t.subscribe;return{...e,...t,subscribe:pG(e.subscribe,n??Ql)}},oi=({api:e,children:t,devToolsVisible:n=!0})=>(I.useEffect(()=>{if(!(!n||!e.subscribe))return vi.register(e)},[e,n]),g.jsx(G$.Provider,{value:e,children:t}));class M_{#e;constructor(t){this.#e=t}get threads(){return this.#e.threads().getState()}get tools(){return this.#e.tools().getState()}get threadListItem(){return this.#e.threadListItem().getState()}get thread(){return this.#e.thread().getState()}get composer(){return this.#e.composer().getState()}get message(){return this.#e.message().getState()}get part(){return this.#e.part().getState()}get attachment(){return this.#e.attachment().getState()}}const te=e=>{const t=Re(),n=I.useMemo(()=>new M_(t),[t]),i=I.useSyncExternalStore(t.subscribe,()=>e(n),()=>e(n));if(I.useDebugValue(i),i instanceof M_)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return i},Ff=(e,t)=>{const n=Re(),i=I.useRef(t);I.useEffect(()=>{i.current=t});const{scope:r,event:o}=ss(e);I.useEffect(()=>n.on({scope:r,event:o},s=>i.current(s)),[n,r,o])};function hG(e,t){function n(i){const r=I.useContext(e);if(!i?.optional&&!r)throw new Error(`This component must be used within ${t}.`);return r}return n}function J$(e,t){function n(r){const o=e(r);return o?o[t]:null}function i(r){let o=!1,s;typeof r=="function"?s=r:r&&typeof r=="object"&&(o=!!r.optional,s=r.selector);const a=n({optional:o});return a?s?a(s):a():null}return{[t]:i,[`${t}Store`]:n}}const K$=I.createContext(null),mG=hG(K$,"ThreadPrimitive.Viewport"),{useThreadViewport:ca,useThreadViewportStore:Fd}=J$(mG,"useThreadViewport"),Y$=e=>{const t={role:"assistant",content:[]};for(const n of e)if(n.role==="tool"){const i=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===n.toolCallId);if(i!==-1){const r=t.content[i];if(n.toolName!==void 0&&r.toolName!==n.toolName)throw new Error(`Tool call name ${n.toolCallId} ${n.toolName} does not match existing tool call ${r.toolName}`);t.content[i]={...r,[Qt]:[...r[Qt]??[],n],result:n.result,artifact:n.artifact,isError:n.isError,messages:n.messages}}else throw new Error(`Tool call ${n.toolCallId} ${n.toolName} not found in assistant message`)}else{const i=n.role,r=(typeof n.content=="string"?[{type:"text",text:n.content}]:n.content).map(o=>({...o,[Qt]:[n]}));switch(i){case"system":case"user":return{...n,content:r};case"assistant":t.content.length===0&&(t.id=n.id,t.createdAt??=n.createdAt,t.status??=n.status,n.attachments&&(t.attachments=[...t.attachments??[],...n.attachments]),n.metadata&&(t.metadata??={},n.metadata.unstable_state&&(t.metadata.unstable_state=n.metadata.unstable_state),n.metadata.unstable_annotations&&(t.metadata.unstable_annotations=[...t.metadata.unstable_annotations??[],...n.metadata.unstable_annotations]),n.metadata.unstable_data&&(t.metadata.unstable_data=[...t.metadata.unstable_data??[],...n.metadata.unstable_data]),n.metadata.steps&&(t.metadata.steps=[...t.metadata.steps??[],...n.metadata.steps]),n.metadata.custom&&(t.metadata.custom={...t.metadata.custom??{},...n.metadata.custom}),n.metadata.submittedFeedback&&(t.metadata.submittedFeedback=n.metadata.submittedFeedback))),t.content.push(...r);break;default:{const o=i;throw new Error(`Unknown message role: ${o}`)}}}return t},X$=(e,t)=>{const n=[];let i=!1,r=!1,o=[],s=[];const a=()=>{s.length&&n.push({inputs:o,outputs:s}),o=[],s=[],i=!1,r=!1};for(const l of e)for(const u of l.outputs)(r&&u.role!=="tool"||!i||u.role==="user"||u.role==="system")&&a(),i=u.role==="assistant"||u.role==="tool",o.at(-1)!==l.input&&o.push(l.input),s.push(u),u.role==="assistant"&&(u.convertConfig?.joinStrategy==="none"||t==="none")&&(r=!0);return a(),n},gG=(e,t,n,i)=>{const r=[];for(const s of e){const a=t(s,i),l=Array.isArray(a)?a:[a],u={input:s,outputs:l};r.push(u)}const o=X$(r);return o.map((s,a)=>{const l=a===o.length-1,u=Y$(s.outputs),c=typeof u.content=="object"&&u.content.some(m=>m.type==="tool-call"&&m.result===void 0),d=typeof u.content=="object"&&u.content.some(m=>m.type==="tool-call"&&m.result===void 0),f=hu(l,n,c,d,l?i.error:void 0),p=Vi(u,a.toString(),f);return p[Qt]=s.inputs,p})},vG=({callback:e,messages:t,isRunning:n,joinStrategy:i,metadata:r})=>{const o=I.useMemo(()=>({metadata:r??{},callback:e,callbackCache:new WeakMap,chunkCache:new WeakMap,converterCache:new ph}),[e,r]);return I.useMemo(()=>{const s=[];for(const u of t){let c=o.callbackCache.get(u);if(!c){const d=o.callback(u,o.metadata),f=Array.isArray(d)?d:[d];c={input:u,outputs:f},o.callbackCache.set(u,c)}s.push(c)}const a=X$(s,i).map(u=>{const c=u.outputs[0];if(!c)return u;const d=o.chunkCache.get(c);return d&&j_(d.outputs,u.outputs)?d:(o.chunkCache.set(c,u),u)}),l=o.converterCache.convertMessages(a,(u,c,d)=>{const f=d===a.length-1,p=Y$(c.outputs),m=typeof p.content=="object"&&p.content.some(w=>w.type==="tool-call"&&w.result===void 0),h=typeof p.content=="object"&&p.content.some(w=>w.type==="tool-call"&&w.result===void 0),v=hu(f,n,m,h,f?o.metadata.error:void 0);if(u&&(u.role!=="assistant"||!y$(u.status)||u.status===v)){const w=Ti(u);if(j_(w,c.inputs))return u}const y=Vi(p,d.toString(),v);return y[Qt]=c.inputs,y});return l[Qt]=t,l},[o,t,n,i])},j_=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Zi=e=>{const[,t]=rr(e.getState);return Lt(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},yG=Qe(({runtime:e})=>{const t=Zi(e),n=Tv();return Lt(()=>{const i=[],r=["switched-to","switched-away"];for(const o of r){const s=e.unstable_on(o,()=>{n.emit(`thread-list-item.${o}`,{threadId:e.getState().id})});i.push(s)}return()=>{for(const o of i)o()}},[e,n]),Fn({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),da=e=>{const t=Oe(()=>Object.fromEntries(e),[e]),n=z$(t,o=>o,[]),i=Oe(()=>Object.keys(n),[n]);return{state:Oe(()=>{const o=new Array(i.length);for(let s=0;s<i.length;s++)o[s]=n[i[s]].state;return o},[i,n]),api:o=>{const s="index"in o?n[i[o.index]]?.api:n[o.key]?.api;if(!s)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(o)}`);return s}}},Q$=Qe(({runtime:e})=>{const t=Zi(e);return Fn({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),bG=Qe(({runtime:e,index:t})=>{const n=Oe(()=>e.getAttachmentByIndex(t),[e,t]);return sr(Q$({runtime:n}))}),eO=Qe(({threadIdRef:e,messageIdRef:t,runtime:n})=>{const i=Zi(n),r=Tv();Lt(()=>{const a=[],l=["send","attachment-add"];for(const u of l){const c=n.unstable_on(u,()=>{r.emit(`composer.${u}`,{threadId:e.current,...t&&{messageId:t.current}})});a.push(c)}return()=>{for(const u of a)u()}},[n,r,e,t]);const o=da(i.attachments.map((a,l)=>[a.id,bG({runtime:n,index:l})])),s=Oe(()=>({text:i.text,role:i.role,attachments:o.state,runConfig:i.runConfig,isEditing:i.isEditing,canCancel:i.canCancel,attachmentAccept:i.attachmentAccept,isEmpty:i.isEmpty,type:i.type??"thread"}),[i,o.state]);return Fn({getState:()=>s,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:n.beginEdit??(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:a=>"id"in a?o.api({key:a.id}):o.api(a),__internal_getRuntime:()=>n})}),_G=Qe(({runtime:e})=>{const t=Zi(e);return Fn({getState:()=>t,addToolResult:i=>e.addToolResult(i),resumeToolCall:i=>e.resumeToolCall(i),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),wG=Qe(({runtime:e,index:t})=>{const n=Oe(()=>e.getAttachmentByIndex(t),[e,t]);return sr(Q$({runtime:n}))}),xG=Qe(({runtime:e,index:t})=>{const n=Oe(()=>e.getMessagePartByIndex(t),[e,t]);return sr(_G({runtime:n}))}),SG=Qe(({runtime:e,threadIdRef:t})=>{const n=Zi(e),[i,r]=rr(!1),[o,s]=rr(!1),a=Oe(()=>({get current(){return e.getState().id}}),[e]),l=sr(eO({runtime:e.composer,threadIdRef:t,messageIdRef:a})),u=da(n.content.map((f,p)=>["toolCallId"in f&&f.toolCallId!=null?`toolCallId-${f.toolCallId}`:`index-${p}`,xG({runtime:e,index:p})])),c=da(n.attachments?.map((f,p)=>[f.id,wG({runtime:e,index:p})])??[]),d=Oe(()=>({...n,parts:u.state,composer:l.state,isCopied:i,isHovering:o}),[n,u.state,l.state,i,o]);return Fn({getState:()=>d,composer:l.api,reload:f=>e.reload(f),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:f=>e.submitFeedback(f),switchToBranch:f=>e.switchToBranch(f),getCopyText:()=>e.unstable_getCopyText(),part:f=>"index"in f?u.api({index:f.index}):u.api({key:`toolCallId-${f.toolCallId}`}),attachment:f=>"id"in f?c.api({key:f.id}):c.api(f),setIsCopied:r,setIsHovering:s,__internal_getRuntime:()=>e},{key:n.id})}),EG=Qe(({runtime:e,id:t,threadIdRef:n})=>{const i=Oe(()=>e.getMessageById(t),[e,t]);return sr(SG({runtime:i,threadIdRef:n}))}),IG=Qe(({runtime:e})=>{const t=Zi(e),n=Tv();Lt(()=>{const a=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const c=e.unstable_on(u,()=>{const d=e.getState()?.threadId||"unknown";n.emit(`thread.${u}`,{threadId:d})});a.push(c)}return()=>{for(const u of a)u()}},[e]);const i=Oe(()=>({get current(){return e.getState().threadId}}),[e]),r=sr(eO({runtime:e.composer,threadIdRef:i})),o=da(t.messages.map(a=>[a.id,EG({runtime:e,id:a.id,threadIdRef:i})])),s=Oe(()=>({isEmpty:o.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:r.state,messages:o.state}),[t,o,r.state]);return Fn({getState:()=>s,composer:r.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:async()=>{throw new Error("startVoice is not supported in this runtime")},stopVoice:async()=>{throw new Error("stopVoice is not supported in this runtime")},message:a=>"id"in a?o.api({key:a.id}):o.api(a),__internal_getRuntime:()=>e})}),TG=Qe(({runtime:e,id:t})=>{const n=Oe(()=>e.getItemById(t),[e,t]);return sr(yG({runtime:n}))}),kG=Qe(({runtime:e,__internal_assistantRuntime:t})=>{const n=Zi(e),i=sr(IG({runtime:e.main})),r=da(Object.keys(n.threadItems).map(s=>[s,TG({runtime:e,id:s})])),o=Oe(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThread??null,isLoading:n.isLoading,threadIds:n.threads,archivedThreadIds:n.archivedThreads,threadItems:r.state,main:i.state}),[n,r.state,i.state]);return Fn({getState:()=>o,thread:()=>i.api,item:s=>{if(s==="main")return r.api({key:o.mainThreadId});if("id"in s)return r.api({key:s.id});const{index:a,archived:l=!1}=s,u=l?o.archivedThreadIds[a]:o.threadIds[a];return r.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),CG=Qe(e=>{const t=Z$();return Lt(()=>e.registerModelContextProvider(t),[e,t]),sr(kG({runtime:e.threads,__internal_assistantRuntime:e}))}),Bf=e=>{const t=new Map,n=()=>{let i=0;for(const r of t.values())i+=r;e(i)};return{register:()=>{const i=Symbol();return t.set(i,0),{setHeight:r=>{t.get(i)!==r&&(t.set(i,r),n())},unregister:()=>{t.delete(i),n()}}}}},AG=(e={})=>{const t=new Set,n=Bf(s=>{o.setState({height:{...o.getState().height,viewport:s}})}),i=Bf(s=>{o.setState({height:{...o.getState().height,inset:s}})}),r=Bf(s=>{o.setState({height:{...o.getState().height,userMessage:s}})}),o=ko.create(()=>({isAtBottom:!0,scrollToBottom:({behavior:s="auto"}={})=>{for(const a of t)a({behavior:s})},onScrollToBottom:s=>(t.add(s),()=>{t.delete(s)}),turnAnchor:e.turnAnchor??"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:i.register,registerUserMessageHeight:r.register}));return o},fa=e=>e,RG=e=>{const t=Fd({optional:!0}),[n]=I.useState(()=>AG(e));return I.useEffect(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),I.useEffect(()=>{if(t)return n.subscribe(i=>{t.getState().isAtBottom!==i.isAtBottom&&fa(t).setState({isAtBottom:i.isAtBottom})})},[n,t]),I.useEffect(()=>{const i={turnAnchor:e.turnAnchor??"bottom"};n.getState().turnAnchor!==i.turnAnchor&&fa(n).setState(i)},[n,e.turnAnchor]),n},tO=({children:e,options:t={}})=>{const n=RG(t),[i]=I.useState(()=>({useThreadViewport:n}));return g.jsx(K$.Provider,{value:i,children:e})},$G=e=>e._core?.RenderComponent,OG=({children:e,runtime:t})=>{const n=Re({threads:CG(t)}),i=$G(t);return g.jsxs(oi,{api:n,children:[i&&g.jsx(i,{}),g.jsx(tO,{children:e})]})},nO=I.memo(OG),NG=({index:e,archived:t,children:n})=>{const i=Re(),r=qi({threadListItem:Yr({source:"threads",query:{type:"index",index:e,archived:t},get:()=>i.threads().item({index:e,archived:t})}),on(o,s){const a=()=>i.threads().item({index:e,archived:t}),{event:l,scope:u}=ss(o);return ki("thread-list-item",u)?i.on({scope:"*",event:l},c=>{c.threadId===a().getState().id&&s(c)}):i.on(o,s)}});return g.jsx(oi,{api:r,children:n})},PG=({id:e,children:t})=>{const n=Re(),i=qi({threadListItem:Yr({source:"threads",query:{type:"id",id:e},get:()=>n.threads().item({id:e})}),on(r,o){const s=()=>n.threads().item({id:e}),{event:a,scope:l}=ss(r);return ki("thread-list-item",l)?n.on({scope:"*",event:a},u=>{u.threadId===s().getState().id&&o(u)}):n.on(r,o)}});return g.jsx(oi,{api:i,children:t})},MG=({index:e,children:t})=>{const n=Re(),i=qi({message:Yr({source:"thread",query:{type:"index",index:e},get:()=>n.thread().message({index:e})}),composer:Yr({source:"message",query:{},get:()=>n.thread().message({index:e}).composer}),on(r,o){const s=()=>n.thread().message({index:e}),{event:a,scope:l}=ss(r);return!ki("composer",l)&&!ki("message",l)?n.on(r,o):n.on({scope:"thread",event:a},u=>{u.messageId===s().getState().id&&o(u)})}});return g.jsx(oi,{api:i,children:t})},jG=({index:e,children:t})=>{const n=Re(),i=qi({part:Yr({source:"message",query:{type:"index",index:e},get:()=>n.message().part({index:e})})});return g.jsx(oi,{api:i,children:t})},DG=({index:e,children:t})=>{const n=Re(),i=qi({attachment:Yr({source:"message",query:{type:"index",index:e},get:()=>n.message().attachment({index:e})})});return g.jsx(oi,{api:i,children:t})},zG=({index:e,children:t})=>{const n=Re(),i=qi({attachment:Yr({source:"composer",query:{type:"index",index:e},get:()=>n.composer().attachment({index:e})})});return g.jsx(oi,{api:i,children:t})},LG=Qe(({text:e,isRunning:t})=>{const n=Oe(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return Fn({getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),UG=({text:e,isRunning:t=!1,children:n})=>{const i=Ev(V$(LG({text:e,isRunning:t}))),r=qi({part:Yr({source:"root",query:{},get:()=>i.getState().api}),subscribe:i.subscribe});return g.jsx(oi,{api:r,children:n})},FG=e=>{const t={useThreadMessages:({messages:n,isRunning:i,joinStrategy:r,metadata:o})=>vG({callback:e,messages:n,isRunning:i,joinStrategy:r,metadata:o}),toThreadMessages:(n,i=!1,r={})=>gG(n,e,i,r),toOriginalMessages:n=>{const i=Ti(n);if(i.length===0)throw new Error("No original messages found");return i},toOriginalMessage:n=>t.toOriginalMessages(n)[0],useOriginalMessage:()=>t.useOriginalMessages()[0],useOriginalMessages:()=>{const n=Re(),i=te(s=>{if(n.part.source)return Ti(s.part)}),r=te(({message:s})=>Ti(s)),o=i??r;if(o.length===0)throw new Error("No original messages found");return o}};return t},D_=e=>{try{const n=e.split(".")[1];if(!n)throw new Error("Invalid JWT format");let i=n.replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4!==0;)i+="=";const r=atob(i),s=JSON.parse(r).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}};class rO{strategy="jwt";cachedToken=null;tokenExpiry=null;#e;constructor(t){this.#e=t}async getAuthHeaders(){const t=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-t>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const n=await this.#e();return n?(this.cachedToken=n,this.tokenExpiry=D_(n),{Authorization:`Bearer ${n}`}):!1}readAuthHeaders(t){const n=t.get("Authorization");if(!n)return;const[i,r]=n.split(" ");if(i!=="Bearer"||!r)throw new Error("Invalid auth header received");this.cachedToken=r,this.tokenExpiry=D_(r)}}class BG{strategy="api-key";#e;#t;#n;constructor(t,n,i){this.#e=t,this.#t=n,this.#n=i}async getAuthHeaders(){return{Authorization:`Bearer ${this.#e}`,"Aui-User-Id":this.#t,"Aui-Workspace-Id":this.#n}}readAuthHeaders(){}}const Wu="aui:refresh_token";class VG{strategy="anon";baseUrl;jwtStrategy;constructor(t){this.baseUrl=t,this.jwtStrategy=new rO(async()=>{const n=Date.now(),i=localStorage.getItem(Wu),r=i?JSON.parse(i):void 0;if(r)if(new Date(r.expires_at).getTime()-n>30*1e3){const c=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:r.token})});if(c.ok){const d=await c.json(),{access_token:f,refresh_token:p}=d;return p&&localStorage.setItem(Wu,JSON.stringify(p)),f}}else localStorage.removeItem(Wu);const o=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!o.ok)return null;const s=await o.json(),{access_token:a,refresh_token:l}=s;return!a||!l?null:(localStorage.setItem(Wu,JSON.stringify(l)),a)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(t){this.jwtStrategy.readAuthHeaders(t)}}class qG extends Error{constructor(t){super(t),this.name="APIError"}}class ZG{_auth;_baseUrl;constructor(t){if("authToken"in t)this._baseUrl=t.baseUrl,this._auth=new rO(t.authToken);else if("apiKey"in t)this._baseUrl="https://backend.assistant-api.com",this._auth=new BG(t.apiKey,t.userId,t.workspaceId);else if("anonymous"in t)this._baseUrl=t.baseUrl,this._auth=new VG(t.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(t,n={}){const i=await this._auth.getAuthHeaders();if(!i)throw new Error("Authorization failed");const r={...i,...n.headers,"Content-Type":"application/json"},o=new URLSearchParams;if(n.query)for(const[l,u]of Object.entries(n.query))u!==!1&&(u===!0?o.set(l,"true"):o.set(l,u.toString()));const s=new URL(`${this._baseUrl}/v1${t}`);s.search=o.toString();const a=await fetch(s,{method:n.method??"GET",headers:r,body:n.body?JSON.stringify(n.body):null});if(this._auth.readAuthHeaders(a.headers),!a.ok){const l=await a.text();try{const u=JSON.parse(l);throw new qG(u.message)}catch{throw new Error(`Request failed with status ${a.status}, ${l}`)}}return a}async makeRequest(t,n={}){return(await this.makeRawRequest(t,n)).json()}}class HG{cloud;constructor(t){this.cloud=t}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}}class GG{cloud;constructor(t){this.cloud=t}__internal_getAssistantOptions(t){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:async()=>{const n=await this.cloud._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");return{...n,Accept:"text/plain"}},body:{assistant_id:t,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}async stream(t){const n=await this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:t});return dh.fromResponse(n,new s9)}}class WG{cloud;constructor(t){this.cloud=t}async list(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{query:n})}async create(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:n})}}class JG{cloud;messages;constructor(t){this.cloud=t,this.messages=new WG(t)}async list(t){return this.cloud.makeRequest("/threads",{query:t})}async get(t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`)}async create(t){return this.cloud.makeRequest("/threads",{method:"POST",body:t})}async update(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"PUT",body:n})}async delete(t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"DELETE"})}}class KG{cloud;constructor(t){this.cloud=t}async pdfToImages(t){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:t})}async generatePresignedUploadUrl(t){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:t})}}class YG{threads;auth;runs;files;constructor(t){const n=new ZG(t);this.threads=new JG(n),this.auth={tokens:new HG(n)},this.runs=new GG(n),this.files=new KG(n)}}function mh(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(n=>mh(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,i])=>typeof n=="string"&&mh(i,t+1)):!1}const XG=e=>({role:e.role,content:e.content.map(t=>{const n=t.type;switch(n){case"text":return{type:"text",text:t.text};case"reasoning":return{type:"reasoning",text:t.text};case"source":return{type:"source",sourceType:t.sourceType,id:t.id,url:t.url,...t.title?{title:t.title}:void 0};case"tool-call":return mh(t.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(t)}`),{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,...JSON.stringify(t.args)===t.argsText?{args:t.args}:{argsText:t.argsText},...t.result?{result:t.result}:{},...t.isError?{isError:!0}:{}};default:{const i=n;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata,...e.status?{status:e.status?.type==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0}),QG=e=>{const t=e.content,n=Vi({id:e.id,createdAt:e.created_at,...t},e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},Vf=new WeakMap;class eW{parent;formatAdapter;constructor(t,n){this.parent=t,this.formatAdapter=n}async append(t){const n=this.formatAdapter.encode(t),i=this.formatAdapter.getId(t.message);return this.parent._appendWithFormat(t.parentId,i,this.formatAdapter.format,n)}async load(){return this.parent._loadWithFormat(this.formatAdapter.format,t=>this.formatAdapter.decode(t))}}class tW{cloudRef;store;constructor(t,n){this.cloudRef=t,this.store=n}get _getIdForLocalId(){return Vf.has(this.store.threadListItem())||Vf.set(this.store.threadListItem(),{}),Vf.get(this.store.threadListItem())}withFormat(t){return new eW(this,t)}async append({parentId:t,message:n}){const{remoteId:i}=await this.store.threadListItem().initialize(),r=this.cloudRef.current.threads.messages.create(i,{parent_id:t?await this._getIdForLocalId[t]??t:null,format:"aui/v0",content:XG(n)}).then(({message_id:o})=>(this._getIdForLocalId[n.id]=o,o));return this._getIdForLocalId[n.id]=r,r.then(()=>{})}async load(){const t=this.store.threadListItem().getState().remoteId;if(!t)return{messages:[]};const{messages:n}=await this.cloudRef.current.threads.messages.list(t,{format:"aui/v0"});return{messages:n.filter(r=>r.format==="aui/v0").map(QG).reverse()}}async _appendWithFormat(t,n,i,r){const{remoteId:o}=await this.store.threadListItem().initialize(),s=this.cloudRef.current.threads.messages.create(o,{parent_id:t?await this._getIdForLocalId[t]??t:null,format:i,content:r}).then(({message_id:a})=>(this._getIdForLocalId[n]=a,a));return this._getIdForLocalId[n]=s,s.then(()=>{})}async _loadWithFormat(t,n){const i=this.store.threadListItem().getState().remoteId;if(!i)return{messages:[]};const{messages:r}=await this.cloudRef.current.threads.messages.list(i,{format:t});return{messages:r.filter(o=>o.format===t).map(o=>n({id:o.id,parent_id:o.parent_id,format:o.format,content:o.content})).reverse()}}}const nW=e=>{const t=Re(),[n]=I.useState(()=>new tW(e,t));return n},z_=typeof process<"u"&&process?.env?.NEXT_PUBLIC_ASSISTANT_BASE_URL,qf=z_?new YG({baseUrl:z_,anonymous:!0}):void 0,rW=e=>{const t=I.useRef(e);I.useEffect(()=>{t.current=e},[e]);const n=I.useCallback(function({children:o}){const s=nW({get current(){return t.current.cloud??qf}}),a=t.current.cloud??qf,l=I.useMemo(()=>new T9(a),[a]),u=I.useMemo(()=>({history:s,attachments:l}),[s,l]);return g.jsx(xv,{adapters:u,children:o})},[]),i=e.cloud??qf;return i?{list:async()=>{const{threads:r}=await i.threads.list();return{threads:r.map(o=>({status:o.is_archived?"archived":"regular",remoteId:o.id,title:o.title,externalId:o.external_id??void 0}))}},initialize:async()=>{const o=await(e.create?.()??Promise.resolve()),s=o?o.externalId:void 0,{thread_id:a}=await i.threads.create({last_message_at:new Date,external_id:s});return{externalId:s,remoteId:a}},rename:async(r,o)=>i.threads.update(r,{title:o}),archive:async r=>i.threads.update(r,{is_archived:!0}),unarchive:async r=>i.threads.update(r,{is_archived:!1}),delete:async r=>(await e.delete?.(r),i.threads.delete(r)),generateTitle:async(r,o)=>i.runs.stream({thread_id:r,assistant_id:"system/thread_title",messages:o}),fetch:async r=>{const o=await i.threads.get(r);return{status:o.is_archived?"archived":"regular",remoteId:o.id,title:o.title,externalId:o.external_id??void 0}},unstable_Provider:n}:new z9};class kv{_core;threads;get threadList(){return this.threads}_thread;constructor(t){this._core=t,this.threads=new E9(t.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(t){return this._core.threads.switchToThread(t)}registerModelContextProvider(t){return this._core.registerModelContextProvider(t)}registerModelConfigProvider(t){return this.registerModelContextProvider(t)}reset({initialMessages:t}={}){return this._core.threads.getMainThreadRuntimeCore().import(bv.fromArray(t??[]))}}const iW=e=>{const{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o,...s}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o},otherOptions:s}};function sn(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e}),x.useMemo(()=>(...n)=>t.current?.(...n),[])}const iO=I.createContext(null),oW=e=>({useSmoothStatus:ko.create(()=>e)}),sW=({children:e})=>{const t=oO({optional:!0}),n=Re(),[i]=I.useState(()=>oW(n.part().getState().status));return t?e:g.jsx(iO.Provider,{value:i,children:e})},aW=e=>{const t=I.forwardRef((n,i)=>g.jsx(sW,{children:g.jsx(e,{...n,ref:i})}));return t.displayName=e.displayName,t};function oO(e){const t=I.useContext(iO);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:uW,useSmoothStatusStore:lW}=J$(oO,"useSmoothStatus");class cW{currentText;setText;animationFrameId=null;lastUpdateTime=Date.now();targetText="";constructor(t,n){this.currentText=t,this.setText=n}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{const t=Date.now();let i=t-this.lastUpdateTime;const r=this.targetText.length-this.currentText.length,o=Math.min(5,250/r);let s=0;for(;i>=o&&s<r;)s++,i-=o;s!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=t-i,this.setText(this.currentText))}}const Zf=Object.freeze({type:"running"}),sO=(e,t=!1)=>{const{text:n}=e,i=te(({message:c})=>c.id),r=I.useRef(i),[o,s]=I.useState(n),a=lW({optional:!0}),l=sn(c=>{if(s(c),a){const d=o!==c||e.status.type==="running"?Zf:e.status;fa(a).setState(d,!0)}});I.useEffect(()=>{if(a){const c=t&&(o!==n||e.status.type==="running")?Zf:e.status;fa(a).setState(c,!0)}},[a,t,n,o,e.status]);const[u]=I.useState(new cW(n,l));return I.useEffect(()=>{if(!t){u.stop();return}if(r.current!==i||!n.startsWith(u.targetText)){r.current=i,l(n),u.currentText=n,u.targetText=n,u.stop();return}u.targetText=n,u.start()},[l,u,i,t,n]),I.useEffect(()=>()=>{u.stop()},[u]),I.useMemo(()=>t?{type:"text",text:o,status:n===o?e.status:Zf}:e,[t,o,e,n])},aO=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:kv,BaseAssistantRuntimeCore:gv,CompositeContextProvider:mv,DefaultThreadComposerRuntimeCore:g$,MessageRepository:_v,ThreadRuntimeImpl:O$,fromThreadMessageLike:Vi,generateId:pu,getAutoStatus:hu,splitLocalRuntimeOptions:iW,useSmooth:sO,useSmoothStatus:uW,useToolInvocations:M$,withSmoothContextProvider:aW},Symbol.toStringTag,{value:"Module"}));class dW extends jd{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=ko.create(()=>({}));constructor(t){super(),this.useRuntimeHook=ko.create(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((n,i)=>{const r=()=>{const s=this.instances.get(t);if(!s)o(),i(new Error("Thread was deleted before runtime was started"));else if(s.runtime)o(),n(s.runtime);else return},o=this.subscribe(r);r()})}getThreadRuntimeCore(t){const n=this.instances.get(t);if(n)return n.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}_InnerActiveThreadProvider=({threadId:t})=>{const{useRuntime:n}=this.useRuntimeHook(),i=n(),r=i.thread.__internal_threadBinding,o=I.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=r.getState(),this._notifySubscribers()},[t,r]),s=I.useRef(!1);s.current||o(),I.useEffect(()=>(s.current=!0,o(),r.outerSubscribe(o)),[r,o]);const a=Re();return I.useEffect(()=>i.threads.main.unstable_on("initialize",()=>{if(a.threadListItem().getState().status==="new"){a.threadListItem().initialize();const u=i.thread.unstable_on("run-end",()=>{u(),a.threadListItem().generateTitle()})}}),[i,a]),null};_OuterActiveThreadProvider=I.memo(({threadId:t,provider:n})=>g.jsx(PG,{id:t,children:g.jsx(n,{children:g.jsx(this._InnerActiveThreadProvider,{threadId:t})})}));__internal_RenderThreadRuntimes=({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(n=>g.jsx(this._OuterActiveThreadProvider,{threadId:n,provider:t},n)))}const ot=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),fW={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ot},append(){throw ot},startRun(){throw ot},resumeRun(){throw ot},cancelRun(){throw ot},addToolResult(){throw ot},resumeToolCall(){throw ot},speak(){throw ot},stopSpeaking(){throw ot},submitFeedback(){throw ot},getModelContext(){return{}},unstable_loadExternalState(){throw ot},composer:{attachments:[],attachmentAccept:"*",async addAttachment(){throw ot},async removeAttachment(){throw ot},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ot},role:"user",setRole(){throw ot},runConfig:{},setRunConfig(){throw ot},async reset(){},async clearAttachments(){},send(){throw ot},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ot},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw ot},export(){return{messages:[]}},reset(){throw ot},unstable_on(){return()=>{}}},L_=(e,t,n)=>n.reduce((i,r)=>r?.(i,t)??i,e);class pW extends jd{_pendingTransforms=[];_baseValue;_cachedValue;constructor(t){super(),this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,n)=>L_(t,n.task,[n.loading,n.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}async optimisticUpdate(t){const n=t.execute(),i={...t,task:n};try{this._pendingTransforms.push(i),this._updateState();const r=await n;return this._baseValue=L_(this._baseValue,r,[t.optimistic,t.then]),r}finally{const r=this._pendingTransforms.indexOf(i);r>-1&&this._pendingTransforms.splice(r,1),this._updateState()}}}const yl=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},Ju=(e,t,n)=>{const i=yl(e,t);if(!i)return e;const{id:r,remoteId:o,status:s}=i;if(s===n)return e;const a={...e};switch(s){case"new":a.newThreadId=void 0;break;case"regular":a.threadIds=a.threadIds.filter(l=>l!==r);break;case"archived":a.archivedThreadIds=a.archivedThreadIds.filter(l=>l!==r);break;default:{const l=s;throw new Error(`Unsupported state: ${l}`)}}switch(n){case"regular":a.threadIds=[r,...a.threadIds];break;case"archived":a.archivedThreadIds=[r,...a.archivedThreadIds];break;case"deleted":a.threadData=Object.fromEntries(Object.entries(a.threadData).filter(([l])=>l!==r)),a.threadIdMap=Object.fromEntries(Object.entries(a.threadIdMap).filter(([l])=>l!==r&&l!==o));break;default:{const l=n;throw new Error(`Unsupported state: ${l}`)}}return n!=="deleted"&&(a.threadData={...a.threadData,[r]:{...i,status:n}}),a};class hW extends jd{contextProvider;_options;_hookManager;_loadThreadsPromise;_mainThreadId;_state=new pW({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>({...t,isLoading:!0}),then:(t,n)=>{const i=[],r=[],o={},s={};for(const a of n.threads){switch(a.status){case"regular":i.push(a.remoteId);break;case"archived":r.push(a.remoteId);break;default:{const u=a.status;throw new Error(`Unsupported state: ${u}`)}}const l=a.remoteId;o[a.remoteId]=l,s[l]={id:a.remoteId,remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId})}}return{...t,threadIds:i,archivedThreadIds:r,threadIdMap:{...t.threadIdMap,...o},threadData:{...t.threadData,...s}}}}).then(()=>{})),this._loadThreadsPromise}constructor(t,n){super(),this.contextProvider=n,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new dW(t.runtimeHook),this.useProvider=ko.create(()=>({Provider:t.adapter.unstable_Provider??I.Fragment})),this.__internal_setOptions(t),this.switchToNewThread()}useProvider;__internal_setOptions(t){if(this._options===t)return;this._options=t;const n=t.adapter.unstable_Provider??I.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||fW}getThreadRuntimeCore(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");const i=this._hookManager.getThreadRuntimeCore(n.id);if(!i)throw new Error("Thread not found");return i}getItemById(t){return yl(this._state.value,t)}async switchToThread(t){let n=this.getItemById(t);if(!n){const r=await this._options.adapter.fetch(t),o=this._state.value,s=r.remoteId,a={...o.threadData,[s]:{id:s,initializeTask:Promise.resolve({remoteId:r.remoteId,externalId:r.externalId}),remoteId:r.remoteId,externalId:r.externalId,status:r.status,title:r.title}},l={...o.threadIdMap,[r.remoteId]:s},u=r.status==="regular"?[...o.threadIds,r.remoteId]:o.threadIds,c=r.status==="archived"?[...o.archivedThreadIds,r.remoteId]:o.archivedThreadIds;this._state.update({...o,threadIds:u,archivedThreadIds:c,threadIdMap:l,threadData:a}),n=this.getItemById(t)}if(!n)throw new Error("Thread not found");if(this._mainThreadId===n.id)return;const i=this._hookManager.startThreadRuntime(n.id);this.mainThreadId!==void 0?await i:i.then(()=>this._notifySubscribers()),n.status==="archived"&&await this.unarchive(n.id),this._mainThreadId=n.id,this._notifySubscribers()}async switchToNewThread(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)await this._state.waitForUpdate();const t=this._state.value;let n=this._state.value.newThreadId;if(n===void 0){do n=`__LOCALID_${pu()}`;while(t.threadIdMap[n]);const i=n;this._state.update({...t,newThreadId:n,threadIdMap:{...t.threadIdMap,[n]:i},threadData:{...t.threadData,[i]:{status:"new",id:n,remoteId:void 0,externalId:void 0,title:void 0}}})}return this.switchToThread(n)}initialize=async t=>{if(this._state.value.newThreadId!==t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Unexpected new state");return n.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:n=>Ju(n,t,"regular"),loading:(n,i)=>{const r=t;return{...n,threadData:{...n.threadData,[r]:{...n.threadData[r],initializeTask:i}}}},then:(n,{remoteId:i,externalId:r})=>{const o=yl(n,t);if(!o)return n;const s=t;return{...n,threadIdMap:{...n.threadIdMap,[i]:s},threadData:{...n.threadData,[s]:{...o,initializeTask:Promise.resolve({remoteId:i,externalId:r}),remoteId:i,externalId:r}}}}})};generateTitle=async t=>{const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:i}=await n.initializeTask,r=this._hookManager.getThreadRuntimeCore(n.id);if(!r)return;const o=r.messages,s=await this._options.adapter.generateTitle(i,o),a=zs.fromAssistantStream(s);for await(const l of a){const u=l.parts.filter(d=>d.type==="text")[0]?.text,c=this._state.baseValue;this._state.update({...c,threadData:{...c.threadData,[n.id]:{...n,title:u}}})}};rename(t,n){const i=this.getItemById(t);if(!i)throw new Error("Thread not found");if(i.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{const{remoteId:r}=await i.initializeTask;return this._options.adapter.rename(r,n)},optimistic:r=>{const o=yl(r,t);return o?{...r,threadData:{...r.threadData,[o.id]:{...o,title:n}}}:r}})}async _ensureThreadIsNotMain(t){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&await this.switchToNewThread()}async archive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:async()=>{await this._ensureThreadIsNotMain(n.id);const{remoteId:i}=await n.initializeTask;return this._options.adapter.archive(i)},optimistic:i=>Ju(i,n.id,"archived")})}unarchive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:async()=>{try{const{remoteId:i}=await n.initializeTask;return await this._options.adapter.unarchive(i)}catch(i){throw await this._ensureThreadIsNotMain(n.id),i}},optimistic:i=>Ju(i,n.id,"regular")})}async delete(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{await this._ensureThreadIsNotMain(n.id);const{remoteId:i}=await n.initializeTask;return await this._options.adapter.delete(i)},optimistic:i=>Ju(i,n.id,"deleted")})}async detach(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");await this._ensureThreadIsNotMain(n.id),this._hookManager.stopThreadRuntime(n.id)}useBoundIds=ko.create(()=>[]);__internal_RenderComponent=()=>{const t=I.useId();I.useEffect(()=>(this.useBoundIds.setState(o=>[...o,t],!0),()=>{this.useBoundIds.setState(o=>o.filter(s=>s!==t),!0)}),[t]);const n=this.useBoundIds(),{Provider:i}=this.useProvider(),r={modelContext:this.contextProvider};return(n.length===0||n[0]===t)&&g.jsx(xv,{adapters:r,children:g.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:i})})}}class mW extends gv{threads;constructor(t){super(),this.threads=new hW(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}}const gW=e=>{const[t]=I.useState(()=>new mW(e));return I.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),I.useMemo(()=>new kv(t),[t])},uO=e=>{if(Ud().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return gW(e)};var vW=Symbol.for("react.lazy"),ec=x[" use ".trim().toString()];function yW(e){return typeof e=="object"&&e!==null&&"then"in e}function lO(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===vW&&"_payload"in e&&yW(e._payload)}function cO(e){const t=bW(e),n=x.forwardRef((i,r)=>{let{children:o,...s}=i;lO(o)&&typeof ec=="function"&&(o=ec(o._payload));const a=x.Children.toArray(o),l=a.find(xW);if(l){const u=l.props.children,c=a.map(d=>d===l?x.Children.count(u)>1?x.Children.only(null):x.isValidElement(u)?u.props.children:null:d);return g.jsx(t,{...s,ref:r,children:x.isValidElement(u)?x.cloneElement(u,void 0,c):null})}return g.jsx(t,{...s,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}var Cv=cO("Slot");function bW(e){const t=x.forwardRef((n,i)=>{let{children:r,...o}=n;if(lO(r)&&typeof ec=="function"&&(r=ec(r._payload)),x.isValidElement(r)){const s=EW(r),a=SW(o,r.props);return r.type!==x.Fragment&&(a.ref=i?Iv(i,s):s),x.cloneElement(r,a)}return x.Children.count(r)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var dO=Symbol("radix.slottable");function _W(e){const t=({children:n})=>g.jsx(g.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=dO,t}var wW=_W("Slottable");function xW(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dO}function SW(e,t){const n={...t};for(const i in t){const r=e[i],o=t[i];/^on[A-Z]/.test(i)?r&&o?n[i]=(...a)=>{const l=o(...a);return r(...a),l}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function EW(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var IW=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gt=IW.reduce((e,t)=>{const n=cO(`Primitive.${t}`),i=x.forwardRef((r,o)=>{const{asChild:s,...a}=r,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),g.jsx(l,{...a,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{}),gr;(function(e){e.Hidden="hidden",e.Floating="floating",e.Normal="normal"})(gr||(gr={}));const TW=({hideWhenRunning:e,autohide:t,autohideFloat:n})=>te(({thread:i,message:r})=>e&&i.isRunning?gr.Hidden:t==="always"||t==="not-last"&&!r.isLast?r.isHovering?n==="always"||n==="single-branch"&&r.branchCount<=1?gr.Floating:gr.Normal:gr.Hidden:gr.Normal),Av=I.forwardRef(({hideWhenRunning:e,autohide:t,autohideFloat:n,...i},r)=>{const o=TW({hideWhenRunning:e,autohide:t,autohideFloat:n});return o===gr.Hidden?null:g.jsx(gt.div,{...o===gr.Floating?{"data-floating":"true"}:null,...i,ref:r})});Av.displayName="ActionBarPrimitive.Root";function Le(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}const kW=({copiedDuration:e=3e3}={})=>{const t=Re(),n=te(({message:s})=>(s.role!=="assistant"||s.status?.type!=="running")&&s.parts.some(a=>a.type==="text"&&a.text.length>0)),i=te(({composer:s})=>s.isEditing),r=te(({composer:s})=>s.text),o=I.useCallback(()=>{const s=i?r:t.message().getCopyText();s&&navigator.clipboard.writeText(s).then(()=>{t.message().setIsCopied(!0),setTimeout(()=>t.message().setIsCopied(!1),e)})},[t,i,r,e]);return n?o:null},fO=I.forwardRef(({copiedDuration:e,onClick:t,disabled:n,...i},r)=>{const o=te(({message:a})=>a.isCopied),s=kW({copiedDuration:e});return g.jsx(gt.button,{type:"button",...o?{"data-copied":"true"}:{},...i,ref:r,disabled:n||!s,onClick:Le(t,()=>{s?.()})})});fO.displayName="ActionBarPrimitive.Copy";const ar=(e,t,n=[])=>{const i=I.forwardRef((r,o)=>{const s={},a={};Object.keys(r).forEach(u=>{n.includes(u)?s[u]=r[u]:a[u]=r[u]});const l=t(s)??void 0;return g.jsx(gt.button,{type:"button",...a,ref:o,disabled:a.disabled||!l,onClick:Le(a.onClick,l)})});return i.displayName=e,i},CW=()=>{const e=Re(),t=te(({composer:i})=>i.isEditing),n=I.useCallback(()=>{e.composer().beginEdit()},[e]);return t?null:n},AW=ar("ActionBarPrimitive.Edit",CW);function pO(e,t=globalThis?.document){const n=sn(e);x.useEffect(()=>{const i=r=>{r.key==="Escape"&&n(r)};return t.addEventListener("keydown",i,{capture:!0}),()=>t.removeEventListener("keydown",i,{capture:!0})},[n,t])}function RW(e,t){const n=x.createContext(t),i=o=>{const{children:s,...a}=o,l=x.useMemo(()=>a,Object.values(a));return g.jsx(n.Provider,{value:l,children:s})};i.displayName=e+"Provider";function r(o){const s=x.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[i,r]}function vu(e,t=[]){let n=[];function i(o,s){const a=x.createContext(s),l=n.length;n=[...n,s];const u=d=>{const{scope:f,children:p,...m}=d,h=f?.[e]?.[l]||a,v=x.useMemo(()=>m,Object.values(m));return g.jsx(h.Provider,{value:v,children:p})};u.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[l]||a,m=x.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[u,c]}const r=()=>{const o=n.map(s=>x.createContext(s));return function(a){const l=a?.[e]||o;return x.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return r.scopeName=e,[i,$W(r,...t)]}function $W(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const i=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(o){const s=i.reduce((a,{useScope:l,scopeName:u})=>{const d=l(o)[`__scope${u}`];return{...a,...d}},{});return x.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}function Rv(e){const t=OW(e),n=x.forwardRef((i,r)=>{const{children:o,...s}=i,a=x.Children.toArray(o),l=a.find(PW);if(l){const u=l.props.children,c=a.map(d=>d===l?x.Children.count(u)>1?x.Children.only(null):x.isValidElement(u)?u.props.children:null:d);return g.jsx(t,{...s,ref:r,children:x.isValidElement(u)?x.cloneElement(u,void 0,c):null})}return g.jsx(t,{...s,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}function OW(e){const t=x.forwardRef((n,i)=>{const{children:r,...o}=n;if(x.isValidElement(r)){const s=jW(r),a=MW(o,r.props);return r.type!==x.Fragment&&(a.ref=i?Iv(i,s):s),x.cloneElement(r,a)}return x.Children.count(r)>1?x.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var hO=Symbol("radix.slottable");function NW(e){const t=({children:n})=>g.jsx(g.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=hO,t}function PW(e){return x.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===hO}function MW(e,t){const n={...t};for(const i in t){const r=e[i],o=t[i];/^on[A-Z]/.test(i)?r&&o?n[i]=(...a)=>{const l=o(...a);return r(...a),l}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function jW(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var DW=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],dt=DW.reduce((e,t)=>{const n=Rv(`Primitive.${t}`),i=x.forwardRef((r,o)=>{const{asChild:s,...a}=r,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),g.jsx(l,{...a,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{});function zW(e,t){e&&SS.flushSync(()=>e.dispatchEvent(t))}var LW="DismissableLayer",gh="dismissableLayer.update",UW="dismissableLayer.pointerDownOutside",FW="dismissableLayer.focusOutside",U_,mO=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Bd=x.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:o,onInteractOutside:s,onDismiss:a,...l}=e,u=x.useContext(mO),[c,d]=x.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=x.useState({}),m=mt(t,k=>d(k)),h=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=h.indexOf(v),w=c?h.indexOf(c):-1,S=u.layersWithOutsidePointerEventsDisabled.size>0,b=w>=y,C=qW(k=>{const R=k.target,M=[...u.branches].some(U=>U.contains(R));!b||M||(r?.(k),s?.(k),k.defaultPrevented||a?.())},f),_=ZW(k=>{const R=k.target;[...u.branches].some(U=>U.contains(R))||(o?.(k),s?.(k),k.defaultPrevented||a?.())},f);return pO(k=>{w===u.layers.size-1&&(i?.(k),!k.defaultPrevented&&a&&(k.preventDefault(),a()))},f),x.useEffect(()=>{if(c)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(U_=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),F_(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=U_)}},[c,f,n,u]),x.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),F_())},[c,u]),x.useEffect(()=>{const k=()=>p({});return document.addEventListener(gh,k),()=>document.removeEventListener(gh,k)},[]),g.jsx(dt.div,{...l,ref:m,style:{pointerEvents:S?b?"auto":"none":void 0,...e.style},onFocusCapture:Le(e.onFocusCapture,_.onFocusCapture),onBlurCapture:Le(e.onBlurCapture,_.onBlurCapture),onPointerDownCapture:Le(e.onPointerDownCapture,C.onPointerDownCapture)})});Bd.displayName=LW;var BW="DismissableLayerBranch",VW=x.forwardRef((e,t)=>{const n=x.useContext(mO),i=x.useRef(null),r=mt(t,i);return x.useEffect(()=>{const o=i.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),g.jsx(dt.div,{...e,ref:r})});VW.displayName=BW;function qW(e,t=globalThis?.document){const n=sn(e),i=x.useRef(!1),r=x.useRef(()=>{});return x.useEffect(()=>{const o=a=>{if(a.target&&!i.current){let l=function(){gO(UW,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=l,t.addEventListener("click",r.current,{once:!0})):l()}else t.removeEventListener("click",r.current);i.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",o),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>i.current=!0}}function ZW(e,t=globalThis?.document){const n=sn(e),i=x.useRef(!1);return x.useEffect(()=>{const r=o=>{o.target&&!i.current&&gO(FW,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",r),()=>t.removeEventListener("focusin",r)},[t,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function F_(){const e=new CustomEvent(gh);document.dispatchEvent(e)}function gO(e,t,n,{discrete:i}){const r=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),i?zW(r,o):r.dispatchEvent(o)}var Hf=0;function vO(){x.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??B_()),document.body.insertAdjacentElement("beforeend",e[1]??B_()),Hf++,()=>{Hf===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Hf--}},[])}function B_(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Gf="focusScope.autoFocusOnMount",Wf="focusScope.autoFocusOnUnmount",V_={bubbles:!1,cancelable:!0},HW="FocusScope",$v=x.forwardRef((e,t)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:o,...s}=e,[a,l]=x.useState(null),u=sn(r),c=sn(o),d=x.useRef(null),f=mt(t,h=>l(h)),p=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(i){let h=function(S){if(p.paused||!a)return;const b=S.target;a.contains(b)?d.current=b:Mr(d.current,{select:!0})},v=function(S){if(p.paused||!a)return;const b=S.relatedTarget;b!==null&&(a.contains(b)||Mr(d.current,{select:!0}))},y=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Mr(a)};document.addEventListener("focusin",h),document.addEventListener("focusout",v);const w=new MutationObserver(y);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",v),w.disconnect()}}},[i,a,p.paused]),x.useEffect(()=>{if(a){Z_.add(p);const h=document.activeElement;if(!a.contains(h)){const y=new CustomEvent(Gf,V_);a.addEventListener(Gf,u),a.dispatchEvent(y),y.defaultPrevented||(GW(XW(yO(a)),{select:!0}),document.activeElement===h&&Mr(a))}return()=>{a.removeEventListener(Gf,u),setTimeout(()=>{const y=new CustomEvent(Wf,V_);a.addEventListener(Wf,c),a.dispatchEvent(y),y.defaultPrevented||Mr(h??document.body,{select:!0}),a.removeEventListener(Wf,c),Z_.remove(p)},0)}}},[a,u,c,p]);const m=x.useCallback(h=>{if(!n&&!i||p.paused)return;const v=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,y=document.activeElement;if(v&&y){const w=h.currentTarget,[S,b]=WW(w);S&&b?!h.shiftKey&&y===b?(h.preventDefault(),n&&Mr(S,{select:!0})):h.shiftKey&&y===S&&(h.preventDefault(),n&&Mr(b,{select:!0})):y===w&&h.preventDefault()}},[n,i,p.paused]);return g.jsx(dt.div,{tabIndex:-1,...s,ref:f,onKeyDown:m})});$v.displayName=HW;function GW(e,{select:t=!1}={}){const n=document.activeElement;for(const i of e)if(Mr(i,{select:t}),document.activeElement!==n)return}function WW(e){const t=yO(e),n=q_(t,e),i=q_(t.reverse(),e);return[n,i]}function yO(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function q_(e,t){for(const n of e)if(!JW(n,{upTo:t}))return n}function JW(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function KW(e){return e instanceof HTMLInputElement&&"select"in e}function Mr(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&KW(e)&&t&&e.select()}}var Z_=YW();function YW(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=H_(e,t),e.unshift(t)},remove(t){e=H_(e,t),e[0]?.resume()}}}function H_(e,t){const n=[...e],i=n.indexOf(t);return i!==-1&&n.splice(i,1),n}function XW(e){return e.filter(t=>t.tagName!=="A")}var xn=globalThis?.document?x.useLayoutEffect:()=>{},QW=x[" useId ".trim().toString()]||(()=>{}),eJ=0;function _o(e){const[t,n]=x.useState(QW());return xn(()=>{n(i=>i??String(eJ++))},[e]),t?`radix-${t}`:""}const tJ=["top","right","bottom","left"],Xr=Math.min,Kt=Math.max,tc=Math.round,Ku=Math.floor,Qn=e=>({x:e,y:e}),nJ={left:"right",right:"left",bottom:"top",top:"bottom"},rJ={start:"end",end:"start"};function vh(e,t,n){return Kt(e,Xr(t,n))}function Tr(e,t){return typeof e=="function"?e(t):e}function kr(e){return e.split("-")[0]}function as(e){return e.split("-")[1]}function Ov(e){return e==="x"?"y":"x"}function Nv(e){return e==="y"?"height":"width"}const iJ=new Set(["top","bottom"]);function Xn(e){return iJ.has(kr(e))?"y":"x"}function Pv(e){return Ov(Xn(e))}function oJ(e,t,n){n===void 0&&(n=!1);const i=as(e),r=Pv(e),o=Nv(r);let s=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=nc(s)),[s,nc(s)]}function sJ(e){const t=nc(e);return[yh(e),t,yh(t)]}function yh(e){return e.replace(/start|end/g,t=>rJ[t])}const G_=["left","right"],W_=["right","left"],aJ=["top","bottom"],uJ=["bottom","top"];function lJ(e,t,n){switch(e){case"top":case"bottom":return n?t?W_:G_:t?G_:W_;case"left":case"right":return t?aJ:uJ;default:return[]}}function cJ(e,t,n,i){const r=as(e);let o=lJ(kr(e),n==="start",i);return r&&(o=o.map(s=>s+"-"+r),t&&(o=o.concat(o.map(yh)))),o}function nc(e){return e.replace(/left|right|bottom|top/g,t=>nJ[t])}function dJ(e){return{top:0,right:0,bottom:0,left:0,...e}}function bO(e){return typeof e!="number"?dJ(e):{top:e,right:e,bottom:e,left:e}}function rc(e){const{x:t,y:n,width:i,height:r}=e;return{width:i,height:r,top:n,left:t,right:t+i,bottom:n+r,x:t,y:n}}function J_(e,t,n){let{reference:i,floating:r}=e;const o=Xn(t),s=Pv(t),a=Nv(s),l=kr(t),u=o==="y",c=i.x+i.width/2-r.width/2,d=i.y+i.height/2-r.height/2,f=i[a]/2-r[a]/2;let p;switch(l){case"top":p={x:c,y:i.y-r.height};break;case"bottom":p={x:c,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:d};break;case"left":p={x:i.x-r.width,y:d};break;default:p={x:i.x,y:i.y}}switch(as(t)){case"start":p[s]-=f*(n&&u?-1:1);break;case"end":p[s]+=f*(n&&u?-1:1);break}return p}const fJ=async(e,t,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:o=[],platform:s}=n,a=o.filter(Boolean),l=await(s.isRTL==null?void 0:s.isRTL(t));let u=await s.getElementRects({reference:e,floating:t,strategy:r}),{x:c,y:d}=J_(u,i,l),f=i,p={},m=0;for(let h=0;h<a.length;h++){const{name:v,fn:y}=a[h],{x:w,y:S,data:b,reset:C}=await y({x:c,y:d,initialPlacement:i,placement:f,strategy:r,middlewareData:p,rects:u,platform:s,elements:{reference:e,floating:t}});c=w??c,d=S??d,p={...p,[v]:{...p[v],...b}},C&&m<=50&&(m++,typeof C=="object"&&(C.placement&&(f=C.placement),C.rects&&(u=C.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:r}):C.rects),{x:c,y:d}=J_(u,f,l)),h=-1)}return{x:c,y:d,placement:f,strategy:r,middlewareData:p}};async function pa(e,t){var n;t===void 0&&(t={});const{x:i,y:r,platform:o,rects:s,elements:a,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Tr(t,e),m=bO(p),v=a[f?d==="floating"?"reference":"floating":d],y=rc(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(v)))==null||n?v:v.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:u,rootBoundary:c,strategy:l})),w=d==="floating"?{x:i,y:r,width:s.floating.width,height:s.floating.height}:s.reference,S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),b=await(o.isElement==null?void 0:o.isElement(S))?await(o.getScale==null?void 0:o.getScale(S))||{x:1,y:1}:{x:1,y:1},C=rc(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(y.top-C.top+m.top)/b.y,bottom:(C.bottom-y.bottom+m.bottom)/b.y,left:(y.left-C.left+m.left)/b.x,right:(C.right-y.right+m.right)/b.x}}const pJ=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:i,placement:r,rects:o,platform:s,elements:a,middlewareData:l}=t,{element:u,padding:c=0}=Tr(e,t)||{};if(u==null)return{};const d=bO(c),f={x:n,y:i},p=Pv(r),m=Nv(p),h=await s.getDimensions(u),v=p==="y",y=v?"top":"left",w=v?"bottom":"right",S=v?"clientHeight":"clientWidth",b=o.reference[m]+o.reference[p]-f[p]-o.floating[m],C=f[p]-o.reference[p],_=await(s.getOffsetParent==null?void 0:s.getOffsetParent(u));let k=_?_[S]:0;(!k||!await(s.isElement==null?void 0:s.isElement(_)))&&(k=a.floating[S]||o.floating[m]);const R=b/2-C/2,M=k/2-h[m]/2-1,U=Xr(d[y],M),z=Xr(d[w],M),Z=U,W=k-h[m]-z,j=k/2-h[m]/2+R,L=vh(Z,j,W),Y=!l.arrow&&as(r)!=null&&j!==L&&o.reference[m]/2-(j<Z?U:z)-h[m]/2<0,ne=Y?j<Z?j-Z:j-W:0;return{[p]:f[p]+ne,data:{[p]:L,centerOffset:j-L-ne,...Y&&{alignmentOffset:ne}},reset:Y}}}),hJ=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:r,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:u}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:h=!0,...v}=Tr(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const y=kr(r),w=Xn(a),S=kr(a)===a,b=await(l.isRTL==null?void 0:l.isRTL(u.floating)),C=f||(S||!h?[nc(a)]:sJ(a)),_=m!=="none";!f&&_&&C.push(...cJ(a,h,m,b));const k=[a,...C],R=await pa(t,v),M=[];let U=((i=o.flip)==null?void 0:i.overflows)||[];if(c&&M.push(R[y]),d){const j=oJ(r,s,b);M.push(R[j[0]],R[j[1]])}if(U=[...U,{placement:r,overflows:M}],!M.every(j=>j<=0)){var z,Z;const j=(((z=o.flip)==null?void 0:z.index)||0)+1,L=k[j];if(L&&(!(d==="alignment"?w!==Xn(L):!1)||U.every(Q=>Xn(Q.placement)===w?Q.overflows[0]>0:!0)))return{data:{index:j,overflows:U},reset:{placement:L}};let Y=(Z=U.filter(ne=>ne.overflows[0]<=0).sort((ne,Q)=>ne.overflows[1]-Q.overflows[1])[0])==null?void 0:Z.placement;if(!Y)switch(p){case"bestFit":{var W;const ne=(W=U.filter(Q=>{if(_){const se=Xn(Q.placement);return se===w||se==="y"}return!0}).map(Q=>[Q.placement,Q.overflows.filter(se=>se>0).reduce((se,E)=>se+E,0)]).sort((Q,se)=>Q[1]-se[1])[0])==null?void 0:W[0];ne&&(Y=ne);break}case"initialPlacement":Y=a;break}if(r!==Y)return{reset:{placement:Y}}}return{}}}};function K_(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Y_(e){return tJ.some(t=>e[t]>=0)}const mJ=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:i="referenceHidden",...r}=Tr(e,t);switch(i){case"referenceHidden":{const o=await pa(t,{...r,elementContext:"reference"}),s=K_(o,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:Y_(s)}}}case"escaped":{const o=await pa(t,{...r,altBoundary:!0}),s=K_(o,n.floating);return{data:{escapedOffsets:s,escaped:Y_(s)}}}default:return{}}}}},_O=new Set(["left","top"]);async function gJ(e,t){const{placement:n,platform:i,elements:r}=e,o=await(i.isRTL==null?void 0:i.isRTL(r.floating)),s=kr(n),a=as(n),l=Xn(n)==="y",u=_O.has(s)?-1:1,c=o&&l?-1:1,d=Tr(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*c,y:f*u}:{x:f*u,y:p*c}}const vJ=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:r,y:o,placement:s,middlewareData:a}=t,l=await gJ(t,e);return s===((n=a.offset)==null?void 0:n.placement)&&(i=a.arrow)!=null&&i.alignmentOffset?{}:{x:r+l.x,y:o+l.y,data:{...l,placement:s}}}}},yJ=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:i,placement:r}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:a={fn:v=>{let{x:y,y:w}=v;return{x:y,y:w}}},...l}=Tr(e,t),u={x:n,y:i},c=await pa(t,l),d=Xn(kr(r)),f=Ov(d);let p=u[f],m=u[d];if(o){const v=f==="y"?"top":"left",y=f==="y"?"bottom":"right",w=p+c[v],S=p-c[y];p=vh(w,p,S)}if(s){const v=d==="y"?"top":"left",y=d==="y"?"bottom":"right",w=m+c[v],S=m-c[y];m=vh(w,m,S)}const h=a.fn({...t,[f]:p,[d]:m});return{...h,data:{x:h.x-n,y:h.y-i,enabled:{[f]:o,[d]:s}}}}}},bJ=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:i,placement:r,rects:o,middlewareData:s}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Tr(e,t),c={x:n,y:i},d=Xn(r),f=Ov(d);let p=c[f],m=c[d];const h=Tr(a,t),v=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const S=f==="y"?"height":"width",b=o.reference[f]-o.floating[S]+v.mainAxis,C=o.reference[f]+o.reference[S]-v.mainAxis;p<b?p=b:p>C&&(p=C)}if(u){var y,w;const S=f==="y"?"width":"height",b=_O.has(kr(r)),C=o.reference[d]-o.floating[S]+(b&&((y=s.offset)==null?void 0:y[d])||0)+(b?0:v.crossAxis),_=o.reference[d]+o.reference[S]+(b?0:((w=s.offset)==null?void 0:w[d])||0)-(b?v.crossAxis:0);m<C?m=C:m>_&&(m=_)}return{[f]:p,[d]:m}}}},_J=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,i;const{placement:r,rects:o,platform:s,elements:a}=t,{apply:l=()=>{},...u}=Tr(e,t),c=await pa(t,u),d=kr(r),f=as(r),p=Xn(r)==="y",{width:m,height:h}=o.floating;let v,y;d==="top"||d==="bottom"?(v=d,y=f===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(y=d,v=f==="end"?"top":"bottom");const w=h-c.top-c.bottom,S=m-c.left-c.right,b=Xr(h-c[v],w),C=Xr(m-c[y],S),_=!t.middlewareData.shift;let k=b,R=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=S),(i=t.middlewareData.shift)!=null&&i.enabled.y&&(k=w),_&&!f){const U=Kt(c.left,0),z=Kt(c.right,0),Z=Kt(c.top,0),W=Kt(c.bottom,0);p?R=m-2*(U!==0||z!==0?U+z:Kt(c.left,c.right)):k=h-2*(Z!==0||W!==0?Z+W:Kt(c.top,c.bottom))}await l({...t,availableWidth:R,availableHeight:k});const M=await s.getDimensions(a.floating);return m!==M.width||h!==M.height?{reset:{rects:!0}}:{}}}};function Vd(){return typeof window<"u"}function us(e){return wO(e)?(e.nodeName||"").toLowerCase():"#document"}function en(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function ur(e){var t;return(t=(wO(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function wO(e){return Vd()?e instanceof Node||e instanceof en(e).Node:!1}function zn(e){return Vd()?e instanceof Element||e instanceof en(e).Element:!1}function ir(e){return Vd()?e instanceof HTMLElement||e instanceof en(e).HTMLElement:!1}function X_(e){return!Vd()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof en(e).ShadowRoot}const wJ=new Set(["inline","contents"]);function yu(e){const{overflow:t,overflowX:n,overflowY:i,display:r}=Ln(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&!wJ.has(r)}const xJ=new Set(["table","td","th"]);function SJ(e){return xJ.has(us(e))}const EJ=[":popover-open",":modal"];function qd(e){return EJ.some(t=>{try{return e.matches(t)}catch{return!1}})}const IJ=["transform","translate","scale","rotate","perspective"],TJ=["transform","translate","scale","rotate","perspective","filter"],kJ=["paint","layout","strict","content"];function Mv(e){const t=jv(),n=zn(e)?Ln(e):e;return IJ.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||TJ.some(i=>(n.willChange||"").includes(i))||kJ.some(i=>(n.contain||"").includes(i))}function CJ(e){let t=Qr(e);for(;ir(t)&&!Zo(t);){if(Mv(t))return t;if(qd(t))return null;t=Qr(t)}return null}function jv(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const AJ=new Set(["html","body","#document"]);function Zo(e){return AJ.has(us(e))}function Ln(e){return en(e).getComputedStyle(e)}function Zd(e){return zn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Qr(e){if(us(e)==="html")return e;const t=e.assignedSlot||e.parentNode||X_(e)&&e.host||ur(e);return X_(t)?t.host:t}function xO(e){const t=Qr(e);return Zo(t)?e.ownerDocument?e.ownerDocument.body:e.body:ir(t)&&yu(t)?t:xO(t)}function ha(e,t,n){var i;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=xO(e),o=r===((i=e.ownerDocument)==null?void 0:i.body),s=en(r);if(o){const a=bh(s);return t.concat(s,s.visualViewport||[],yu(r)?r:[],a&&n?ha(a):[])}return t.concat(r,ha(r,[],n))}function bh(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function SO(e){const t=Ln(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const r=ir(e),o=r?e.offsetWidth:n,s=r?e.offsetHeight:i,a=tc(n)!==o||tc(i)!==s;return a&&(n=o,i=s),{width:n,height:i,$:a}}function Dv(e){return zn(e)?e:e.contextElement}function wo(e){const t=Dv(e);if(!ir(t))return Qn(1);const n=t.getBoundingClientRect(),{width:i,height:r,$:o}=SO(t);let s=(o?tc(n.width):n.width)/i,a=(o?tc(n.height):n.height)/r;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}const RJ=Qn(0);function EO(e){const t=en(e);return!jv()||!t.visualViewport?RJ:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function $J(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==en(e)?!1:t}function Oi(e,t,n,i){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),o=Dv(e);let s=Qn(1);t&&(i?zn(i)&&(s=wo(i)):s=wo(e));const a=$J(o,n,i)?EO(o):Qn(0);let l=(r.left+a.x)/s.x,u=(r.top+a.y)/s.y,c=r.width/s.x,d=r.height/s.y;if(o){const f=en(o),p=i&&zn(i)?en(i):i;let m=f,h=bh(m);for(;h&&i&&p!==m;){const v=wo(h),y=h.getBoundingClientRect(),w=Ln(h),S=y.left+(h.clientLeft+parseFloat(w.paddingLeft))*v.x,b=y.top+(h.clientTop+parseFloat(w.paddingTop))*v.y;l*=v.x,u*=v.y,c*=v.x,d*=v.y,l+=S,u+=b,m=en(h),h=bh(m)}}return rc({width:c,height:d,x:l,y:u})}function zv(e,t){const n=Zd(e).scrollLeft;return t?t.left+n:Oi(ur(e)).left+n}function IO(e,t,n){n===void 0&&(n=!1);const i=e.getBoundingClientRect(),r=i.left+t.scrollLeft-(n?0:zv(e,i)),o=i.top+t.scrollTop;return{x:r,y:o}}function OJ(e){let{elements:t,rect:n,offsetParent:i,strategy:r}=e;const o=r==="fixed",s=ur(i),a=t?qd(t.floating):!1;if(i===s||a&&o)return n;let l={scrollLeft:0,scrollTop:0},u=Qn(1);const c=Qn(0),d=ir(i);if((d||!d&&!o)&&((us(i)!=="body"||yu(s))&&(l=Zd(i)),ir(i))){const p=Oi(i);u=wo(i),c.x=p.x+i.clientLeft,c.y=p.y+i.clientTop}const f=s&&!d&&!o?IO(s,l,!0):Qn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+c.x+f.x,y:n.y*u.y-l.scrollTop*u.y+c.y+f.y}}function NJ(e){return Array.from(e.getClientRects())}function PJ(e){const t=ur(e),n=Zd(e),i=e.ownerDocument.body,r=Kt(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),o=Kt(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let s=-n.scrollLeft+zv(e);const a=-n.scrollTop;return Ln(i).direction==="rtl"&&(s+=Kt(t.clientWidth,i.clientWidth)-r),{width:r,height:o,x:s,y:a}}function MJ(e,t){const n=en(e),i=ur(e),r=n.visualViewport;let o=i.clientWidth,s=i.clientHeight,a=0,l=0;if(r){o=r.width,s=r.height;const u=jv();(!u||u&&t==="fixed")&&(a=r.offsetLeft,l=r.offsetTop)}return{width:o,height:s,x:a,y:l}}const jJ=new Set(["absolute","fixed"]);function DJ(e,t){const n=Oi(e,!0,t==="fixed"),i=n.top+e.clientTop,r=n.left+e.clientLeft,o=ir(e)?wo(e):Qn(1),s=e.clientWidth*o.x,a=e.clientHeight*o.y,l=r*o.x,u=i*o.y;return{width:s,height:a,x:l,y:u}}function Q_(e,t,n){let i;if(t==="viewport")i=MJ(e,n);else if(t==="document")i=PJ(ur(e));else if(zn(t))i=DJ(t,n);else{const r=EO(e);i={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return rc(i)}function TO(e,t){const n=Qr(e);return n===t||!zn(n)||Zo(n)?!1:Ln(n).position==="fixed"||TO(n,t)}function zJ(e,t){const n=t.get(e);if(n)return n;let i=ha(e,[],!1).filter(a=>zn(a)&&us(a)!=="body"),r=null;const o=Ln(e).position==="fixed";let s=o?Qr(e):e;for(;zn(s)&&!Zo(s);){const a=Ln(s),l=Mv(s);!l&&a.position==="fixed"&&(r=null),(o?!l&&!r:!l&&a.position==="static"&&!!r&&jJ.has(r.position)||yu(s)&&!l&&TO(e,s))?i=i.filter(c=>c!==s):r=a,s=Qr(s)}return t.set(e,i),i}function LJ(e){let{element:t,boundary:n,rootBoundary:i,strategy:r}=e;const s=[...n==="clippingAncestors"?qd(t)?[]:zJ(t,this._c):[].concat(n),i],a=s[0],l=s.reduce((u,c)=>{const d=Q_(t,c,r);return u.top=Kt(d.top,u.top),u.right=Xr(d.right,u.right),u.bottom=Xr(d.bottom,u.bottom),u.left=Kt(d.left,u.left),u},Q_(t,a,r));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function UJ(e){const{width:t,height:n}=SO(e);return{width:t,height:n}}function FJ(e,t,n){const i=ir(t),r=ur(t),o=n==="fixed",s=Oi(e,!0,o,t);let a={scrollLeft:0,scrollTop:0};const l=Qn(0);function u(){l.x=zv(r)}if(i||!i&&!o)if((us(t)!=="body"||yu(r))&&(a=Zd(t)),i){const p=Oi(t,!0,o,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else r&&u();o&&!i&&r&&u();const c=r&&!i&&!o?IO(r,a):Qn(0),d=s.left+a.scrollLeft-l.x-c.x,f=s.top+a.scrollTop-l.y-c.y;return{x:d,y:f,width:s.width,height:s.height}}function Jf(e){return Ln(e).position==="static"}function ew(e,t){if(!ir(e)||Ln(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return ur(e)===n&&(n=n.ownerDocument.body),n}function kO(e,t){const n=en(e);if(qd(e))return n;if(!ir(e)){let r=Qr(e);for(;r&&!Zo(r);){if(zn(r)&&!Jf(r))return r;r=Qr(r)}return n}let i=ew(e,t);for(;i&&SJ(i)&&Jf(i);)i=ew(i,t);return i&&Zo(i)&&Jf(i)&&!Mv(i)?n:i||CJ(e)||n}const BJ=async function(e){const t=this.getOffsetParent||kO,n=this.getDimensions,i=await n(e.floating);return{reference:FJ(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function VJ(e){return Ln(e).direction==="rtl"}const qJ={convertOffsetParentRelativeRectToViewportRelativeRect:OJ,getDocumentElement:ur,getClippingRect:LJ,getOffsetParent:kO,getElementRects:BJ,getClientRects:NJ,getDimensions:UJ,getScale:wo,isElement:zn,isRTL:VJ};function CO(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ZJ(e,t){let n=null,i;const r=ur(e);function o(){var a;clearTimeout(i),(a=n)==null||a.disconnect(),n=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),o();const u=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=u;if(a||t(),!f||!p)return;const m=Ku(d),h=Ku(r.clientWidth-(c+f)),v=Ku(r.clientHeight-(d+p)),y=Ku(c),S={rootMargin:-m+"px "+-h+"px "+-v+"px "+-y+"px",threshold:Kt(0,Xr(1,l))||1};let b=!0;function C(_){const k=_[0].intersectionRatio;if(k!==l){if(!b)return s();k?s(!1,k):i=setTimeout(()=>{s(!1,1e-7)},1e3)}k===1&&!CO(u,e.getBoundingClientRect())&&s(),b=!1}try{n=new IntersectionObserver(C,{...S,root:r.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return s(!0),o}function HJ(e,t,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:o=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=i,u=Dv(e),c=r||o?[...u?ha(u):[],...ha(t)]:[];c.forEach(y=>{r&&y.addEventListener("scroll",n,{passive:!0}),o&&y.addEventListener("resize",n)});const d=u&&a?ZJ(u,n):null;let f=-1,p=null;s&&(p=new ResizeObserver(y=>{let[w]=y;w&&w.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let m,h=l?Oi(e):null;l&&v();function v(){const y=Oi(e);h&&!CO(h,y)&&n(),h=y,m=requestAnimationFrame(v)}return n(),()=>{var y;c.forEach(w=>{r&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),d?.(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const GJ=vJ,WJ=yJ,JJ=hJ,KJ=_J,YJ=mJ,tw=pJ,XJ=bJ,QJ=(e,t,n)=>{const i=new Map,r={platform:qJ,...n},o={...r.platform,_c:i};return fJ(e,t,{...r,platform:o})};var eK=typeof document<"u",tK=function(){},bl=eK?I.useLayoutEffect:tK;function ic(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,i,r;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(i=n;i--!==0;)if(!ic(e[i],t[i]))return!1;return!0}if(r=Object.keys(e),n=r.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(t,r[i]))return!1;for(i=n;i--!==0;){const o=r[i];if(!(o==="_owner"&&e.$$typeof)&&!ic(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function AO(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function nw(e,t){const n=AO(e);return Math.round(t*n)/n}function Kf(e){const t=x.useRef(e);return bl(()=>{t.current=e}),t}function nK(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:o,floating:s}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[c,d]=x.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=x.useState(i);ic(f,i)||p(i);const[m,h]=x.useState(null),[v,y]=x.useState(null),w=x.useCallback(Q=>{Q!==_.current&&(_.current=Q,h(Q))},[]),S=x.useCallback(Q=>{Q!==k.current&&(k.current=Q,y(Q))},[]),b=o||m,C=s||v,_=x.useRef(null),k=x.useRef(null),R=x.useRef(c),M=l!=null,U=Kf(l),z=Kf(r),Z=Kf(u),W=x.useCallback(()=>{if(!_.current||!k.current)return;const Q={placement:t,strategy:n,middleware:f};z.current&&(Q.platform=z.current),QJ(_.current,k.current,Q).then(se=>{const E={...se,isPositioned:Z.current!==!1};j.current&&!ic(R.current,E)&&(R.current=E,SS.flushSync(()=>{d(E)}))})},[f,t,n,z,Z]);bl(()=>{u===!1&&R.current.isPositioned&&(R.current.isPositioned=!1,d(Q=>({...Q,isPositioned:!1})))},[u]);const j=x.useRef(!1);bl(()=>(j.current=!0,()=>{j.current=!1}),[]),bl(()=>{if(b&&(_.current=b),C&&(k.current=C),b&&C){if(U.current)return U.current(b,C,W);W()}},[b,C,W,U,M]);const L=x.useMemo(()=>({reference:_,floating:k,setReference:w,setFloating:S}),[w,S]),Y=x.useMemo(()=>({reference:b,floating:C}),[b,C]),ne=x.useMemo(()=>{const Q={position:n,left:0,top:0};if(!Y.floating)return Q;const se=nw(Y.floating,c.x),E=nw(Y.floating,c.y);return a?{...Q,transform:"translate("+se+"px, "+E+"px)",...AO(Y.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:se,top:E}},[n,a,Y.floating,c.x,c.y]);return x.useMemo(()=>({...c,update:W,refs:L,elements:Y,floatingStyles:ne}),[c,W,L,Y,ne])}const rK=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:i,padding:r}=typeof e=="function"?e(n):e;return i&&t(i)?i.current!=null?tw({element:i.current,padding:r}).fn(n):{}:i?tw({element:i,padding:r}).fn(n):{}}}},iK=(e,t)=>({...GJ(e),options:[e,t]}),oK=(e,t)=>({...WJ(e),options:[e,t]}),sK=(e,t)=>({...XJ(e),options:[e,t]}),aK=(e,t)=>({...JJ(e),options:[e,t]}),uK=(e,t)=>({...KJ(e),options:[e,t]}),lK=(e,t)=>({...YJ(e),options:[e,t]}),cK=(e,t)=>({...rK(e),options:[e,t]});var dK="Arrow",RO=x.forwardRef((e,t)=>{const{children:n,width:i=10,height:r=5,...o}=e;return g.jsx(dt.svg,{...o,ref:t,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:g.jsx("polygon",{points:"0,0 30,0 15,10"})})});RO.displayName=dK;var fK=RO;function pK(e){const[t,n]=x.useState(void 0);return xn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const o=r[0];let s,a;if("borderBoxSize"in o){const l=o.borderBoxSize,u=Array.isArray(l)?l[0]:l;s=u.inlineSize,a=u.blockSize}else s=e.offsetWidth,a=e.offsetHeight;n({width:s,height:a})});return i.observe(e,{box:"border-box"}),()=>i.unobserve(e)}else n(void 0)},[e]),t}var Lv="Popper",[$O,Hd]=vu(Lv),[hK,OO]=$O(Lv),NO=e=>{const{__scopePopper:t,children:n}=e,[i,r]=x.useState(null);return g.jsx(hK,{scope:t,anchor:i,onAnchorChange:r,children:n})};NO.displayName=Lv;var PO="PopperAnchor",MO=x.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:i,...r}=e,o=OO(PO,n),s=x.useRef(null),a=mt(t,s),l=x.useRef(null);return x.useEffect(()=>{const u=l.current;l.current=i?.current||s.current,u!==l.current&&o.onAnchorChange(l.current)}),i?null:g.jsx(dt.div,{...r,ref:a})});MO.displayName=PO;var Uv="PopperContent",[mK,gK]=$O(Uv),jO=x.forwardRef((e,t)=>{const{__scopePopper:n,side:i="bottom",sideOffset:r=0,align:o="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:m,...h}=e,v=OO(Uv,n),[y,w]=x.useState(null),S=mt(t,ke=>w(ke)),[b,C]=x.useState(null),_=pK(b),k=_?.width??0,R=_?.height??0,M=i+(o!=="center"?"-"+o:""),U=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},z=Array.isArray(u)?u:[u],Z=z.length>0,W={padding:U,boundary:z.filter(yK),altBoundary:Z},{refs:j,floatingStyles:L,placement:Y,isPositioned:ne,middlewareData:Q}=nK({strategy:"fixed",placement:M,whileElementsMounted:(...ke)=>HJ(...ke,{animationFrame:p==="always"}),elements:{reference:v.anchor},middleware:[iK({mainAxis:r+R,alignmentAxis:s}),l&&oK({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?sK():void 0,...W}),l&&aK({...W}),uK({...W,apply:({elements:ke,rects:ze,availableWidth:Vn,availableHeight:pn})=>{const{width:wt,height:Ji}=ze.reference,ut=ke.floating.style;ut.setProperty("--radix-popper-available-width",`${Vn}px`),ut.setProperty("--radix-popper-available-height",`${pn}px`),ut.setProperty("--radix-popper-anchor-width",`${wt}px`),ut.setProperty("--radix-popper-anchor-height",`${Ji}px`)}}),b&&cK({element:b,padding:a}),bK({arrowWidth:k,arrowHeight:R}),f&&lK({strategy:"referenceHidden",...W})]}),[se,E]=LO(Y),we=sn(m);xn(()=>{ne&&we?.()},[ne,we]);const de=Q.arrow?.x,A=Q.arrow?.y,H=Q.arrow?.centerOffset!==0,[re,ie]=x.useState();return xn(()=>{y&&ie(window.getComputedStyle(y).zIndex)},[y]),g.jsx("div",{ref:j.setFloating,"data-radix-popper-content-wrapper":"",style:{...L,transform:ne?L.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[Q.transformOrigin?.x,Q.transformOrigin?.y].join(" "),...Q.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:g.jsx(mK,{scope:n,placedSide:se,onArrowChange:C,arrowX:de,arrowY:A,shouldHideArrow:H,children:g.jsx(dt.div,{"data-side":se,"data-align":E,...h,ref:S,style:{...h.style,animation:ne?void 0:"none"}})})})});jO.displayName=Uv;var DO="PopperArrow",vK={top:"bottom",right:"left",bottom:"top",left:"right"},zO=x.forwardRef(function(t,n){const{__scopePopper:i,...r}=t,o=gK(DO,i),s=vK[o.placedSide];return g.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:g.jsx(fK,{...r,ref:n,style:{...r.style,display:"block"}})})});zO.displayName=DO;function yK(e){return e!==null}var bK=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:i,middlewareData:r}=t,s=r.arrow?.centerOffset!==0,a=s?0:e.arrowWidth,l=s?0:e.arrowHeight,[u,c]=LO(n),d={start:"0%",center:"50%",end:"100%"}[c],f=(r.arrow?.x??0)+a/2,p=(r.arrow?.y??0)+l/2;let m="",h="";return u==="bottom"?(m=s?d:`${f}px`,h=`${-l}px`):u==="top"?(m=s?d:`${f}px`,h=`${i.floating.height+l}px`):u==="right"?(m=`${-l}px`,h=s?d:`${p}px`):u==="left"&&(m=`${i.floating.width+l}px`,h=s?d:`${p}px`),{data:{x:m,y:h}}}});function LO(e){const[t,n="center"]=e.split("-");return[t,n]}var UO=NO,Fv=MO,FO=jO,BO=zO,_K="Portal",Bv=x.forwardRef((e,t)=>{const{container:n,...i}=e,[r,o]=x.useState(!1);xn(()=>o(!0),[]);const s=n||r&&globalThis?.document?.body;return s?xS.createPortal(g.jsx(dt.div,{...i,ref:t}),s):null});Bv.displayName=_K;function wK(e,t){return x.useReducer((n,i)=>t[n][i]??n,e)}var si=e=>{const{present:t,children:n}=e,i=xK(t),r=typeof n=="function"?n({present:i.isPresent}):x.Children.only(n),o=mt(i.ref,SK(r));return typeof n=="function"||i.isPresent?x.cloneElement(r,{ref:o}):null};si.displayName="Presence";function xK(e){const[t,n]=x.useState(),i=x.useRef(null),r=x.useRef(e),o=x.useRef("none"),s=e?"mounted":"unmounted",[a,l]=wK(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const u=Yu(i.current);o.current=a==="mounted"?u:"none"},[a]),xn(()=>{const u=i.current,c=r.current;if(c!==e){const f=o.current,p=Yu(u);e?l("MOUNT"):p==="none"||u?.display==="none"?l("UNMOUNT"):l(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,l]),xn(()=>{if(t){let u;const c=t.ownerDocument.defaultView??window,d=p=>{const h=Yu(i.current).includes(CSS.escape(p.animationName));if(p.target===t&&h&&(l("ANIMATION_END"),!r.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",u=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},f=p=>{p.target===t&&(o.current=Yu(i.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{c.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:x.useCallback(u=>{i.current=u?getComputedStyle(u):null,n(u)},[])}}function Yu(e){return e?.animationName||"none"}function SK(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var EK=x[" useInsertionEffect ".trim().toString()]||xn;function Gd({prop:e,defaultProp:t,onChange:n=()=>{},caller:i}){const[r,o,s]=IK({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:r;{const c=x.useRef(e!==void 0);x.useEffect(()=>{const d=c.current;d!==a&&console.warn(`${i} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=a},[a,i])}const u=x.useCallback(c=>{if(a){const d=TK(c)?c(e):c;d!==e&&s.current?.(d)}else o(c)},[a,e,o,s]);return[l,u]}function IK({defaultProp:e,onChange:t}){const[n,i]=x.useState(e),r=x.useRef(n),o=x.useRef(t);return EK(()=>{o.current=t},[t]),x.useEffect(()=>{r.current!==n&&(o.current?.(n),r.current=n)},[n,r]),[n,i,o]}function TK(e){return typeof e=="function"}var kK=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},io=new WeakMap,Xu=new WeakMap,Qu={},Yf=0,VO=function(e){return e&&(e.host||VO(e.parentNode))},CK=function(e,t){return t.map(function(n){if(e.contains(n))return n;var i=VO(n);return i&&e.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},AK=function(e,t,n,i){var r=CK(t,Array.isArray(e)?e:[e]);Qu[n]||(Qu[n]=new WeakMap);var o=Qu[n],s=[],a=new Set,l=new Set(r),u=function(d){!d||a.has(d)||(a.add(d),u(d.parentNode))};r.forEach(u);var c=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))c(f);else try{var p=f.getAttribute(i),m=p!==null&&p!=="false",h=(io.get(f)||0)+1,v=(o.get(f)||0)+1;io.set(f,h),o.set(f,v),s.push(f),h===1&&m&&Xu.set(f,!0),v===1&&f.setAttribute(n,"true"),m||f.setAttribute(i,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return c(t),a.clear(),Yf++,function(){s.forEach(function(d){var f=io.get(d)-1,p=o.get(d)-1;io.set(d,f),o.set(d,p),f||(Xu.has(d)||d.removeAttribute(i),Xu.delete(d)),p||d.removeAttribute(n)}),Yf--,Yf||(io=new WeakMap,io=new WeakMap,Xu=new WeakMap,Qu={})}},qO=function(e,t,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),r=kK(e);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),AK(i,r,n,"aria-hidden")):function(){return null}},Wn=function(){return Wn=Object.assign||function(t){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},Wn.apply(this,arguments)};function ZO(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function RK(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))}var _l="right-scroll-bar-position",wl="width-before-scroll-bar",$K="with-scroll-bars-hidden",OK="--removed-body-scroll-bar-size";function Xf(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function NK(e,t){var n=I.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=t,n.facade}var PK=typeof window<"u"?x.useLayoutEffect:x.useEffect,rw=new WeakMap;function MK(e,t){var n=NK(null,function(i){return e.forEach(function(r){return Xf(r,i)})});return PK(function(){var i=rw.get(n);if(i){var r=new Set(i),o=new Set(e),s=n.current;r.forEach(function(a){o.has(a)||Xf(a,null)}),o.forEach(function(a){r.has(a)||Xf(a,s)})}rw.set(n,e)},[e]),n}function jK(e){return e}function DK(e,t){t===void 0&&(t=jK);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(o){var s=t(o,i);return n.push(s),function(){n=n.filter(function(a){return a!==s})}},assignSyncMedium:function(o){for(i=!0;n.length;){var s=n;n=[],s.forEach(o)}n={push:function(a){return o(a)},filter:function(){return n}}},assignMedium:function(o){i=!0;var s=[];if(n.length){var a=n;n=[],a.forEach(o),s=n}var l=function(){var c=s;s=[],c.forEach(o)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(c){s.push(c),u()},filter:function(c){return s=s.filter(c),n}}}};return r}function zK(e){e===void 0&&(e={});var t=DK(null);return t.options=Wn({async:!0,ssr:!1},e),t}var HO=function(e){var t=e.sideCar,n=ZO(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return x.createElement(i,Wn({},n))};HO.isSideCarExport=!0;function LK(e,t){return e.useMedium(t),HO}var GO=zK(),Qf=function(){},Wd=x.forwardRef(function(e,t){var n=x.useRef(null),i=x.useState({onScrollCapture:Qf,onWheelCapture:Qf,onTouchMoveCapture:Qf}),r=i[0],o=i[1],s=e.forwardProps,a=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,m=e.noIsolation,h=e.inert,v=e.allowPinchZoom,y=e.as,w=y===void 0?"div":y,S=e.gapMode,b=ZO(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=f,_=MK([n,t]),k=Wn(Wn({},b),r);return x.createElement(x.Fragment,null,c&&x.createElement(C,{sideCar:GO,removeScrollBar:u,shards:d,noRelative:p,noIsolation:m,inert:h,setCallbacks:o,allowPinchZoom:!!v,lockRef:n,gapMode:S}),s?x.cloneElement(x.Children.only(a),Wn(Wn({},k),{ref:_})):x.createElement(w,Wn({},k,{className:l,ref:_}),a))});Wd.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Wd.classNames={fullWidth:wl,zeroRight:_l};var UK=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function FK(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=UK();return t&&e.setAttribute("nonce",t),e}function BK(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function VK(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var qK=function(){var e=0,t=null;return{add:function(n){e==0&&(t=FK())&&(BK(t,n),VK(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ZK=function(){var e=qK();return function(t,n){x.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},WO=function(){var e=ZK(),t=function(n){var i=n.styles,r=n.dynamic;return e(i,r),null};return t},HK={left:0,top:0,right:0,gap:0},ep=function(e){return parseInt(e||"",10)||0},GK=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],i=t[e==="padding"?"paddingTop":"marginTop"],r=t[e==="padding"?"paddingRight":"marginRight"];return[ep(n),ep(i),ep(r)]},WK=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return HK;var t=GK(e),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-n+t[2]-t[0])}},JK=WO(),xo="data-scroll-locked",KK=function(e,t,n,i){var r=e.left,o=e.top,s=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
42
|
+
.`.concat($K,` {
|
|
43
|
+
overflow: hidden `).concat(i,`;
|
|
44
|
+
padding-right: `).concat(a,"px ").concat(i,`;
|
|
45
|
+
}
|
|
46
|
+
body[`).concat(xo,`] {
|
|
47
|
+
overflow: hidden `).concat(i,`;
|
|
48
|
+
overscroll-behavior: contain;
|
|
49
|
+
`).concat([t&&"position: relative ".concat(i,";"),n==="margin"&&`
|
|
50
|
+
padding-left: `.concat(r,`px;
|
|
51
|
+
padding-top: `).concat(o,`px;
|
|
52
|
+
padding-right: `).concat(s,`px;
|
|
53
|
+
margin-left:0;
|
|
54
|
+
margin-top:0;
|
|
55
|
+
margin-right: `).concat(a,"px ").concat(i,`;
|
|
56
|
+
`),n==="padding"&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
.`).concat(_l,` {
|
|
60
|
+
right: `).concat(a,"px ").concat(i,`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
.`).concat(wl,` {
|
|
64
|
+
margin-right: `).concat(a,"px ").concat(i,`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
.`).concat(_l," .").concat(_l,` {
|
|
68
|
+
right: 0 `).concat(i,`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
.`).concat(wl," .").concat(wl,` {
|
|
72
|
+
margin-right: 0 `).concat(i,`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
body[`).concat(xo,`] {
|
|
76
|
+
`).concat(OK,": ").concat(a,`px;
|
|
77
|
+
}
|
|
78
|
+
`)},iw=function(){var e=parseInt(document.body.getAttribute(xo)||"0",10);return isFinite(e)?e:0},YK=function(){x.useEffect(function(){return document.body.setAttribute(xo,(iw()+1).toString()),function(){var e=iw()-1;e<=0?document.body.removeAttribute(xo):document.body.setAttribute(xo,e.toString())}},[])},XK=function(e){var t=e.noRelative,n=e.noImportant,i=e.gapMode,r=i===void 0?"margin":i;YK();var o=x.useMemo(function(){return WK(r)},[r]);return x.createElement(JK,{styles:KK(o,!t,r,n?"":"!important")})},_h=!1;if(typeof window<"u")try{var el=Object.defineProperty({},"passive",{get:function(){return _h=!0,!0}});window.addEventListener("test",el,el),window.removeEventListener("test",el,el)}catch{_h=!1}var oo=_h?{passive:!1}:!1,QK=function(e){return e.tagName==="TEXTAREA"},JO=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!QK(e)&&n[t]==="visible")},e8=function(e){return JO(e,"overflowY")},t8=function(e){return JO(e,"overflowX")},ow=function(e,t){var n=t.ownerDocument,i=t;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=KO(e,i);if(r){var o=YO(e,i),s=o[1],a=o[2];if(s>a)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},n8=function(e){var t=e.scrollTop,n=e.scrollHeight,i=e.clientHeight;return[t,n,i]},r8=function(e){var t=e.scrollLeft,n=e.scrollWidth,i=e.clientWidth;return[t,n,i]},KO=function(e,t){return e==="v"?e8(t):t8(t)},YO=function(e,t){return e==="v"?n8(t):r8(t)},i8=function(e,t){return e==="h"&&t==="rtl"?-1:1},o8=function(e,t,n,i,r){var o=i8(e,window.getComputedStyle(t).direction),s=o*i,a=n.target,l=t.contains(a),u=!1,c=s>0,d=0,f=0;do{if(!a)break;var p=YO(e,a),m=p[0],h=p[1],v=p[2],y=h-v-o*m;(m||y)&&KO(e,a)&&(d+=y,f+=m);var w=a.parentNode;a=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(c&&Math.abs(d)<1||!c&&Math.abs(f)<1)&&(u=!0),u},tl=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},sw=function(e){return[e.deltaX,e.deltaY]},aw=function(e){return e&&"current"in e?e.current:e},s8=function(e,t){return e[0]===t[0]&&e[1]===t[1]},a8=function(e){return`
|
|
79
|
+
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
80
|
+
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
81
|
+
`)},u8=0,so=[];function l8(e){var t=x.useRef([]),n=x.useRef([0,0]),i=x.useRef(),r=x.useState(u8++)[0],o=x.useState(WO)[0],s=x.useRef(e);x.useEffect(function(){s.current=e},[e]),x.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var h=RK([e.lockRef.current],(e.shards||[]).map(aw),!0).filter(Boolean);return h.forEach(function(v){return v.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),h.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var a=x.useCallback(function(h,v){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var y=tl(h),w=n.current,S="deltaX"in h?h.deltaX:w[0]-y[0],b="deltaY"in h?h.deltaY:w[1]-y[1],C,_=h.target,k=Math.abs(S)>Math.abs(b)?"h":"v";if("touches"in h&&k==="h"&&_.type==="range")return!1;var R=ow(k,_);if(!R)return!0;if(R?C=k:(C=k==="v"?"h":"v",R=ow(k,_)),!R)return!1;if(!i.current&&"changedTouches"in h&&(S||b)&&(i.current=C),!C)return!0;var M=i.current||C;return o8(M,v,h,M==="h"?S:b)},[]),l=x.useCallback(function(h){var v=h;if(!(!so.length||so[so.length-1]!==o)){var y="deltaY"in v?sw(v):tl(v),w=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&s8(C.delta,y)})[0];if(w&&w.should){v.cancelable&&v.preventDefault();return}if(!w){var S=(s.current.shards||[]).map(aw).filter(Boolean).filter(function(C){return C.contains(v.target)}),b=S.length>0?a(v,S[0]):!s.current.noIsolation;b&&v.cancelable&&v.preventDefault()}}},[]),u=x.useCallback(function(h,v,y,w){var S={name:h,delta:v,target:y,should:w,shadowParent:c8(y)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(b){return b!==S})},1)},[]),c=x.useCallback(function(h){n.current=tl(h),i.current=void 0},[]),d=x.useCallback(function(h){u(h.type,sw(h),h.target,a(h,e.lockRef.current))},[]),f=x.useCallback(function(h){u(h.type,tl(h),h.target,a(h,e.lockRef.current))},[]);x.useEffect(function(){return so.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,oo),document.addEventListener("touchmove",l,oo),document.addEventListener("touchstart",c,oo),function(){so=so.filter(function(h){return h!==o}),document.removeEventListener("wheel",l,oo),document.removeEventListener("touchmove",l,oo),document.removeEventListener("touchstart",c,oo)}},[]);var p=e.removeScrollBar,m=e.inert;return x.createElement(x.Fragment,null,m?x.createElement(o,{styles:a8(r)}):null,p?x.createElement(XK,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function c8(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const d8=LK(GO,l8);var Vv=x.forwardRef(function(e,t){return x.createElement(Wd,Wn({},e,{ref:t,sideCar:d8}))});Vv.classNames=Wd.classNames;var Jd="Popover",[XO]=vu(Jd,[Hd]),bu=Hd(),[f8,Hi]=XO(Jd),QO=e=>{const{__scopePopover:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:s=!1}=e,a=bu(t),l=x.useRef(null),[u,c]=x.useState(!1),[d,f]=Gd({prop:i,defaultProp:r??!1,onChange:o,caller:Jd});return g.jsx(UO,{...a,children:g.jsx(f8,{scope:t,contentId:_o(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:x.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:u,onCustomAnchorAdd:x.useCallback(()=>c(!0),[]),onCustomAnchorRemove:x.useCallback(()=>c(!1),[]),modal:s,children:n})})};QO.displayName=Jd;var e1="PopoverAnchor",p8=x.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=Hi(e1,n),o=bu(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=r;return x.useEffect(()=>(s(),()=>a()),[s,a]),g.jsx(Fv,{...o,...i,ref:t})});p8.displayName=e1;var t1="PopoverTrigger",n1=x.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=Hi(t1,n),o=bu(n),s=mt(t,r.triggerRef),a=g.jsx(dt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":s1(r.open),...i,ref:s,onClick:Le(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?a:g.jsx(Fv,{asChild:!0,...o,children:a})});n1.displayName=t1;var h8="PopoverPortal",[cfe,m8]=XO(h8,{forceMount:void 0}),Ho="PopoverContent",r1=x.forwardRef((e,t)=>{const n=m8(Ho,e.__scopePopover),{forceMount:i=n.forceMount,...r}=e,o=Hi(Ho,e.__scopePopover);return g.jsx(si,{present:i||o.open,children:o.modal?g.jsx(v8,{...r,ref:t}):g.jsx(y8,{...r,ref:t})})});r1.displayName=Ho;var g8=Rv("PopoverContent.RemoveScroll"),v8=x.forwardRef((e,t)=>{const n=Hi(Ho,e.__scopePopover),i=x.useRef(null),r=mt(t,i),o=x.useRef(!1);return x.useEffect(()=>{const s=i.current;if(s)return qO(s)},[]),g.jsx(Vv,{as:g8,allowPinchZoom:!0,children:g.jsx(i1,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Le(e.onCloseAutoFocus,s=>{s.preventDefault(),o.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Le(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;o.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Le(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),y8=x.forwardRef((e,t)=>{const n=Hi(Ho,e.__scopePopover),i=x.useRef(!1),r=x.useRef(!1);return g.jsx(i1,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||n.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),i1=x.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:c,...d}=e,f=Hi(Ho,n),p=bu(n);return vO(),g.jsx($v,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:g.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:c,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:g.jsx(FO,{"data-state":s1(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),o1="PopoverClose",b8=x.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=Hi(o1,n);return g.jsx(dt.button,{type:"button",...i,ref:t,onClick:Le(e.onClick,()=>r.onOpenChange(!1))})});b8.displayName=o1;var _8="PopoverArrow",w8=x.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=bu(n);return g.jsx(BO,{...r,...i,ref:t})});w8.displayName=_8;function s1(e){return e?"open":"closed"}var x8=QO,S8=n1,E8=r1;const a1=I.forwardRef((e,t)=>g.jsx(gt.div,{...e,ref:t}));a1.displayName="AttachmentPrimitive.Root";const u1=()=>{const e=te(({attachment:t})=>t.name);return g.jsx(g.Fragment,{children:e})};u1.displayName="AttachmentPrimitive.Name";const I8=()=>{const e=Re();return I.useCallback(()=>{e.attachment().remove()},[e])},T8=ar("AttachmentPrimitive.Remove",I8),k8=()=>{const e=Re(),t=te(({thread:i,message:r})=>!!(r.branchNumber>=r.branchCount||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=I.useCallback(()=>{e.message().switchToBranch({position:"next"})},[e]);return t?null:n},C8=ar("BranchPickerPrimitive.Next",k8),A8=()=>{const e=Re(),t=te(({thread:i,message:r})=>!!(r.branchNumber<=1||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=I.useCallback(()=>{e.message().switchToBranch({position:"previous"})},[e]);return t?null:n},R8=ar("BranchPickerPrimitive.Previous",A8),$8=()=>te(({message:t})=>t.branchCount),l1=()=>{const e=$8();return g.jsx(g.Fragment,{children:e})};l1.displayName="BranchPickerPrimitive.Count";const O8=()=>te(({message:t})=>t.branchNumber),c1=()=>{const e=O8();return g.jsx(g.Fragment,{children:e})};c1.displayName="BranchPickerPrimitive.Number";const _u=e=>{const t=I.useRef(void 0);return I.useCallback(i=>{t.current&&t.current(),i&&(t.current=e(i))},[e])},d1=(e,t)=>{const n=I.useCallback(i=>{if(!e)return;const r=e(),o=()=>{const a=t?t(i):i.offsetHeight;r.setHeight(a)},s=new ResizeObserver(o);return s.observe(i),o(),()=>{s.disconnect(),r.unregister()}},[e,t]);return _u(n)},uw=I.createContext(!1),lw=(e,t)=>{const n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;const i=parseFloat(n[1]),r=n[2];if(r==="px")return i;if(r==="em"){const o=parseFloat(getComputedStyle(t).fontSize)||16;return i*o}if(r==="rem"){const o=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return i*o}return 0},f1=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const i=te(({message:l})=>l.isLast&&l.index>=2),r=Fd({optional:!0}),o=I.useContext(uw),s=I.useCallback(l=>{if(!r||o)return;const u=()=>{const c=r.getState();if(c.turnAnchor==="top"&&i){const{viewport:d,inset:f,userMessage:p}=c.height,m=lw(t,l),h=lw(n,l),v=p<=m?p:h,y=Math.max(0,d-f-v);l.style.minHeight=`${y}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),r.subscribe(u)},[r,i,o,t,n]),a=_u(s);return g.jsx(uw.Provider,{value:!0,children:g.jsx(Cv,{ref:a,children:e})})};f1.displayName="ThreadPrimitive.ViewportSlack";const N8=()=>{const e=Re(),t=te(()=>e.message()),n=I.useCallback(i=>{const r=()=>{t.setIsHovering(!0)},o=()=>{t.setIsHovering(!1)};return i.addEventListener("mouseenter",r),i.addEventListener("mouseleave",o),i.matches(":hover")&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{i.removeEventListener("mouseenter",r),i.removeEventListener("mouseleave",o),t.setIsHovering(!1)}},[t]);return _u(n)},P8=()=>{const e=ca(r=>r.turnAnchor),t=ca(r=>r.registerUserMessageHeight),n=te(({thread:r,message:o})=>e==="top"&&o.role==="user"&&o.index===r.messages.length-2&&r.messages.at(-1)?.role==="assistant"),i=I.useCallback(r=>r.offsetHeight,[]);return d1(n?t:null,i)},qv=I.forwardRef((e,t)=>{const n=N8(),i=P8(),r=mt(t,n,i);return g.jsx(f1,{children:g.jsx(gt.div,{...e,ref:r})})});qv.displayName="MessagePrimitive.Root";const p1=()=>te(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),h1=I.forwardRef(({smooth:e=!0,component:t="span",...n},i)=>{const{text:r,status:o}=sO(p1(),e);return g.jsx(t,{"data-status":o.type,...n,ref:i,children:r})});h1.displayName="MessagePartPrimitive.Text";const M8=()=>te(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),m1=I.forwardRef((e,t)=>{const{image:n}=M8();return g.jsx(gt.img,{src:n,...e,ref:t})});m1.displayName="MessagePartPrimitive.Image";const g1=({children:e})=>te(({part:n})=>n.status.type==="running")?e:null;g1.displayName="MessagePartPrimitive.InProgress";const cw=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,i)=>{t!==-1&&(i.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,i)=>{t!==-1&&i.push({type:e,startIndex:t,endIndex:n})}}},j8=e=>{const t=[],n=cw("toolGroup"),i=cw("reasoningGroup");for(let r=0;r<e.length;r++){const o=e[r];o==="tool-call"?(i.endGroup(r-1,t),n.startGroup(r)):o==="reasoning"?(n.endGroup(r-1,t),i.startGroup(r)):(n.endGroup(r-1,t),i.endGroup(r-1,t),t.push({type:"single",index:r}))}return n.finalize(e.length-1,t),i.finalize(e.length-1,t),t},D8=()=>{const e=te(wS.useShallow(t=>t.message.parts.map(n=>n.type)));return I.useMemo(()=>e.length===0?[]:j8(e),[e])},z8=({Fallback:e,...t})=>{const n=te(({tools:i})=>{const r=i.tools[t.toolName]??e;return Array.isArray(r)?r[0]??e:r});return n?g.jsx(n,{...t}):null},fr={Text:()=>g.jsxs("p",{style:{whiteSpace:"pre-line"},children:[g.jsx(h1,{}),g.jsx(g1,{children:g.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>g.jsx(m1,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},L8=({components:{Text:e=fr.Text,Reasoning:t=fr.Reasoning,Image:n=fr.Image,Source:i=fr.Source,File:r=fr.File,Unstable_Audio:o=fr.Unstable_Audio,tools:s={}}={}})=>{const a=Re(),l=te(({part:c})=>c),u=l.type;if(u==="tool-call"){const c=a.part().addToolResult,d=a.part().resumeToolCall;if("Override"in s)return g.jsx(s.Override,{...l,addResult:c,resume:d});const f=s.by_name?.[l.toolName]??s.Fallback;return g.jsx(z8,{...l,Fallback:f,addResult:c,resume:d})}if(l.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return g.jsx(e,{...l});case"reasoning":return g.jsx(t,{...l});case"source":return g.jsx(i,{...l});case"image":return g.jsx(n,{...l});case"file":return g.jsx(r,{...l});case"audio":return g.jsx(o,{...l});case"data":return null;default:const c=u;throw new Error(`Unknown message part type: ${c}`)}},xl=I.memo(({index:e,components:t})=>g.jsx(jG,{index:e,children:g.jsx(L8,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);xl.displayName="MessagePrimitive.PartByIndex";const U8=({status:e,component:t})=>g.jsx(UG,{text:"",isRunning:e.type==="running",children:g.jsx(t,{type:"text",text:"",status:e})}),F8=Object.freeze({type:"complete"}),B8=({components:e})=>{const t=te(n=>n.message.status??F8);return e?.Empty?g.jsx(e.Empty,{status:t}):g.jsx(U8,{status:t,component:e?.Text??fr.Text})},V8=I.memo(B8,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),Zv=({components:e})=>{const t=te(({message:r})=>r.parts.length),n=D8(),i=I.useMemo(()=>t===0?g.jsx(V8,{components:e}):n.map(r=>{if(r.type==="single")return g.jsx(xl,{index:r.index,components:e},r.index);if(r.type==="toolGroup"){const o=e?.ToolGroup??fr.ToolGroup;return g.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(s,a)=>g.jsx(xl,{index:r.startIndex+a,components:e},a))},`tool-${r.startIndex}`)}else{const o=e?.ReasoningGroup??fr.ReasoningGroup;return g.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(s,a)=>g.jsx(xl,{index:r.startIndex+a,components:e},a))},`reasoning-${r.startIndex}`)}}),[n,e,t]);return g.jsx(g.Fragment,{children:i})};Zv.displayName="MessagePrimitive.Parts";const q8=e=>te(({message:t})=>{const{role:n,attachments:i,parts:r,branchCount:o,isLast:s,speech:a,isCopied:l,isHovering:u}=t;return!(e.hasBranches===!0&&o<2||e.user&&n!=="user"||e.assistant&&n!=="assistant"||e.system&&n!=="system"||e.lastOrHover===!0&&!u&&!s||e.last!==void 0&&e.last!==s||e.copied===!0&&!l||e.copied===!1&&l||e.speaking===!0&&a==null||e.speaking===!1&&a!=null||e.hasAttachments===!0&&(n!=="user"||!i?.length)||e.hasAttachments===!1&&n==="user"&&i?.length||e.hasContent===!0&&r.length===0||e.hasContent===!1&&r.length>0||e.submittedFeedback!==void 0&&(t.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)}),oc=({children:e,...t})=>q8(t)?e:null;oc.displayName="MessagePrimitive.If";const Z8=(e,t)=>{const n=t.type;switch(n){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:const i=n;throw new Error(`Unknown attachment type: ${i}`)}},H8=({components:e})=>{const t=te(({attachment:i})=>i);if(!t)return null;const n=Z8(e,t);return n?g.jsx(n,{}):null},v1=I.memo(({index:e,components:t})=>g.jsx(DG,{index:e,children:g.jsx(H8,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);v1.displayName="MessagePrimitive.AttachmentByIndex";const y1=({components:e})=>{const t=te(({message:i})=>i.role!=="user"?0:i.attachments.length);return I.useMemo(()=>Array.from({length:t},(i,r)=>g.jsx(v1,{index:r,components:e},r)),[t,e])};y1.displayName="MessagePrimitive.Attachments";const b1=({children:e})=>te(({message:n})=>n.status?.type==="incomplete"&&n.status.reason==="error")?e:null;b1.displayName="MessagePrimitive.Error";const _1=I.forwardRef(({hideWhenSingleBranch:e,...t},n)=>g.jsx(oc,{hasBranches:e?!0:void 0,children:g.jsx(gt.div,{...t,ref:n})}));_1.displayName="BranchPickerPrimitive.Root";const w1=()=>{const e=Re(),t=te(i=>i.thread.isRunning||!i.composer.isEditing||i.composer.isEmpty),n=I.useCallback(()=>{e.composer().send()},[e]);return t?null:n},x1=ar("ComposerPrimitive.Send",w1),Hv=I.forwardRef(({onSubmit:e,...t},n)=>{const i=w1(),r=o=>{o.preventDefault(),i&&i()};return g.jsx(gt.form,{...t,ref:n,onSubmit:Le(e,r)})});Hv.displayName="ComposerPrimitive.Root";function wh(){return wh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},wh.apply(null,arguments)}function G8(e,t){if(e==null)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(t.indexOf(i)!==-1)continue;n[i]=e[i]}return n}var W8=I.useLayoutEffect,J8=function(t){var n=I.useRef(t);return W8(function(){n.current=t}),n},dw=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},K8=function(t,n){var i=I.useRef();return I.useCallback(function(r){t.current=r,i.current&&dw(i.current,null),i.current=n,n&&dw(n,r)},[n])},fw={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Y8=function(t){Object.keys(fw).forEach(function(n){t.style.setProperty(n,fw[n],"important")})},pw=Y8,Ot=null,hw=function(t,n){var i=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?i+n.borderSize:i-n.paddingSize};function X8(e,t,n,i){n===void 0&&(n=1),i===void 0&&(i=1/0),Ot||(Ot=document.createElement("textarea"),Ot.setAttribute("tabindex","-1"),Ot.setAttribute("aria-hidden","true"),pw(Ot)),Ot.parentNode===null&&document.body.appendChild(Ot);var r=e.paddingSize,o=e.borderSize,s=e.sizingStyle,a=s.boxSizing;Object.keys(s).forEach(function(f){var p=f;Ot.style[p]=s[p]}),pw(Ot),Ot.value=t;var l=hw(Ot,e);Ot.value=t,l=hw(Ot,e),Ot.value="x";var u=Ot.scrollHeight-r,c=u*n;a==="border-box"&&(c=c+r+o),l=Math.max(c,l);var d=u*i;return a==="border-box"&&(d=d+r+o),l=Math.min(d,l),[l,u]}var mw=function(){},Q8=function(t,n){return t.reduce(function(i,r){return i[r]=n[r],i},{})},e7=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],t7=!!document.documentElement.currentStyle,n7=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var i=Q8(e7,n),r=i.boxSizing;if(r==="")return null;t7&&r==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var o=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),s=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:o,borderSize:s}},r7=n7;function Gv(e,t,n){var i=J8(n);x.useLayoutEffect(function(){var r=function(s){return i.current(s)};if(e)return e.addEventListener(t,r),function(){return e.removeEventListener(t,r)}},[])}var i7=function(t,n){Gv(document.body,"reset",function(i){t.current.form===i.target&&n(i)})},o7=function(t){Gv(window,"resize",t)},s7=function(t){Gv(document.fonts,"loadingdone",t)},a7=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],u7=function(t,n){var i=t.cacheMeasurements,r=t.maxRows,o=t.minRows,s=t.onChange,a=s===void 0?mw:s,l=t.onHeightChange,u=l===void 0?mw:l,c=G8(t,a7),d=c.value!==void 0,f=x.useRef(null),p=K8(f,n),m=x.useRef(0),h=x.useRef(),v=function(){var S=f.current,b=i&&h.current?h.current:r7(S);if(b){h.current=b;var C=X8(b,S.value||S.placeholder||"x",o,r),_=C[0],k=C[1];m.current!==_&&(m.current=_,S.style.setProperty("height",_+"px","important"),u(_,{rowHeight:k}))}},y=function(S){d||v(),a(S)};return x.useLayoutEffect(v),i7(f,function(){if(!d){var w=f.current.value;requestAnimationFrame(function(){var S=f.current;S&&w!==S.value&&v()})}}),o7(v),s7(v),x.createElement("textarea",wh({},c,{onChange:y,ref:p}))},l7=x.forwardRef(u7);const S1=e=>{const t=sn(e),n=ca(i=>i.onScrollToBottom);I.useEffect(()=>n(t),[n,t])},Wv=I.forwardRef(({autoFocus:e=!1,asChild:t,disabled:n,onChange:i,onKeyDown:r,onPaste:o,submitOnEnter:s=!0,cancelOnEscape:a=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0,...f},p)=>{const m=Re(),h=te(({composer:R})=>R.isEditing?R.text:""),v=t?Cv:l7,y=te(({thread:R})=>R.isDisabled)||n,w=I.useRef(null),S=mt(p,w);pO(R=>{if(!a||!w.current?.contains(R.target))return;const M=m.composer();M.getState().canCancel&&(M.cancel(),R.preventDefault())});const b=R=>{y||!s||R.nativeEvent.isComposing||R.key==="Enter"&&R.shiftKey===!1&&(m.thread().getState().isRunning||(R.preventDefault(),w.current?.closest("form")?.requestSubmit()))},C=async R=>{if(!d)return;const M=m.thread().getState().capabilities,U=Array.from(R.clipboardData?.files||[]);if(M.attachments&&U.length>0)try{R.preventDefault(),await Promise.all(U.map(z=>m.composer().addAttachment(z)))}catch(z){console.error("Error adding attachment:",z)}},_=e&&!y,k=I.useCallback(()=>{const R=w.current;!R||!_||(R.focus({preventScroll:!0}),R.setSelectionRange(R.value.length,R.value.length))},[_]);return I.useEffect(()=>k(),[k]),S1(()=>{m.composer().getState().type==="thread"&&u&&k()}),I.useEffect(()=>{if(!(m.composer().getState().type!=="thread"||!l))return m.on("thread.run-start",k)},[l,k,m]),I.useEffect(()=>{if(!(m.composer().getState().type!=="thread"||!c))return m.on("thread-list-item.switched-to",k)},[c,k,m]),g.jsx(v,{name:"input",value:h,...f,ref:S,disabled:y,onChange:Le(i,R=>{m.composer().getState().isEditing&&hh(()=>{m.composer().setText(R.target.value)})}),onKeyDown:Le(r,b),onPaste:Le(o,C)})});Wv.displayName="ComposerPrimitive.Input";const c7=()=>{const e=Re(),t=te(({composer:i})=>!i.canCancel),n=I.useCallback(()=>{e.composer().cancel()},[e]);return t?null:n},E1=ar("ComposerPrimitive.Cancel",c7),d7=({multiple:e=!0}={})=>{const t=te(({composer:r})=>!r.isEditing),n=Re(),i=I.useCallback(()=>{const r=document.createElement("input");r.type="file",r.multiple=e,r.hidden=!0;const o=n.composer().getState().attachmentAccept;o!=="*"&&(r.accept=o),document.body.appendChild(r),r.onchange=s=>{const a=s.target.files;if(a){for(const l of a)n.composer().addAttachment(l);document.body.removeChild(r)}},r.oncancel=()=>{(!r.files||r.files.length===0)&&document.body.removeChild(r)},r.click()},[n,e]);return t?null:i},f7=ar("ComposerPrimitive.AddAttachment",d7,["multiple"]),p7=(e,t)=>{const n=t.type;switch(n){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:const i=n;throw new Error(`Unknown attachment type: ${i}`)}},h7=({components:e})=>{const t=te(({attachment:i})=>i);if(!t)return null;const n=p7(e,t);return n?g.jsx(n,{}):null},I1=I.memo(({index:e,components:t})=>g.jsx(zG,{index:e,children:g.jsx(h7,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);I1.displayName="ComposerPrimitive.AttachmentByIndex";const T1=({components:e})=>{const t=te(i=>i.composer.attachments.length);return I.useMemo(()=>Array.from({length:t},(i,r)=>g.jsx(I1,{index:r,components:e},r)),[t,e])};T1.displayName="ComposerPrimitive.Attachments";const k1=I.forwardRef((e,t)=>g.jsx(gt.div,{role:"alert",...e,ref:t}));k1.displayName="ErrorPrimitive.Root";const C1=I.forwardRef(({children:e,...t},n)=>{const i=te(({message:r})=>r.status?.type==="incomplete"&&r.status.reason==="error"?r.status.error:void 0);return i===void 0?null:g.jsx(gt.span,{...t,ref:n,children:e??String(i)})});C1.displayName="ErrorPrimitive.Message";const A1=I.forwardRef((e,t)=>g.jsx(gt.div,{...e,ref:t}));A1.displayName="ThreadPrimitive.Root";const m7=e=>te(({thread:t})=>!(e.empty===!0&&!t.isEmpty||e.empty===!1&&t.isEmpty||e.running===!0&&!t.isRunning||e.running===!1&&t.isRunning||e.disabled===!0&&!t.isDisabled||e.disabled===!1&&t.isDisabled)),ma=({children:e,...t})=>m7(t)?e:null;ma.displayName="ThreadPrimitive.If";const g7=e=>{const t=sn(e),n=I.useCallback(i=>{const r=new ResizeObserver(()=>{t()}),o=new MutationObserver(()=>{t()});return r.observe(i),o.observe(i,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{r.disconnect(),o.disconnect()}},[t]);return _u(n)},v7=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:i=!0})=>{const r=I.useRef(null),o=Fd();e===void 0&&(e=o.getState().turnAnchor!=="top");const s=I.useRef(0),a=I.useRef(null),l=I.useCallback(p=>{const m=r.current;m&&(a.current=p,m.scrollTo({top:m.scrollHeight,behavior:p}))},[]),u=()=>{const p=r.current;if(!p)return;const m=o.getState().isAtBottom,h=Math.abs(p.scrollHeight-p.scrollTop-p.clientHeight)<1||p.scrollHeight<=p.clientHeight;!h&&s.current<p.scrollTop||(h&&(a.current=null),(h||a.current===null)&&h!==m&&fa(o).setState({isAtBottom:h})),s.current=p.scrollTop},c=g7(()=>{const p=a.current;p?l(p):e&&o.getState().isAtBottom&&l("instant"),u()}),d=_u(p=>(p.addEventListener("scroll",u),()=>{p.removeEventListener("scroll",u)}));return S1(({behavior:p})=>{l(p)}),Ff("thread.run-start",()=>{t&&(a.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Ff("thread.initialize",()=>{n&&(a.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Ff("thread-list-item.switched-to",()=>{i&&(a.current="instant",requestAnimationFrame(()=>{l("instant")}))}),mt(c,d,r)},y7=()=>{const e=ca(n=>n.registerViewport),t=I.useCallback(n=>n.clientHeight,[]);return d1(e,t)},R1=I.forwardRef(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i,children:r,...o},s)=>{const a=v7({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i}),l=y7(),u=mt(s,a,l);return g.jsx(gt.div,{...o,ref:u,children:r})});R1.displayName="ThreadPrimitive.ViewportScrollable";const $1=I.forwardRef(({turnAnchor:e,...t},n)=>g.jsx(tO,{options:{turnAnchor:e},children:g.jsx(R1,{...t,ref:n})}));$1.displayName="ThreadPrimitive.Viewport";const O1=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,b7=()=>null,_7=(e,t,n)=>{switch(t){case"user":return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case"assistant":return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case"system":return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??b7;default:const i=t;throw new Error(`Unknown message role: ${i}`)}},w7=({components:e})=>{const t=te(({message:r})=>r.role),n=te(({message:r})=>r.composer.isEditing),i=_7(e,t,n);return g.jsx(i,{})},N1=I.memo(({index:e,components:t})=>g.jsx(MG,{index:e,children:g.jsx(w7,{components:t})}),(e,t)=>e.index===t.index&&O1(e.components,t.components));N1.displayName="ThreadPrimitive.MessageByIndex";const P1=({components:e})=>{const t=te(({thread:i})=>i.messages.length);return I.useMemo(()=>t===0?null:Array.from({length:t},(i,r)=>g.jsx(N1,{index:r,components:e},r)),[t,e])};P1.displayName="ThreadPrimitive.Messages";const x7=I.memo(P1,(e,t)=>O1(e.components,t.components)),S7=({behavior:e}={})=>{const t=ca(r=>r.isAtBottom),n=Fd(),i=I.useCallback(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:i},E7=ar("ThreadPrimitive.ScrollToBottom",S7,["behavior"]),I7=({prompt:e,send:t,clearComposer:n=!0,autoSend:i,method:r})=>{const o=Re(),s=te(({thread:u})=>u.isDisabled),a=t??i??!1,l=I.useCallback(()=>{const u=o.thread().getState().isRunning;if(a&&!u)o.thread().append(e),n&&o.composer().setText("");else if(n)o.composer().setText(e);else{const c=o.composer().getState().text;o.composer().setText(c.trim()?`${c} ${e}`:e)}},[o,a,n,e]);return s?null:l},T7=ar("ThreadPrimitive.Suggestion",I7,["prompt","send","clearComposer","autoSend","method"]),M1=I.forwardRef(({onClick:e,disabled:t,...n},i)=>{const r=te(({threads:s})=>s.newThreadId===s.mainThreadId),o=Re();return g.jsx(gt.button,{type:"button",...r?{"data-active":"true","aria-current":"true"}:null,...n,ref:i,disabled:t,onClick:Le(e,()=>{o.threads().switchToNewThread()})})});M1.displayName="ThreadListPrimitive.New";const j1=I.memo(({index:e,archived:t=!1,components:n})=>{const i=n.ThreadListItem;return g.jsx(NG,{index:e,archived:t,children:g.jsx(i,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);j1.displayName="ThreadListPrimitive.ItemByIndex";const D1=({archived:e=!1,components:t})=>{const n=te(({threads:r})=>e?r.archivedThreadIds.length:r.threadIds.length);return I.useMemo(()=>Array.from({length:n},(r,o)=>g.jsx(j1,{index:o,archived:e,components:t},o)),[n,e,t])};D1.displayName="ThreadListPrimitive.Items";const z1=I.forwardRef((e,t)=>g.jsx(gt.div,{...e,ref:t}));z1.displayName="ThreadListPrimitive.Root";const L1=I.forwardRef((e,t)=>{const n=te(({threads:i,threadListItem:r})=>i.mainThreadId===r.id);return g.jsx(gt.div,{...n?{"data-active":"true","aria-current":"true"}:null,...e,ref:t})});L1.displayName="ThreadListItemPrimitive.Root";const k7=()=>{const e=Re();return I.useCallback(()=>{e.threadListItem().switchTo()},[e])},C7=ar("ThreadListItemPrimitive.Trigger",k7),U1=({fallback:e})=>{const t=te(({threadListItem:n})=>n.title);return g.jsx(g.Fragment,{children:t||e})};U1.displayName="ThreadListItemPrimitive.Title";const A7=(e,t)=>{const n=I.useRef(null),i=I.useRef(null);return I.useEffect(()=>()=>{i.current?.()},[]),I.useCallback(()=>{i.current?.(),(function(){if(n.current||!e.current)return;let d=e.current;for(;d;){const{overflowY:f}=getComputedStyle(d);if(f==="scroll"||f==="auto"){n.current=d;break}d=d.parentElement}})();const o=n.current;if(!o)return;const s=o.scrollTop,a=o.style.scrollbarWidth;o.style.scrollbarWidth="none";const l=()=>o.scrollTop=s;o.addEventListener("scroll",l);const u=setTimeout(()=>{o.removeEventListener("scroll",l),o.style.scrollbarWidth=a,i.current=null},t);i.current=()=>{clearTimeout(u),o.removeEventListener("scroll",l),o.style.scrollbarWidth=a}},[t,e])},R7=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof jl.ZodType?jl.toJSONSchema(n.parameters):n.parameters}])),$7=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let sc=null;function O7(e,t){const n=F1(t);sc={helpers:e,requiresApproval:n}}function N7(){sc=null}function F1(e){if(!e)return()=>!1;if(typeof e=="function")return n=>e({toolName:n});const t=new Set(e);return n=>t.has(n)}const P7=(e,t)=>eG({...e,execute:async(n,i)=>{if(sc?.requiresApproval(t)){const{helpers:r}=sc,o=i.toolCallId??"";if(!r.isToolApproved(t)&&!await r.requestApproval(t,o,n))return{content:[{type:"text",text:`Tool "${t}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}return e.execute?.(n,i)},toolName:t});function M7(e,t,n){if(!t||Array.isArray(t)&&t.length===0)return e;const i=F1(t);return Object.fromEntries(Object.entries(e).map(([r,o])=>{if(!i(r))return[r,o];const s=o.execute;return s?[r,{...o,execute:async(a,l)=>{const u=l??{},c=u.toolCallId??"";return n.isToolApproved(r)||await n.requestApproval(r,c,a)?s(a,u):{content:[{type:"text",text:`Tool "${r}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}}]:[r,o]}))}const j7=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],D7=O.createLucideIcon("arrow-down",j7);const z7=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],L7=O.createLucideIcon("arrow-up",z7);const U7=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],F7=O.createLucideIcon("brain",U7);const B7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],qr=O.createLucideIcon("check",B7);const V7=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ac=O.createLucideIcon("chevron-down",V7);const q7=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Z7=O.createLucideIcon("chevron-left",q7);const H7=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],B1=O.createLucideIcon("chevron-right",H7);const G7=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Jv=O.createLucideIcon("copy",G7);const W7=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],J7=O.createLucideIcon("file-text",W7);const K7=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],uc=O.createLucideIcon("loader",K7);const Y7=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],X7=O.createLucideIcon("maximize",Y7);const Q7=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],eY=O.createLucideIcon("message-circle",Q7);const tY=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],nY=O.createLucideIcon("minimize",tY);const rY=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],iY=O.createLucideIcon("panel-right-close",rY);const oY=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],sY=O.createLucideIcon("panel-right-open",oY);const aY=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],uY=O.createLucideIcon("pencil",aY);const lY=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],V1=O.createLucideIcon("plus",lY);const cY=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],dY=O.createLucideIcon("settings-2",cY);const fY=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],pY=O.createLucideIcon("square",fY);const hY=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],wu=O.createLucideIcon("x",hY);var xu=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,s=new Array(t);for(let a=0;a<t;a++)s[a]=n[Math.random()*o|0];return s.join("")};if(e==null)return r;if(n.includes(i))throw new xc({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},q1=xu();function gw(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fi(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function vw(e,...t){const n=new Headers(fi(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var mY=/"__proto__"\s*:/,gY=/"constructor"\s*:/;function yw(e){const t=JSON.parse(e);return t===null||typeof t!="object"||mY.test(e)===!1&&gY.test(e)===!1?t:vY(t)}function vY(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function yY(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return yw(e)}try{return yw(e)}finally{Error.stackTraceLimit=t}}var lc=Symbol.for("vercel.ai.validator");function bY(e){return{[lc]:!0,validate:e}}function _Y(e){return typeof e=="object"&&e!==null&&lc in e&&e[lc]===!0&&"validate"in e}function wY(e){let t;return()=>(t==null&&(t=e()),t)}function xY(e){return _Y(e)?e:typeof e=="function"?e():SY(e)}function SY(e){return bY(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yr({value:t,cause:n.issues})}})}async function bw({value:e,schema:t}){const n=await Kv({value:e,schema:t});if(!n.success)throw yr.wrap({value:e,cause:n.error});return n.value}async function Kv({value:e,schema:t}){const n=xY(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:yr.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:yr.wrap({value:e,cause:i}),rawValue:e}}}async function cc({text:e,schema:t}){try{const n=yY(e);return t==null?{success:!0,value:n,rawValue:n}:await Kv({value:n,schema:t})}catch(n){return{success:!1,error:Co.isInstance(n)?n:new Co({text:e,cause:n}),rawValue:void 0}}}function EY({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gs).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await cc({text:n,schema:t}))}}))}async function ao(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}function Sl(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const n in t)t[n]=Sl(t[n])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Sl(t)):e.items=Sl(e.items)),e}var IY=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},TY=Symbol("Let zodToJsonSchema decide on which parser to use"),_w={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},kY=e=>typeof e=="string"?{..._w,name:e}:{..._w,...e};function an(){return{}}function CY(e,t){var n,i,r;const o={type:"array"};return(n=e.type)!=null&&n._def&&((r=(i=e.type)==null?void 0:i._def)==null?void 0:r.typeName)!==G.ZodAny&&(o.items=Me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function AY(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function RY(){return{type:"boolean"}}function Z1(e,t){return Me(e.type._def,t)}var $Y=(e,t)=>Me(e.innerType._def,t);function H1(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>H1(e,t,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return OY(e)}}var OY=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function NY(e,t){return{...Me(e.innerType._def,t),default:e.defaultValue()}}function PY(e,t){return t.effectStrategy==="input"?Me(e.schema._def,t):an()}function MY(e){return{type:"string",enum:Array.from(e.values)}}var jY=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function DY(e,t){const n=[Me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(jY(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:s,...a}=r;o=a}i.push(o)}}),i.length?{allOf:i}:void 0}function zY(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var tp=void 0,Tn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(tp===void 0&&(tp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function G1(e,t){const n={type:"string"};if(e.checks)for(const i of e.checks)switch(i.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"email":switch(t.emailStrategy){case"format:email":kn(n,"email",i.message,t);break;case"format:idn-email":kn(n,"idn-email",i.message,t);break;case"pattern:zod":Nt(n,Tn.email,i.message,t);break}break;case"url":kn(n,"uri",i.message,t);break;case"uuid":kn(n,"uuid",i.message,t);break;case"regex":Nt(n,i.regex,i.message,t);break;case"cuid":Nt(n,Tn.cuid,i.message,t);break;case"cuid2":Nt(n,Tn.cuid2,i.message,t);break;case"startsWith":Nt(n,RegExp(`^${np(i.value,t)}`),i.message,t);break;case"endsWith":Nt(n,RegExp(`${np(i.value,t)}$`),i.message,t);break;case"datetime":kn(n,"date-time",i.message,t);break;case"date":kn(n,"date",i.message,t);break;case"time":kn(n,"time",i.message,t);break;case"duration":kn(n,"duration",i.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"includes":{Nt(n,RegExp(np(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&kn(n,"ipv4",i.message,t),i.version!=="v4"&&kn(n,"ipv6",i.message,t);break}case"base64url":Nt(n,Tn.base64url,i.message,t);break;case"jwt":Nt(n,Tn.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&Nt(n,Tn.ipv4Cidr,i.message,t),i.version!=="v4"&&Nt(n,Tn.ipv6Cidr,i.message,t);break}case"emoji":Nt(n,Tn.emoji(),i.message,t);break;case"ulid":{Nt(n,Tn.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{kn(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Nt(n,Tn.base64,i.message,t);break}}break}case"nanoid":Nt(n,Tn.nanoid,i.message,t)}return n}function np(e,t){return t.patternStrategy==="escape"?UY(e):e}var LY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UY(e){let t="";for(let n=0;n<e.length;n++)LY.has(e[n])||(t+="\\"),t+=e[n];return t}function kn(e,t,n,i){var r;e.format||(r=e.anyOf)!=null&&r.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&i.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function Nt(e,t,n,i){var r;e.pattern||(r=e.allOf)!=null&&r.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:ww(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=ww(t,i)}function ww(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const i={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=i.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,l=!1;for(let u=0;u<r.length;u++){if(s){o+=r[u],s=!1;continue}if(i.i){if(a){if(r[u].match(/[a-z]/)){l?(o+=r[u],o+=`${r[u-2]}-${r[u]}`.toUpperCase(),l=!1):r[u+1]==="-"&&((n=r[u+2])!=null&&n.match(/[a-z]/))?(o+=r[u],l=!0):o+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){o+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(i.m){if(r[u]==="^"){o+=`(^|(?<=[\r
|
|
82
|
+
]))`;continue}else if(r[u]==="$"){o+=`($|(?=[\r
|
|
83
|
+
]))`;continue}}if(i.s&&r[u]==="."){o+=a?`${r[u]}\r
|
|
84
|
+
`:`[${r[u]}\r
|
|
85
|
+
]`;continue}o+=r[u],r[u]==="\\"?s=!0:a&&r[u]==="]"?a=!1:!a&&r[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function W1(e,t){var n,i,r,o,s,a;const l={type:"object",additionalProperties:(n=Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===G.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:u,...c}=G1(e.keyType._def,t);return{...l,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===G.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((s=e.keyType)==null?void 0:s._def.typeName)===G.ZodBranded&&e.keyType._def.type._def.typeName===G.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:u,...c}=Z1(e.keyType._def,t);return{...l,propertyNames:c}}}return l}function FY(e,t){if(t.mapStrategy==="record")return W1(e,t);const n=Me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||an(),i=Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||an();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function BY(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function VY(){return{not:an()}}function qY(){return{type:"null"}}var xh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ZY(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in xh&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const s=xh[o._def.typeName];return s&&!r.includes(s)?[...r,s]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=n.reduce((r,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...r,s];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(i.length===n.length){const r=i.filter((o,s,a)=>a.indexOf(o)===s);return{type:r.length>1?r:r[0],enum:n.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return HY(e,t)}var HY=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>Me(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function GY(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[xh[e.innerType._def.typeName],"null"]};const n=Me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function WY(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function JY(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const s in r){let a=r[s];if(a===void 0||a._def===void 0)continue;const l=YY(a),u=Me(a._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||i.push(s))}i.length&&(n.required=i);const o=KY(e,t);return o!==void 0&&(n.additionalProperties=o),n}function KY(e,t){if(e.catchall._def.typeName!=="ZodNever")return Me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function YY(e){try{return e.isOptional()}catch{return!0}}var XY=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Me(e.innerType._def,t);const i=Me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:an()},i]}:an()},QY=(e,t)=>{if(t.pipeStrategy==="input")return Me(e.in._def,t);if(t.pipeStrategy==="output")return Me(e.out._def,t);const n=Me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=Me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function eX(e,t){return Me(e.type._def,t)}function tX(e,t){const i={type:"array",uniqueItems:!0,items:Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(i.minItems=e.minSize.value),e.maxSize&&(i.maxItems=e.maxSize.value),i}function nX(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>Me(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:Me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>Me(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function rX(){return{not:an()}}function iX(){return an()}var oX=(e,t)=>Me(e.innerType._def,t),sX=(e,t,n)=>{switch(t){case G.ZodString:return G1(e,n);case G.ZodNumber:return WY(e);case G.ZodObject:return JY(e,n);case G.ZodBigInt:return AY(e);case G.ZodBoolean:return RY();case G.ZodDate:return H1(e,n);case G.ZodUndefined:return rX();case G.ZodNull:return qY();case G.ZodArray:return CY(e,n);case G.ZodUnion:case G.ZodDiscriminatedUnion:return ZY(e,n);case G.ZodIntersection:return DY(e,n);case G.ZodTuple:return nX(e,n);case G.ZodRecord:return W1(e,n);case G.ZodLiteral:return zY(e);case G.ZodEnum:return MY(e);case G.ZodNativeEnum:return BY(e);case G.ZodNullable:return GY(e,n);case G.ZodOptional:return XY(e,n);case G.ZodMap:return FY(e,n);case G.ZodSet:return tX(e,n);case G.ZodLazy:return()=>e.getter()._def;case G.ZodPromise:return eX(e,n);case G.ZodNaN:case G.ZodNever:return VY();case G.ZodEffects:return PY(e,n);case G.ZodAny:return an();case G.ZodUnknown:return iX();case G.ZodDefault:return NY(e,n);case G.ZodBranded:return Z1(e,n);case G.ZodReadonly:return oX(e,n);case G.ZodCatch:return $Y(e,n);case G.ZodPipeline:return QY(e,n);case G.ZodFunction:case G.ZodVoid:case G.ZodSymbol:return;default:return(i=>{})()}};function Me(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const l=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(l!==TY)return l}if(r&&!n){const l=aX(r,t);if(l!==void 0)return l}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=sX(e,e.typeName,t),a=typeof s=="function"?Me(s(),t):s;if(a&&uX(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return o.jsonSchema=a,l}return o.jsonSchema=a,a}var aX=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:IY(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),an()):t.$refStrategy==="seen"?an():void 0}},uX=(e,t,n)=>(e.description&&(n.description=e.description),n),lX=e=>{const t=kY(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([i,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}},cX=(e,t)=>{var n;const i=lX(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,d])=>{var f;return{...u,[c]:(f=Me(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:an()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=(n=Me(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:an(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a);const l=o===void 0?r?{...s,[i.definitionPath]:r}:s:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:s}};return l.$schema="http://json-schema.org/draft-07/schema#",l},dX=cX;function fX(e,t){var n;const i=(n=void 0)!=null?n:!1;return Kd(()=>dX(e,{$refStrategy:i?"root":"none"}),{validate:async r=>{const o=await e.safeParseAsync(r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function pX(e,t){var n;const i=(n=void 0)!=null?n:!1;return Kd(()=>Sl(Vc(e,{target:"draft-7",io:"input",reused:i?"ref":"inline"})),{validate:async r=>{const o=await qc(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function hX(e){return"_zod"in e}function J1(e,t){return hX(e)?pX(e):fX(e)}var Sh=Symbol.for("vercel.ai.schema");function Kd(e,{validate:t}={}){return{[Sh]:!0,_type:void 0,[lc]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function mX(e){return typeof e=="object"&&e!==null&&Sh in e&&e[Sh]===!0&&"jsonSchema"in e&&"validate"in e}function gX(e){return e==null?Kd({properties:{},additionalProperties:!1}):mX(e)?e:typeof e=="function"?e():J1(e)}var vX=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Si="1.9.0",xw=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function yX(e){var t=new Set([e]),n=new Set,i=e.match(xw);if(!i)return function(){return!1};var r={major:+i[1],minor:+i[2],patch:+i[3],prerelease:i[4]};if(r.prerelease!=null)return function(l){return l===e};function o(a){return n.add(a),!1}function s(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var u=l.match(xw);if(!u)return o(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||r.major!==c.major?o(l):r.major===0?r.minor===c.minor&&r.patch<=c.patch?s(l):o(l):r.minor<=c.minor?s(l):o(l)}}var bX=yX(Si),_X=Si.split(".")[0],ga=Symbol.for("opentelemetry.js.api."+_X),va=vX;function Yv(e,t,n,i){var r;i===void 0&&(i=!1);var o=va[ga]=(r=va[ga])!==null&&r!==void 0?r:{version:Si};if(!i&&o[e]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(s.stack||s.message),!1}if(o.version!==Si){var s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+Si);return n.error(s.stack||s.message),!1}return o[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Si+"."),!0}function ya(e){var t,n,i=(t=va[ga])===null||t===void 0?void 0:t.version;if(!(!i||!bX(i)))return(n=va[ga])===null||n===void 0?void 0:n[e]}function Xv(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Si+".");var n=va[ga];n&&delete n[e]}var wX=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o},xX=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},SX=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return _s("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return _s("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return _s("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return _s("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return _s("verbose",this._namespace,t)},e})();function _s(e,t,n){var i=ya("diag");if(i)return n.unshift(t),i[e].apply(i,xX([],wX(n),!1))}var Jt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Jt||(Jt={}));function EX(e,t){e<Jt.NONE?e=Jt.NONE:e>Jt.ALL&&(e=Jt.ALL),t=t||{};function n(i,r){var o=t[i];return typeof o=="function"&&e>=r?o.bind(t):function(){}}return{error:n("error",Jt.ERROR),warn:n("warn",Jt.WARN),info:n("info",Jt.INFO),debug:n("debug",Jt.DEBUG),verbose:n("verbose",Jt.VERBOSE)}}var IX=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o},TX=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},kX="diag",dc=(function(){function e(){function t(r){return function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=ya("diag");if(a)return a[r].apply(a,TX([],IX(o),!1))}}var n=this,i=function(r,o){var s,a,l;if(o===void 0&&(o={logLevel:Jt.INFO}),r===n){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((s=u.stack)!==null&&s!==void 0?s:u.message),!1}typeof o=="number"&&(o={logLevel:o});var c=ya("diag"),d=EX((a=o.logLevel)!==null&&a!==void 0?a:Jt.INFO,r);if(c&&!o.suppressOverrideMessage){var f=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+f),d.warn("Current logger will overwrite one already registered from "+f)}return Yv("diag",d,n,!0)};n.setLogger=i,n.disable=function(){Xv(kX,n)},n.createComponentLogger=function(r){return new SX(r)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function CX(e){return Symbol.for(e)}var AX=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(i){return n._currentContext.get(i)},n.setValue=function(i,r){var o=new e(n._currentContext);return o._currentContext.set(i,r),o},n.deleteValue=function(i){var r=new e(n._currentContext);return r._currentContext.delete(i),r}}return e})(),RX=new AX,$X=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o},OX=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},NX=(function(){function e(){}return e.prototype.active=function(){return RX},e.prototype.with=function(t,n,i){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return n.call.apply(n,OX([i],$X(r),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),PX=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o},MX=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},rp="context",jX=new NX,K1=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yv(rp,t,dc.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,i){for(var r,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return(r=this._getContextManager()).with.apply(r,MX([t,n,i],PX(o),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return ya(rp)||jX},e.prototype.disable=function(){this._getContextManager().disable(),Xv(rp,dc.instance())},e})(),Eh;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Eh||(Eh={}));var Y1="0000000000000000",X1="00000000000000000000000000000000",DX={traceId:X1,spanId:Y1,traceFlags:Eh.NONE},Bs=(function(){function e(t){t===void 0&&(t=DX),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),Qv=CX("OpenTelemetry Context Key SPAN");function ey(e){return e.getValue(Qv)||void 0}function zX(){return ey(K1.getInstance().active())}function ty(e,t){return e.setValue(Qv,t)}function LX(e){return e.deleteValue(Qv)}function UX(e,t){return ty(e,new Bs(t))}function Q1(e){var t;return(t=ey(e))===null||t===void 0?void 0:t.spanContext()}var FX=/^([0-9a-f]{32})$/i,BX=/^[0-9a-f]{16}$/i;function VX(e){return FX.test(e)&&e!==X1}function qX(e){return BX.test(e)&&e!==Y1}function eN(e){return VX(e.traceId)&&qX(e.spanId)}function ZX(e){return new Bs(e)}var ip=K1.getInstance(),tN=(function(){function e(){}return e.prototype.startSpan=function(t,n,i){i===void 0&&(i=ip.active());var r=!!n?.root;if(r)return new Bs;var o=i&&Q1(i);return HX(o)&&eN(o)?new Bs(o):new Bs},e.prototype.startActiveSpan=function(t,n,i,r){var o,s,a;if(!(arguments.length<2)){arguments.length===2?a=n:arguments.length===3?(o=n,a=i):(o=n,s=i,a=r);var l=s??ip.active(),u=this.startSpan(t,o,l),c=ty(l,u);return ip.with(c,a,void 0,u)}},e})();function HX(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var GX=new tN,WX=(function(){function e(t,n,i,r){this._provider=t,this.name=n,this.version=i,this.options=r}return e.prototype.startSpan=function(t,n,i){return this._getTracer().startSpan(t,n,i)},e.prototype.startActiveSpan=function(t,n,i,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):GX},e})(),JX=(function(){function e(){}return e.prototype.getTracer=function(t,n,i){return new tN},e})(),KX=new JX,Sw=(function(){function e(){}return e.prototype.getTracer=function(t,n,i){var r;return(r=this.getDelegateTracer(t,n,i))!==null&&r!==void 0?r:new WX(this,t,n,i)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:KX},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,n,i)},e})(),fc;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(fc||(fc={}));var op="trace",YX=(function(){function e(){this._proxyTracerProvider=new Sw,this.wrapSpanContext=ZX,this.isSpanContextValid=eN,this.deleteSpan=LX,this.getSpan=ey,this.getActiveSpan=zX,this.getSpanContext=Q1,this.setSpan=ty,this.setSpanContext=UX}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Yv(op,this._proxyTracerProvider,dc.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return ya(op)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Xv(op,dc.instance()),this._proxyTracerProvider=new Sw},e})(),XX=YX.getInstance(),QX=Object.defineProperty,eQ=(e,t)=>{for(var n in t)QX(e,n,{get:t[n],enumerable:!0})},nN="AI_NoObjectGeneratedError",rN=`vercel.ai.error.${nN}`,tQ=Symbol.for(rN),iN,Ew=class extends fe{constructor({message:t="No object generated.",cause:n,text:i,response:r,usage:o,finishReason:s}){super({name:nN,message:t,cause:n}),this[iN]=!0,this.text=i,this.response=r,this.usage=o,this.finishReason=s}static isInstance(t){return fe.hasMarker(t,rN)}};iN=tQ;var Iw="5.0.116",oN=le([T(),er(Uint8Array),er(ArrayBuffer),Qa(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]),ba=Ya(()=>le([Ga(),T(),ee(),De(),nn(T(),ba),J(ba)])),nt=nn(T(),nn(T(),ba)),sN=N({type:F("text"),text:T(),providerOptions:nt.optional()}),nQ=N({type:F("image"),image:le([oN,er(URL)]),mediaType:T().optional(),providerOptions:nt.optional()}),aN=N({type:F("file"),data:le([oN,er(URL)]),filename:T().optional(),mediaType:T(),providerOptions:nt.optional()}),rQ=N({type:F("reasoning"),text:T(),providerOptions:nt.optional()}),iQ=N({type:F("tool-call"),toolCallId:T(),toolName:T(),input:Je(),providerOptions:nt.optional(),providerExecuted:De().optional()}),oQ=fd("type",[N({type:F("text"),value:T()}),N({type:F("json"),value:ba}),N({type:F("error-text"),value:T()}),N({type:F("error-json"),value:ba}),N({type:F("content"),value:J(le([N({type:F("text"),text:T()}),N({type:F("media"),data:T(),mediaType:T()})]))})]),uN=N({type:F("tool-result"),toolCallId:T(),toolName:T(),output:oQ,providerOptions:nt.optional()}),sQ=N({role:F("system"),content:T(),providerOptions:nt.optional()}),aQ=N({role:F("user"),content:le([T(),J(le([sN,nQ,aN]))]),providerOptions:nt.optional()}),uQ=N({role:F("assistant"),content:le([T(),J(le([sN,aN,rQ,iQ,uN]))]),providerOptions:nt.optional()}),lQ=N({role:F("tool"),content:J(uN),providerOptions:nt.optional()});le([sQ,aQ,uQ,lQ]);xu({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
86
|
+
|
|
87
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
88
|
+
|
|
89
|
+
`)}})}});var cQ=wY(()=>J1(le([He({type:F("text-start"),id:T(),providerMetadata:nt.optional()}),He({type:F("text-delta"),id:T(),delta:T(),providerMetadata:nt.optional()}),He({type:F("text-end"),id:T(),providerMetadata:nt.optional()}),He({type:F("error"),errorText:T()}),He({type:F("tool-input-start"),toolCallId:T(),toolName:T(),providerExecuted:De().optional(),dynamic:De().optional()}),He({type:F("tool-input-delta"),toolCallId:T(),inputTextDelta:T()}),He({type:F("tool-input-available"),toolCallId:T(),toolName:T(),input:Je(),providerExecuted:De().optional(),providerMetadata:nt.optional(),dynamic:De().optional()}),He({type:F("tool-input-error"),toolCallId:T(),toolName:T(),input:Je(),providerExecuted:De().optional(),providerMetadata:nt.optional(),dynamic:De().optional(),errorText:T()}),He({type:F("tool-output-available"),toolCallId:T(),output:Je(),providerExecuted:De().optional(),dynamic:De().optional(),preliminary:De().optional()}),He({type:F("tool-output-error"),toolCallId:T(),errorText:T(),providerExecuted:De().optional(),dynamic:De().optional()}),He({type:F("reasoning-start"),id:T(),providerMetadata:nt.optional()}),He({type:F("reasoning-delta"),id:T(),delta:T(),providerMetadata:nt.optional()}),He({type:F("reasoning-end"),id:T(),providerMetadata:nt.optional()}),He({type:F("source-url"),sourceId:T(),url:T(),title:T().optional(),providerMetadata:nt.optional()}),He({type:F("source-document"),sourceId:T(),mediaType:T(),title:T(),filename:T().optional(),providerMetadata:nt.optional()}),He({type:F("file"),url:T(),mediaType:T(),providerMetadata:nt.optional()}),He({type:Qa(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:T().optional(),data:Je(),transient:De().optional()}),He({type:F("start-step")}),He({type:F("finish-step")}),He({type:F("start"),messageId:T().optional(),messageMetadata:Je().optional()}),He({type:F("finish"),finishReason:ni(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Je().optional()}),He({type:F("abort")}),He({type:F("message-metadata"),messageMetadata:Je()})])));function dQ(e){return e.type.startsWith("data-")}function lN(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const r=t[i];if(r===void 0)continue;const o=i in e?e[i]:void 0,s=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);s&&a?n[i]=lN(o,r):n[i]=r}return n}function fQ(e){const t=["ROOT"];let n=-1,i=null;function r(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,i=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":r(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?a+="true".slice(c.length):"false".startsWith(c)?a+="false".slice(c.length):"null".startsWith(c)&&(a+="null".slice(c.length))}}return a}async function cN(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await cc({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await cc({text:fQ(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function So(e){return e.type.startsWith("tool-")}function pQ(e){return e.type==="dynamic-tool"}function Tw(e){return So(e)||pQ(e)}function kw(e){return e.type.split("-").slice(1).join("-")}function hQ({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function mQ({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:s}){return e.pipeThrough(new TransformStream({async transform(a,l){await i(async({state:u,write:c})=>{var d,f,p,m;function h(b){const _=u.message.parts.filter(So).find(k=>k.toolCallId===b);if(_==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return _}function v(b){const _=u.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===b);if(_==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return _}function y(b){var C;const _=u.message.parts.find(M=>So(M)&&M.toolCallId===b.toolCallId),k=b,R=_;_!=null?(_.state=b.state,R.input=k.input,R.output=k.output,R.errorText=k.errorText,R.rawInput=k.rawInput,R.preliminary=k.preliminary,R.providerExecuted=(C=k.providerExecuted)!=null?C:_.providerExecuted,k.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(b){var C,_;const k=u.message.parts.find(U=>U.type==="dynamic-tool"&&U.toolCallId===b.toolCallId),R=b,M=k;k!=null?(k.state=b.state,M.toolName=b.toolName,M.input=R.input,M.output=R.output,M.errorText=R.errorText,M.rawInput=(C=R.rawInput)!=null?C:M.rawInput,M.preliminary=R.preliminary,M.providerExecuted=(_=R.providerExecuted)!=null?_:k.providerExecuted,R.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=R.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function S(b){if(b!=null){const C=u.message.metadata!=null?lN(u.message.metadata,b):b;t!=null&&await bw({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const b={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=b,u.message.parts.push(b),c();break}case"text-delta":{const b=u.activeTextParts[a.id];b.text+=a.delta,b.providerMetadata=(d=a.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=u.activeTextParts[a.id];b.state="done",b.providerMetadata=(f=a.providerMetadata)!=null?f:b.providerMetadata,delete u.activeTextParts[a.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=b,u.message.parts.push(b),c();break}case"reasoning-delta":{const b=u.activeReasoningParts[a.id];b.text+=a.delta,b.providerMetadata=(p=a.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=u.activeReasoningParts[a.id];b.providerMetadata=(m=a.providerMetadata)!=null?m:b.providerMetadata,b.state="done",delete u.activeReasoningParts[a.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),c();break}case"tool-input-start":{const b=u.message.parts.filter(So);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:b.length,dynamic:a.dynamic},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),c();break}case"tool-input-delta":{const b=u.partialToolCalls[a.toolCallId];b.text+=a.inputTextDelta;const{value:C}=await cN(b.text);b.dynamic?w({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}):y({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}),c();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),c(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),c();break}case"tool-output-available":{if(a.dynamic){const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:a.output,preliminary:a.preliminary})}else{const b=h(a.toolCallId);y({toolCallId:a.toolCallId,toolName:kw(b),state:"output-available",input:b.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}c();break}case"tool-output-error":{if(a.dynamic){const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const b=h(a.toolCallId);y({toolCallId:a.toolCallId,toolName:kw(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await S(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&c();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await S(a.messageMetadata),a.messageMetadata!=null&&c();break}case"message-metadata":{await S(a.messageMetadata),a.messageMetadata!=null&&c();break}case"error":{r?.(new Error(a.errorText));break}default:if(dQ(a)){n?.[a.type]!=null&&await bw({value:a.data,schema:n[a.type]});const b=a;if(b.transient){s?.(b);break}const C=b.id!=null?u.message.parts.find(_=>b.type===_.type&&b.id===_.id):void 0;C!=null?C.data=b.data:u.message.parts.push(b),s?.(b),c()}}l.enqueue(a)})}}))}async function gQ({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:i}=await n.read();if(i)break}}catch(i){t?.(i)}finally{n.releaseLock()}}xu({prefix:"aitxt",size:24});xu({prefix:"aiobj",size:24});var vQ=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(i){n(i)}}),this.processQueue()})}};xu({prefix:"aiobj",size:24});var yQ={};eQ(yQ,{object:()=>_Q,text:()=>bQ});var bQ=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),_Q=({schema:e})=>{const t=gX(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await cN(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value};default:{const r=i.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},i){const r=await cc({text:n});if(!r.success)throw new Ew({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});const o=await Kv({value:r.value,schema:t});if(!o.success)throw new Ew({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return o.value}}};async function wQ(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:i}=t,r=await new Promise((o,s)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>s(l),a.readAsDataURL(t)});return{type:"file",mediaType:i,filename:n,url:r}}))}var xQ=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:i,fetch:r,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=i,this.fetch=r,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,i,r,o,s;const a=await ao(this.body),l=await ao(this.headers),u=await ao(this.credentials),c={...fi(l),...fi(t.headers)},d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:c,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(i=d?.api)!=null?i:this.api,p=d?.headers!==void 0?fi(d.headers):c,m=d?.body!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},h=(r=d?.credentials)!=null?r:u,y=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:vw({"Content-Type":"application/json",...p},`ai-sdk/${Iw}`,gw()),body:JSON.stringify(m),credentials:h,signal:e});if(!y.ok)throw new Error((s=await y.text())!=null?s:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,i,r,o;const s=await ao(this.body),a=await ao(this.headers),l=await ao(this.credentials),u={...fi(a),...fi(e.headers)},c=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...s,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),d=(n=c?.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=c?.headers!==void 0?fi(c.headers):u,p=(i=c?.credentials)!=null?i:l,h=await((r=this.fetch)!=null?r:globalThis.fetch)(d,{method:"GET",headers:vw(f,`ai-sdk/${Iw}`,gw()),credentials:p});if(h.status===204)return null;if(!h.ok)throw new Error((o=await h.text())!=null?o:"Failed to fetch the chat response.");if(!h.body)throw new Error("The response body is empty.");return this.processResponseStream(h.body)}},dN=class extends xQ{constructor(e={}){super(e)}processResponseStream(e){return EY({stream:e,schema:cQ}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},SQ=class{constructor({generateId:e=q1,id:t=e(),transport:n=new dN,messageMetadataSchema:i,dataPartSchemas:r,state:o,onError:s,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new vQ,this.sendMessage=async(d,f)=>{var p,m,h,v;if(d==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...f});return}let y;if("text"in d||"files"in d?y={parts:[...Array.isArray(d.files)?d.files:await wQ(d.files),..."text"in d&&d.text!=null?[{type:"text",text:d.text}]:[]]}:y=d,d.messageId!=null){const w=this.state.messages.findIndex(S=>S.id===d.messageId);if(w===-1)throw new Error(`message with id ${d.messageId} not found`);if(this.state.messages[w].role!=="user")throw new Error(`message with id ${d.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,w+1),this.state.replaceMessage(w,{...y,id:d.messageId,role:(m=y.role)!=null?m:"user",metadata:d.metadata})}else this.state.pushMessage({...y,id:(h=y.id)!=null?h:this.generateId(),role:(v=y.role)!=null?v:"user",metadata:d.metadata});await this.makeRequest({trigger:"submit-message",messageId:d.messageId,...f})},this.regenerate=async({messageId:d,...f}={})=>{const p=d==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===d);if(p===-1)throw new Error(`message ${d} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:d,...f})},this.resumeStream=async(d={})=>{await this.makeRequest({trigger:"resume-stream",...d})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:d="output-available",tool:f,toolCallId:p,output:m,errorText:h})=>this.jobExecutor.run(async()=>{var v,y;const w=this.state.messages,S=w[w.length-1];this.state.replaceMessage(w.length-1,{...S,parts:S.parts.map(b=>Tw(b)&&b.toolCallId===p?{...b,state:d,output:m,errorText:h}:b)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(b=>Tw(b)&&b.toolCallId===p?{...b,state:d,output:m,errorText:h}:b)),this.status!=="streaming"&&this.status!=="submitted"&&((v=this.sendAutomaticallyWhen)!=null&&v.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var d;this.status!=="streaming"&&this.status!=="submitted"||(d=this.activeResponse)!=null&&d.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=i,this.dataPartSchemas=r,this.state=o,this.onError=s,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:i,messageId:r}){var o,s,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let c=!1,d=!1,f=!1;try{const p={state:hQ({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{c=!0}),this.activeResponse=p;let m;if(e==="resume-stream"){const v=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:i});if(v==null){this.setStatus({status:"ready"});return}m=v}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:i,trigger:e,messageId:r});const h=v=>this.jobExecutor.run(()=>v({state:p.state,write:()=>{var y;this.setStatus({status:"streaming"}),p.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await gQ({stream:mQ({stream:m,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:h,onError:v=>{throw v}}),onError:v=>{throw v}}),this.setStatus({status:"ready"})}catch(p){if(c||p.name==="AbortError")return c=!0,this.setStatus({status:"ready"}),null;f=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(s=this.onFinish)==null||s.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,isDisconnect:d,isError:f,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:i})}};const Cw=(e,t)=>{if(t==null)return[];let n=e.findIndex(i=>i.id===t);if(n===-1)throw new Error("useVercelAIThreadState: Message not found. This is likely an internal bug in assistant-ui.");for(;e[n+1]?.role==="assistant";)n++;return e.slice(0,n+1)},Aw=e=>{const n=[...e.content.filter(i=>i.type!=="file"),...e.attachments?.flatMap(i=>i.content.map(r=>({...r,filename:i.name})))??[]].map(i=>{switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"file",url:i.image,...i.filename&&{filename:i.filename},mediaType:"image/png"};case"file":return{type:"file",url:i.data,mediaType:i.mimeType,...i.filename&&{filename:i.filename}};default:throw new Error(`Unsupported part type: ${i.type}`)}});return{role:e.role,parts:n}},EQ=e=>new Promise((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=r=>n(r),i.readAsDataURL(e)}),IQ={accept:"image/*, text/plain, text/html, text/markdown, text/csv, text/xml, text/json, text/css",async add({file:e}){return{id:q1(),type:e.type.startsWith("image/")?"image":"file",name:e.name,file:e,contentType:e.type,content:[],status:{type:"requires-action",reason:"composer-send"}}},async send(e){return{...e,status:{type:"complete"},content:[{type:"file",mimeType:e.contentType,filename:e.name,data:await EQ(e.file)}]}},async remove(){}},Rw=e=>Ti(e);function TQ(e){return e.replace(/[}\]"]+$/,"")}const sp=(e,t)=>!e.parts||e.parts.length===0?[]:e.parts.filter(n=>n.type!=="step-start"&&n.type!=="file").map(n=>{const i=n.type;if(i==="text")return{type:"text",text:n.text};if(i==="reasoning")return{type:"reasoning",text:n.text};if(So(n)){const r=i.replace("tool-",""),o=n.toolCallId;let s={},a,l=!1;n.state==="input-streaming"||n.state==="input-available"?s=n.input||{}:n.state==="output-available"?(s=n.input||{},a=n.output):n.state==="output-error"&&(s=n.input||{},l=!0,a={error:n.errorText});let u=JSON.stringify(s);n.state==="input-streaming"&&(u=TQ(u));const c=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:u,args:s,result:a,isError:l,...c?.type==="interrupt"&&{interrupt:c.payload,status:{type:"requires-action",reason:"interrupt"}}}}if(i==="dynamic-tool"){const r=n.toolName,o=n.toolCallId;let s={},a,l=!1;n.state==="input-streaming"||n.state==="input-available"?s=n.input||{}:n.state==="output-available"?(s=n.input||{},a=n.output):n.state==="output-error"&&(s=n.input||{},l=!0,a={error:n.errorText});const u=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:JSON.stringify(s),args:s,result:a,isError:l,...u?.type==="interrupt"&&{interrupt:u.payload,status:{type:"requires-action",reason:"interrupt"}}}}return i==="source-url"?{type:"source",sourceType:"url",id:n.sourceId,url:n.url,title:n.title||""}:i==="source-document"?(console.warn(`Source document part type ${i} is not yet supported in conversion`),null):i.startsWith("data-")?{type:"data",name:i.substring(5),data:n.data}:(console.warn(`Unsupported message part type: ${i}`),null)}).filter(Boolean),$w=FG((e,t)=>{const n=new Date;switch(e.role){case"user":return{role:"user",id:e.id,createdAt:n,content:sp(e,t),attachments:e.parts?.filter(i=>i.type==="file").map((i,r)=>({id:r.toString(),type:i.mediaType.startsWith("image/")?"image":"file",name:i.filename??"file",content:[i.mediaType.startsWith("image/")?{type:"image",image:i.url,filename:i.filename}:{type:"file",filename:i.filename,data:i.url,mimeType:i.mediaType}],contentType:i.mediaType??"unknown/unknown",status:{type:"complete"}}))};case"system":return{role:"system",id:e.id,createdAt:n,content:sp(e,t)};case"assistant":return{role:"assistant",id:e.id,createdAt:n,content:sp(e,t),metadata:{unstable_annotations:e.annotations,unstable_data:Array.isArray(e.data)?e.data:e.data?[e.data]:void 0,custom:{}}};default:return console.warn(`Unsupported message role: ${e.role}`),[]}}),kQ={format:"ai-sdk/v5",encode({message:{id:e,parts:t,...n}}){return{...n,parts:t.filter(i=>i.type!=="file")}},decode(e){return{parentId:e.parent_id,message:{id:e.id,...e.content}}},getId(e){return e.id}},{MessageRepository:CQ}=aO,AQ=(e,t)=>({headId:t.headId,messages:t.messages.map(n=>{const i=e([n.message])[0];return{...n,message:i}})}),RQ=(e,t,n,i,r)=>{const o=I.useRef(!1),s=Re(),a=I.useCallback(()=>s.threadListItem.source?s.threadListItem():null,[s]),[l,u]=I.useState(!1),c=I.useRef(new Set),d=I.useRef(()=>r);return I.useEffect(()=>{d.current=r}),I.useEffect(()=>{if(!t||o.current)return;const f=async()=>{u(!0);try{const p=await t.withFormat?.(i).load();if(p&&p.messages.length>0){const m=AQ(n,p);e.current.thread.import(m);const h=new CQ;h.import(m);const v=h.getMessages();d.current(v.map(Ti).flat()),c.current=new Set(m.messages.map(y=>y.message.id))}}catch(p){console.error("Failed to load message history:",p)}finally{u(!1)}};if(!o.current){if(o.current=!0,!a()?.getState().remoteId){u(!1);return}f()}},[s,t,i,n,e,a]),I.useEffect(()=>e.current.thread.subscribe(async()=>{const{messages:f,isRunning:p}=e.current.thread.getState();if(!p)for(let m=0;m<f.length;m++){const h=f[m];if(h.status===void 0||h.status.type==="complete"||h.status.type==="incomplete"){if(c.current.has(h.id))continue;c.current.add(h.id);const v=m>0?f[m-1].id:null;await t?.withFormat?.(i).append({parentId:v,message:Ti(h)[0]})}}}),[t,i,e]),l},$Q=(e,{adapters:t,toCreateMessage:n,cancelPendingToolCallsOnSend:i=!0}={})=>{const r=N$(),[o,s]=I.useState({}),a=Object.values(o).some(h=>h?.type==="executing"),l=e.status==="submitted"||e.status==="streaming"||a,u=$w.useThreadMessages({isRunning:l,messages:e.messages,metadata:I.useMemo(()=>({toolStatuses:o,...e.error&&{error:e.error.message}}),[o,e.error])}),[c]=I.useState(()=>({get current(){return m}})),d=M$({state:{messages:u,isRunning:l},getTools:()=>c.current.thread.getModelContext().tools,onResult:h=>{h.type==="add-tool-result"&&e.addToolResult({tool:h.toolName,toolCallId:h.toolCallId,output:h.result})},setToolStatuses:s}),f=RQ(c,t?.history??r?.history,$w.toThreadMessages,kQ,h=>{e.setMessages(h)}),p=async()=>{i&&(await d.abort(),e.setMessages(h=>{const v=h.at(-1);if(v?.role!=="assistant")return h;let y=!1;const w=v.parts?.map(S=>!So(S)||S.state==="output-available"||S.state==="output-error"?S:(y=!0,{...S,state:"output-error",errorText:"User cancelled tool call by sending a new message."}));return y?[...h.slice(0,-1),{...v,parts:w}]:h}))},m=j9({isRunning:l,messages:u,setMessages:h=>e.setMessages(h.map(Rw).filter(Boolean).flat()),onImport:h=>e.setMessages(h.map(Rw).filter(Boolean).flat()),onCancel:async()=>{e.stop(),await d.abort()},onNew:async h=>{await p();const v=(n??Aw)(h);await e.sendMessage(v,{metadata:h.runConfig})},onEdit:async h=>{const v=Cw(e.messages,h.parentId);e.setMessages(v);const y=(n??Aw)(h);await e.sendMessage(y,{metadata:h.runConfig})},onReload:async(h,v)=>{const y=Cw(e.messages,h);e.setMessages(y),await e.regenerate({metadata:v.runConfig})},onAddToolResult:({toolCallId:h,result:v,isError:y})=>{y?e.addToolOutput({state:"output-error",tool:h,toolCallId:h,errorText:typeof v=="string"?v:JSON.stringify(v)}):e.addToolOutput({state:"output-available",tool:h,toolCallId:h,output:v})},onResumeToolCall:h=>d.resume(h.toolCallId,h.payload),adapters:{attachments:IQ,...r,...t},isLoading:f});return m};var ap,Ow;function OQ(){if(Ow)return ap;Ow=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let i,r=0;return function(...s){clearTimeout(i);const a=Date.now(),l=a-r,u=n-l;u<=0?(r=a,t.apply(this,s)):i=setTimeout(()=>{r=Date.now(),t.apply(this,s)},u)}}return ap=e,ap}var NQ=OQ();const PQ=mu(NQ);var nl={exports:{}},up={};var Nw;function MQ(){if(Nw)return up;Nw=1;var e=I;function t(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var n=typeof Object.is=="function"?Object.is:t,i=e.useState,r=e.useEffect,o=e.useLayoutEffect,s=e.useDebugValue;function a(d,f){var p=f(),m=i({inst:{value:p,getSnapshot:f}}),h=m[0].inst,v=m[1];return o(function(){h.value=p,h.getSnapshot=f,l(h)&&v({inst:h})},[d,p,f]),r(function(){return l(h)&&v({inst:h}),d(function(){l(h)&&v({inst:h})})},[d]),s(p),p}function l(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!n(d,p)}catch{return!0}}function u(d,f){return f()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:a;return up.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,up}var lp={};var Pw;function jQ(){return Pw||(Pw=1,process.env.NODE_ENV!=="production"&&(function(){function e(p,m){return p===m&&(p!==0||1/p===1/m)||p!==p&&m!==m}function t(p,m){c||r.startTransition===void 0||(c=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var h=m();if(!d){var v=m();o(h,v)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),d=!0)}v=s({inst:{value:h,getSnapshot:m}});var y=v[0].inst,w=v[1];return l(function(){y.value=h,y.getSnapshot=m,n(y)&&w({inst:y})},[p,h,m]),a(function(){return n(y)&&w({inst:y}),p(function(){n(y)&&w({inst:y})})},[p]),u(h),h}function n(p){var m=p.getSnapshot;p=p.value;try{var h=m();return!o(p,h)}catch{return!0}}function i(p,m){return m()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=I,o=typeof Object.is=="function"?Object.is:e,s=r.useState,a=r.useEffect,l=r.useLayoutEffect,u=r.useDebugValue,c=!1,d=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?i:t;lp.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:f,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),lp}var Mw;function DQ(){return Mw||(Mw=1,process.env.NODE_ENV==="production"?nl.exports=MQ():nl.exports=jQ()),nl.exports}var zQ=DQ(),fN=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Ge=(e,t,n)=>(fN(e,t,"read from private field"),n?n.call(e):t.get(e)),Zn=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},jr=(e,t,n,i)=>(fN(e,t,"write to private field"),t.set(e,n),n);function LQ(e,t){return t!=null?PQ(e,t):e}var gn,El,Il,Rs,$s,Os,fo,Ih,Th,UQ=class{constructor(e=[]){Zn(this,gn,void 0),Zn(this,El,"ready"),Zn(this,Il,void 0),Zn(this,Rs,new Set),Zn(this,$s,new Set),Zn(this,Os,new Set),this.pushMessage=t=>{jr(this,gn,Ge(this,gn).concat(t)),Ge(this,fo).call(this)},this.popMessage=()=>{jr(this,gn,Ge(this,gn).slice(0,-1)),Ge(this,fo).call(this)},this.replaceMessage=(t,n)=>{jr(this,gn,[...Ge(this,gn).slice(0,t),this.snapshot(n),...Ge(this,gn).slice(t+1)]),Ge(this,fo).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const i=n?LQ(t,n):t;return Ge(this,Rs).add(i),()=>{Ge(this,Rs).delete(i)}},this["~registerStatusCallback"]=t=>(Ge(this,$s).add(t),()=>{Ge(this,$s).delete(t)}),this["~registerErrorCallback"]=t=>(Ge(this,Os).add(t),()=>{Ge(this,Os).delete(t)}),Zn(this,fo,()=>{Ge(this,Rs).forEach(t=>t())}),Zn(this,Ih,()=>{Ge(this,$s).forEach(t=>t())}),Zn(this,Th,()=>{Ge(this,Os).forEach(t=>t())}),jr(this,gn,e)}get status(){return Ge(this,El)}set status(e){jr(this,El,e),Ge(this,Ih).call(this)}get error(){return Ge(this,Il)}set error(e){jr(this,Il,e),Ge(this,Th).call(this)}get messages(){return Ge(this,gn)}set messages(e){jr(this,gn,[...e]),Ge(this,fo).call(this)}};gn=new WeakMap;El=new WeakMap;Il=new WeakMap;Rs=new WeakMap;$s=new WeakMap;Os=new WeakMap;fo=new WeakMap;Ih=new WeakMap;Th=new WeakMap;var po,jw=class extends SQ{constructor({messages:t,...n}){const i=new UQ(t);super({...n,state:i}),Zn(this,po,void 0),this["~registerMessagesCallback"]=(r,o)=>Ge(this,po)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>Ge(this,po)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Ge(this,po)["~registerErrorCallback"](r),jr(this,po,i)}};po=new WeakMap;function FQ({experimental_throttle:e,resume:t=!1,...n}={}){const i=I.useRef("chat"in n?n.chat:new jw(n));("chat"in n&&n.chat!==i.current||"id"in n&&i.current.id!==n.id)&&(i.current="chat"in n?n.chat:new jw(n));const o=I.useCallback(c=>i.current["~registerMessagesCallback"](c,e),[e,i.current.id]),s=I.useSyncExternalStore(o,()=>i.current.messages,()=>i.current.messages),a=I.useSyncExternalStore(i.current["~registerStatusCallback"],()=>i.current.status,()=>i.current.status),l=I.useSyncExternalStore(i.current["~registerErrorCallback"],()=>i.current.error,()=>i.current.error),u=I.useCallback(c=>{typeof c=="function"&&(c=c(i.current.messages)),i.current.messages=c},[i]);return I.useEffect(()=>{t&&i.current.resumeStream()},[t,i]),{id:i.current.id,messages:s,setMessages:u,sendMessage:i.current.sendMessage,regenerate:i.current.regenerate,clearError:i.current.clearError,stop:i.current.stop,error:l,resumeStream:i.current.resumeStream,status:a,addToolResult:i.current.addToolOutput,addToolOutput:i.current.addToolOutput}}const BQ=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof jl.ZodType?jl.toJSONSchema(n.parameters):n.parameters}])),VQ=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));class Dw extends dN{runtime;constructor(t){super({...t,prepareSendMessagesRequest:async n=>{const i=this.runtime?.thread.getModelContext(),r=(await this.runtime?.threads.mainItem.initialize())?.remoteId??n.id,o={...n,body:{callSettings:i?.callSettings,system:i?.system,tools:BQ(VQ(i?.tools??{})),...n?.body}},s=await t?.prepareSendMessagesRequest?.(o);return{...s,body:s?.body??{...o.body,id:r,messages:n.messages,trigger:n.trigger,messageId:n.messageId,metadata:n.requestMetadata}}}})}setRuntime(t){this.runtime=t}}const qQ=e=>{const t=I.useRef(e);return I.useEffect(()=>{t.current=e}),I.useMemo(()=>new Proxy(t.current,{get(i,r){const o=t.current[r];return typeof o=="function"?o.bind(t.current):o}}),[])},ZQ=e=>{const{adapters:t,transport:n,toCreateMessage:i,...r}=e??{},o=qQ(n??new Dw),s=te(({threadListItem:u})=>u.id),a=FQ({...r,id:s,transport:o}),l=$Q(a,{adapters:t,...i&&{toCreateMessage:i}});return o instanceof Dw&&o.setRuntime(l),l},pN=({cloud:e,...t}={})=>{const n=rW({cloud:e});return uO({runtimeHook:function(){return ZQ(t)},adapter:n,allowNesting:!0})},HQ=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,inputSchema:Kd(n.parameters)}]));var GQ=Object.defineProperty,WQ=Object.defineProperties,JQ=Object.getOwnPropertyDescriptors,zw=Object.getOwnPropertySymbols,KQ=Object.prototype.hasOwnProperty,YQ=Object.prototype.propertyIsEnumerable,Lw=(e,t,n)=>t in e?GQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pe=(e,t)=>{for(var n in t||(t={}))KQ.call(t,n)&&Lw(e,n,t[n]);if(zw)for(var n of zw(t))YQ.call(t,n)&&Lw(e,n,t[n]);return e},pc=(e,t)=>WQ(e,JQ(t)),hN="vercel.ai.error",XQ=Symbol.for(hN),mN,QQ=class gN extends Error{constructor({name:t,message:n,cause:i}){super(n),this[mN]=!0,this.name=t,this.cause=i}static isInstance(t){return gN.hasMarker(t,hN)}static hasMarker(t,n){const i=Symbol.for(n);return t!=null&&typeof t=="object"&&i in t&&typeof t[i]=="boolean"&&t[i]===!0}};mN=XQ;var at=QQ,vN="AI_APICallError",yN=`vercel.ai.error.${vN}`,eee=Symbol.for(yN),bN,Pn=class extends at{constructor({message:e,url:t,requestBodyValues:n,statusCode:i,responseHeaders:r,responseBody:o,cause:s,isRetryable:a=i!=null&&(i===408||i===409||i===429||i>=500),data:l}){super({name:vN,message:e,cause:s}),this[bN]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=i,this.responseHeaders=r,this.responseBody=o,this.isRetryable=a,this.data=l}static isInstance(e){return at.hasMarker(e,yN)}};bN=eee;var _N="AI_EmptyResponseBodyError",wN=`vercel.ai.error.${_N}`,tee=Symbol.for(wN),xN,nee=class extends at{constructor({message:e="Empty response body"}={}){super({name:_N,message:e}),this[xN]=!0}static isInstance(e){return at.hasMarker(e,wN)}};xN=tee;function SN(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var EN="AI_InvalidArgumentError",IN=`vercel.ai.error.${EN}`,ree=Symbol.for(IN),TN,kN=class extends at{constructor({message:t,cause:n,argument:i}){super({name:EN,message:t,cause:n}),this[TN]=!0,this.argument=i}static isInstance(t){return at.hasMarker(t,IN)}};TN=ree;var CN="AI_InvalidPromptError",AN=`vercel.ai.error.${CN}`,iee=Symbol.for(AN),RN,oee=class extends at{constructor({prompt:e,message:t,cause:n}){super({name:CN,message:`Invalid prompt: ${t}`,cause:n}),this[RN]=!0,this.prompt=e}static isInstance(e){return at.hasMarker(e,AN)}};RN=iee;var $N="AI_InvalidResponseDataError",ON=`vercel.ai.error.${$N}`,see=Symbol.for(ON),NN,ws=class extends at{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:$N,message:t}),this[NN]=!0,this.data=e}static isInstance(e){return at.hasMarker(e,ON)}};NN=see;var PN="AI_JSONParseError",MN=`vercel.ai.error.${PN}`,aee=Symbol.for(MN),jN,hc=class extends at{constructor({text:e,cause:t}){super({name:PN,message:`JSON parsing failed: Text: ${e}.
|
|
90
|
+
Error message: ${SN(t)}`,cause:t}),this[jN]=!0,this.text=e}static isInstance(e){return at.hasMarker(e,MN)}};jN=aee;var DN="AI_LoadAPIKeyError",zN=`vercel.ai.error.${DN}`,uee=Symbol.for(zN),LN,rl=class extends at{constructor({message:e}){super({name:DN,message:e}),this[LN]=!0}static isInstance(e){return at.hasMarker(e,zN)}};LN=uee;var UN="AI_NoContentGeneratedError",FN=`vercel.ai.error.${UN}`,lee=Symbol.for(FN),BN,VN=class extends at{constructor({message:e="No content generated."}={}){super({name:UN,message:e}),this[BN]=!0}static isInstance(e){return at.hasMarker(e,FN)}};BN=lee;var qN="AI_TypeValidationError",ZN=`vercel.ai.error.${qN}`,cee=Symbol.for(ZN),HN,dee=class kh extends at{constructor({value:t,cause:n}){super({name:qN,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
91
|
+
Error message: ${SN(n)}`,cause:n}),this[HN]=!0,this.value=t}static isInstance(t){return at.hasMarker(t,ZN)}static wrap({value:t,cause:n}){return kh.isInstance(n)&&n.value===t?n:new kh({value:t,cause:n})}};HN=cee;var _a=dee,GN="AI_UnsupportedFunctionalityError",WN=`vercel.ai.error.${GN}`,fee=Symbol.for(WN),JN,Dr=class extends at{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:GN,message:t}),this[JN]=!0,this.functionality=e}static isInstance(e){return at.hasMarker(e,WN)}};JN=fee;var Uw=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function cp(e){}function pee(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=cp,onError:n=cp,onRetry:i=cp,onComment:r}=e;let o="",s=!0,a,l="",u="";function c(h){const v=s?h.replace(/^\xEF\xBB\xBF/,""):h,[y,w]=hee(`${o}${v}`);for(const S of y)d(S);o=w,s=!1}function d(h){if(h===""){p();return}if(h.startsWith(":")){r&&r(h.slice(h.startsWith(": ")?2:1));return}const v=h.indexOf(":");if(v!==-1){const y=h.slice(0,v),w=h[v+1]===" "?2:1,S=h.slice(v+w);f(y,S,h);return}f(h,"",h)}function f(h,v,y){switch(h){case"event":u=v;break;case"data":l=`${l}${v}
|
|
92
|
+
`;break;case"id":a=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?i(parseInt(v,10)):n(new Uw(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:y}));break;default:n(new Uw(`Unknown field "${h.length>20?`${h.slice(0,20)}…`:h}"`,{type:"unknown-field",field:h,value:v,line:y}));break}}function p(){l.length>0&&t({id:a,event:u||void 0,data:l.endsWith(`
|
|
93
|
+
`)?l.slice(0,-1):l}),a=void 0,l="",u=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",u="",o=""}return{feed:c,reset:m}}function hee(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
94
|
+
`,i);let s=-1;if(r!==-1&&o!==-1?s=Math.min(r,o):r!==-1?s=r:o!==-1&&(s=o),s===-1){n=e.slice(i);break}else{const a=e.slice(i,s);t.push(a),i=s+1,e[i-1]==="\r"&&e[i]===`
|
|
95
|
+
`&&i++}}return[t,n]}var mee=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let i;super({start(r){i=pee({onEvent:o=>{r.enqueue(o)},onError(o){e==="terminate"?r.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:n})},transform(r){i.feed(r)}})}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wa(...e){return e.reduce((t,n)=>Pe(Pe({},t),n??{}),{})}function Yd(e){return Object.fromEntries([...e.headers])}var gee=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,s=new Array(t);for(let a=0;a<t;a++)s[a]=n[Math.random()*o|0];return s.join("")};if(e==null)return r;if(n.includes(i))throw new kN({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},Rn=gee();function Ch(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var vee=["fetch failed","failed to fetch"];function yee({error:e,url:t,requestBodyValues:n}){if(Ch(e))return e;if(e instanceof TypeError&&vee.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new Pn({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function bee(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function _ee({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:i}){if(typeof e=="string")return e;if(e!=null)throw new rl({message:`${i} API key must be a string.`});if(typeof process>"u")throw new rl({message:`${i} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new rl({message:`${i} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new rl({message:`${i} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var wee=/"__proto__"\s*:/,xee=/"constructor"\s*:/;function See(e){const t=JSON.parse(e);return t===null||typeof t!="object"||wee.test(e)===!1&&xee.test(e)===!1?t:Eee(t)}function Eee(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function ny(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return See(e)}finally{Error.stackTraceLimit=t}}var Ah=Symbol.for("vercel.ai.validator");function Iee(e){return{[Ah]:!0,validate:e}}function Tee(e){return typeof e=="object"&&e!==null&&Ah in e&&e[Ah]===!0&&"validate"in e}function kee(e){return Tee(e)?e:Cee(e)}function Cee(e){return Iee(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new _a({value:t,cause:n.issues})}})}async function Aee({value:e,schema:t}){const n=await KN({value:e,schema:t});if(!n.success)throw _a.wrap({value:e,cause:n.error});return n.value}async function KN({value:e,schema:t}){const n=kee(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:_a.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:_a.wrap({value:e,cause:i}),rawValue:e}}}async function Ree({text:e,schema:t}){try{const n=ny(e);return t==null?n:Aee({value:n,schema:t})}catch(n){throw hc.isInstance(n)||_a.isInstance(n)?n:new hc({text:e,cause:n})}}async function YN({text:e,schema:t}){try{const n=ny(e);return t==null?{success:!0,value:n,rawValue:n}:await KN({value:n,schema:t})}catch(n){return{success:!1,error:hc.isInstance(n)?n:new hc({text:e,cause:n}),rawValue:void 0}}}function dp(e){try{return ny(e),!0}catch{return!1}}function $ee({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new mee).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await YN({text:n,schema:t}))}}))}var Oee=()=>globalThis.fetch,xa=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:s})=>Nee({url:e,headers:Pe({"Content-Type":"application/json"},t),body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:s}),Nee=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:s=Oee()})=>{try{const a=await s(e,{method:"POST",headers:bee(t),body:n.content,signal:o}),l=Yd(a);if(!a.ok){let u;try{u=await r({response:a,url:e,requestBodyValues:n.values})}catch(c){throw Ch(c)||Pn.isInstance(c)?c:new Pn({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await i({response:a,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Ch(u)||Pn.isInstance(u))?u:new Pn({message:"Failed to process successful response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(a){throw yee({error:a,url:e,requestBodyValues:n.values})}},Pee=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const s=await i.text(),a=Yd(i);if(s.trim()==="")return{responseHeaders:a,value:new Pn({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,isRetryable:n?.(i)})};try{const l=await Ree({text:s,schema:e});return{responseHeaders:a,value:new Pn({message:t(l),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,data:l,isRetryable:n?.(i,l)})}}catch{return{responseHeaders:a,value:new Pn({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,isRetryable:n?.(i)})}}},XN=e=>async({response:t})=>{const n=Yd(t);if(t.body==null)throw new nee({});return{responseHeaders:n,value:$ee({stream:t.body,schema:e})}},ry=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await YN({text:r,schema:e}),s=Yd(t);if(!o.success)throw new Pn({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:s,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},{btoa:Mee}=globalThis;function jee(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Mee(t)}function Dee(e){return e?.replace(/\/$/,"")}function fp(e){return e!=null}var QN=(e=>(e.Unknown="unknown",e.OpenAIResponsesV1="openai-responses-v1",e.XAIResponsesV1="xai-responses-v1",e.AnthropicClaudeV1="anthropic-claude-v1",e.GoogleGeminiV1="google-gemini-v1",e))(QN||{}),iy=N({id:T().nullish(),format:ni(QN).nullish(),index:ee().optional()}).loose(),zee=N({type:F("reasoning.summary"),summary:T()}).extend(iy.shape),Lee=N({type:F("reasoning.encrypted"),data:T()}).extend(iy.shape),Uee=N({type:F("reasoning.text"),text:T().nullish(),signature:T().nullish()}).extend(iy.shape),oy=le([zee,Lee,Uee]),Tl=le([oy,Je().transform(()=>null)]),sy=J(Tl).transform(e=>e.filter(t=>!!t));le([N({delta:N({reasoning_details:J(Tl)})}).transform(e=>e.delta.reasoning_details.filter(fp)),N({message:N({reasoning_details:J(Tl)})}).transform(e=>e.message.reasoning_details.filter(fp)),N({text:T(),reasoning_details:J(Tl)}).transform(e=>e.reasoning_details.filter(fp))]);var Xd=N({error:N({code:le([T(),ee()]).nullable().optional().default(null),message:T(),type:T().nullable().optional().default(null),param:lt().nullable().optional().default(null)}).passthrough()}).passthrough(),Sa=Pee({errorSchema:Xd,errorToMessage:e=>e.error.message}),eP=N({type:F("file"),file:N({hash:T(),name:T(),content:J(N({type:T(),text:T().optional()}).catchall(lt())).optional()}).catchall(lt())}).catchall(lt()),Fee=N({provider:T(),reasoning_details:J(oy).optional(),annotations:J(eP).optional(),usage:N({promptTokens:ee(),promptTokensDetails:N({cachedTokens:ee()}).catchall(lt()).optional(),completionTokens:ee(),completionTokensDetails:N({reasoningTokens:ee()}).catchall(lt()).optional(),totalTokens:ee(),cost:ee().optional(),costDetails:N({upstreamInferenceCost:ee()}).catchall(lt()).optional()}).catchall(lt())}).catchall(lt()),Fw=N({openrouter:N({reasoning_details:J(oy).optional(),annotations:J(eP).optional()}).optional()}).optional();function mc(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Bee=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function ay({url:e,protocols:t}){try{const n=new URL(e);return t.has(n.protocol)}catch{return!1}}function Rh({part:e,defaultMediaType:t}){var n,i;if(e.data instanceof Uint8Array){const o=jee(e.data);return`data:${(n=e.mediaType)!=null?n:t};base64,${o}`}const r=e.data.toString();return ay({url:r,protocols:new Set(["http:","https:"])})||r.startsWith("data:")?r:`data:${(i=e.mediaType)!=null?i:t};base64,${r}`}function Bw(e,t){var n;const i=e.match(/^data:([^;]+)/);return i&&(n=i[1])!=null?n:t}function $h(e){const t=e.match(/^data:[^;]*;base64,(.+)$/);return t?t[1]:e}var Vee={mpeg:"mp3",mp3:"mp3","x-wav":"wav",wave:"wav",wav:"wav",ogg:"ogg",vorbis:"ogg",aac:"aac","x-aac":"aac",m4a:"m4a","x-m4a":"m4a",mp4:"m4a",aiff:"aiff","x-aiff":"aiff",flac:"flac","x-flac":"flac",pcm16:"pcm16",pcm24:"pcm24"};function qee(e){const t=Rh({part:e,defaultMediaType:"audio/mpeg"});if(ay({url:t,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
96
|
+
|
|
97
|
+
OpenRouter requires audio to be base64-encoded. Please:
|
|
98
|
+
1. Download the audio file locally
|
|
99
|
+
2. Read it as a Buffer or Uint8Array
|
|
100
|
+
3. Pass it as the data parameter
|
|
101
|
+
|
|
102
|
+
The AI SDK will automatically handle base64 encoding.
|
|
103
|
+
|
|
104
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=$h(t),i=e.mediaType||"audio/mpeg",r=i.replace("audio/",""),o=Vee[r];if(o===void 0){const s=Bee.join(", ");throw new Error(`Unsupported audio format: "${i}"
|
|
105
|
+
|
|
106
|
+
OpenRouter supports the following audio formats: ${s}
|
|
107
|
+
|
|
108
|
+
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:n,format:o}}function Nr(e){var t,n,i;const r=e?.anthropic,o=e?.openrouter;return(i=(n=(t=o?.cacheControl)!=null?t:o?.cache_control)!=null?n:r?.cacheControl)!=null?i:r?.cache_control}function Zee(e){var t,n,i,r,o,s,a,l,u,c;const d=[];for(const{role:f,content:p,providerOptions:m}of e)switch(f){case"system":{d.push({role:"system",content:p,cache_control:Nr(m)});break}case"user":{if(p.length===1&&((t=p[0])==null?void 0:t.type)==="text"){const y=(n=Nr(m))!=null?n:Nr(p[0].providerOptions),w=y?[{type:"text",text:p[0].text,cache_control:y}]:p[0].text;d.push({role:"user",content:w});break}const h=Nr(m),v=p.map(y=>{var w,S,b,C,_,k,R;const M=(w=Nr(y.providerOptions))!=null?w:h;switch(y.type){case"text":return{type:"text",text:y.text,cache_control:M};case"file":{if((S=y.mediaType)!=null&&S.startsWith("image/"))return{type:"image_url",image_url:{url:Rh({part:y,defaultMediaType:"image/jpeg"})},cache_control:M};if((b=y.mediaType)!=null&&b.startsWith("audio/"))return{type:"input_audio",input_audio:qee(y),cache_control:M};const U=String((R=(k=(_=(C=y.providerOptions)==null?void 0:C.openrouter)==null?void 0:_.filename)!=null?k:y.filename)!=null?R:""),z=Rh({part:y,defaultMediaType:"application/pdf"});return ay({url:z,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:U,file_data:z}}:{type:"file",file:{filename:U,file_data:z},cache_control:M}}default:return{type:"text",text:"",cache_control:M}}});d.push({role:"user",content:v});break}case"assistant":{let h="",v="";const y=[],w=[];for(const k of p)switch(k.type){case"text":{h+=k.text;break}case"tool-call":{const R=(i=k.providerOptions)==null?void 0:i.openrouter;R?.reasoning_details&&Array.isArray(R.reasoning_details)&&w.push(...R.reasoning_details),y.push({id:k.toolCallId,type:"function",function:{name:k.toolName,arguments:JSON.stringify(k.input)}});break}case"reasoning":{v+=k.text;const R=Fw.safeParse(k.providerOptions);R.success&&((o=(r=R.data)==null?void 0:r.openrouter)!=null&&o.reasoning_details)&&w.push(...R.data.openrouter.reasoning_details);break}}const S=Fw.safeParse(m),b=S.success?(a=(s=S.data)==null?void 0:s.openrouter)==null?void 0:a.reasoning_details:void 0,C=S.success?(u=(l=S.data)==null?void 0:l.openrouter)==null?void 0:u.annotations:void 0,_=b&&Array.isArray(b)&&b.length>0?b:w.length>0?w:void 0;d.push({role:"assistant",content:h,tool_calls:y.length>0?y:void 0,reasoning:v||void 0,reasoning_details:_,annotations:C,cache_control:Nr(m)});break}case"tool":{for(const h of p){const v=Hee(h);d.push({role:"tool",tool_call_id:h.toolCallId,content:v,cache_control:(c=Nr(m))!=null?c:Nr(h.providerOptions)})}break}}return d}function Hee(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}le([F("auto"),F("none"),F("required"),N({type:F("function"),function:N({name:T()})})]);function Gee(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new kN({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var Wee=N({type:F("image_url"),image_url:N({url:T()}).passthrough()}).passthrough(),Jee=le([Wee,Je().transform(()=>null)]),tP=J(Jee).transform(e=>e.filter(t=>!!t)),nP=N({id:T().optional(),model:T().optional(),provider:T().optional(),usage:N({prompt_tokens:ee(),prompt_tokens_details:N({cached_tokens:ee()}).passthrough().nullish(),completion_tokens:ee(),completion_tokens_details:N({reasoning_tokens:ee()}).passthrough().nullish(),total_tokens:ee(),cost:ee().optional(),cost_details:N({upstream_inference_cost:ee().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Kee=le([nP.extend({choices:J(N({message:N({role:F("assistant"),content:T().nullable().optional(),reasoning:T().nullable().optional(),reasoning_details:sy.nullish(),images:tP.nullish(),tool_calls:J(N({id:T().optional().nullable(),type:F("function"),function:N({name:T(),arguments:T()}).passthrough()}).passthrough()).optional(),annotations:J(le([N({type:F("url_citation"),url_citation:N({end_index:ee(),start_index:ee(),title:T(),url:T(),content:T().optional()}).passthrough()}).passthrough(),N({type:F("file_annotation"),file_annotation:N({file_id:T(),quote:T().optional()}).passthrough()}).passthrough(),N({type:F("file"),file:N({hash:T(),name:T(),content:J(N({type:T(),text:T().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:ee().nullish(),logprobs:N({content:J(N({token:T(),logprob:ee(),top_logprobs:J(N({token:T(),logprob:ee()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:T().optional().nullable()}).passthrough())}),Xd.extend({user_id:T().optional()})]),Yee=le([nP.extend({choices:J(N({delta:N({role:ni(["assistant"]).optional(),content:T().nullish(),reasoning:T().nullish().optional(),reasoning_details:sy.nullish(),images:tP.nullish(),tool_calls:J(N({index:ee().nullish(),id:T().nullish(),type:F("function").optional(),function:N({name:T().nullish(),arguments:T().nullish()}).passthrough()}).passthrough()).nullish(),annotations:J(le([N({type:F("url_citation"),url_citation:N({end_index:ee(),start_index:ee(),title:T(),url:T(),content:T().optional()}).passthrough()}).passthrough(),N({type:F("file_annotation"),file_annotation:N({file_id:T(),quote:T().optional()}).passthrough()}).passthrough(),N({type:F("file"),file:N({hash:T(),name:T(),content:J(N({type:T(),text:T().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:N({content:J(N({token:T(),logprob:ee(),top_logprobs:J(N({token:T(),logprob:ee()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:T().nullable().optional(),index:ee().nullish()}).passthrough())}),Xd]),Xee=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:i,frequencyPenalty:r,presencePenalty:o,seed:s,stopSequences:a,responseFormat:l,topK:u,tools:c,toolChoice:d}){var f;const p=Pe(Pe({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:i,frequency_penalty:r,presence_penalty:o,seed:s,stop:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:Pe({schema:l.schema,strict:!0,name:(f=l.name)!=null?f:"response"},l.description&&{description:l.description})}:{type:"json_object"}:void 0,top_k:u,messages:Zee(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug},this.config.extraBody),this.settings.extraBody);if(c&&c.length>0){const m=c.filter(h=>h.type==="function").map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.inputSchema}}));return pc(Pe({},p),{tools:m,tool_choice:d?Gee(d):void 0})}return p}async doGenerate(e){var t,n,i,r,o,s,a,l,u,c,d,f,p,m,h,v,y,w,S,b,C,_,k;const M=(e.providerOptions||{}).openrouter||{},U=Pe(Pe({},this.getArgs(e)),M),{value:z,responseHeaders:Z}=await xa({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:wa(this.config.headers(),e.headers),body:U,failedResponseHandler:Sa,successfulResponseHandler:ry(Kee),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in z){const H=z.error;throw new Pn({message:H.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:U,statusCode:200,responseHeaders:Z,data:H})}const W=z,j=W.choices[0];if(!j)throw new VN({message:"No choice in response"});const L=W.usage?{inputTokens:(t=W.usage.prompt_tokens)!=null?t:0,outputTokens:(n=W.usage.completion_tokens)!=null?n:0,totalTokens:((i=W.usage.prompt_tokens)!=null?i:0)+((r=W.usage.completion_tokens)!=null?r:0),reasoningTokens:(s=(o=W.usage.completion_tokens_details)==null?void 0:o.reasoning_tokens)!=null?s:0,cachedInputTokens:(l=(a=W.usage.prompt_tokens_details)==null?void 0:a.cached_tokens)!=null?l:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},Y=(u=j.message.reasoning_details)!=null?u:[],ne=Y.length>0?Y.map(H=>{switch(H.type){case"reasoning.text":{if(H.text)return{type:"reasoning",text:H.text,providerMetadata:{openrouter:{reasoning_details:[H]}}};break}case"reasoning.summary":{if(H.summary)return{type:"reasoning",text:H.summary,providerMetadata:{openrouter:{reasoning_details:[H]}}};break}case"reasoning.encrypted":{if(H.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[H]}}};break}}return null}).filter(H=>H!==null):j.message.reasoning?[{type:"reasoning",text:j.message.reasoning}]:[],Q=[];if(Q.push(...ne),j.message.content&&Q.push({type:"text",text:j.message.content}),j.message.tool_calls)for(const H of j.message.tool_calls)Q.push({type:"tool-call",toolCallId:(c=H.id)!=null?c:Rn(),toolName:H.function.name,input:H.function.arguments,providerMetadata:{openrouter:{reasoning_details:Y}}});if(j.message.images)for(const H of j.message.images)Q.push({type:"file",mediaType:Bw(H.image_url.url,"image/jpeg"),data:$h(H.image_url.url)});if(j.message.annotations)for(const H of j.message.annotations)H.type==="url_citation"&&Q.push({type:"source",sourceType:"url",id:H.url_citation.url,url:H.url_citation.url,title:H.url_citation.title,providerMetadata:{openrouter:{content:H.url_citation.content||""}}});const se=(d=j.message.annotations)==null?void 0:d.filter(H=>H.type==="file"),E=j.message.tool_calls&&j.message.tool_calls.length>0,we=Y.some(H=>H.type==="reasoning.encrypted"&&H.data),A=E&&we&&j.finish_reason==="stop"?"tool-calls":mc(j.finish_reason);return{content:Q,finishReason:A,usage:L,warnings:[],providerMetadata:{openrouter:Fee.parse({provider:(f=W.provider)!=null?f:"",reasoning_details:(p=j.message.reasoning_details)!=null?p:[],annotations:se&&se.length>0?se:void 0,usage:Pe(Pe(Pe({promptTokens:(m=L.inputTokens)!=null?m:0,completionTokens:(h=L.outputTokens)!=null?h:0,totalTokens:(v=L.totalTokens)!=null?v:0,cost:(y=W.usage)==null?void 0:y.cost},((S=(w=W.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:S.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:W.usage.prompt_tokens_details.cached_tokens}}:{}),((C=(b=W.usage)==null?void 0:b.completion_tokens_details)==null?void 0:C.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:W.usage.completion_tokens_details.reasoning_tokens}}:{}),((k=(_=W.usage)==null?void 0:_.cost_details)==null?void 0:k.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:W.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:U},response:{id:W.id,modelId:W.model,headers:Z}}}async doStream(e){var t;const i=(e.providerOptions||{}).openrouter||{},r=Pe(Pe({},this.getArgs(e)),i),{value:o,responseHeaders:s}=await xa({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:wa(this.config.headers(),e.headers),body:pc(Pe({},r),{stream:!0,stream_options:this.config.compatibility==="strict"?Pe({include_usage:!0},(t=this.settings.usage)!=null&&t.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:Sa,successfulResponseHandler:XN(Yee),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let l="other";const u={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},c={},d=[],f=[];let p=!1,m=!1,h,v,y,w;return{stream:o.pipeThrough(new TransformStream({transform(S,b){var C,_,k,R,M,U,z,Z,W,j,L,Y,ne,Q,se;if(!S.success){l="error",b.enqueue({type:"error",error:S.error});return}const E=S.value;if("error"in E){l="error",b.enqueue({type:"error",error:E.error});return}if(E.provider&&(w=E.provider),E.id&&(y=E.id,b.enqueue({type:"response-metadata",id:E.id})),E.model&&b.enqueue({type:"response-metadata",modelId:E.model}),E.usage!=null){if(u.inputTokens=E.usage.prompt_tokens,u.outputTokens=E.usage.completion_tokens,u.totalTokens=E.usage.prompt_tokens+E.usage.completion_tokens,c.promptTokens=E.usage.prompt_tokens,E.usage.prompt_tokens_details){const re=(C=E.usage.prompt_tokens_details.cached_tokens)!=null?C:0;u.cachedInputTokens=re,c.promptTokensDetails={cachedTokens:re}}if(c.completionTokens=E.usage.completion_tokens,E.usage.completion_tokens_details){const re=(_=E.usage.completion_tokens_details.reasoning_tokens)!=null?_:0;u.reasoningTokens=re,c.completionTokensDetails={reasoningTokens:re}}c.cost=E.usage.cost,c.totalTokens=E.usage.total_tokens;const H=(k=E.usage.cost_details)==null?void 0:k.upstream_inference_cost;H!=null&&(c.costDetails={upstreamInferenceCost:H})}const we=E.choices[0];if(we?.finish_reason!=null&&(l=mc(we.finish_reason)),we?.delta==null)return;const de=we.delta,A=(H,re)=>{m||(v=y||Rn(),b.enqueue({providerMetadata:re,type:"reasoning-start",id:v}),m=!0),b.enqueue({providerMetadata:re,type:"reasoning-delta",delta:H,id:v||Rn()})};if(de.reasoning_details&&de.reasoning_details.length>0){for(const re of de.reasoning_details)if(re.type==="reasoning.text"){const ie=d[d.length-1];ie?.type==="reasoning.text"?(ie.text=(ie.text||"")+(re.text||""),ie.signature=ie.signature||re.signature,ie.format=ie.format||re.format):d.push(Pe({},re))}else d.push(re);const H={openrouter:{reasoning_details:de.reasoning_details}};for(const re of de.reasoning_details)switch(re.type){case"reasoning.text":{re.text&&A(re.text,H);break}case"reasoning.encrypted":{re.data&&A("[REDACTED]",H);break}case"reasoning.summary":{re.summary&&A(re.summary,H);break}}}else de.reasoning&&A(de.reasoning);if(de.content&&(m&&!p&&(b.enqueue({type:"reasoning-end",id:v||Rn()}),m=!1),p||(h=y||Rn(),b.enqueue({type:"text-start",id:h}),p=!0),b.enqueue({type:"text-delta",delta:de.content,id:h||Rn()})),de.annotations){for(const H of de.annotations)if(H.type==="url_citation")b.enqueue({type:"source",sourceType:"url",id:H.url_citation.url,url:H.url_citation.url,title:H.url_citation.title,providerMetadata:{openrouter:{content:H.url_citation.content||""}}});else if(H.type==="file"){const re=H.file;re&&typeof re=="object"&&"hash"in re&&"name"in re&&f.push(H)}}if(de.tool_calls!=null)for(const H of de.tool_calls){const re=(R=H.index)!=null?R:a.length-1;if(a[re]==null){if(H.type!=="function")throw new ws({data:H,message:"Expected 'function' type."});if(H.id==null)throw new ws({data:H,message:"Expected 'id' to be a string."});if(((M=H.function)==null?void 0:M.name)==null)throw new ws({data:H,message:"Expected 'function.name' to be a string."});a[re]={id:H.id,type:"function",function:{name:H.function.name,arguments:(U=H.function.arguments)!=null?U:""},inputStarted:!1,sent:!1};const ke=a[re];if(ke==null)throw new ws({data:{index:re,toolCallsLength:a.length},message:`Tool call at index ${re} is missing after creation.`});((z=ke.function)==null?void 0:z.name)!=null&&((Z=ke.function)==null?void 0:Z.arguments)!=null&&dp(ke.function.arguments)&&(ke.inputStarted=!0,b.enqueue({type:"tool-input-start",id:ke.id,toolName:ke.function.name}),b.enqueue({type:"tool-input-delta",id:ke.id,delta:ke.function.arguments}),b.enqueue({type:"tool-input-end",id:ke.id}),b.enqueue({type:"tool-call",toolCallId:ke.id,toolName:ke.function.name,input:ke.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),ke.sent=!0);continue}const ie=a[re];if(ie==null)throw new ws({data:{index:re,toolCallsLength:a.length,toolCallDelta:H},message:`Tool call at index ${re} is missing during merge.`});ie.inputStarted||(ie.inputStarted=!0,b.enqueue({type:"tool-input-start",id:ie.id,toolName:ie.function.name})),((W=H.function)==null?void 0:W.arguments)!=null&&(ie.function.arguments+=(L=(j=H.function)==null?void 0:j.arguments)!=null?L:""),b.enqueue({type:"tool-input-delta",id:ie.id,delta:(Y=H.function.arguments)!=null?Y:""}),((ne=ie.function)==null?void 0:ne.name)!=null&&((Q=ie.function)==null?void 0:Q.arguments)!=null&&dp(ie.function.arguments)&&(b.enqueue({type:"tool-call",toolCallId:(se=ie.id)!=null?se:Rn(),toolName:ie.function.name,input:ie.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),ie.sent=!0)}if(de.images!=null)for(const H of de.images)b.enqueue({type:"file",mediaType:Bw(H.image_url.url,"image/jpeg"),data:$h(H.image_url.url)})},flush(S){var b;const C=a.length>0,_=d.some(R=>R.type==="reasoning.encrypted"&&R.data);if(C&&_&&l==="stop"&&(l="tool-calls"),l==="tool-calls")for(const R of a)R&&!R.sent&&(S.enqueue({type:"tool-call",toolCallId:(b=R.id)!=null?b:Rn(),toolName:R.function.name,input:dp(R.function.arguments)?R.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:d}}}),R.sent=!0);m&&S.enqueue({type:"reasoning-end",id:v||Rn()}),p&&S.enqueue({type:"text-end",id:h||Rn()});const k={usage:c};w!==void 0&&(k.provider=w),d.length>0&&(k.reasoning_details=d),f.length>0&&(k.annotations=f),S.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:{openrouter:k}})}})),warnings:[],request:{body:r},response:{headers:s}}}};function Qee({prompt:e,inputFormat:t,user:n="user",assistant:i="assistant"}){if(e.length===1&&e[0]&&e[0].role==="user"&&e[0].content.length===1&&e[0].content[0]&&e[0].content[0].type==="text")return{prompt:e[0].content[0].text};let r="";e[0]&&e[0].role==="system"&&(r+=`${e[0].content}
|
|
109
|
+
|
|
110
|
+
`,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new oee({message:`Unexpected system message in prompt: ${s}`,prompt:e});case"user":{const a=s.map(l=>{switch(l.type){case"text":return l.text;case"file":throw new Dr({functionality:"file attachments"});default:return""}}).join("");r+=`${n}:
|
|
111
|
+
${a}
|
|
112
|
+
|
|
113
|
+
`;break}case"assistant":{const a=s.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new Dr({functionality:"tool-call messages"});case"tool-result":throw new Dr({functionality:"tool-result messages"});case"reasoning":throw new Dr({functionality:"reasoning messages"});case"file":throw new Dr({functionality:"file attachments"});default:return""}}).join("");r+=`${i}:
|
|
114
|
+
${a}
|
|
115
|
+
|
|
116
|
+
`;break}case"tool":throw new Dr({functionality:"tool messages"})}return r+=`${i}:
|
|
117
|
+
`,{prompt:r}}var Vw=le([N({id:T().optional(),model:T().optional(),choices:J(N({text:T(),reasoning:T().nullish().optional(),reasoning_details:sy.nullish(),finish_reason:T().nullish(),index:ee().nullish(),logprobs:N({tokens:J(T()),token_logprobs:J(ee()),top_logprobs:J(nn(T(),ee())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:N({prompt_tokens:ee(),prompt_tokens_details:N({cached_tokens:ee()}).passthrough().nullish(),completion_tokens:ee(),completion_tokens_details:N({reasoning_tokens:ee()}).passthrough().nullish(),total_tokens:ee(),cost:ee().optional(),cost_details:N({upstream_inference_cost:ee().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),Xd]),ete=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:i,frequencyPenalty:r,presencePenalty:o,seed:s,responseFormat:a,topK:l,stopSequences:u,tools:c,toolChoice:d}){const{prompt:f}=Qee({prompt:e,inputFormat:"prompt"});if(c?.length)throw new Dr({functionality:"tools"});if(d)throw new Dr({functionality:"toolChoice"});return Pe(Pe({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:t,temperature:n,top_p:i,frequency_penalty:r,presence_penalty:o,seed:s,stop:u,response_format:a,top_k:l,prompt:f,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var t,n,i,r,o,s,a,l,u,c,d,f,p,m,h;const y=(e.providerOptions||{}).openrouter||{},w=Pe(Pe({},this.getArgs(e)),y),{value:S,responseHeaders:b}=await xa({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:wa(this.config.headers(),e.headers),body:w,failedResponseHandler:Sa,successfulResponseHandler:ry(Vw),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in S){const _=S.error;throw new Pn({message:_.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:w,statusCode:200,responseHeaders:b,data:_})}const C=S.choices[0];if(!C)throw new VN({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=C.text)!=null?t:""}],finishReason:mc(C.finish_reason),usage:{inputTokens:(i=(n=S.usage)==null?void 0:n.prompt_tokens)!=null?i:0,outputTokens:(o=(r=S.usage)==null?void 0:r.completion_tokens)!=null?o:0,totalTokens:((a=(s=S.usage)==null?void 0:s.prompt_tokens)!=null?a:0)+((u=(l=S.usage)==null?void 0:l.completion_tokens)!=null?u:0),reasoningTokens:(f=(d=(c=S.usage)==null?void 0:c.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:0,cachedInputTokens:(h=(m=(p=S.usage)==null?void 0:p.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?h:0},warnings:[],response:{headers:b}}}async doStream(e){const n=(e.providerOptions||{}).openrouter||{},i=Pe(Pe({},this.getArgs(e)),n),{value:r,responseHeaders:o}=await xa({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:wa(this.config.headers(),e.headers),body:pc(Pe({},i),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:Sa,successfulResponseHandler:XN(Vw),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="other";const a={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},l={};return{stream:r.pipeThrough(new TransformStream({transform(u,c){var d,f,p;if(!u.success){s="error",c.enqueue({type:"error",error:u.error});return}const m=u.value;if("error"in m){s="error",c.enqueue({type:"error",error:m.error});return}if(m.usage!=null){if(a.inputTokens=m.usage.prompt_tokens,a.outputTokens=m.usage.completion_tokens,a.totalTokens=m.usage.prompt_tokens+m.usage.completion_tokens,l.promptTokens=m.usage.prompt_tokens,m.usage.prompt_tokens_details){const y=(d=m.usage.prompt_tokens_details.cached_tokens)!=null?d:0;a.cachedInputTokens=y,l.promptTokensDetails={cachedTokens:y}}if(l.completionTokens=m.usage.completion_tokens,m.usage.completion_tokens_details){const y=(f=m.usage.completion_tokens_details.reasoning_tokens)!=null?f:0;a.reasoningTokens=y,l.completionTokensDetails={reasoningTokens:y}}l.cost=m.usage.cost,l.totalTokens=m.usage.total_tokens;const v=(p=m.usage.cost_details)==null?void 0:p.upstream_inference_cost;v!=null&&(l.costDetails={upstreamInferenceCost:v})}const h=m.choices[0];h?.finish_reason!=null&&(s=mc(h.finish_reason)),h?.text!=null&&c.enqueue({type:"text-delta",delta:h.text,id:Rn()})},flush(u){u.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:{openrouter:{usage:l}}})}})),response:{headers:o}}}},tte=N({prompt_tokens:ee(),total_tokens:ee(),cost:ee().optional()}),nte=N({object:F("embedding"),embedding:J(ee()),index:ee().optional()}),rte=N({id:T().optional(),object:F("list"),data:J(nte),model:T(),usage:tte.optional()}),ite=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=t,this.config=n}async doEmbed(e){var t;const{values:n,abortSignal:i,headers:r}=e,o=Pe(Pe({model:this.modelId,input:n,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:s,responseHeaders:a}=await xa({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:wa(this.config.headers(),r),body:o,failedResponseHandler:Sa,successfulResponseHandler:ry(rte),abortSignal:i,fetch:this.config.fetch});return{embeddings:s.data.map(l=>l.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,providerMetadata:(t=s.usage)!=null&&t.cost?{openrouter:{usage:{cost:s.usage.cost}}}:void 0,response:{headers:a,body:s}}}};function ote(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null))}function ste(e,...t){const n=ote(e??{}),r=[n["user-agent"]||"",...t].filter(Boolean).join(" ");return pc(Pe({},n),{"user-agent":r})}var ate="1.5.4";function rP(e={}){var t,n,i;const r=(n=Dee((t=e.baseURL)!=null?t:e.baseUrl))!=null?n:"https://openrouter.ai/api/v1",o=(i=e.compatibility)!=null?i:"compatible",s=()=>ste(Pe(Pe({Authorization:`Bearer ${_ee({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${ate}`),a=(f,p={})=>new Xee(f,p,{provider:"openrouter.chat",url:({path:m})=>`${r}${m}`,headers:s,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),l=(f,p={})=>new ete(f,p,{provider:"openrouter.completion",url:({path:m})=>`${r}${m}`,headers:s,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),u=(f,p={})=>new ite(f,p,{provider:"openrouter.embedding",url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch,extraBody:e.extraBody}),c=(f,p)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return f==="openai/gpt-3.5-turbo-instruct"?l(f,p):a(f,p)},d=(f,p)=>c(f,p);return d.languageModel=c,d.chat=a,d.completion=l,d.textEmbeddingModel=u,d.embedding=u,d}rP({compatibility:"strict"});function Oh(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function iP(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((i,r)=>{if(n?.aborted){r(qw());return}const o=setTimeout(()=>{s(),i()},e),s=()=>{clearTimeout(o),n?.removeEventListener("abort",a)},a=()=>{s(),r(qw())};n?.addEventListener("abort",a)})}function qw(){return new DOMException("Delay was aborted","AbortError")}function Su(e){return Object.fromEntries([...e.headers])}var Eu=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,s=new Array(t);for(let a=0;a<t;a++)s[a]=n[Math.random()*o|0];return s.join("")};if(e==null)return r;if(n.includes(i))throw new xc({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},ute=Eu();function oP(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Ni(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var lte=["fetch failed","failed to fetch"];function sP({error:e,url:t,requestBodyValues:n}){if(Ni(e))return e;if(e instanceof TypeError&<e.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new Dt({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function uy(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function cte(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function Qd(e,...t){const n=new Headers(cte(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var aP="3.0.16",dte=()=>globalThis.fetch,Zw=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:i,abortSignal:r,fetch:o=dte()})=>{try{const s=await o(e,{method:"GET",headers:Qd(t,`ai-sdk/provider-utils/${aP}`,uy()),signal:r}),a=Su(s);if(!s.ok){let l;try{l=await i({response:s,url:e,requestBodyValues:{}})}catch(u){throw Ni(u)||Dt.isInstance(u)?u:new Dt({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await n({response:s,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Ni(l)||Dt.isInstance(l))?l:new Dt({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(s){throw sP({error:s,url:e,requestBodyValues:{}})}};function fte({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([i,r])=>{const o=i.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:r}:{mediaTypePrefix:o.replace(/\*/,""),regexes:r}}).filter(({mediaTypePrefix:i})=>e.startsWith(i)).flatMap(({regexes:i})=>i).some(i=>i.test(t))}function kl({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var pte=/"__proto__"\s*:/,hte=/"constructor"\s*:/;function mte(e){const t=JSON.parse(e);return t===null||typeof t!="object"||pte.test(e)===!1&&hte.test(e)===!1?t:gte(t)}function gte(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function uP(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return mte(e)}finally{Error.stackTraceLimit=t}}var gc=Symbol.for("vercel.ai.validator");function vte(e){return{[gc]:!0,validate:e}}function yte(e){return typeof e=="object"&&e!==null&&gc in e&&e[gc]===!0&&"validate"in e}function ls(e){let t;return()=>(t==null&&(t=e()),t)}function bte(e){return yte(e)?e:typeof e=="function"?e():_te(e)}function _te(e){return vte(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yr({value:t,cause:n.issues})}})}async function Nh({value:e,schema:t}){const n=await ei({value:e,schema:t});if(!n.success)throw yr.wrap({value:e,cause:n.error});return n.value}async function ei({value:e,schema:t}){const n=bte(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:yr.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:yr.wrap({value:e,cause:i}),rawValue:e}}}async function wte({text:e,schema:t}){try{const n=uP(e);return t==null?n:Nh({value:n,schema:t})}catch(n){throw Co.isInstance(n)||yr.isInstance(n)?n:new Co({text:e,cause:n})}}async function Pi({text:e,schema:t}){try{const n=uP(e);return t==null?{success:!0,value:n,rawValue:n}:await ei({value:n,schema:t})}catch(n){return{success:!1,error:Co.isInstance(n)?n:new Co({text:e,cause:n}),rawValue:void 0}}}function xte({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gs).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await Pi({text:n,schema:t}))}}))}var Ste=()=>globalThis.fetch,Ph=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:s})=>Ete({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:s}),Ete=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:s=Ste()})=>{try{const a=await s(e,{method:"POST",headers:Qd(t,`ai-sdk/provider-utils/${aP}`,uy()),body:n.content,signal:o}),l=Su(a);if(!a.ok){let u;try{u=await r({response:a,url:e,requestBodyValues:n.values})}catch(c){throw Ni(c)||Dt.isInstance(c)?c:new Dt({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await i({response:a,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Ni(u)||Dt.isInstance(u))?u:new Dt({message:"Failed to process successful response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(a){throw sP({error:a,url:e,requestBodyValues:n.values})}};async function Ur(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Ea=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const s=await i.text(),a=Su(i);if(s.trim()==="")return{responseHeaders:a,value:new Dt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,isRetryable:n?.(i)})};try{const l=await wte({text:s,schema:e});return{responseHeaders:a,value:new Dt({message:t(l),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,data:l,isRetryable:n?.(i,l)})}}catch{return{responseHeaders:a,value:new Dt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:a,responseBody:s,isRetryable:n?.(i)})}}},Ite=e=>async({response:t})=>{const n=Su(t);if(t.body==null)throw new lD({});return{responseHeaders:n,value:xte({stream:t.body,schema:e})}},vc=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await Pi({text:r,schema:e}),s=Su(t);if(!o.success)throw new Dt({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:s,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},Tte=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},kte=Symbol("Let zodToJsonSchema decide on which parser to use"),Hw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Cte=e=>typeof e=="string"?{...Hw,name:e}:{...Hw,...e};function un(){return{}}function Ate(e,t){var n,i,r;const o={type:"array"};return(n=e.type)!=null&&n._def&&((r=(i=e.type)==null?void 0:i._def)==null?void 0:r.typeName)!==G.ZodAny&&(o.items=je(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function Rte(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function $te(){return{type:"boolean"}}function lP(e,t){return je(e.type._def,t)}var Ote=(e,t)=>je(e.innerType._def,t);function cP(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>cP(e,t,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Nte(e)}}var Nte=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function Pte(e,t){return{...je(e.innerType._def,t),default:e.defaultValue()}}function Mte(e,t){return t.effectStrategy==="input"?je(e.schema._def,t):un()}function jte(e){return{type:"string",enum:Array.from(e.values)}}var Dte=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function zte(e,t){const n=[je(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),je(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(Dte(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:s,...a}=r;o=a}i.push(o)}}),i.length?{allOf:i}:void 0}function Lte(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var pp=void 0,Cn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(pp===void 0&&(pp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function dP(e,t){const n={type:"string"};if(e.checks)for(const i of e.checks)switch(i.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"email":switch(t.emailStrategy){case"format:email":An(n,"email",i.message,t);break;case"format:idn-email":An(n,"idn-email",i.message,t);break;case"pattern:zod":Pt(n,Cn.email,i.message,t);break}break;case"url":An(n,"uri",i.message,t);break;case"uuid":An(n,"uuid",i.message,t);break;case"regex":Pt(n,i.regex,i.message,t);break;case"cuid":Pt(n,Cn.cuid,i.message,t);break;case"cuid2":Pt(n,Cn.cuid2,i.message,t);break;case"startsWith":Pt(n,RegExp(`^${hp(i.value,t)}`),i.message,t);break;case"endsWith":Pt(n,RegExp(`${hp(i.value,t)}$`),i.message,t);break;case"datetime":An(n,"date-time",i.message,t);break;case"date":An(n,"date",i.message,t);break;case"time":An(n,"time",i.message,t);break;case"duration":An(n,"duration",i.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"includes":{Pt(n,RegExp(hp(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&An(n,"ipv4",i.message,t),i.version!=="v4"&&An(n,"ipv6",i.message,t);break}case"base64url":Pt(n,Cn.base64url,i.message,t);break;case"jwt":Pt(n,Cn.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&Pt(n,Cn.ipv4Cidr,i.message,t),i.version!=="v4"&&Pt(n,Cn.ipv6Cidr,i.message,t);break}case"emoji":Pt(n,Cn.emoji(),i.message,t);break;case"ulid":{Pt(n,Cn.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{An(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Pt(n,Cn.base64,i.message,t);break}}break}case"nanoid":Pt(n,Cn.nanoid,i.message,t)}return n}function hp(e,t){return t.patternStrategy==="escape"?Fte(e):e}var Ute=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Fte(e){let t="";for(let n=0;n<e.length;n++)Ute.has(e[n])||(t+="\\"),t+=e[n];return t}function An(e,t,n,i){var r;e.format||(r=e.anyOf)!=null&&r.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&i.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function Pt(e,t,n,i){var r;e.pattern||(r=e.allOf)!=null&&r.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Gw(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Gw(t,i)}function Gw(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const i={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=i.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,l=!1;for(let u=0;u<r.length;u++){if(s){o+=r[u],s=!1;continue}if(i.i){if(a){if(r[u].match(/[a-z]/)){l?(o+=r[u],o+=`${r[u-2]}-${r[u]}`.toUpperCase(),l=!1):r[u+1]==="-"&&((n=r[u+2])!=null&&n.match(/[a-z]/))?(o+=r[u],l=!0):o+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){o+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(i.m){if(r[u]==="^"){o+=`(^|(?<=[\r
|
|
118
|
+
]))`;continue}else if(r[u]==="$"){o+=`($|(?=[\r
|
|
119
|
+
]))`;continue}}if(i.s&&r[u]==="."){o+=a?`${r[u]}\r
|
|
120
|
+
`:`[${r[u]}\r
|
|
121
|
+
]`;continue}o+=r[u],r[u]==="\\"?s=!0:a&&r[u]==="]"?a=!1:!a&&r[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function fP(e,t){var n,i,r,o,s,a;const l={type:"object",additionalProperties:(n=je(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===G.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:u,...c}=dP(e.keyType._def,t);return{...l,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===G.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((s=e.keyType)==null?void 0:s._def.typeName)===G.ZodBranded&&e.keyType._def.type._def.typeName===G.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:u,...c}=lP(e.keyType._def,t);return{...l,propertyNames:c}}}return l}function Bte(e,t){if(t.mapStrategy==="record")return fP(e,t);const n=je(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||un(),i=je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||un();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function Vte(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function qte(){return{not:un()}}function Zte(){return{type:"null"}}var Mh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Hte(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in Mh&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const s=Mh[o._def.typeName];return s&&!r.includes(s)?[...r,s]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=n.reduce((r,o)=>{const s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...r,s];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(i.length===n.length){const r=i.filter((o,s,a)=>a.indexOf(o)===s);return{type:r.length>1?r:r[0],enum:n.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return Gte(e,t)}var Gte=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>je(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function Wte(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Mh[e.innerType._def.typeName],"null"]};const n=je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Jte(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Kte(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const s in r){let a=r[s];if(a===void 0||a._def===void 0)continue;const l=Xte(a),u=je(a._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||i.push(s))}i.length&&(n.required=i);const o=Yte(e,t);return o!==void 0&&(n.additionalProperties=o),n}function Yte(e,t){if(e.catchall._def.typeName!=="ZodNever")return je(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Xte(e){try{return e.isOptional()}catch{return!0}}var Qte=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return je(e.innerType._def,t);const i=je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:un()},i]}:un()},ene=(e,t)=>{if(t.pipeStrategy==="input")return je(e.in._def,t);if(t.pipeStrategy==="output")return je(e.out._def,t);const n=je(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=je(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function tne(e,t){return je(e.type._def,t)}function nne(e,t){const i={type:"array",uniqueItems:!0,items:je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(i.minItems=e.minSize.value),e.maxSize&&(i.maxItems=e.maxSize.value),i}function rne(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>je(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:je(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>je(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function ine(){return{not:un()}}function one(){return un()}var sne=(e,t)=>je(e.innerType._def,t),ane=(e,t,n)=>{switch(t){case G.ZodString:return dP(e,n);case G.ZodNumber:return Jte(e);case G.ZodObject:return Kte(e,n);case G.ZodBigInt:return Rte(e);case G.ZodBoolean:return $te();case G.ZodDate:return cP(e,n);case G.ZodUndefined:return ine();case G.ZodNull:return Zte();case G.ZodArray:return Ate(e,n);case G.ZodUnion:case G.ZodDiscriminatedUnion:return Hte(e,n);case G.ZodIntersection:return zte(e,n);case G.ZodTuple:return rne(e,n);case G.ZodRecord:return fP(e,n);case G.ZodLiteral:return Lte(e);case G.ZodEnum:return jte(e);case G.ZodNativeEnum:return Vte(e);case G.ZodNullable:return Wte(e,n);case G.ZodOptional:return Qte(e,n);case G.ZodMap:return Bte(e,n);case G.ZodSet:return nne(e,n);case G.ZodLazy:return()=>e.getter()._def;case G.ZodPromise:return tne(e,n);case G.ZodNaN:case G.ZodNever:return qte();case G.ZodEffects:return Mte(e,n);case G.ZodAny:return un();case G.ZodUnknown:return one();case G.ZodDefault:return Pte(e,n);case G.ZodBranded:return lP(e,n);case G.ZodReadonly:return sne(e,n);case G.ZodCatch:return Ote(e,n);case G.ZodPipeline:return ene(e,n);case G.ZodFunction:case G.ZodVoid:case G.ZodSymbol:return;default:return(i=>{})()}};function je(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const l=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(l!==kte)return l}if(r&&!n){const l=une(r,t);if(l!==void 0)return l}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=ane(e,e.typeName,t),a=typeof s=="function"?je(s(),t):s;if(a&&lne(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return o.jsonSchema=a,l}return o.jsonSchema=a,a}var une=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Tte(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),un()):t.$refStrategy==="seen"?un():void 0}},lne=(e,t,n)=>(e.description&&(n.description=e.description),n),cne=e=>{const t=Cte(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([i,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}},dne=(e,t)=>{var n;const i=cne(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[c,d])=>{var f;return{...u,[c]:(f=je(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:un()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=(n=je(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:un(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a);const l=o===void 0?r?{...s,[i.definitionPath]:r}:s:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:s}};return l.$schema="http://json-schema.org/draft-07/schema#",l},fne=dne;function pne(e,t){var n;const i=(n=void 0)!=null?n:!1;return ly(()=>fne(e,{$refStrategy:i?"root":"none"}),{validate:async r=>{const o=await e.safeParseAsync(r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function hne(e,t){var n;const i=(n=void 0)!=null?n:!1;return ly(()=>Vc(e,{target:"draft-7",io:"output",reused:i?"ref":"inline"}),{validate:async r=>{const o=await qc(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function mne(e){return"_zod"in e}function Gi(e,t){return mne(e)?hne(e):pne(e)}var jh=Symbol.for("vercel.ai.schema");function ly(e,{validate:t}={}){return{[jh]:!0,_type:void 0,[gc]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function gne(e){return typeof e=="object"&&e!==null&&jh in e&&e[jh]===!0&&"jsonSchema"in e&&"validate"in e}function ef(e){return e==null?ly({properties:{},additionalProperties:!1}):gne(e)?e:typeof e=="function"?e():Gi(e)}var{btoa:vne,atob:yne}=globalThis;function cy(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=yne(t);return Uint8Array.from(n,i=>i.codePointAt(0))}function Dh(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return vne(t)}function bne(e){return e?.replace(/\/$/,"")}function _ne(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*wne({execute:e,input:t,options:n}){const i=e(t,n);if(_ne(i)){let r;for await(const o of i)r=o,yield{type:"preliminary",output:o};yield{type:"final",output:r}}else yield{type:"final",output:await i}}var mp,Ww;function xne(){if(Ww)return mp;Ww=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,r=(c,d)=>{for(var f in d)e(c,f,{get:d[f],enumerable:!0})},o=(c,d,f,p)=>{if(d&&typeof d=="object"||typeof d=="function")for(let m of n(d))!i.call(c,m)&&m!==f&&e(c,m,{get:()=>d[m],enumerable:!(p=t(d,m))||p.enumerable});return c},s=c=>o(e({},"__esModule",{value:!0}),c),a={};r(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>u}),mp=s(a);const l=Symbol.for("@vercel/request-context");function u(){return globalThis[l]?.get?.()??{}}return mp}var gp,Jw;function Sne(){if(Jw)return gp;Jw=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,r=(d,f)=>{for(var p in f)e(d,p,{get:f[p],enumerable:!0})},o=(d,f,p,m)=>{if(f&&typeof f=="object"||typeof f=="function")for(let h of n(f))!i.call(d,h)&&h!==p&&e(d,h,{get:()=>f[h],enumerable:!(m=t(f,h))||m.enumerable});return d},s=d=>o(e({},"__esModule",{value:!0}),d),a={};r(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>u,getVercelOidcTokenSync:()=>c}),gp=s(a);var l=xne();async function u(){return""}function c(){return""}return gp}var pP=Sne(),Ene="vercel.ai.gateway.error",vp=Symbol.for(Ene),Kw,Yw,ln=class hP extends(Yw=Error,Kw=vp,Yw){constructor({message:t,statusCode:n=500,cause:i}){super(t),this[Kw]=!0,this.statusCode=n,this.cause=i}static isInstance(t){return hP.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&vp in t&&t[vp]===!0}},mP="GatewayAuthenticationError",Ine=`vercel.ai.gateway.error.${mP}`,Xw=Symbol.for(Ine),Qw,ex,dy=class gP extends(ex=ln,Qw=Xw,ex){constructor({message:t="Authentication failed",statusCode:n=401,cause:i}={}){super({message:t,statusCode:n,cause:i}),this[Qw]=!0,this.name=mP,this.type="authentication_error"}static isInstance(t){return ln.hasMarker(t)&&Xw in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:i="Authentication failed",statusCode:r=401,cause:o}){let s;return t?s=`AI Gateway authentication failed: Invalid API key.
|
|
122
|
+
|
|
123
|
+
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
124
|
+
|
|
125
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?s=`AI Gateway authentication failed: Invalid OIDC token.
|
|
126
|
+
|
|
127
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
128
|
+
|
|
129
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:s=`AI Gateway authentication failed: No authentication provided.
|
|
130
|
+
|
|
131
|
+
Option 1 - API key:
|
|
132
|
+
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
133
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
134
|
+
|
|
135
|
+
Option 2 - OIDC token:
|
|
136
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new gP({message:s,statusCode:r,cause:o})}},vP="GatewayInvalidRequestError",Tne=`vercel.ai.gateway.error.${vP}`,tx=Symbol.for(Tne),nx,rx,kne=class extends(rx=ln,nx=tx,rx){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[nx]=!0,this.name=vP,this.type="invalid_request_error"}static isInstance(e){return ln.hasMarker(e)&&tx in e}},yP="GatewayRateLimitError",Cne=`vercel.ai.gateway.error.${yP}`,ix=Symbol.for(Cne),ox,sx,Ane=class extends(sx=ln,ox=ix,sx){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[ox]=!0,this.name=yP,this.type="rate_limit_exceeded"}static isInstance(e){return ln.hasMarker(e)&&ix in e}},bP="GatewayModelNotFoundError",Rne=`vercel.ai.gateway.error.${bP}`,ax=Symbol.for(Rne),$ne=ls(()=>Gi(N({modelId:T()}))),ux,lx,_P=class extends(lx=ln,ux=ax,lx){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:i}={}){super({message:e,statusCode:t,cause:i}),this[ux]=!0,this.name=bP,this.type="model_not_found",this.modelId=n}static isInstance(e){return ln.hasMarker(e)&&ax in e}},wP="GatewayInternalServerError",One=`vercel.ai.gateway.error.${wP}`,cx=Symbol.for(One),dx,fx,px=class extends(fx=ln,dx=cx,fx){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[dx]=!0,this.name=wP,this.type="internal_server_error"}static isInstance(e){return ln.hasMarker(e)&&cx in e}},xP="GatewayResponseError",Nne=`vercel.ai.gateway.error.${xP}`,hx=Symbol.for(Nne),mx,gx,Pne=class extends(gx=ln,mx=hx,gx){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:i,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[mx]=!0,this.name=xP,this.type="response_error",this.response=n,this.validationError=i}static isInstance(e){return ln.hasMarker(e)&&hx in e}};async function vx({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:i,authMethod:r}){const o=await ei({value:e,schema:Mne});if(!o.success)return new Pne({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:o.error,cause:i});const s=o.value,a=s.error.type,l=s.error.message;switch(a){case"authentication_error":return dy.createContextualError({apiKeyProvided:r==="api-key",oidcTokenProvided:r==="oidc",statusCode:t,cause:i});case"invalid_request_error":return new kne({message:l,statusCode:t,cause:i});case"rate_limit_exceeded":return new Ane({message:l,statusCode:t,cause:i});case"model_not_found":{const u=await ei({value:s.error.param,schema:$ne});return new _P({message:l,statusCode:t,modelId:u.success?u.value.modelId:void 0,cause:i})}case"internal_server_error":return new px({message:l,statusCode:t,cause:i});default:return new px({message:l,statusCode:t,cause:i})}}var Mne=ls(()=>Gi(N({error:N({message:T(),type:T().nullish(),param:Je().nullish(),code:le([T(),ee()]).nullish()})})));function Mi(e,t){var n;return ln.isInstance(e)?e:Dt.isInstance(e)?vx({response:jne(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):vx({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function jne(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var SP="ai-gateway-auth-method";async function Ia(e){const t=await ei({value:e[SP],schema:Dne});return t.success?t.value:void 0}var Dne=ls(()=>Gi(le([F("api-key"),F("oidc")]))),yx=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Zw({url:`${this.config.baseURL}/config`,headers:await Ur(this.config.headers()),successfulResponseHandler:vc(zne),failedResponseHandler:Ea({errorSchema:lt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Mi(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Zw({url:`${e.origin}/v1/credits`,headers:await Ur(this.config.headers()),successfulResponseHandler:vc(Lne),failedResponseHandler:Ea({errorSchema:lt(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await Mi(e)}}},zne=ls(()=>Gi(N({models:J(N({id:T(),name:T(),description:T().nullish(),pricing:N({input:T(),output:T(),input_cache_read:T().nullish(),input_cache_write:T().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:i})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...i?{cacheCreationInputTokens:i}:{}})).nullish(),specification:N({specificationVersion:F("v2"),provider:T(),modelId:T()}),modelType:ni(["language","embedding","image"]).nullish()}))}))),Lne=ls(()=>Gi(N({balance:T(),total_used:T()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),Une=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:i}=e,r=await Ur(this.config.headers());try{const{responseHeaders:o,value:s,rawValue:a}=await Ph({url:this.getUrl(),headers:Oh(r,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ur(this.config.o11yHeaders)),body:t,successfulResponseHandler:vc(lt()),failedResponseHandler:Ea({errorSchema:lt(),errorToMessage:l=>l}),...i&&{abortSignal:i},fetch:this.config.fetch});return{...s,request:{body:t},response:{headers:o,body:a},warnings:n}}catch(o){throw await Mi(o,await Ia(r))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:i}=e,r=await Ur(this.config.headers());try{const{value:o,responseHeaders:s}=await Ph({url:this.getUrl(),headers:Oh(r,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ur(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ite(lt()),failedResponseHandler:Ea({errorSchema:lt(),errorToMessage:a=>a}),...i&&{abortSignal:i},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(a){n.length>0&&a.enqueue({type:"stream-start",warnings:n})},transform(a,l){if(a.success){const u=a.value;if(u.type==="raw"&&!e.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(a.error)}})),request:{body:t},response:{headers:s}}}catch(o){throw await Mi(o,await Ia(r))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const i=n;if(i.data instanceof Uint8Array){const r=Uint8Array.from(i.data),o=Buffer.from(r).toString("base64");i.data=new URL(`data:${i.mediaType||"application/octet-stream"};base64,${o}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Fne=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:i}){var r;const o=await Ur(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:l}=await Ph({url:this.getUrl(),headers:Oh(o,t??{},this.getModelConfigHeaders(),await Ur(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...i?{providerOptions:i}:{}},successfulResponseHandler:vc(Bne),failedResponseHandler:Ea({errorSchema:lt(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:a.embeddings,usage:(r=a.usage)!=null?r:void 0,providerMetadata:a.providerMetadata,response:{headers:s,body:l}}}catch(s){throw await Mi(s,await Ia(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Bne=ls(()=>Gi(N({embeddings:J(J(ee())),usage:N({tokens:ee()}).nullish(),providerMetadata:nn(T(),nn(T(),Je())).optional()})));async function Vne(){var e;return(e=pP.getContext().headers)==null?void 0:e["x-vercel-id"]}var qne="2.0.7",Zne="0.0.1";function Hne(e={}){var t,n;let i=null,r=null;const o=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let s=0;const a=(n=bne(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const m=await Wne(e);if(m)return Qd({Authorization:`Bearer ${m.token}`,"ai-gateway-protocol-version":Zne,[SP]:m.authMethod,...e.headers},`ai-sdk/gateway/${qne}`);throw dy.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const m=kl({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),h=kl({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),v=kl({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await Vne();return{...m&&{"ai-o11y-deployment-id":m},...h&&{"ai-o11y-environment":h},...v&&{"ai-o11y-region":v},...y&&{"ai-o11y-request-id":y}}}},c=m=>new Une(m,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:u()}),d=async()=>{var m,h,v;const y=(v=(h=(m=e._internal)==null?void 0:m.currentDate)==null?void 0:h.call(m).getTime())!=null?v:Date.now();return(!i||y-s>o)&&(s=y,i=new yx({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(w=>(r=w,w)).catch(async w=>{throw await Mi(w,await Ia(await l()))})),r?Promise.resolve(r):i},f=async()=>new yx({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async m=>{throw await Mi(m,await Ia(await l()))}),p=function(m){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(m)};return p.getAvailableModels=d,p.getCredits=f,p.imageModel=m=>{throw new hD({modelId:m,modelType:"imageModel"})},p.languageModel=c,p.textEmbeddingModel=m=>new Fne(m,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:u()}),p}var Gne=Hne();async function Wne(e){const t=kl({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await pP.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Jne=Object.defineProperty,Kne=(e,t)=>{for(var n in t)Jne(e,n,{get:t[n],enumerable:!0})},EP="AI_NoOutputSpecifiedError",IP=`vercel.ai.error.${EP}`,Yne=Symbol.for(IP),TP,Xne=class extends fe{constructor({message:e="No output specified."}={}){super({name:EP,message:e}),this[TP]=!0}static isInstance(e){return fe.hasMarker(e,IP)}};TP=Yne;function Qne(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let i=`${t} The tool "${n}" is not supported by this model`;return e.details&&(i+=` - ${e.details}`),i}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var ere="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",bx=!1,tre=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}bx||(bx=!0,console.info(ere));for(const n of e)console.warn(Qne(n))}},kP="AI_InvalidArgumentError",CP=`vercel.ai.error.${kP}`,nre=Symbol.for(CP),AP,Hn=class extends fe{constructor({parameter:e,value:t,message:n}){super({name:kP,message:`Invalid argument for parameter ${e}: ${n}`}),this[AP]=!0,this.parameter=e,this.value=t}static isInstance(e){return fe.hasMarker(e,CP)}};AP=nre;var RP="AI_InvalidToolInputError",$P=`vercel.ai.error.${RP}`,rre=Symbol.for($P),OP,NP=class extends fe{constructor({toolInput:e,toolName:t,cause:n,message:i=`Invalid input for tool ${t}: ${Wo(n)}`}){super({name:RP,message:i,cause:n}),this[OP]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return fe.hasMarker(e,$P)}};OP=rre;var PP="AI_NoObjectGeneratedError",MP=`vercel.ai.error.${PP}`,ire=Symbol.for(MP),jP,_x=class extends fe{constructor({message:e="No object generated.",cause:t,text:n,response:i,usage:r,finishReason:o}){super({name:PP,message:e,cause:t}),this[jP]=!0,this.text=n,this.response=i,this.usage=r,this.finishReason=o}static isInstance(e){return fe.hasMarker(e,MP)}};jP=ire;var DP="AI_NoOutputGeneratedError",zP=`vercel.ai.error.${DP}`,ore=Symbol.for(zP),LP,sre=class extends fe{constructor({message:e="No output generated.",cause:t}={}){super({name:DP,message:e,cause:t}),this[LP]=!0}static isInstance(e){return fe.hasMarker(e,zP)}};LP=ore;var UP="AI_NoSuchToolError",FP=`vercel.ai.error.${UP}`,are=Symbol.for(FP),BP,zh=class extends fe{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:UP,message:n}),this[BP]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return fe.hasMarker(e,FP)}};BP=are;var VP="AI_ToolCallRepairError",qP=`vercel.ai.error.${VP}`,ure=Symbol.for(qP),ZP,lre=class extends fe{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Wo(e)}`}){super({name:VP,message:n,cause:e}),this[ZP]=!0,this.originalError=t}static isInstance(e){return fe.hasMarker(e,qP)}};ZP=ure;var cre=class extends fe{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},HP="AI_InvalidMessageRoleError",GP=`vercel.ai.error.${HP}`,dre=Symbol.for(GP),WP,fre=class extends fe{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:HP,message:t}),this[WP]=!0,this.role=e}static isInstance(e){return fe.hasMarker(e,GP)}};WP=dre;var JP="AI_MessageConversionError",KP=`vercel.ai.error.${JP}`,pre=Symbol.for(KP),YP,hre=class extends fe{constructor({originalMessage:e,message:t}){super({name:JP,message:t}),this[YP]=!0,this.originalMessage=e}static isInstance(e){return fe.hasMarker(e,KP)}};YP=pre;var XP="AI_DownloadError",QP=`vercel.ai.error.${XP}`,mre=Symbol.for(QP),eM,yp=class extends fe{constructor({url:e,statusCode:t,statusText:n,cause:i,message:r=i==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${i}`}){super({name:XP,message:r,cause:i}),this[eM]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return fe.hasMarker(e,QP)}};eM=mre;var tM="AI_RetryError",nM=`vercel.ai.error.${tM}`,gre=Symbol.for(nM),rM,wx=class extends fe{constructor({message:e,reason:t,errors:n}){super({name:tM,message:e}),this[rM]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return fe.hasMarker(e,nM)}};rM=gre;function iM(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new cre({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return vre().languageModel(e)}function vre(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Gne}var yre=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],bre=e=>{const t=typeof e=="string"?cy(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function _re(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?bre(e):e}function wre({data:e,signatures:t}){const n=_re(e),i=typeof n=="string"?cy(n.substring(0,Math.min(n.length,24))):n;for(const r of t)if(i.length>=r.bytesPrefix.length&&r.bytesPrefix.every((o,s)=>o===null||i[s]===o))return r.mediaType}var xre="5.0.90",Sre=async({url:e})=>{var t;const n=e.toString();try{const i=await fetch(n,{headers:Qd({},`ai-sdk/${xre}`,uy())});if(!i.ok)throw new yp({url:n,statusCode:i.status,statusText:i.statusText});return{data:new Uint8Array(await i.arrayBuffer()),mediaType:(t=i.headers.get("content-type"))!=null?t:void 0}}catch(i){throw yp.isInstance(i)?i:new yp({url:n,cause:i})}},Ere=(e=Sre)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function Ire(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var oM=le([T(),er(Uint8Array),er(ArrayBuffer),Qa(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function sM(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=Ire(e.toString());if(t==null||n==null)throw new fe({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Tre(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Dh(new Uint8Array(e)):Dh(e)}async function kre({prompt:e,supportedUrls:t,download:n=Ere()}){const i=await Are(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(r=>Cre({message:r,downloadedAssets:i}))]}function Cre({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(i=>Rre(i,t)).filter(i=>i.type!=="text"||i.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(i=>i.type!=="text"||i.text!==""||i.providerOptions!=null).map(i=>{const r=i.providerOptions;switch(i.type){case"file":{const{data:o,mediaType:s}=sM(i.data);return{type:"file",data:o,filename:i.filename,mediaType:s??i.mediaType,providerOptions:r}}case"reasoning":return{type:"reasoning",text:i.text,providerOptions:r};case"text":return{type:"text",text:i.text,providerOptions:r};case"tool-call":return{type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:r};case"tool-result":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:i.output,providerOptions:r}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(i=>({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:i.output,providerOptions:i.providerOptions})),providerOptions:e.providerOptions};default:{const i=n;throw new fre({role:i})}}}async function Are(e,t,n){const i=e.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var s;const a=(s=o.mediaType)!=null?s:o.type==="image"?"image/*":void 0;let l=o.type==="image"?o.image:o.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:a,data:l}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&fte({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:n})})),r=await t(i);return Object.fromEntries(r.map((o,s)=>o==null?null:[i[s].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function Rre(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let i;const r=e.type;switch(r){case"image":i=e.image;break;case"file":i=e.data;break;default:throw new Error(`Unsupported part type: ${r}`)}const{data:o,mediaType:s}=sM(i);let a=s??e.mediaType,l=o;if(l instanceof URL){const u=t[l.toString()];u&&(l=u.data,a??(a=u.mediaType))}switch(r){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(a=(n=wre({data:l,signatures:yre}))!=null?n:a),{type:"file",mediaType:a??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(a==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:a,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function $re({maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,seed:s,stopSequences:a}){if(e!=null){if(!Number.isInteger(e))throw new Hn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Hn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Hn({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Hn({parameter:"topP",value:n,message:"topP must be a number"});if(i!=null&&typeof i!="number")throw new Hn({parameter:"topK",value:i,message:"topK must be a number"});if(r!=null&&typeof r!="number")throw new Hn({parameter:"presencePenalty",value:r,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new Hn({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(s!=null&&!Number.isInteger(s))throw new Hn({parameter:"seed",value:s,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,stopSequences:a,seed:s}}function Ore(e){return e!=null&&Object.keys(e).length>0}function Nre({tools:e,toolChoice:t,activeTools:n}){return Ore(e)?{tools:(n!=null?Object.entries(e).filter(([r])=>n.includes(r)):Object.entries(e)).map(([r,o])=>{const s=o.type;switch(s){case void 0:case"dynamic":case"function":return{type:"function",name:r,description:o.description,inputSchema:ef(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:r,id:o.id,args:o.args};default:{const a=s;throw new Error(`Unsupported tool type: ${a}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Ta=Ya(()=>le([Ga(),T(),ee(),De(),nn(T(),Ta),J(Ta)])),lr=nn(T(),nn(T(),Ta)),aM=N({type:F("text"),text:T(),providerOptions:lr.optional()}),Pre=N({type:F("image"),image:le([oM,er(URL)]),mediaType:T().optional(),providerOptions:lr.optional()}),uM=N({type:F("file"),data:le([oM,er(URL)]),filename:T().optional(),mediaType:T(),providerOptions:lr.optional()}),Mre=N({type:F("reasoning"),text:T(),providerOptions:lr.optional()}),jre=N({type:F("tool-call"),toolCallId:T(),toolName:T(),input:Je(),providerOptions:lr.optional(),providerExecuted:De().optional()}),Dre=fd("type",[N({type:F("text"),value:T()}),N({type:F("json"),value:Ta}),N({type:F("error-text"),value:T()}),N({type:F("error-json"),value:Ta}),N({type:F("content"),value:J(le([N({type:F("text"),text:T()}),N({type:F("media"),data:T(),mediaType:T()})]))})]),lM=N({type:F("tool-result"),toolCallId:T(),toolName:T(),output:Dre,providerOptions:lr.optional()}),zre=N({role:F("system"),content:T(),providerOptions:lr.optional()}),Lre=N({role:F("user"),content:le([T(),J(le([aM,Pre,uM]))]),providerOptions:lr.optional()}),Ure=N({role:F("assistant"),content:le([T(),J(le([aM,uM,Mre,jre,lM]))]),providerOptions:lr.optional()}),Fre=N({role:F("tool"),content:J(lM),providerOptions:lr.optional()}),Bre=le([zre,Lre,Ure,Fre]);async function Vre(e){if(e.prompt==null&&e.messages==null)throw new Yi({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Yi({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Yi({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Yi({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Yi({prompt:e,message:"messages must not be empty"});const n=await ei({value:t,schema:J(Bre)});if(!n.success)throw new Yi({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function qre(e){return dy.isInstance(e)||_P.isInstance(e)?new fe({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function Lh({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function Zre({model:e,settings:t,telemetry:n,headers:i}){var r;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((o,[s,a])=>(o[`ai.settings.${s}`]=a,o),{}),...Object.entries((r=n?.metadata)!=null?r:{}).reduce((o,[s,a])=>(o[`ai.telemetry.metadata.${s}`]=a,o),{}),...Object.entries(i??{}).reduce((o,[s,a])=>(a!==void 0&&(o[`ai.request.headers.${s}`]=a),o),{})}}var Hre={startSpan(){return il},startActiveSpan(e,t,n,i){if(typeof t=="function")return t(il);if(typeof n=="function")return n(il);if(typeof i=="function")return i(il)}},il={spanContext(){return Gre},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Gre={traceId:"",spanId:"",traceFlags:0};function Wre({isEnabled:e=!1,tracer:t}={}){return e?t||XX.getTracer("ai"):Hre}function Uh({name:e,tracer:t,attributes:n,fn:i,endWhenDone:r=!0}){return t.startActiveSpan(e,{attributes:n},async o=>{try{const s=await i(o);return r&&o.end(),s}catch(s){try{cM(o,s)}finally{o.end()}throw s}})}function cM(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:fc.ERROR,message:t.message})):e.setStatus({code:fc.ERROR})}function vo({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((n,[i,r])=>{if(r==null)return n;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(e?.recordInputs===!1)return n;const o=r.input();return o==null?n:{...n,[i]:o}}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(e?.recordOutputs===!1)return n;const o=r.output();return o==null?n:{...n,[i]:o}}return{...n,[i]:r}},{})}function Jre(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Tre(n.data):n.data}:n)})))}function Kre(e,t){return{inputTokens:xs(e.inputTokens,t.inputTokens),outputTokens:xs(e.outputTokens,t.outputTokens),totalTokens:xs(e.totalTokens,t.totalTokens),reasoningTokens:xs(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:xs(e.cachedInputTokens,t.cachedInputTokens)}}function xs(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function xx(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Yre({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let i;const r=n["retry-after-ms"];if(r){const s=parseFloat(r);Number.isNaN(s)||(i=s)}const o=n["retry-after"];if(o&&i===void 0){const s=parseFloat(o);Number.isNaN(s)?i=Date.parse(o)-Date.now():i=s*1e3}return i!=null&&!Number.isNaN(i)&&0<=i&&(i<60*1e3||i<t)?i:t}var Xre=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:i}={})=>async r=>dM(r,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:i});async function dM(e,{maxRetries:t,delayInMs:n,backoffFactor:i,abortSignal:r},o=[]){try{return await e()}catch(s){if(Ni(s)||t===0)throw s;const a=oP(s),l=[...o,s],u=l.length;if(u>t)throw new wx({message:`Failed after ${u} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(s instanceof Error&&Dt.isInstance(s)&&s.isRetryable===!0&&u<=t)return await iP(Yre({error:s,exponentialBackoffDelay:n}),{abortSignal:r}),dM(e,{maxRetries:t,delayInMs:i*n,backoffFactor:i,abortSignal:r},l);throw u===1?s:new wx({message:`Failed after ${u} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function Qre({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Hn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Hn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:Xre({maxRetries:n,abortSignal:t})}}var eie=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Dh(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=cy(this.base64Data)),this.uint8ArrayData}},tie=class extends eie{constructor(e){super(e),this.type="file"}};async function nie({toolCall:e,tools:t,repairToolCall:n,system:i,messages:r}){try{if(t==null)throw new zh({toolName:e.toolName});try{return await Sx({toolCall:e,tools:t})}catch(o){if(n==null||!(zh.isInstance(o)||NP.isInstance(o)))throw o;let s=null;try{s=await n({toolCall:e,tools:t,inputSchema:({toolName:a})=>{const{inputSchema:l}=t[a];return ef(l).jsonSchema},system:i,messages:r,error:o})}catch(a){throw new lre({cause:a,originalError:o})}if(s==null)throw o;return await Sx({toolCall:s,tools:t})}}catch(o){const s=await Pi({text:e.input}),a=s.success?s.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a,dynamic:!0,invalid:!0,error:o}}}async function Sx({toolCall:e,tools:t}){const n=e.toolName,i=t[n];if(i==null)throw new zh({toolName:e.toolName,availableTools:Object.keys(t)});const r=ef(i.inputSchema),o=e.input.trim()===""?await ei({value:{},schema:r}):await Pi({text:e.input,schema:r});if(o.success===!1)throw new NP({toolName:n,toolInput:e.input,cause:o.error});return i.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var rie=class{constructor({content:e,finishReason:t,usage:n,warnings:i,request:r,response:o,providerMetadata:s}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=i,this.request=r,this.response=o,this.providerMetadata=s}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function fM(e){return({steps:t})=>t.length===e}async function iie({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function Vs({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:Wo(e)}:n==="json"?{type:"error-json",value:Ex(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:Ex(e)}}function Ex(e){return e===void 0?null:e}function Ix({content:e,tools:t}){const n=[],i=e.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Vs({tool:t?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Vs({tool:t?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});i.length>0&&n.push({role:"assistant",content:i});const r=e.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Vs({tool:t?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"})}));return r.length>0&&n.push({role:"tool",content:r}),n}Eu({prefix:"aitxt",size:24});function tf(e,t){const n=new Headers(e??{});for(const[i,r]of Object.entries(t))n.has(i)||n.set(i,r);return n}function oie({status:e,statusText:t,headers:n,textStream:i}){return new Response(i.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:tf(n,{"content-type":"text/plain; charset=utf-8"})})}function pM({response:e,status:t,statusText:n,headers:i,stream:r}){e.writeHead(t??200,n,i);const o=r.getReader();(async()=>{try{for(;;){const{done:a,value:l}=await o.read();if(a)break;e.write(l)||await new Promise(c=>{e.once("drain",c)})}}catch(a){throw a}finally{e.end()}})()}function sie({response:e,status:t,statusText:n,headers:i,textStream:r}){pM({response:e,status:t,statusText:n,headers:Object.fromEntries(tf(i,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:r.pipeThrough(new TextEncoderStream)})}var hM=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
137
|
+
|
|
138
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
139
|
+
|
|
140
|
+
`)}})}},mM={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function aie({status:e,statusText:t,headers:n,stream:i,consumeSseStream:r}){let o=i.pipeThrough(new hM);if(r){const[s,a]=o.tee();o=s,r({stream:a})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:tf(n,mM)})}function uie({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return n?.role==="assistant"?n.id:typeof t=="function"?t():t}function lie(e){return e.type.startsWith("data-")}function gM(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const r=t[i];if(r===void 0)continue;const o=i in e?e[i]:void 0,s=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);s&&a?n[i]=gM(o,r):n[i]=r}return n}function cie(e){const t=["ROOT"];let n=-1,i=null;function r(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,i=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":r(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,l+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&s(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?a+="true".slice(c.length):"false".startsWith(c)?a+="false".slice(c.length):"null".startsWith(c)&&(a+="null".slice(c.length))}}return a}async function vM(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Pi({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Pi({text:cie(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function bp(e){return e.type.startsWith("data-")}function _p(e){return e.type==="text"}function wp(e){return e.type==="file"}function Tx(e){return e.type==="reasoning"}function Eo(e){return e.type.startsWith("tool-")}function fy(e){return e.type==="dynamic-tool"}function kx(e){return Eo(e)||fy(e)}function yc(e){return e.type.split("-").slice(1).join("-")}function die(e){return fy(e)?e.toolName:yc(e)}function fie({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function pie({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:s}){return e.pipeThrough(new TransformStream({async transform(a,l){await i(async({state:u,write:c})=>{var d,f,p,m;function h(b){const _=u.message.parts.filter(Eo).find(k=>k.toolCallId===b);if(_==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return _}function v(b){const _=u.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===b);if(_==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return _}function y(b){var C;const _=u.message.parts.find(M=>Eo(M)&&M.toolCallId===b.toolCallId),k=b,R=_;_!=null?(_.state=b.state,R.input=k.input,R.output=k.output,R.errorText=k.errorText,R.rawInput=k.rawInput,R.preliminary=k.preliminary,R.providerExecuted=(C=k.providerExecuted)!=null?C:_.providerExecuted,k.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(b){var C,_;const k=u.message.parts.find(U=>U.type==="dynamic-tool"&&U.toolCallId===b.toolCallId),R=b,M=k;k!=null?(k.state=b.state,M.toolName=b.toolName,M.input=R.input,M.output=R.output,M.errorText=R.errorText,M.rawInput=(C=R.rawInput)!=null?C:M.rawInput,M.preliminary=R.preliminary,M.providerExecuted=(_=R.providerExecuted)!=null?_:k.providerExecuted,R.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=R.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function S(b){if(b!=null){const C=u.message.metadata!=null?gM(u.message.metadata,b):b;t!=null&&await Nh({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const b={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=b,u.message.parts.push(b),c();break}case"text-delta":{const b=u.activeTextParts[a.id];b.text+=a.delta,b.providerMetadata=(d=a.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=u.activeTextParts[a.id];b.state="done",b.providerMetadata=(f=a.providerMetadata)!=null?f:b.providerMetadata,delete u.activeTextParts[a.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=b,u.message.parts.push(b),c();break}case"reasoning-delta":{const b=u.activeReasoningParts[a.id];b.text+=a.delta,b.providerMetadata=(p=a.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=u.activeReasoningParts[a.id];b.providerMetadata=(m=a.providerMetadata)!=null?m:b.providerMetadata,b.state="done",delete u.activeReasoningParts[a.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),c();break}case"tool-input-start":{const b=u.message.parts.filter(Eo);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:b.length,dynamic:a.dynamic},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),c();break}case"tool-input-delta":{const b=u.partialToolCalls[a.toolCallId];b.text+=a.inputTextDelta;const{value:C}=await vM(b.text);b.dynamic?w({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}):y({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}),c();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),c(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),c();break}case"tool-output-available":{if(a.dynamic){const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:a.output,preliminary:a.preliminary})}else{const b=h(a.toolCallId);y({toolCallId:a.toolCallId,toolName:yc(b),state:"output-available",input:b.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}c();break}case"tool-output-error":{if(a.dynamic){const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const b=h(a.toolCallId);y({toolCallId:a.toolCallId,toolName:yc(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await S(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&c();break}case"finish":{await S(a.messageMetadata),a.messageMetadata!=null&&c();break}case"message-metadata":{await S(a.messageMetadata),a.messageMetadata!=null&&c();break}case"error":{r?.(new Error(a.errorText));break}default:if(lie(a)){n?.[a.type]!=null&&await Nh({value:a.data,schema:n[a.type]});const b=a;if(b.transient){s?.(b);break}const C=b.id!=null?u.message.parts.find(_=>b.type===_.type&&b.id===_.id):void 0;C!=null?C.data=b.data:u.message.parts.push(b),s?.(b),c()}}l.enqueue(a)})}}))}function hie({messageId:e,originalMessages:t=[],onFinish:n,onError:i,stream:r}){let o=t?.[t.length-1];o?.role!=="assistant"?o=void 0:e=o.id;let s=!1;const a=r.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const m=f;m.messageId==null&&e!=null&&(m.messageId=e)}f.type==="abort"&&(s=!0),p.enqueue(f)}}));if(n==null)return a;const l=fie({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),u=async f=>{await f({state:l,write:()=>{}})};let c=!1;const d=async()=>{if(c||!n)return;c=!0;const f=l.message.id===o?.id;await n({isAborted:s,isContinuation:f,responseMessage:l.message,messages:[...f?t.slice(0,-1):t,l.message]})};return pie({stream:a,runUpdateMessageJob:u,onError:i}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function mie({response:e,status:t,statusText:n,headers:i,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new hM);if(o){const[a,l]=s.tee();s=a,o({stream:l})}pM({response:e,status:t,statusText:n,headers:Object.fromEntries(tf(i,mM).entries()),stream:s.pipeThrough(new TextEncoderStream)})}function ol(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let i=!1;async function r(o){var s;i=!0;try{o&&await((s=n.cancel)==null?void 0:s.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(i)return{done:!0,value:void 0};const{done:o,value:s}=await n.read();return o?(await r(!0),{done:!0,value:void 0}):{done:!1,value:s}},async return(){return await r(!0),{done:!0,value:void 0}},async throw(o){throw await r(!0),o}}},t}async function gie({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:i}=await n.read();if(i)break}}catch(i){t?.(i)}finally{n.releaseLock()}}function Cx(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}function vie(){let e=[],t=null,n=!1,i=Cx();const r=()=>{n=!0,i.resolve(),e.forEach(s=>s.cancel()),e=[],t?.close()},o=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return i=Cx(),await i.promise,o();try{const{value:s,done:a}=await e[0].read();a?(e.shift(),e.length>0?await o():n&&t?.close()):t?.enqueue(s)}catch(s){t?.error(s),e.shift(),r()}};return{stream:new ReadableStream({start(s){t=s},pull:o,async cancel(){for(const s of e)await s.cancel();e=[],n=!0}}),addStream:s=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(s.getReader()),i.resolve()},close:()=>{n=!0,i.resolve(),e.length===0&&t?.close()},terminate:r}}var sl=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function yie(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function bie({tools:e,generatorStream:t,tracer:n,telemetry:i,system:r,messages:o,abortSignal:s,repairToolCall:a,experimental_context:l}){let u=null;const c=new ReadableStream({start(y){u=y}}),d=new Set,f=new Map;let p=!1,m;function h(){p&&d.size===0&&(m!=null&&u.enqueue(m),u.close())}const v=new TransformStream({async transform(y,w){const S=y.type;switch(S){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(y);break}case"file":{w.enqueue({type:"file",file:new tie({data:y.data,mediaType:y.mediaType})});break}case"finish":{m={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const b=await nie({toolCall:y,tools:e,repairToolCall:a,system:r,messages:o});if(w.enqueue(b),b.invalid){u.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:oP(b.error),dynamic:!0});break}const C=e[b.toolName];if(f.set(b.toolCallId,b.input),C.onInputAvailable!=null&&await C.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:s,experimental_context:l}),C.execute!=null&&b.providerExecuted!==!0){const _=ute();d.add(_),Uh({name:"ai.toolCall",attributes:vo({telemetry:i,attributes:{...Lh({operationId:"ai.toolCall",telemetry:i}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:n,fn:async k=>{let R;try{const M=wne({execute:C.execute.bind(C),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:s,experimental_context:l}});for await(const U of M)u.enqueue({...b,type:"tool-result",output:U.output,...U.type==="preliminary"&&{preliminary:!0}}),U.type==="final"&&(R=U.output)}catch(M){cM(k,M),u.enqueue({...b,type:"tool-error",error:M}),d.delete(_),h();return}d.delete(_),h();try{k.setAttributes(vo({telemetry:i,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(R)}}}))}catch{}}})}}catch(b){u.enqueue({type:"error",error:b})}break}case"tool-result":{const b=y.toolName;y.isError?u.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:b,input:f.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):w.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:b,input:f.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const b=S;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(v).pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){}})),c.pipeTo(new WritableStream({write(w){y.enqueue(w)},close(){y.close()}}))])}})}var _ie=Eu({prefix:"aitxt",size:24});function wie({model:e,tools:t,toolChoice:n,system:i,prompt:r,messages:o,maxRetries:s,abortSignal:a,headers:l,stopWhen:u=fM(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:m,activeTools:h=m,experimental_repairToolCall:v,experimental_transform:y,experimental_download:w,includeRawChunks:S=!1,onChunk:b,onError:C=({error:j})=>{console.error(j)},onFinish:_,onAbort:k,onStepFinish:R,experimental_context:M,_internal:{now:U=yie,generateId:z=_ie,currentDate:Z=()=>new Date}={},...W}){return new Sie({model:iM(e),telemetry:d,headers:l,settings:W,maxRetries:s,abortSignal:a,system:i,prompt:r,messages:o,tools:t,toolChoice:n,transforms:xx(y),activeTools:h,repairToolCall:v,stopConditions:xx(u),output:c,providerOptions:p,prepareStep:f,includeRawChunks:S,onChunk:b,onError:C,onFinish:_,onAbort:k,onStepFinish:R,now:U,currentDate:Z,generateId:z,experimental_context:M,download:w})}function xie(e){if(!e)return new TransformStream({transform(s,a){a.enqueue({part:s,partialOutput:void 0})}});let t,n="",i="",r="";function o({controller:s,partialOutput:a=void 0}){s.enqueue({part:{type:"text-delta",id:t,text:i},partialOutput:a}),i=""}return new TransformStream({async transform(s,a){if(s.type==="finish-step"&&i.length>0&&o({controller:a}),s.type!=="text-delta"&&s.type!=="text-start"&&s.type!=="text-end"){a.enqueue({part:s,partialOutput:void 0});return}if(t==null)t=s.id;else if(s.id!==t){a.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-start"){a.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-end"){i.length>0&&o({controller:a}),a.enqueue({part:s,partialOutput:void 0});return}n+=s.text,i+=s.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==r&&(o({controller:a,partialOutput:l.partial}),r=u)}}})}var Sie=class{constructor({model:e,telemetry:t,headers:n,settings:i,maxRetries:r,abortSignal:o,system:s,prompt:a,messages:l,tools:u,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:m,output:h,providerOptions:v,prepareStep:y,includeRawChunks:w,now:S,currentDate:b,generateId:C,onChunk:_,onError:k,onFinish:R,onAbort:M,onStepFinish:U,experimental_context:z,download:Z}){this._totalUsage=new sl,this._finishReason=new sl,this._steps=new sl,this.output=h,this.includeRawChunks=w,this.tools=u;let W,j=[];const L=[];let Y,ne,Q={},se=[];const E=[];let we,de={},A={};const H=new TransformStream({async transform(et,Xe){var it,Te,Gt,Rr;Xe.enqueue(et);const{part:X}=et;if((X.type==="text-delta"||X.type==="reasoning-delta"||X.type==="source"||X.type==="tool-call"||X.type==="tool-result"||X.type==="tool-input-start"||X.type==="tool-input-delta"||X.type==="raw")&&await _?.({chunk:X}),X.type==="error"&&await k({error:qre(X.error)}),X.type==="text-start"&&(de[X.id]={type:"text",text:"",providerMetadata:X.providerMetadata},j.push(de[X.id])),X.type==="text-delta"){const Ze=de[X.id];if(Ze==null){Xe.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}Ze.text+=X.text,Ze.providerMetadata=(it=X.providerMetadata)!=null?it:Ze.providerMetadata}if(X.type==="text-end"){const Ze=de[X.id];if(Ze==null){Xe.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}Ze.providerMetadata=(Te=X.providerMetadata)!=null?Te:Ze.providerMetadata,delete de[X.id]}if(X.type==="reasoning-start"&&(A[X.id]={type:"reasoning",text:"",providerMetadata:X.providerMetadata},j.push(A[X.id])),X.type==="reasoning-delta"){const Ze=A[X.id];if(Ze==null){Xe.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}Ze.text+=X.text,Ze.providerMetadata=(Gt=X.providerMetadata)!=null?Gt:Ze.providerMetadata}if(X.type==="reasoning-end"){const Ze=A[X.id];if(Ze==null){Xe.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}Ze.providerMetadata=(Rr=X.providerMetadata)!=null?Rr:Ze.providerMetadata,delete A[X.id]}if(X.type==="file"&&j.push({type:"file",file:X.file}),X.type==="source"&&j.push(X),X.type==="tool-call"&&j.push(X),X.type==="tool-result"&&!X.preliminary&&j.push(X),X.type==="tool-error"&&j.push(X),X.type==="start-step"&&(Q=X.request,se=X.warnings),X.type==="finish-step"){const Ze=Ix({content:j,tools:u}),ui=new rie({content:j,finishReason:X.finishReason,usage:X.usage,warnings:se,request:Q,response:{...X.response,messages:[...L,...Ze]},providerMetadata:X.providerMetadata});await U?.(ui),tre(se),E.push(ui),j=[],A={},de={},L.push(...Ze),W.resolve()}X.type==="finish"&&(ne=X.totalUsage,Y=X.finishReason)},async flush(et){try{if(E.length===0){const Gt=new sre({message:"No output generated. Check the stream for errors."});ut._finishReason.reject(Gt),ut._totalUsage.reject(Gt),ut._steps.reject(Gt);return}const Xe=Y??"unknown",it=ne??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};ut._finishReason.resolve(Xe),ut._totalUsage.resolve(it),ut._steps.resolve(E);const Te=E[E.length-1];await R?.({finishReason:Xe,totalUsage:it,usage:Te.usage,content:Te.content,text:Te.text,reasoningText:Te.reasoningText,reasoning:Te.reasoning,files:Te.files,sources:Te.sources,toolCalls:Te.toolCalls,staticToolCalls:Te.staticToolCalls,dynamicToolCalls:Te.dynamicToolCalls,toolResults:Te.toolResults,staticToolResults:Te.staticToolResults,dynamicToolResults:Te.dynamicToolResults,request:Te.request,response:Te.response,warnings:Te.warnings,providerMetadata:Te.providerMetadata,steps:E}),we.setAttributes(vo({telemetry:t,attributes:{"ai.response.finishReason":Xe,"ai.response.text":{output:()=>Te.text},"ai.response.toolCalls":{output:()=>{var Gt;return(Gt=Te.toolCalls)!=null&&Gt.length?JSON.stringify(Te.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Te.providerMetadata),"ai.usage.inputTokens":it.inputTokens,"ai.usage.outputTokens":it.outputTokens,"ai.usage.totalTokens":it.totalTokens,"ai.usage.reasoningTokens":it.reasoningTokens,"ai.usage.cachedInputTokens":it.cachedInputTokens}}))}catch(Xe){et.error(Xe)}finally{we.end()}}}),re=vie();this.addStream=re.addStream,this.closeStream=re.close;const ie=re.stream.getReader();let ke=new ReadableStream({async start(et){et.enqueue({type:"start"})},async pull(et){function Xe(){M?.({steps:E}),et.enqueue({type:"abort"}),et.close()}try{const{done:it,value:Te}=await ie.read();if(it){et.close();return}if(o?.aborted){Xe();return}et.enqueue(Te)}catch(it){Ni(it)&&o?.aborted?Xe():et.error(it)}},cancel(et){return re.stream.cancel(et)}});for(const et of d)ke=ke.pipeThrough(et({tools:u,stopStream(){re.terminate()}}));this.baseStream=ke.pipeThrough(xie(h)).pipeThrough(H);const{maxRetries:ze,retry:Vn}=Qre({maxRetries:r,abortSignal:o}),pn=Wre(t),wt=$re(i),Ji=Zre({model:e,telemetry:t,headers:n,settings:{...wt,maxRetries:ze}}),ut=this;Uh({name:"ai.streamText",attributes:vo({telemetry:t,attributes:{...Lh({operationId:"ai.streamText",telemetry:t}),...Ji,"ai.prompt":{input:()=>JSON.stringify({system:s,prompt:a,messages:l})}}}),tracer:pn,endWhenDone:!1,fn:async et=>{we=et;async function Xe({currentStep:it,responseMessages:Te,usage:Gt}){var Rr,X,Ze,ui,Cu;const Au=ut.includeRawChunks;W=new sl;const Ru=await Vre({system:s,prompt:a,messages:l}),P=[...Ru.messages,...Te],V=await y?.({model:e,steps:E,stepNumber:E.length,messages:P}),oe=iM((Rr=V?.model)!=null?Rr:e),Se=await kre({prompt:{system:(X=V?.system)!=null?X:Ru.system,messages:(Ze=V?.messages)!=null?Ze:P},supportedUrls:await oe.supportedUrls,download:Z}),{toolChoice:Ce,tools:Ct}=Nre({tools:u,toolChoice:(ui=V?.toolChoice)!=null?ui:c,activeTools:(Cu=V?.activeTools)!=null?Cu:f}),{result:{stream:cr,response:hn,request:$r},doStreamSpan:mn,startTimestampMs:xt}=await Vn(()=>Uh({name:"ai.streamText.doStream",attributes:vo({telemetry:t,attributes:{...Lh({operationId:"ai.streamText.doStream",telemetry:t}),...Ji,"ai.model.provider":oe.provider,"ai.model.id":oe.modelId,"ai.prompt.messages":{input:()=>Jre(Se)},"ai.prompt.tools":{input:()=>Ct?.map(ae=>JSON.stringify(ae))},"ai.prompt.toolChoice":{input:()=>Ce!=null?JSON.stringify(Ce):void 0},"gen_ai.system":oe.provider,"gen_ai.request.model":oe.modelId,"gen_ai.request.frequency_penalty":wt.frequencyPenalty,"gen_ai.request.max_tokens":wt.maxOutputTokens,"gen_ai.request.presence_penalty":wt.presencePenalty,"gen_ai.request.stop_sequences":wt.stopSequences,"gen_ai.request.temperature":wt.temperature,"gen_ai.request.top_k":wt.topK,"gen_ai.request.top_p":wt.topP}}),tracer:pn,endWhenDone:!1,fn:async ae=>({startTimestampMs:S(),doStreamSpan:ae,result:await oe.doStream({...wt,tools:Ct,toolChoice:Ce,responseFormat:h?.responseFormat,prompt:Se,providerOptions:v,abortSignal:o,headers:n,includeRawChunks:Au})})})),Or=bie({tools:u,generatorStream:cr,tracer:pn,telemetry:t,system:s,messages:P,repairToolCall:p,abortSignal:o,experimental_context:z}),En=$r??{},$u=[],cf=[];let df;const ff={};let Ki="unknown",In={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},pf,Hy=!0,qn={id:C(),timestamp:b(),modelId:e.modelId},Gy="";ut.addStream(Or.pipeThrough(new TransformStream({async transform(ae,vt){var fs,ps,Ou,dr;if(ae.type==="stream-start"){df=ae.warnings;return}if(Hy){const At=S()-xt;Hy=!1,mn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":At}),mn.setAttributes({"ai.response.msToFirstChunk":At}),vt.enqueue({type:"start-step",request:En,warnings:df??[]})}const Wy=ae.type;switch(Wy){case"text-start":case"text-end":{vt.enqueue(ae);break}case"text-delta":{ae.delta.length>0&&(vt.enqueue({type:"text-delta",id:ae.id,text:ae.delta,providerMetadata:ae.providerMetadata}),Gy+=ae.delta);break}case"reasoning-start":case"reasoning-end":{vt.enqueue(ae);break}case"reasoning-delta":{vt.enqueue({type:"reasoning-delta",id:ae.id,text:ae.delta,providerMetadata:ae.providerMetadata});break}case"tool-call":{vt.enqueue(ae),$u.push(ae);break}case"tool-result":{vt.enqueue(ae),ae.preliminary||cf.push(ae);break}case"tool-error":{vt.enqueue(ae),cf.push(ae);break}case"response-metadata":{qn={id:(fs=ae.id)!=null?fs:qn.id,timestamp:(ps=ae.timestamp)!=null?ps:qn.timestamp,modelId:(Ou=ae.modelId)!=null?Ou:qn.modelId};break}case"finish":{In=ae.usage,Ki=ae.finishReason,pf=ae.providerMetadata;const At=S()-xt;mn.addEvent("ai.stream.finish"),mn.setAttributes({"ai.response.msToFinish":At,"ai.response.avgOutputTokensPerSecond":1e3*((dr=In.outputTokens)!=null?dr:0)/At});break}case"file":{vt.enqueue(ae);break}case"source":{vt.enqueue(ae);break}case"tool-input-start":{ff[ae.id]=ae.toolName;const At=u?.[ae.toolName];At?.onInputStart!=null&&await At.onInputStart({toolCallId:ae.id,messages:P,abortSignal:o,experimental_context:z}),vt.enqueue({...ae,dynamic:At?.type==="dynamic"});break}case"tool-input-end":{delete ff[ae.id],vt.enqueue(ae);break}case"tool-input-delta":{const At=ff[ae.id],hf=u?.[At];hf?.onInputDelta!=null&&await hf.onInputDelta({inputTextDelta:ae.delta,toolCallId:ae.id,messages:P,abortSignal:o,experimental_context:z}),vt.enqueue(ae);break}case"error":{vt.enqueue(ae),Ki="error";break}case"raw":{Au&&vt.enqueue(ae);break}default:{const At=Wy;throw new Error(`Unknown chunk type: ${At}`)}}},async flush(ae){const vt=$u.length>0?JSON.stringify($u):void 0;try{mn.setAttributes(vo({telemetry:t,attributes:{"ai.response.finishReason":Ki,"ai.response.text":{output:()=>Gy},"ai.response.toolCalls":{output:()=>vt},"ai.response.id":qn.id,"ai.response.model":qn.modelId,"ai.response.timestamp":qn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(pf),"ai.usage.inputTokens":In.inputTokens,"ai.usage.outputTokens":In.outputTokens,"ai.usage.totalTokens":In.totalTokens,"ai.usage.reasoningTokens":In.reasoningTokens,"ai.usage.cachedInputTokens":In.cachedInputTokens,"gen_ai.response.finish_reasons":[Ki],"gen_ai.response.id":qn.id,"gen_ai.response.model":qn.modelId,"gen_ai.usage.input_tokens":In.inputTokens,"gen_ai.usage.output_tokens":In.outputTokens}}))}catch{}finally{mn.end()}ae.enqueue({type:"finish-step",finishReason:Ki,usage:In,providerMetadata:pf,response:{...qn,headers:hn?.headers}});const fs=Kre(Gt,In);await W.promise;const ps=$u.filter(dr=>dr.providerExecuted!==!0),Ou=cf.filter(dr=>dr.providerExecuted!==!0);if(ps.length>0&&Ou.length===ps.length&&!await iie({stopConditions:m,steps:E})){Te.push(...Ix({content:E[E.length-1].content,tools:u}));try{await Xe({currentStep:it+1,responseMessages:Te,usage:fs})}catch(dr){ae.enqueue({type:"error",error:dr}),ut.closeStream()}}else ae.enqueue({type:"finish",finishReason:Ki,totalUsage:fs}),ut.closeStream()}})))}await Xe({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(et=>{ut.addStream(new ReadableStream({start(Xe){Xe.enqueue({type:"error",error:et}),Xe.close()}})),ut.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ol(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ol(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await gie({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new Xne;return ol(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r=!0,sendSources:o=!1,sendStart:s=!0,sendFinish:a=!0,onError:l=Wo}={}){const u=t!=null?uie({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var m,h;const v=c[p];return((h=(m=this.tools)==null?void 0:m[v])==null?void 0:h.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,m)=>{const h=i?.({part:p}),v=p.type;switch(v){case"text-start":{m.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{m.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{r&&m.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{m.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{m.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{o&&p.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),o&&p.sourceType==="document"&&m.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{c[p.id]=p.toolName;const y=d(p.id);m.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{c[p.toolCallId]=p.toolName;const y=d(p.toolCallId);p.invalid?m.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error)}):m.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=d(p.toolCallId);m.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=d(p.toolCallId);m.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{m.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{s&&m.enqueue({type:"start",...h!=null?{messageMetadata:h}:{},...u!=null?{messageId:u}:{}});break}case"finish":{a&&m.enqueue({type:"finish",...h!=null?{messageMetadata:h}:{}});break}case"abort":{m.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=v;throw new Error(`Unknown chunk type: ${y}`)}}h!=null&&v!=="start"&&v!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:h})}}));return ol(hie({stream:f,messageId:u??t?.(),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:l,onError:u,...c}={}){mie({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){sie({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:s,sendStart:a,onError:l,...u}={}){return aie({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:s,sendStart:a,onError:l}),...u})}toTextStreamResponse(e){return oie({textStream:this.textStream,...e})}};function Eie(e,t){const n=[];t?.ignoreIncompleteToolCalls&&(e=e.map(i=>({...i,parts:i.parts.filter(r=>!kx(r)||r.state!=="input-streaming"&&r.state!=="input-available")})));for(const i of e)switch(i.role){case"system":{const r=i.parts.filter(s=>s.type==="text"),o=r.reduce((s,a)=>a.providerMetadata!=null?{...s,...a.providerMetadata}:s,{});n.push({role:"system",content:r.map(s=>s.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{n.push({role:"user",content:i.parts.map(r=>{var o;if(_p(r))return{type:"text",text:r.text,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(wp(r))return{type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(bp(r))return(o=t?.convertDataPart)==null?void 0:o.call(t,r)}).filter(r=>r!=null)});break}case"assistant":{if(i.parts!=null){let r=function(){var s,a,l;if(o.length===0)return;const u=[];for(const d of o)if(_p(d))u.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(wp(d))u.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(Tx(d))u.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(fy(d)){const f=d.toolName;d.state!=="input-streaming"&&u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.input,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}})}else if(Eo(d)){const f=yc(d);d.state!=="input-streaming"&&(u.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(s=d.input)!=null?s:d.rawInput:d.input,providerExecuted:d.providerExecuted,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}}),d.providerExecuted===!0&&(d.state==="output-available"||d.state==="output-error")&&u.push({type:"tool-result",toolCallId:d.toolCallId,toolName:f,output:Vs({output:d.state==="output-error"?d.errorText:d.output,tool:(a=t?.tools)==null?void 0:a[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(bp(d)){const f=(l=t?.convertDataPart)==null?void 0:l.call(t,d);f!=null&&u.push(f)}else{const f=d;throw new Error(`Unsupported part: ${f}`)}n.push({role:"assistant",content:u});const c=o.filter(d=>Eo(d)&&d.providerExecuted!==!0||d.type==="dynamic-tool");c.length>0&&n.push({role:"tool",content:c.map(d=>{var f;switch(d.state){case"output-error":case"output-available":{const p=die(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:Vs({output:d.state==="output-error"?d.errorText:d.output,tool:(f=t?.tools)==null?void 0:f[p],errorMode:d.state==="output-error"?"text":"none"})}}default:return null}}).filter(d=>d!=null)}),o=[]},o=[];for(const s of i.parts)_p(s)||Tx(s)||wp(s)||kx(s)||bp(s)?o.push(s):s.type==="step-start"&&r();r();break}break}default:{const r=i.role;throw new hre({originalMessage:i,message:`Unsupported role: ${r}`})}}return n}Eu({prefix:"aiobj",size:24});Eu({prefix:"aiobj",size:24});var Iie={};Kne(Iie,{object:()=>kie,text:()=>Tie});var Tie=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),kie=({schema:e})=>{const t=ef(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await vM(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value};default:{const r=i.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},i){const r=await Pi({text:n});if(!r.success)throw new _x({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});const o=await ei({value:r.value,schema:t});if(!o.success)throw new _x({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return o.value}}},Cie={word:/\S+\s+/m,line:/\n+/m};function Aie({delayInMs:e=10,chunking:t="word",_internal:{delay:n=iP}={}}={}){let i;if(typeof t=="function")i=r=>{const o=t(r);if(o==null)return null;if(!o.length)throw new Error("Chunking function must return a non-empty string.");if(!r.startsWith(o))throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: "${o}" expected to start with "${r}"`);return o};else{const r=typeof t=="string"?Cie[t]:t;if(r==null)throw new xc({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});i=o=>{const s=r.exec(o);return s?o.slice(0,s.index)+s?.[0]:null}}return()=>{let r="",o="";return new TransformStream({async transform(s,a){if(s.type!=="text-delta"){r.length>0&&(a.enqueue({type:"text-delta",text:r,id:o}),r=""),a.enqueue(s);return}s.id!==o&&r.length>0&&(a.enqueue({type:"text-delta",text:r,id:o}),r=""),r+=s.text,o=s.id;let l;for(;(l=i(r))!=null;)a.enqueue({type:"text-delta",text:l,id:o}),r=r.slice(l.length),await n(e)}})}}function Ax(e){return!!e&&"sessionToken"in e}function Rie(e){return e?"sessionFn"in e:!1}const $ie=({getSession:e,projectSlug:t})=>{const n=oA(),i=["chatSession",t],r=n.getQueryState(i),o=r?.data!==void 0,s=r?.dataUpdatedAt??0,l=o&&Date.now()-s>1/0,u=!o||l,{data:c}=aA({queryKey:i,queryFn:()=>e({projectSlug:t}),enabled:u&&e!==null,staleTime:1/0,gcTime:1/0});return c??null};async function Oie(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const Nie=({projectSlug:e,auth:t})=>{const n=I.useMemo(()=>Ax(t)?()=>Promise.resolve(t.sessionToken):!Ax(t)&&Rie(t)?t.sessionFn:Oie,[t]),i=$ie({getSession:n,projectSlug:e});return i?{headers:{"Gram-Project":e,"Gram-Chat-Session":i},isLoading:!1}:{isLoading:!0}};function Pie({children:e}){const[t,n]=I.useState(new Map),[i,r]=I.useState(new Set),o=I.useCallback((d,f,p)=>new Promise(m=>{const h={toolCallId:f,toolName:d,args:p,resolve:m};n(v=>{const y=new Map(v);return y.set(f,h),y})}),[]),s=I.useCallback(d=>{r(f=>{const p=new Set(f);return p.add(d),p})},[]),a=I.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!0);const m=new Map(f);return m.delete(d),m}return f})},[]),l=I.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!1);const m=new Map(f);return m.delete(d),m}return f})},[]),u=I.useCallback(d=>i.has(d),[i]),c=I.useCallback(d=>t.get(d),[t]);return g.jsx(O.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:i,requestApproval:o,whitelistTool:s,confirmPendingApproval:a,rejectPendingApproval:l,isToolApproved:u,getPendingApproval:c},children:e})}function Mie(e){return e==="user"?"user":e==="assistant"?"assistant":e==="system"?"system":"assistant"}function jie(e){return typeof e=="string"?new Date(e):e}function Die(e){const t=[];return e.content&&t.push({type:"text",text:e.content}),t.length===0&&t.push({type:"text",text:""}),t}function zie(e){const t=[];if(e.content&&t.push({type:"text",text:e.content}),e.toolCalls)try{const n=JSON.parse(e.toolCalls);for(const i of n){const r=i.function?.arguments??i.args??{},o=typeof r=="string"?r:JSON.stringify(r);t.push({type:"tool-call",toolCallId:i.id??i.toolCallId??"",toolName:i.function?.name??i.toolName??"",args:typeof r=="string"?JSON.parse(r):r,argsText:o,result:void 0})}}catch{}return t.length===0&&t.push({type:"text",text:""}),t}function Lie(e){const t=Mie(e.role),n=jie(e.createdAt),i={unstable_state:void 0,unstable_annotations:void 0,unstable_data:void 0,steps:void 0,submittedFeedback:void 0,custom:{}};return t==="user"?{id:e.id,role:"user",createdAt:n,content:Die(e),attachments:[],metadata:i}:t==="system"?{id:e.id,role:"system",createdAt:n,content:[{type:"text",text:e.content??""}],metadata:i}:{id:e.id,role:"assistant",createdAt:n,content:zie(e),status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],submittedFeedback:void 0,custom:{}}}}function Uie(e){if(e.length===0)return{messages:[],headId:null};const t=[];let n=null;for(const i of e){if(i.role==="system")continue;const r=Lie(i);t.push({message:r,parentId:n,runConfig:void 0}),n=i.id}return{messages:t,headId:n}}class Fie{constructor(t,n,i){this.apiUrl=t,this.headers=n,this.store=i}async load(){const t=this.store.threadListItem().getState().remoteId;if(!t)return{messages:[],headId:null};try{const n=await fetch(`${this.apiUrl}/rpc/chat.load?id=${encodeURIComponent(t)}`,{headers:this.headers});if(!n.ok)return console.error("Failed to load chat:",n.status),{messages:[],headId:null};const i=await n.json();return Uie(i.messages)}catch(n){return console.error("Error loading chat:",n),{messages:[],headId:null}}}async append(){}withFormat(t){return{load:async()=>{const n=this.store.threadListItem().getState().remoteId;if(!n)return{messages:[],headId:null};try{const i=await fetch(`${this.apiUrl}/rpc/chat.load?id=${encodeURIComponent(n)}`,{headers:this.headers});if(!i.ok)return console.error("Failed to load chat (withFormat):",i.status),{messages:[],headId:null};const o=(await i.json()).messages.filter(l=>l.role!=="system");if(o.length===0)return{messages:[],headId:null};let s=null;const a=o.map((l,u)=>{const c=l.id||`fallback-${u}-${Date.now()}`,d={parentId:s,message:{id:c,role:l.role,parts:[{type:"text",text:l.content||""}],createdAt:l.createdAt?new Date(l.createdAt):new Date}};return s=c,d});return{headId:s,messages:a}}catch(i){return console.error("Error loading chat (withFormat):",i),{messages:[],headId:null}}},append:async()=>{}}}}function Bie(e){const t=Re(),[n]=I.useState(()=>new Fie(e.current.apiUrl,e.current.headers,t));return n}function Vie(e){const t=I.useRef(e);I.useEffect(()=>{t.current=e},[e]);const n=I.useCallback(function({children:r}){const o=Bie(t),s=I.useMemo(()=>({history:o}),[o]);return g.jsx(xv,{adapters:s,children:r})},[]);return I.useMemo(()=>({unstable_Provider:n,async list(){try{const i=await fetch(`${t.current.apiUrl}/rpc/chat.list`,{headers:t.current.headers});return i.ok?{threads:(await i.json()).chats.map(o=>({remoteId:o.id,externalId:o.id,status:"regular",title:o.title||"New Chat"}))}:(console.error("Failed to list chats:",i.status),{threads:[]})}catch(i){return console.error("Error listing chats:",i),{threads:[]}}},async initialize(i){return{remoteId:i,externalId:i}},async rename(){},async archive(){},async unarchive(){},async delete(){},async generateTitle(i,r){return new ReadableStream({start(o){o.close()}})},async fetch(i){try{const r=await fetch(`${t.current.apiUrl}/rpc/chat.load?id=${encodeURIComponent(i)}`,{headers:t.current.headers});if(!r.ok)return console.error("Failed to fetch thread:",r.status),{remoteId:i,status:"regular"};const o=await r.json();return{remoteId:o.id,externalId:o.id,status:"regular",title:o.title||"New Chat"}}catch(r){return console.error("Error fetching thread:",r),{remoteId:i,status:"regular"}}}}),[n])}const qie="You are a helpful assistant that can answer questions and help with tasks.";function Zie(e,t){return`
|
|
141
|
+
${qie}
|
|
142
|
+
|
|
143
|
+
User-provided System Prompt:
|
|
144
|
+
${e??"None provided"}
|
|
145
|
+
|
|
146
|
+
Utilities:
|
|
147
|
+
${t.map(n=>`- ${n.language}: ${n.prompt}`).join(`
|
|
148
|
+
`)}`}function Hie(e){return e.map(t=>{const n=t.parts;if(!Array.isArray(n))return t;const i=n.map(r=>{const{callProviderMetadata:o,...s}=r;return s});return{...t,parts:i}})}const Gie=({children:e,config:t})=>{const n=q4(t),i=Nie({auth:t.api,projectSlug:t.projectSlug}),r=uA(),[o,s]=I.useState(t.model?.defaultModel??hv[0]),[a,l]=I.useState(t.modal?.defaultExpanded??!1),[u,c]=I.useState(t.modal?.defaultOpen),d=t.plugins??O.recommended,f=Zie(t.systemPrompt,d);I.useEffect(()=>{pH({enabled:t.errorTracking?.enabled,projectSlug:t.projectSlug,variant:t.variant})},[]);const{data:p}=B4({auth:i,mcp:t.mcp,environment:t.environment??{}}),m=I.useRef({requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool});m.current={requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool};const h=I.useCallback(()=>({requestApproval:(..._)=>m.current.requestApproval(..._),isToolApproved:(..._)=>m.current.isToolApproved(..._),whitelistTool:(..._)=>m.current.whitelistTool(..._)}),[]);I.useEffect(()=>(t.tools?.toolsRequiringApproval&&O7(h(),t.tools.toolsRequiringApproval),()=>{N7()}),[t.tools?.toolsRequiringApproval,h]);const v=I.useRef(null),y=I.useRef(null),w=I.useMemo(()=>({sendMessages:async({messages:_,abortSignal:k})=>{const R=!!t.languageModel;if(i.isLoading)throw new Error("Session is loading");y.current||(y.current=crypto.randomUUID());const M=v.current?.thread.getModelContext(),U=R7($7(M?.tools??{})),z={...i.headers,"Gram-Chat-ID":y.current},Z=R?null:rP({baseURL:n,apiKey:"unused, but must be set",headers:z});t.languageModel&&console.log("Using custom language model",t.languageModel);const W={...p,...HQ(U)},j=M7(W,t.tools?.toolsRequiringApproval,h()),L=t.languageModel?t.languageModel:Z.chat(o);try{const Y=Hie(_),ne=Eie(Y);return wie({system:f,model:L,messages:ne,tools:j,stopWhen:fM(10),experimental_transform:Aie({delayInMs:15}),abortSignal:k,onError:({error:se})=>{console.error("Stream error in onError callback:",se),Kl(se,{source:"streaming"})}}).toUIMessageStream()}catch(Y){throw console.error("Error creating stream:",Y),Kl(Y,{source:"stream-creation"}),Y}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t.languageModel,t.tools?.toolsRequiringApproval,o,f,p,h,n,i.headers,i.isLoading]),S=t.history?.enabled??!1,b=I.useMemo(()=>({config:t,setModel:s,model:o,isExpanded:a,setIsExpanded:l,isOpen:u??!1,setIsOpen:c,plugins:d}),[t,o,a,u,d]),C=t.tools?.frontendTools??{};return S&&!i.isLoading?g.jsx(Wie,{transport:w,apiUrl:n,headers:i.headers,contextValue:b,runtimeRef:v,frontendTools:C,children:e}):g.jsx(Jie,{transport:w,contextValue:b,runtimeRef:v,frontendTools:C,children:e})},Wie=({children:e,transport:t,apiUrl:n,headers:i,contextValue:r,runtimeRef:o,frontendTools:s})=>{const a=Vie({apiUrl:n,headers:i}),l=I.useCallback(()=>pN({transport:t}),[t]),u=uO({adapter:a,runtimeHook:l});I.useEffect(()=>{o.current=u},[u,o]);const c=a.unstable_Provider??(({children:d})=>g.jsx(g.Fragment,{children:d}));return g.jsx(nO,{runtime:u,children:g.jsx(c,{children:g.jsxs(O.ElementsContext.Provider,{value:r,children:[e,g.jsx(ES,{tools:s})]})})})},Jie=({children:e,transport:t,contextValue:n,runtimeRef:i,frontendTools:r})=>{const o=pN({transport:t});return I.useEffect(()=>{i.current=o},[o,i]),g.jsx(nO,{runtime:o,children:g.jsxs(O.ElementsContext.Provider,{value:n,children:[e,g.jsx(ES,{tools:r})]})})},Kie=new A4,Yie=e=>g.jsx(R4,{client:Kie,children:g.jsx(Pie,{children:g.jsx(Gie,{...e})})}),Rx=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,$x=O.clsx,yM=(e,t)=>n=>{var i;if(t?.variants==null)return $x(e,n?.class,n?.className);const{variants:r,defaultVariants:o}=t,s=Object.keys(r).map(u=>{const c=n?.[u],d=o?.[u];if(c===null)return null;const f=Rx(c)||Rx(d);return r[u][f]}),a=n&&Object.entries(n).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=t==null||(i=t.compoundVariants)===null||i===void 0?void 0:i.reduce((u,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(m=>{let[h,v]=m;return Array.isArray(v)?v.includes({...o,...a}[h]):{...o,...a}[h]===v})?[...u,d,f]:u},[]);return $x(e,s,l,n?.class,n?.className)},Xie=yM("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),tn=x.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...r},o)=>{const s=i?Cv:"button";return g.jsx(s,{"data-slot":"button",className:O.cn(Xie({variant:t,size:n,className:e})),ref:o,...r})});tn.displayName="Button";const Qie=({error:e,onRetry:t})=>g.jsx("div",{className:O.cn("aui-root aui-error-boundary bg-background flex h-full w-full flex-col items-center justify-center p-6"),children:g.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[g.jsx("div",{className:"text-destructive",children:g.jsx(O.CircleAlert,{className:"size-12 stroke-[1.5px]"})}),g.jsxs("div",{className:"flex flex-col gap-2",children:[g.jsx("h3",{className:"text-foreground text-xl font-semibold",children:"Something went wrong"}),g.jsx("p",{className:"text-muted-foreground text-base",children:"An error occurred while loading the chat."}),e&&g.jsx("p",{className:"text-muted-foreground/60 max-w-md truncate text-sm",children:e.message})]}),g.jsx(tn,{onClick:t,variant:"default",className:"mt-2",children:"Try again"})]})}),eoe=({children:e})=>g.jsx(g.Fragment,{children:e});class py extends I.Component{constructor(t){super(t),this.handleRetry=()=>{this.setState(n=>({hasError:!1,error:null,resetKey:n.resetKey+1})),this.props.onReset?.()},this.state={hasError:!1,error:null,resetKey:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){Kl(t,{source:"error-boundary",componentStack:n.componentStack??void 0}),this.props.onError?.(t,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:g.jsx(Qie,{error:this.state.error,onRetry:this.handleRetry}):g.jsx(eoe,{children:this.props.children},this.state.resetKey)}}var toe=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),noe="VisuallyHidden",bM=x.forwardRef((e,t)=>g.jsx(dt.span,{...e,ref:t,style:{...toe,...e.style}}));bM.displayName=noe;var roe=bM,[nf]=vu("Tooltip",[Hd]),rf=Hd(),_M="TooltipProvider",ioe=700,Fh="tooltip.open",[ooe,hy]=nf(_M),wM=e=>{const{__scopeTooltip:t,delayDuration:n=ioe,skipDelayDuration:i=300,disableHoverableContent:r=!1,children:o}=e,s=x.useRef(!0),a=x.useRef(!1),l=x.useRef(0);return x.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),g.jsx(ooe,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:x.useCallback(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:x.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,i)},[i]),isPointerInTransitRef:a,onPointerInTransitChange:x.useCallback(u=>{a.current=u},[]),disableHoverableContent:r,children:o})};wM.displayName=_M;var ka="Tooltip",[soe,Iu]=nf(ka),xM=e=>{const{__scopeTooltip:t,children:n,open:i,defaultOpen:r,onOpenChange:o,disableHoverableContent:s,delayDuration:a}=e,l=hy(ka,e.__scopeTooltip),u=rf(t),[c,d]=x.useState(null),f=_o(),p=x.useRef(0),m=s??l.disableHoverableContent,h=a??l.delayDuration,v=x.useRef(!1),[y,w]=Gd({prop:i,defaultProp:r??!1,onChange:k=>{k?(l.onOpen(),document.dispatchEvent(new CustomEvent(Fh))):l.onClose(),o?.(k)},caller:ka}),S=x.useMemo(()=>y?v.current?"delayed-open":"instant-open":"closed",[y]),b=x.useCallback(()=>{window.clearTimeout(p.current),p.current=0,v.current=!1,w(!0)},[w]),C=x.useCallback(()=>{window.clearTimeout(p.current),p.current=0,w(!1)},[w]),_=x.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{v.current=!0,w(!0),p.current=0},h)},[h,w]);return x.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),g.jsx(UO,{...u,children:g.jsx(soe,{scope:t,contentId:f,open:y,stateAttribute:S,trigger:c,onTriggerChange:d,onTriggerEnter:x.useCallback(()=>{l.isOpenDelayedRef.current?_():b()},[l.isOpenDelayedRef,_,b]),onTriggerLeave:x.useCallback(()=>{m?C():(window.clearTimeout(p.current),p.current=0)},[C,m]),onOpen:b,onClose:C,disableHoverableContent:m,children:n})})};xM.displayName=ka;var Bh="TooltipTrigger",SM=x.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=Iu(Bh,n),o=hy(Bh,n),s=rf(n),a=x.useRef(null),l=mt(t,a,r.onTriggerChange),u=x.useRef(!1),c=x.useRef(!1),d=x.useCallback(()=>u.current=!1,[]);return x.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),g.jsx(Fv,{asChild:!0,...s,children:g.jsx(dt.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...i,ref:l,onPointerMove:Le(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!o.isPointerInTransitRef.current&&(r.onTriggerEnter(),c.current=!0)}),onPointerLeave:Le(e.onPointerLeave,()=>{r.onTriggerLeave(),c.current=!1}),onPointerDown:Le(e.onPointerDown,()=>{r.open&&r.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Le(e.onFocus,()=>{u.current||r.onOpen()}),onBlur:Le(e.onBlur,r.onClose),onClick:Le(e.onClick,r.onClose)})})});SM.displayName=Bh;var my="TooltipPortal",[aoe,uoe]=nf(my,{forceMount:void 0}),EM=e=>{const{__scopeTooltip:t,forceMount:n,children:i,container:r}=e,o=Iu(my,t);return g.jsx(aoe,{scope:t,forceMount:n,children:g.jsx(si,{present:n||o.open,children:g.jsx(Bv,{asChild:!0,container:r,children:i})})})};EM.displayName=my;var Go="TooltipContent",IM=x.forwardRef((e,t)=>{const n=uoe(Go,e.__scopeTooltip),{forceMount:i=n.forceMount,side:r="top",...o}=e,s=Iu(Go,e.__scopeTooltip);return g.jsx(si,{present:i||s.open,children:s.disableHoverableContent?g.jsx(TM,{side:r,...o,ref:t}):g.jsx(loe,{side:r,...o,ref:t})})}),loe=x.forwardRef((e,t)=>{const n=Iu(Go,e.__scopeTooltip),i=hy(Go,e.__scopeTooltip),r=x.useRef(null),o=mt(t,r),[s,a]=x.useState(null),{trigger:l,onClose:u}=n,c=r.current,{onPointerInTransitChange:d}=i,f=x.useCallback(()=>{a(null),d(!1)},[d]),p=x.useCallback((m,h)=>{const v=m.currentTarget,y={x:m.clientX,y:m.clientY},w=poe(y,v.getBoundingClientRect()),S=hoe(y,w),b=moe(h.getBoundingClientRect()),C=voe([...S,...b]);a(C),d(!0)},[d]);return x.useEffect(()=>()=>f(),[f]),x.useEffect(()=>{if(l&&c){const m=v=>p(v,c),h=v=>p(v,l);return l.addEventListener("pointerleave",m),c.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",m),c.removeEventListener("pointerleave",h)}}},[l,c,p,f]),x.useEffect(()=>{if(s){const m=h=>{const v=h.target,y={x:h.clientX,y:h.clientY},w=l?.contains(v)||c?.contains(v),S=!goe(y,s);w?f():S&&(f(),u())};return document.addEventListener("pointermove",m),()=>document.removeEventListener("pointermove",m)}},[l,c,s,u,f]),g.jsx(TM,{...e,ref:o})}),[coe,doe]=nf(ka,{isInside:!1}),foe=NW("TooltipContent"),TM=x.forwardRef((e,t)=>{const{__scopeTooltip:n,children:i,"aria-label":r,onEscapeKeyDown:o,onPointerDownOutside:s,...a}=e,l=Iu(Go,n),u=rf(n),{onClose:c}=l;return x.useEffect(()=>(document.addEventListener(Fh,c),()=>document.removeEventListener(Fh,c)),[c]),x.useEffect(()=>{if(l.trigger){const d=f=>{f.target?.contains(l.trigger)&&c()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,c]),g.jsx(Bd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:g.jsxs(FO,{"data-state":l.stateAttribute,...u,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[g.jsx(foe,{children:i}),g.jsx(coe,{scope:n,isInside:!0,children:g.jsx(roe,{id:l.contentId,role:"tooltip",children:r||i})})]})})});IM.displayName=Go;var kM="TooltipArrow",CM=x.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=rf(n);return doe(kM,n).isInside?null:g.jsx(BO,{...r,...i,ref:t})});CM.displayName=kM;function poe(e,t){const n=Math.abs(t.top-e.y),i=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,i,r,o)){case o:return"left";case r:return"right";case n:return"top";case i:return"bottom";default:throw new Error("unreachable")}}function hoe(e,t,n=5){const i=[];switch(t){case"top":i.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":i.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":i.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":i.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return i}function moe(e){const{top:t,right:n,bottom:i,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:i},{x:r,y:i}]}function goe(e,t){const{x:n,y:i}=e;let r=!1;for(let o=0,s=t.length-1;o<t.length;s=o++){const a=t[o],l=t[s],u=a.x,c=a.y,d=l.x,f=l.y;c>i!=f>i&&n<(d-u)*(i-c)/(f-c)+u&&(r=!r)}return r}function voe(e){const t=e.slice();return t.sort((n,i)=>n.x<i.x?-1:n.x>i.x?1:n.y<i.y?-1:n.y>i.y?1:0),yoe(t)}function yoe(e){if(e.length<=1)return e.slice();const t=[];for(let i=0;i<e.length;i++){const r=e[i];for(;t.length>=2;){const o=t[t.length-1],s=t[t.length-2];if((o.x-s.x)*(r.y-s.y)>=(o.y-s.y)*(r.x-s.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let i=e.length-1;i>=0;i--){const r=e[i];for(;n.length>=2;){const o=n[n.length-1],s=n[n.length-2];if((o.x-s.x)*(r.y-s.y)>=(o.y-s.y)*(r.x-s.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var boe=wM,_oe=xM,woe=SM,xoe=EM,Soe=IM,Eoe=CM;const AM=I.createContext(null);function RM(){return I.useContext(AM)?.current??null}function $M({delayDuration:e=0,...t}){return g.jsx(boe,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function gy({...e}){return g.jsx($M,{children:g.jsx(_oe,{"data-slot":"tooltip",...e})})}function vy({...e}){return g.jsx(woe,{"data-slot":"tooltip-trigger",...e})}function yy({className:e,sideOffset:t=0,children:n,container:i,...r}){const o=RM();return g.jsx(xoe,{container:i??o,children:g.jsxs(Soe,{"data-slot":"tooltip-content",sideOffset:t,className:O.cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...r,children:[n,g.jsx(Eoe,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}var of="Dialog",[OM]=vu(of),[Ioe,Bn]=OM(of),NM=e=>{const{__scopeDialog:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:s=!0}=e,a=x.useRef(null),l=x.useRef(null),[u,c]=Gd({prop:i,defaultProp:r??!1,onChange:o,caller:of});return g.jsx(Ioe,{scope:t,triggerRef:a,contentRef:l,contentId:_o(),titleId:_o(),descriptionId:_o(),open:u,onOpenChange:c,onOpenToggle:x.useCallback(()=>c(d=>!d),[c]),modal:s,children:n})};NM.displayName=of;var PM="DialogTrigger",MM=x.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=Bn(PM,n),o=mt(t,r.triggerRef);return g.jsx(dt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":wy(r.open),...i,ref:o,onClick:Le(e.onClick,r.onOpenToggle)})});MM.displayName=PM;var by="DialogPortal",[Toe,jM]=OM(by,{forceMount:void 0}),DM=e=>{const{__scopeDialog:t,forceMount:n,children:i,container:r}=e,o=Bn(by,t);return g.jsx(Toe,{scope:t,forceMount:n,children:x.Children.map(i,s=>g.jsx(si,{present:n||o.open,children:g.jsx(Bv,{asChild:!0,container:r,children:s})}))})};DM.displayName=by;var bc="DialogOverlay",zM=x.forwardRef((e,t)=>{const n=jM(bc,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=Bn(bc,e.__scopeDialog);return o.modal?g.jsx(si,{present:i||o.open,children:g.jsx(Coe,{...r,ref:t})}):null});zM.displayName=bc;var koe=Rv("DialogOverlay.RemoveScroll"),Coe=x.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=Bn(bc,n);return g.jsx(Vv,{as:koe,allowPinchZoom:!0,shards:[r.contentRef],children:g.jsx(dt.div,{"data-state":wy(r.open),...i,ref:t,style:{pointerEvents:"auto",...i.style}})})}),ji="DialogContent",LM=x.forwardRef((e,t)=>{const n=jM(ji,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=Bn(ji,e.__scopeDialog);return g.jsx(si,{present:i||o.open,children:o.modal?g.jsx(Aoe,{...r,ref:t}):g.jsx(Roe,{...r,ref:t})})});LM.displayName=ji;var Aoe=x.forwardRef((e,t)=>{const n=Bn(ji,e.__scopeDialog),i=x.useRef(null),r=mt(t,n.contentRef,i);return x.useEffect(()=>{const o=i.current;if(o)return qO(o)},[]),g.jsx(UM,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Le(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Le(e.onPointerDownOutside,o=>{const s=o.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&o.preventDefault()}),onFocusOutside:Le(e.onFocusOutside,o=>o.preventDefault())})}),Roe=x.forwardRef((e,t)=>{const n=Bn(ji,e.__scopeDialog),i=x.useRef(!1),r=x.useRef(!1);return g.jsx(UM,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||n.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=o.target;n.triggerRef.current?.contains(s)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),UM=x.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,...s}=e,a=Bn(ji,n),l=x.useRef(null),u=mt(t,l);return vO(),g.jsxs(g.Fragment,{children:[g.jsx($v,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:g.jsx(Bd,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":wy(a.open),...s,ref:u,onDismiss:()=>a.onOpenChange(!1)})}),g.jsxs(g.Fragment,{children:[g.jsx(Ooe,{titleId:a.titleId}),g.jsx(Poe,{contentRef:l,descriptionId:a.descriptionId})]})]})}),_y="DialogTitle",FM=x.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=Bn(_y,n);return g.jsx(dt.h2,{id:r.titleId,...i,ref:t})});FM.displayName=_y;var BM="DialogDescription",$oe=x.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=Bn(BM,n);return g.jsx(dt.p,{id:r.descriptionId,...i,ref:t})});$oe.displayName=BM;var VM="DialogClose",qM=x.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=Bn(VM,n);return g.jsx(dt.button,{type:"button",...i,ref:t,onClick:Le(e.onClick,()=>r.onOpenChange(!1))})});qM.displayName=VM;function wy(e){return e?"open":"closed"}var ZM="DialogTitleWarning",[hfe,HM]=RW(ZM,{contentName:ji,titleName:_y,docsSlug:"dialog"}),Ooe=({titleId:e})=>{const t=HM(ZM),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
149
|
+
|
|
150
|
+
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
151
|
+
|
|
152
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return x.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Noe="DialogDescriptionWarning",Poe=({contentRef:e,descriptionId:t})=>{const i=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${HM(Noe).contentName}}.`;return x.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(i))},[i,e,t]),null},Moe=NM,joe=MM,Doe=DM,zoe=zM,Loe=LM,Uoe=FM,Foe=qM;function Boe({...e}){return g.jsx(Moe,{"data-slot":"dialog",...e})}function Voe({...e}){return g.jsx(joe,{"data-slot":"dialog-trigger",...e})}function qoe({container:e,...t}){const n=RM();return g.jsx(Doe,{"data-slot":"dialog-portal",container:e??n,...t})}function Zoe({className:e,...t}){return g.jsx(zoe,{"data-slot":"dialog-overlay",className:O.cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Hoe({className:e,children:t,showCloseButton:n=!0,...i}){return g.jsxs(qoe,{"data-slot":"dialog-portal",children:[g.jsx(Zoe,{}),g.jsxs(Loe,{"data-slot":"dialog-content",className:O.cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...i,children:[t,n&&g.jsxs(Foe,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[g.jsx(wu,{}),g.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Goe({className:e,...t}){return g.jsx(Uoe,{"data-slot":"dialog-title",className:O.cn("text-lg leading-none font-semibold",e),...t})}function Woe(e,t=[]){let n=[];function i(o,s){const a=x.createContext(s);a.displayName=o+"Context";const l=n.length;n=[...n,s];const u=d=>{const{scope:f,children:p,...m}=d,h=f?.[e]?.[l]||a,v=x.useMemo(()=>m,Object.values(m));return g.jsx(h.Provider,{value:v,children:p})};u.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[l]||a,m=x.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[u,c]}const r=()=>{const o=n.map(s=>x.createContext(s));return function(a){const l=a?.[e]||o;return x.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return r.scopeName=e,[i,Joe(r,...t)]}function Joe(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const i=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(o){const s=i.reduce((a,{useScope:l,scopeName:u})=>{const d=l(o)[`__scope${u}`];return{...a,...d}},{});return x.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}function Koe(){return zQ.useSyncExternalStore(Yoe,()=>!0,()=>!1)}function Yoe(){return()=>{}}var xy="Avatar",[Xoe]=Woe(xy),[Qoe,GM]=Xoe(xy),WM=x.forwardRef((e,t)=>{const{__scopeAvatar:n,...i}=e,[r,o]=x.useState("idle");return g.jsx(Qoe,{scope:n,imageLoadingStatus:r,onImageLoadingStatusChange:o,children:g.jsx(gt.span,{...i,ref:t})})});WM.displayName=xy;var JM="AvatarImage",KM=x.forwardRef((e,t)=>{const{__scopeAvatar:n,src:i,onLoadingStatusChange:r=()=>{},...o}=e,s=GM(JM,n),a=ese(i,o),l=sn(u=>{r(u),s.onImageLoadingStatusChange(u)});return xn(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?g.jsx(gt.img,{...o,ref:t,src:i}):null});KM.displayName=JM;var YM="AvatarFallback",XM=x.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:i,...r}=e,o=GM(YM,n),[s,a]=x.useState(i===void 0);return x.useEffect(()=>{if(i!==void 0){const l=window.setTimeout(()=>a(!0),i);return()=>window.clearTimeout(l)}},[i]),s&&o.imageLoadingStatus!=="loaded"?g.jsx(gt.span,{...r,ref:t}):null});XM.displayName=YM;function Ox(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function ese(e,{referrerPolicy:t,crossOrigin:n}){const i=Koe(),r=x.useRef(null),o=i?(r.current||(r.current=new window.Image),r.current):null,[s,a]=x.useState(()=>Ox(o,e));return xn(()=>{a(Ox(o,e))},[o,e]),xn(()=>{const l=d=>()=>{a(d)};if(!o)return;const u=l("loaded"),c=l("error");return o.addEventListener("load",u),o.addEventListener("error",c),t&&(o.referrerPolicy=t),typeof n=="string"&&(o.crossOrigin=n),()=>{o.removeEventListener("load",u),o.removeEventListener("error",c)}},[o,n,t]),s}var tse=WM,nse=KM,rse=XM;function ise({className:e,...t}){return g.jsx(tse,{"data-slot":"avatar",className:O.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function ose({className:e,...t}){return g.jsx(nse,{"data-slot":"avatar-image",className:O.cn("aspect-square size-full",e),...t})}function sse({className:e,...t}){return g.jsx(rse,{"data-slot":"avatar-fallback",className:O.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const Un=I.forwardRef(({children:e,tooltip:t,side:n="bottom",align:i="center",className:r,...o},s)=>g.jsxs(gy,{children:[g.jsx(vy,{asChild:!0,children:g.jsxs(tn,{variant:"ghost",size:"icon",...o,className:O.cn("aui-button-icon size-6 p-1",r),ref:s,children:[g.jsx(wW,{children:e}),g.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),g.jsx(yy,{side:n,align:i,children:t})]}));Un.displayName="TooltipIconButton";const ase=e=>{const[t,n]=I.useState(void 0);return I.useEffect(()=>{if(!e){n(void 0);return}const i=URL.createObjectURL(e);return n(i),()=>{URL.revokeObjectURL(i)}},[e]),t},QM=()=>{const{file:e,src:t}=te(wS.useShallow(({attachment:n})=>{if(n.type!=="image")return{};if(n.file)return{file:n.file};const i=n.content?.filter(r=>r.type==="image")[0]?.image;return i?{src:i}:{}}));return ase(e)??t},use=({src:e})=>{const[t,n]=I.useState(!1);return g.jsx("img",{src:e,alt:"Image Preview",className:t?"aui-attachment-preview-image-loaded block h-auto max-h-[80vh] w-auto max-w-full object-contain":"aui-attachment-preview-image-loading hidden",onLoad:()=>n(!0)})},lse=({children:e})=>{const t=QM();return t?g.jsxs(Boe,{children:[g.jsx(Voe,{className:"aui-attachment-preview-trigger",asChild:!0,children:e}),g.jsxs(Hoe,{className:"aui-attachment-preview-dialog-content [&_svg]:text-background [&>button]:bg-foreground/60 [&>button]:hover:[&_svg]:text-destructive p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:!ring-0",children:[g.jsx(Goe,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),g.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:g.jsx(use,{src:t})})]})]}):e},cse=()=>{const e=te(({attachment:n})=>n.type==="image"),t=QM();return g.jsxs(ise,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[g.jsx(ose,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),g.jsx(sse,{delayMs:e?200:0,children:g.jsx(J7,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},ej=()=>{const t=Re().attachment.source==="composer",n=te(({attachment:r})=>r.type==="image"),i=te(({attachment:r})=>{const o=r.type;switch(o){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const s=o;throw new Error(`Unknown attachment type: ${s}`)}}});return g.jsxs(gy,{children:[g.jsxs(a1,{className:O.cn("aui-attachment-root relative",n&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[g.jsx(lse,{children:g.jsx(vy,{asChild:!0,children:g.jsx("div",{className:O.cn("aui-attachment-tile bg-muted size-14 cursor-pointer overflow-hidden rounded-[14px] border transition-opacity hover:opacity-75",t&&"aui-attachment-tile-composer border-foreground/20"),role:"button",id:"attachment-tile","aria-label":`${i} attachment`,children:g.jsx(cse,{})})})}),t&&g.jsx(dse,{})]}),g.jsx(yy,{side:"top",children:g.jsx(u1,{})})]})},dse=()=>g.jsx(T8,{asChild:!0,children:g.jsx(Un,{tooltip:"Remove file",className:"aui-attachment-tile-remove text-muted-foreground hover:[&_svg]:text-destructive absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white opacity-100 shadow-sm hover:!bg-white [&_svg]:text-black",side:"top",children:g.jsx(wu,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),fse=()=>g.jsx("div",{className:"aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2",children:g.jsx(y1,{components:{Attachment:ej}})}),pse=()=>g.jsx("div",{className:"aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden",children:g.jsx(T1,{components:{Attachment:ej}})}),hse=()=>g.jsx(f7,{asChild:!0,children:g.jsx(Un,{tooltip:"Add Attachment",side:"top",variant:"ghost",size:"icon",align:"start",className:"aui-composer-add-attachment hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-[34px] rounded-full p-1 text-xs font-semibold","aria-label":"Add Attachment",children:g.jsx(V1,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})});function mse(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const gse=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,vse=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,yse={};function Nx(e,t){return(yse.jsx?vse:gse).test(e)}const bse=/[ \t\n\f\r]/g;function _se(e){return typeof e=="object"?e.type==="text"?Px(e.value):!1:Px(e)}function Px(e){return e.replace(bse,"")===""}class Tu{constructor(t,n,i){this.normal=n,this.property=t,i&&(this.space=i)}}Tu.prototype.normal={};Tu.prototype.property={};Tu.prototype.space=void 0;function tj(e,t){const n={},i={};for(const r of e)Object.assign(n,r.property),Object.assign(i,r.normal);return new Tu(n,i,t)}function Vh(e){return e.toLowerCase()}class Ht{constructor(t,n){this.attribute=n,this.property=t}}Ht.prototype.attribute="";Ht.prototype.booleanish=!1;Ht.prototype.boolean=!1;Ht.prototype.commaOrSpaceSeparated=!1;Ht.prototype.commaSeparated=!1;Ht.prototype.defined=!1;Ht.prototype.mustUseProperty=!1;Ht.prototype.number=!1;Ht.prototype.overloadedBoolean=!1;Ht.prototype.property="";Ht.prototype.spaceSeparated=!1;Ht.prototype.space=void 0;let wse=0;const ve=Wi(),st=Wi(),qh=Wi(),B=Wi(),Ve=Wi(),Io=Wi(),Wt=Wi();function Wi(){return 2**++wse}const Zh=Object.freeze(Object.defineProperty({__proto__:null,boolean:ve,booleanish:st,commaOrSpaceSeparated:Wt,commaSeparated:Io,number:B,overloadedBoolean:qh,spaceSeparated:Ve},Symbol.toStringTag,{value:"Module"})),xp=Object.keys(Zh);class Sy extends Ht{constructor(t,n,i,r){let o=-1;if(super(t,n),Mx(this,"space",r),typeof i=="number")for(;++o<xp.length;){const s=xp[o];Mx(this,xp[o],(i&Zh[s])===Zh[s])}}}Sy.prototype.defined=!0;function Mx(e,t,n){n&&(e[t]=n)}function cs(e){const t={},n={};for(const[i,r]of Object.entries(e.properties)){const o=new Sy(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),t[i]=o,n[Vh(i)]=i,n[Vh(o.attribute)]=i}return new Tu(t,n,e.space)}const nj=cs({properties:{ariaActiveDescendant:null,ariaAtomic:st,ariaAutoComplete:null,ariaBusy:st,ariaChecked:st,ariaColCount:B,ariaColIndex:B,ariaColSpan:B,ariaControls:Ve,ariaCurrent:null,ariaDescribedBy:Ve,ariaDetails:null,ariaDisabled:st,ariaDropEffect:Ve,ariaErrorMessage:null,ariaExpanded:st,ariaFlowTo:Ve,ariaGrabbed:st,ariaHasPopup:null,ariaHidden:st,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Ve,ariaLevel:B,ariaLive:null,ariaModal:st,ariaMultiLine:st,ariaMultiSelectable:st,ariaOrientation:null,ariaOwns:Ve,ariaPlaceholder:null,ariaPosInSet:B,ariaPressed:st,ariaReadOnly:st,ariaRelevant:null,ariaRequired:st,ariaRoleDescription:Ve,ariaRowCount:B,ariaRowIndex:B,ariaRowSpan:B,ariaSelected:st,ariaSetSize:B,ariaSort:null,ariaValueMax:B,ariaValueMin:B,ariaValueNow:B,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function rj(e,t){return t in e?e[t]:t}function ij(e,t){return rj(e,t.toLowerCase())}const xse=cs({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Io,acceptCharset:Ve,accessKey:Ve,action:null,allow:null,allowFullScreen:ve,allowPaymentRequest:ve,allowUserMedia:ve,alt:null,as:null,async:ve,autoCapitalize:null,autoComplete:Ve,autoFocus:ve,autoPlay:ve,blocking:Ve,capture:null,charSet:null,checked:ve,cite:null,className:Ve,cols:B,colSpan:null,content:null,contentEditable:st,controls:ve,controlsList:Ve,coords:B|Io,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ve,defer:ve,dir:null,dirName:null,disabled:ve,download:qh,draggable:st,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ve,formTarget:null,headers:Ve,height:B,hidden:qh,high:B,href:null,hrefLang:null,htmlFor:Ve,httpEquiv:Ve,id:null,imageSizes:null,imageSrcSet:null,inert:ve,inputMode:null,integrity:null,is:null,isMap:ve,itemId:null,itemProp:Ve,itemRef:Ve,itemScope:ve,itemType:Ve,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ve,low:B,manifest:null,max:null,maxLength:B,media:null,method:null,min:null,minLength:B,multiple:ve,muted:ve,name:null,nonce:null,noModule:ve,noValidate:ve,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ve,optimum:B,pattern:null,ping:Ve,placeholder:null,playsInline:ve,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ve,referrerPolicy:null,rel:Ve,required:ve,reversed:ve,rows:B,rowSpan:B,sandbox:Ve,scope:null,scoped:ve,seamless:ve,selected:ve,shadowRootClonable:ve,shadowRootDelegatesFocus:ve,shadowRootMode:null,shape:null,size:B,sizes:null,slot:null,span:B,spellCheck:st,src:null,srcDoc:null,srcLang:null,srcSet:null,start:B,step:null,style:null,tabIndex:B,target:null,title:null,translate:null,type:null,typeMustMatch:ve,useMap:null,value:st,width:B,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Ve,axis:null,background:null,bgColor:null,border:B,borderColor:null,bottomMargin:B,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ve,declare:ve,event:null,face:null,frame:null,frameBorder:null,hSpace:B,leftMargin:B,link:null,longDesc:null,lowSrc:null,marginHeight:B,marginWidth:B,noResize:ve,noHref:ve,noShade:ve,noWrap:ve,object:null,profile:null,prompt:null,rev:null,rightMargin:B,rules:null,scheme:null,scrolling:st,standby:null,summary:null,text:null,topMargin:B,valueType:null,version:null,vAlign:null,vLink:null,vSpace:B,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ve,disableRemotePlayback:ve,prefix:null,property:null,results:B,security:null,unselectable:null},space:"html",transform:ij}),Sse=cs({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Wt,accentHeight:B,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:B,amplitude:B,arabicForm:null,ascent:B,attributeName:null,attributeType:null,azimuth:B,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:B,by:null,calcMode:null,capHeight:B,className:Ve,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:B,diffuseConstant:B,direction:null,display:null,dur:null,divisor:B,dominantBaseline:null,download:ve,dx:null,dy:null,edgeMode:null,editable:null,elevation:B,enableBackground:null,end:null,event:null,exponent:B,externalResourcesRequired:null,fill:null,fillOpacity:B,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Io,g2:Io,glyphName:Io,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:B,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:B,horizOriginX:B,horizOriginY:B,id:null,ideographic:B,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:B,k:B,k1:B,k2:B,k3:B,k4:B,kernelMatrix:Wt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:B,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:B,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:B,overlineThickness:B,paintOrder:null,panose1:null,path:null,pathLength:B,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Ve,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:B,pointsAtY:B,pointsAtZ:B,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Wt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Wt,rev:Wt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Wt,requiredFeatures:Wt,requiredFonts:Wt,requiredFormats:Wt,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:B,specularExponent:B,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:B,strikethroughThickness:B,string:null,stroke:null,strokeDashArray:Wt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:B,strokeOpacity:B,strokeWidth:null,style:null,surfaceScale:B,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Wt,tabIndex:B,tableValues:null,target:null,targetX:B,targetY:B,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Wt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:B,underlineThickness:B,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:B,values:null,vAlphabetic:B,vMathematical:B,vectorEffect:null,vHanging:B,vIdeographic:B,version:null,vertAdvY:B,vertOriginX:B,vertOriginY:B,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:B,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rj}),oj=cs({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),sj=cs({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:ij}),aj=cs({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Ese={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Ise=/[A-Z]/g,jx=/-[a-z]/g,Tse=/^data[-\w.:]+$/i;function kse(e,t){const n=Vh(t);let i=t,r=Ht;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Tse.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(jx,Ase);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!jx.test(o)){let s=o.replace(Ise,Cse);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}r=Sy}return new r(i,t)}function Cse(e){return"-"+e.toLowerCase()}function Ase(e){return e.charAt(1).toUpperCase()}const Rse=tj([nj,xse,oj,sj,aj],"html"),Ey=tj([nj,Sse,oj,sj,aj],"svg");function $se(e){return e.join(" ").trim()}var uo={},Sp,Dx;function Ose(){if(Dx)return Sp;Dx=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,a=/^\s+|\s+$/g,l=`
|
|
153
|
+
`,u="/",c="*",d="",f="comment",p="declaration";function m(v,y){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];y=y||{};var w=1,S=1;function b(j){var L=j.match(t);L&&(w+=L.length);var Y=j.lastIndexOf(l);S=~Y?j.length-Y:S+j.length}function C(){var j={line:w,column:S};return function(L){return L.position=new _(j),M(),L}}function _(j){this.start=j,this.end={line:w,column:S},this.source=y.source}_.prototype.content=v;function k(j){var L=new Error(y.source+":"+w+":"+S+": "+j);if(L.reason=j,L.filename=y.source,L.line=w,L.column=S,L.source=v,!y.silent)throw L}function R(j){var L=j.exec(v);if(L){var Y=L[0];return b(Y),v=v.slice(Y.length),L}}function M(){R(n)}function U(j){var L;for(j=j||[];L=z();)L!==!1&&j.push(L);return j}function z(){var j=C();if(!(u!=v.charAt(0)||c!=v.charAt(1))){for(var L=2;d!=v.charAt(L)&&(c!=v.charAt(L)||u!=v.charAt(L+1));)++L;if(L+=2,d===v.charAt(L-1))return k("End of comment missing");var Y=v.slice(2,L-2);return S+=2,b(Y),v=v.slice(L),S+=2,j({type:f,comment:Y})}}function Z(){var j=C(),L=R(i);if(L){if(z(),!R(r))return k("property missing ':'");var Y=R(o),ne=j({type:p,property:h(L[0].replace(e,d)),value:Y?h(Y[0].replace(e,d)):d});return R(s),ne}}function W(){var j=[];U(j);for(var L;L=Z();)L!==!1&&(j.push(L),U(j));return j}return M(),W()}function h(v){return v?v.replace(a,d):d}return Sp=m,Sp}var zx;function Nse(){if(zx)return uo;zx=1;var e=uo&&uo.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=n;const t=e(Ose());function n(i,r){let o=null;if(!i||typeof i!="string")return o;const s=(0,t.default)(i),a=typeof r=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;a?r(u,c,l):c&&(o=o||{},o[u]=c)}),o}return uo}var Ss={},Lx;function Pse(){if(Lx)return Ss;Lx=1,Object.defineProperty(Ss,"__esModule",{value:!0}),Ss.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||n.test(u)||e.test(u)},s=function(u,c){return c.toUpperCase()},a=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),o(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(r,a):u=u.replace(i,a),u.replace(t,s))};return Ss.camelCase=l,Ss}var Es,Ux;function Mse(){if(Ux)return Es;Ux=1;var e=Es&&Es.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(Nse()),n=Pse();function i(r,o){var s={};return!r||typeof r!="string"||(0,t.default)(r,function(a,l){a&&l&&(s[(0,n.camelCase)(a,o)]=l)}),s}return i.default=i,Es=i,Es}var jse=Mse();const Dse=mu(jse),uj=lj("end"),Iy=lj("start");function lj(e){return t;function t(n){const i=n&&n.position&&n.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function zse(e){const t=Iy(e),n=uj(e);if(t&&n)return{start:t,end:n}}function qs(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Fx(e.position):"start"in e||"end"in e?Fx(e):"line"in e||"column"in e?Hh(e):""}function Hh(e){return Bx(e&&e.line)+":"+Bx(e&&e.column)}function Fx(e){return Hh(e&&e.start)+"-"+Hh(e&&e.end)}function Bx(e){return e&&typeof e=="number"?e:1}class kt extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",o={},s=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?r=t:!o.cause&&t&&(s=!0,r=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof i=="string"){const l=i.indexOf(":");l===-1?o.ruleId=i:(o.source=i.slice(0,l),o.ruleId=i.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){const l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}const a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=a?a.line:void 0,this.name=qs(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}kt.prototype.file="";kt.prototype.name="";kt.prototype.reason="";kt.prototype.message="";kt.prototype.stack="";kt.prototype.column=void 0;kt.prototype.line=void 0;kt.prototype.ancestors=void 0;kt.prototype.cause=void 0;kt.prototype.fatal=void 0;kt.prototype.place=void 0;kt.prototype.ruleId=void 0;kt.prototype.source=void 0;const Ty={}.hasOwnProperty,Lse=new Map,Use=/[A-Z]/g,Fse=new Set(["table","tbody","thead","tfoot","tr"]),Bse=new Set(["td","th"]),cj="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Vse(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let i;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=Yse(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=Kse(n,t.jsx,t.jsxs)}const r={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:i,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Ey:Rse,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=dj(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function dj(e,t,n){if(t.type==="element")return qse(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Zse(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Gse(e,t,n);if(t.type==="mdxjsEsm")return Hse(e,t);if(t.type==="root")return Wse(e,t,n);if(t.type==="text")return Jse(e,t)}function qse(e,t,n){const i=e.schema;let r=i;t.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Ey,e.schema=r),e.ancestors.push(t);const o=pj(e,t.tagName,!1),s=Xse(e,t);let a=Cy(e,t);return Fse.has(t.tagName)&&(a=a.filter(function(l){return typeof l=="string"?!_se(l):!0})),fj(e,s,o,t),ky(s,a),e.ancestors.pop(),e.schema=i,e.create(t,o,s,n)}function Zse(e,t){if(t.data&&t.data.estree&&e.evaluater){const i=t.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}Ca(e,t.position)}function Hse(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Ca(e,t.position)}function Gse(e,t,n){const i=e.schema;let r=i;t.name==="svg"&&i.space==="html"&&(r=Ey,e.schema=r),e.ancestors.push(t);const o=t.name===null?e.Fragment:pj(e,t.name,!0),s=Qse(e,t),a=Cy(e,t);return fj(e,s,o,t),ky(s,a),e.ancestors.pop(),e.schema=i,e.create(t,o,s,n)}function Wse(e,t,n){const i={};return ky(i,Cy(e,t)),e.create(t,e.Fragment,i,n)}function Jse(e,t){return t.value}function fj(e,t,n,i){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=i)}function ky(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Kse(e,t,n){return i;function i(r,o,s,a){const u=Array.isArray(s.children)?n:t;return a?u(o,s,a):u(o,s)}}function Yse(e,t){return n;function n(i,r,o,s){const a=Array.isArray(o.children),l=Iy(i);return t(r,o,s,a,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Xse(e,t){const n={};let i,r;for(r in t.properties)if(r!=="children"&&Ty.call(t.properties,r)){const o=eae(e,r,t.properties[r]);if(o){const[s,a]=o;e.tableCellAlignToStyle&&s==="align"&&typeof a=="string"&&Bse.has(t.tagName)?i=a:n[s]=a}}if(i){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return n}function Qse(e,t){const n={};for(const i of t.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const s=o.expression;s.type;const a=s.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Ca(e,t.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const a=i.value.data.estree.body[0];a.type,o=e.evaluater.evaluateExpression(a.expression)}else Ca(e,t.position);else o=i.value===null?!0:i.value;n[r]=o}return n}function Cy(e,t){const n=[];let i=-1;const r=e.passKeys?new Map:Lse;for(;++i<t.children.length;){const o=t.children[i];let s;if(e.passKeys){const l=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(l){const u=r.get(l)||0;s=l+"-"+u,r.set(l,u+1)}}const a=dj(e,o,s);a!==void 0&&n.push(a)}return n}function eae(e,t,n){const i=kse(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=i.commaSeparated?mse(n):$se(n)),i.property==="style"){let r=typeof n=="object"?n:tae(e,String(n));return e.stylePropertyNameCase==="css"&&(r=nae(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?Ese[i.property]||i.property:i.attribute,n]}}function tae(e,t){try{return Dse(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const i=n,r=new kt("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=cj+"#cannot-parse-style-attribute",r}}function pj(e,t,n){let i;if(!n)i={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let o=-1,s;for(;++o<r.length;){const a=Nx(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};s=s?{type:"MemberExpression",object:s,property:a,computed:!!(o&&a.type==="Literal"),optional:!1}:a}i=s}else i=Nx(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(i.type==="Literal"){const r=i.value;return Ty.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Ca(e)}function Ca(e,t){const n=new kt("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=cj+"#cannot-handle-mdx-estrees-without-createevaluater",n}function nae(e){const t={};let n;for(n in e)Ty.call(e,n)&&(t[rae(n)]=e[n]);return t}function rae(e){let t=e.replace(Use,iae);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function iae(e){return"-"+e.toLowerCase()}const Ep={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},oae={};function sae(e,t){const n=oae,i=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return hj(e,i,r)}function hj(e,t,n){if(aae(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Vx(e.children,t,n)}return Array.isArray(e)?Vx(e,t,n):""}function Vx(e,t,n){const i=[];let r=-1;for(;++r<e.length;)i[r]=hj(e[r],t,n);return i.join("")}function aae(e){return!!(e&&typeof e=="object")}const qx=document.createElement("i");function Ay(e){const t="&"+e+";";qx.innerHTML=t;const n=qx.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function or(e,t,n,i){const r=e.length;let o=0,s;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,i.length<1e4)s=Array.from(i),s.unshift(t,n),e.splice(...s);else for(n&&e.splice(t,n);o<i.length;)s=i.slice(o,o+1e4),s.unshift(t,0),e.splice(...s),o+=1e4,t+=1e4}function bn(e,t){return e.length>0?(or(e,e.length,0,t),e):t}const Zx={}.hasOwnProperty;function uae(e){const t={};let n=-1;for(;++n<e.length;)lae(t,e[n]);return t}function lae(e,t){let n;for(n in t){const r=(Zx.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let s;if(o)for(s in o){Zx.call(r,s)||(r[s]=[]);const a=o[s];cae(r[s],Array.isArray(a)?a:a?[a]:[])}}}function cae(e,t){let n=-1;const i=[];for(;++n<t.length;)(t[n].add==="after"?e:i).push(t[n]);or(e,0,0,i)}function mj(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function To(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Jn=ai(/[A-Za-z]/),Xt=ai(/[\dA-Za-z]/),dae=ai(/[#-'*+\--9=?A-Z^-~]/);function Gh(e){return e!==null&&(e<32||e===127)}const Wh=ai(/\d/),fae=ai(/[\dA-Fa-f]/),pae=ai(/[!-/:-@[-`{-~]/);function ce(e){return e!==null&&e<-2}function Zt(e){return e!==null&&(e<0||e===32)}function Ae(e){return e===-2||e===-1||e===32}const hae=ai(new RegExp("\\p{P}|\\p{S}","u")),mae=ai(/\s/);function ai(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ds(e){const t=[];let n=-1,i=0,r=0;for(;++n<e.length;){const o=e.charCodeAt(n);let s="";if(o===37&&Xt(e.charCodeAt(n+1))&&Xt(e.charCodeAt(n+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(s=String.fromCharCode(o));else if(o>55295&&o<57344){const a=e.charCodeAt(n+1);o<56320&&a>56319&&a<57344?(s=String.fromCharCode(o,a),r=1):s="�"}else s=String.fromCharCode(o);s&&(t.push(e.slice(i,n),encodeURIComponent(s)),i=n+r+1,s=""),r&&(n+=r,r=0)}return t.join("")+e.slice(i)}function qe(e,t,n,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return s;function s(l){return Ae(l)?(e.enter(n),a(l)):t(l)}function a(l){return Ae(l)&&o++<r?(e.consume(l),a):(e.exit(n),t(l))}}const gae={tokenize:vae};function vae(e){const t=e.attempt(this.parser.constructs.contentInitial,i,r);let n;return t;function i(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),qe(e,t,"linePrefix")}function r(a){return e.enter("paragraph"),o(a)}function o(a){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,s(a)}function s(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return ce(a)?(e.consume(a),e.exit("chunkText"),o):(e.consume(a),s)}}const yae={tokenize:bae},Hx={tokenize:_ae};function bae(e){const t=this,n=[];let i=0,r,o,s;return a;function a(S){if(i<n.length){const b=n[i];return t.containerState=b[1],e.attempt(b[0].continuation,l,u)(S)}return u(S)}function l(S){if(i++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&w();const b=t.events.length;let C=b,_;for(;C--;)if(t.events[C][0]==="exit"&&t.events[C][1].type==="chunkFlow"){_=t.events[C][1].end;break}y(i);let k=b;for(;k<t.events.length;)t.events[k][1].end={..._},k++;return or(t.events,C+1,0,t.events.slice(b)),t.events.length=k,u(S)}return a(S)}function u(S){if(i===n.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return m(S);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Hx,c,d)(S)}function c(S){return r&&w(),y(i),f(S)}function d(S){return t.parser.lazy[t.now().line]=i!==n.length,s=t.now().offset,m(S)}function f(S){return t.containerState={},e.attempt(Hx,p,m)(S)}function p(S){return i++,n.push([t.currentConstruct,t.containerState]),f(S)}function m(S){if(S===null){r&&w(),y(0),e.consume(S);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),h(S)}function h(S){if(S===null){v(e.exit("chunkFlow"),!0),y(0),e.consume(S);return}return ce(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,t.interrupt=void 0,a):(e.consume(S),h)}function v(S,b){const C=t.sliceStream(S);if(b&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),t.parser.lazy[S.start.line]){let _=r.events.length;for(;_--;)if(r.events[_][1].start.offset<s&&(!r.events[_][1].end||r.events[_][1].end.offset>s))return;const k=t.events.length;let R=k,M,U;for(;R--;)if(t.events[R][0]==="exit"&&t.events[R][1].type==="chunkFlow"){if(M){U=t.events[R][1].end;break}M=!0}for(y(i),_=k;_<t.events.length;)t.events[_][1].end={...U},_++;or(t.events,R+1,0,t.events.slice(k)),t.events.length=_}}function y(S){let b=n.length;for(;b-- >S;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=S}function w(){r.write([null]),o=void 0,r=void 0,t.containerState._closeFlow=void 0}}function _ae(e,t,n){return qe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Gx(e){if(e===null||Zt(e)||mae(e))return 1;if(hae(e))return 2}function Ry(e,t,n){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(t=o(t,n),i.push(o))}return t}const Jh={name:"attention",resolveAll:wae,tokenize:xae};function wae(e,t){let n=-1,i,r,o,s,a,l,u,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(i=n;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&t.sliceSerialize(e[i][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[i][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[i][1].end.offset-e[i][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[i][1].end},f={...e[n][1].start};Wx(d,-l),Wx(f,l),s={type:l>1?"strongSequence":"emphasisSequence",start:d,end:{...e[i][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},o={type:l>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},r={type:l>1?"strong":"emphasis",start:{...s.start},end:{...a.end}},e[i][1].end={...s.start},e[n][1].start={...a.end},u=[],e[i][1].end.offset-e[i][1].start.offset&&(u=bn(u,[["enter",e[i][1],t],["exit",e[i][1],t]])),u=bn(u,[["enter",r,t],["enter",s,t],["exit",s,t],["enter",o,t]]),u=bn(u,Ry(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),u=bn(u,[["exit",o,t],["enter",a,t],["exit",a,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=bn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,or(e,i-1,n-i+3,u),n=i+u.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function xae(e,t){const n=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Gx(i);let o;return s;function s(l){return o=l,e.enter("attentionSequence"),a(l)}function a(l){if(l===o)return e.consume(l),a;const u=e.exit("attentionSequence"),c=Gx(l),d=!c||c===2&&r||n.includes(l),f=!r||r===2&&c||n.includes(i);return u._open=!!(o===42?d:d&&(r||!f)),u._close=!!(o===42?f:f&&(c||!d)),t(l)}}function Wx(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Sae={name:"autolink",tokenize:Eae};function Eae(e,t,n){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Jn(p)?(e.consume(p),s):p===64?n(p):u(p)}function s(p){return p===43||p===45||p===46||Xt(p)?(i=1,a(p)):u(p)}function a(p){return p===58?(e.consume(p),i=0,l):(p===43||p===45||p===46||Xt(p))&&i++<32?(e.consume(p),a):(i=0,u(p))}function l(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):p===null||p===32||p===60||Gh(p)?n(p):(e.consume(p),l)}function u(p){return p===64?(e.consume(p),c):dae(p)?(e.consume(p),u):n(p)}function c(p){return Xt(p)?d(p):n(p)}function d(p){return p===46?(e.consume(p),i=0,c):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):f(p)}function f(p){if((p===45||Xt(p))&&i++<63){const m=p===45?f:d;return e.consume(p),m}return n(p)}}const sf={partial:!0,tokenize:Iae};function Iae(e,t,n){return i;function i(o){return Ae(o)?qe(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||ce(o)?t(o):n(o)}}const gj={continuation:{tokenize:kae},exit:Cae,name:"blockQuote",tokenize:Tae};function Tae(e,t,n){const i=this;return r;function r(s){if(s===62){const a=i.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(s),e.exit("blockQuoteMarker"),o}return n(s)}function o(s){return Ae(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function kae(e,t,n){const i=this;return r;function r(s){return Ae(s)?qe(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):o(s)}function o(s){return e.attempt(gj,t,n)(s)}}function Cae(e){e.exit("blockQuote")}const vj={name:"characterEscape",tokenize:Aae};function Aae(e,t,n){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return pae(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const yj={name:"characterReference",tokenize:Rae};function Rae(e,t,n){const i=this;let r=0,o,s;return a;function a(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,s=Xt,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,s=fae,c):(e.enter("characterReferenceValue"),o=7,s=Wh,c(d))}function c(d){if(d===59&&r){const f=e.exit("characterReferenceValue");return s===Xt&&!Ay(i.sliceSerialize(f))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(d)&&r++<o?(e.consume(d),c):n(d)}}const Jx={partial:!0,tokenize:Oae},Kx={concrete:!0,name:"codeFenced",tokenize:$ae};function $ae(e,t,n){const i=this,r={partial:!0,tokenize:C};let o=0,s=0,a;return l;function l(_){return u(_)}function u(_){const k=i.events[i.events.length-1];return o=k&&k[1].type==="linePrefix"?k[2].sliceSerialize(k[1],!0).length:0,a=_,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(_)}function c(_){return _===a?(s++,e.consume(_),c):s<3?n(_):(e.exit("codeFencedFenceSequence"),Ae(_)?qe(e,d,"whitespace")(_):d(_))}function d(_){return _===null||ce(_)?(e.exit("codeFencedFence"),i.interrupt?t(_):e.check(Jx,h,b)(_)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(_))}function f(_){return _===null||ce(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(_)):Ae(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),qe(e,p,"whitespace")(_)):_===96&&_===a?n(_):(e.consume(_),f)}function p(_){return _===null||ce(_)?d(_):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(_))}function m(_){return _===null||ce(_)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(_)):_===96&&_===a?n(_):(e.consume(_),m)}function h(_){return e.attempt(r,b,v)(_)}function v(_){return e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),y}function y(_){return o>0&&Ae(_)?qe(e,w,"linePrefix",o+1)(_):w(_)}function w(_){return _===null||ce(_)?e.check(Jx,h,b)(_):(e.enter("codeFlowValue"),S(_))}function S(_){return _===null||ce(_)?(e.exit("codeFlowValue"),w(_)):(e.consume(_),S)}function b(_){return e.exit("codeFenced"),t(_)}function C(_,k,R){let M=0;return U;function U(L){return _.enter("lineEnding"),_.consume(L),_.exit("lineEnding"),z}function z(L){return _.enter("codeFencedFence"),Ae(L)?qe(_,Z,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):Z(L)}function Z(L){return L===a?(_.enter("codeFencedFenceSequence"),W(L)):R(L)}function W(L){return L===a?(M++,_.consume(L),W):M>=s?(_.exit("codeFencedFenceSequence"),Ae(L)?qe(_,j,"whitespace")(L):j(L)):R(L)}function j(L){return L===null||ce(L)?(_.exit("codeFencedFence"),k(L)):R(L)}}}function Oae(e,t,n){const i=this;return r;function r(s){return s===null?n(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),o)}function o(s){return i.parser.lazy[i.now().line]?n(s):t(s)}}const Ip={name:"codeIndented",tokenize:Pae},Nae={partial:!0,tokenize:Mae};function Pae(e,t,n){const i=this;return r;function r(u){return e.enter("codeIndented"),qe(e,o,"linePrefix",5)(u)}function o(u){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?s(u):n(u)}function s(u){return u===null?l(u):ce(u)?e.attempt(Nae,s,l)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||ce(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),a)}function l(u){return e.exit("codeIndented"),t(u)}}function Mae(e,t,n){const i=this;return r;function r(s){return i.parser.lazy[i.now().line]?n(s):ce(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),r):qe(e,o,"linePrefix",5)(s)}function o(s){const a=i.events[i.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(s):ce(s)?r(s):n(s)}}const jae={name:"codeText",previous:zae,resolve:Dae,tokenize:Lae};function Dae(e){let t=e.length-4,n=3,i,r;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=n;++i<t;)if(e[i][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(i=n-1,t++;++i<=t;)r===void 0?i!==t&&e[i][1].type!=="lineEnding"&&(r=i):(i===t||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),t-=i-r-2,i=r+2),r=void 0);return e}function zae(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Lae(e,t,n){let i=0,r,o;return s;function s(d){return e.enter("codeText"),e.enter("codeTextSequence"),a(d)}function a(d){return d===96?(e.consume(d),i++,a):(e.exit("codeTextSequence"),l(d))}function l(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(o=e.enter("codeTextSequence"),r=0,c(d)):ce(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||ce(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),r++,c):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(o.type="codeTextData",u(d))}}class Uae{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const i=n??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(t,i):t>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(t,n,i){const r=n||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&Is(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Is(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Is(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Is(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Is(this.left,n.reverse())}}}function Is(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function bj(e){const t={};let n=-1,i,r,o,s,a,l,u;const c=new Uae(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(i=c.get(n),n&&i[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(l=i[1]._tokenizer.events,o=0,o<l.length&&l[o][1].type==="lineEndingBlank"&&(o+=2),o<l.length&&l[o][1].type==="content"))for(;++o<l.length&&l[o][1].type!=="content";)l[o][1].type==="chunkText"&&(l[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(t,Fae(c,n)),n=t[n],u=!0);else if(i[1]._container){for(o=n,r=void 0;o--;)if(s=c.get(o),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(r&&(c.get(r)[1].type="lineEndingBlank"),s[1].type="lineEnding",r=o);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;r&&(i[1].end={...c.get(r)[1].start},a=c.slice(r,n),a.unshift(i),c.splice(r,n-r+1,a))}}return or(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function Fae(e,t){const n=e.get(t)[1],i=e.get(t)[2];let r=t-1;const o=[];let s=n._tokenizer;s||(s=i.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const a=s.events,l=[],u={};let c,d,f=-1,p=n,m=0,h=0;const v=[h];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(c=i.sliceStream(p),p.next||c.push(null),d&&s.defineSkip(p.start),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(c),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<a.length;)a[f][0]==="exit"&&a[f-1][0]==="enter"&&a[f][1].type===a[f-1][1].type&&a[f][1].start.line!==a[f][1].end.line&&(h=f+1,v.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(s.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const y=a.slice(v[f],v[f+1]),w=o.pop();l.push([w,w+y.length-1]),e.splice(w,2,y)}for(l.reverse(),f=-1;++f<l.length;)u[m+l[f][0]]=m+l[f][1],m+=l[f][1]-l[f][0]-1;return u}const Bae={resolve:qae,tokenize:Zae},Vae={partial:!0,tokenize:Hae};function qae(e){return bj(e),e}function Zae(e,t){let n;return i;function i(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(a)}function r(a){return a===null?o(a):ce(a)?e.check(Vae,s,o)(a):(e.consume(a),r)}function o(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function s(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function Hae(e,t,n){const i=this;return r;function r(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),qe(e,o,"linePrefix")}function o(s){if(s===null||ce(s))return n(s);const a=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(s):e.interrupt(i.parser.constructs.flow,n,t)(s)}}function _j(e,t,n,i,r,o,s,a,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return d;function d(y){return y===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(y),e.exit(o),f):y===null||y===32||y===41||Gh(y)?n(y):(e.enter(i),e.enter(s),e.enter(a),e.enter("chunkString",{contentType:"string"}),h(y))}function f(y){return y===62?(e.enter(o),e.consume(y),e.exit(o),e.exit(r),e.exit(i),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(e.exit("chunkString"),e.exit(a),f(y)):y===null||y===60||ce(y)?n(y):(e.consume(y),y===92?m:p)}function m(y){return y===60||y===62||y===92?(e.consume(y),p):p(y)}function h(y){return!c&&(y===null||y===41||Zt(y))?(e.exit("chunkString"),e.exit(a),e.exit(s),e.exit(i),t(y)):c<u&&y===40?(e.consume(y),c++,h):y===41?(e.consume(y),c--,h):y===null||y===32||y===40||Gh(y)?n(y):(e.consume(y),y===92?v:h)}function v(y){return y===40||y===41||y===92?(e.consume(y),h):h(y)}}function wj(e,t,n,i,r,o){const s=this;let a=0,l;return u;function u(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),c}function c(p){return a>999||p===null||p===91||p===93&&!l||p===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?n(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),t):ce(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||ce(p)||a++>999?(e.exit("chunkString"),c(p)):(e.consume(p),l||(l=!Ae(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),a++,d):d(p)}}function xj(e,t,n,i,r,o){let s;return a;function a(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),s=f===40?41:f,l):n(f)}function l(f){return f===s?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),t):(e.enter(o),u(f))}function u(f){return f===s?(e.exit(o),l(s)):f===null?n(f):ce(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),qe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===s||f===null||ce(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:c)}function d(f){return f===s||f===92?(e.consume(f),c):c(f)}}function Zs(e,t){let n;return i;function i(r){return ce(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,i):Ae(r)?qe(e,i,n?"linePrefix":"lineSuffix")(r):t(r)}}const Gae={name:"definition",tokenize:Jae},Wae={partial:!0,tokenize:Kae};function Jae(e,t,n){const i=this;let r;return o;function o(p){return e.enter("definition"),s(p)}function s(p){return wj.call(i,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return r=To(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),l):n(p)}function l(p){return Zt(p)?Zs(e,u)(p):u(p)}function u(p){return _j(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function c(p){return e.attempt(Wae,d,d)(p)}function d(p){return Ae(p)?qe(e,f,"whitespace")(p):f(p)}function f(p){return p===null||ce(p)?(e.exit("definition"),i.parser.defined.push(r),t(p)):n(p)}}function Kae(e,t,n){return i;function i(a){return Zt(a)?Zs(e,r)(a):n(a)}function r(a){return xj(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return Ae(a)?qe(e,s,"whitespace")(a):s(a)}function s(a){return a===null||ce(a)?t(a):n(a)}}const Yae={name:"hardBreakEscape",tokenize:Xae};function Xae(e,t,n){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return ce(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const Qae={name:"headingAtx",resolve:eue,tokenize:tue};function eue(e,t){let n=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),n-2>i&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&e[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[n][1].end},o={type:"chunkText",start:e[i][1].start,end:e[n][1].end,contentType:"text"},or(e,i,n-i+1,[["enter",r,t],["enter",o,t],["exit",o,t],["exit",r,t]])),e}function tue(e,t,n){let i=0;return r;function r(c){return e.enter("atxHeading"),o(c)}function o(c){return e.enter("atxHeadingSequence"),s(c)}function s(c){return c===35&&i++<6?(e.consume(c),s):c===null||Zt(c)?(e.exit("atxHeadingSequence"),a(c)):n(c)}function a(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||ce(c)?(e.exit("atxHeading"),t(c)):Ae(c)?qe(e,a,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),a(c))}function u(c){return c===null||c===35||Zt(c)?(e.exit("atxHeadingText"),a(c)):(e.consume(c),u)}}const nue=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Yx=["pre","script","style","textarea"],rue={concrete:!0,name:"htmlFlow",resolveTo:sue,tokenize:aue},iue={partial:!0,tokenize:lue},oue={partial:!0,tokenize:uue};function sue(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function aue(e,t,n){const i=this;let r,o,s,a,l;return u;function u(A){return c(A)}function c(A){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(A),d}function d(A){return A===33?(e.consume(A),f):A===47?(e.consume(A),o=!0,h):A===63?(e.consume(A),r=3,i.interrupt?t:E):Jn(A)?(e.consume(A),s=String.fromCharCode(A),v):n(A)}function f(A){return A===45?(e.consume(A),r=2,p):A===91?(e.consume(A),r=5,a=0,m):Jn(A)?(e.consume(A),r=4,i.interrupt?t:E):n(A)}function p(A){return A===45?(e.consume(A),i.interrupt?t:E):n(A)}function m(A){const H="CDATA[";return A===H.charCodeAt(a++)?(e.consume(A),a===H.length?i.interrupt?t:Z:m):n(A)}function h(A){return Jn(A)?(e.consume(A),s=String.fromCharCode(A),v):n(A)}function v(A){if(A===null||A===47||A===62||Zt(A)){const H=A===47,re=s.toLowerCase();return!H&&!o&&Yx.includes(re)?(r=1,i.interrupt?t(A):Z(A)):nue.includes(s.toLowerCase())?(r=6,H?(e.consume(A),y):i.interrupt?t(A):Z(A)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(A):o?w(A):S(A))}return A===45||Xt(A)?(e.consume(A),s+=String.fromCharCode(A),v):n(A)}function y(A){return A===62?(e.consume(A),i.interrupt?t:Z):n(A)}function w(A){return Ae(A)?(e.consume(A),w):U(A)}function S(A){return A===47?(e.consume(A),U):A===58||A===95||Jn(A)?(e.consume(A),b):Ae(A)?(e.consume(A),S):U(A)}function b(A){return A===45||A===46||A===58||A===95||Xt(A)?(e.consume(A),b):C(A)}function C(A){return A===61?(e.consume(A),_):Ae(A)?(e.consume(A),C):S(A)}function _(A){return A===null||A===60||A===61||A===62||A===96?n(A):A===34||A===39?(e.consume(A),l=A,k):Ae(A)?(e.consume(A),_):R(A)}function k(A){return A===l?(e.consume(A),l=null,M):A===null||ce(A)?n(A):(e.consume(A),k)}function R(A){return A===null||A===34||A===39||A===47||A===60||A===61||A===62||A===96||Zt(A)?C(A):(e.consume(A),R)}function M(A){return A===47||A===62||Ae(A)?S(A):n(A)}function U(A){return A===62?(e.consume(A),z):n(A)}function z(A){return A===null||ce(A)?Z(A):Ae(A)?(e.consume(A),z):n(A)}function Z(A){return A===45&&r===2?(e.consume(A),Y):A===60&&r===1?(e.consume(A),ne):A===62&&r===4?(e.consume(A),we):A===63&&r===3?(e.consume(A),E):A===93&&r===5?(e.consume(A),se):ce(A)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(iue,de,W)(A)):A===null||ce(A)?(e.exit("htmlFlowData"),W(A)):(e.consume(A),Z)}function W(A){return e.check(oue,j,de)(A)}function j(A){return e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),L}function L(A){return A===null||ce(A)?W(A):(e.enter("htmlFlowData"),Z(A))}function Y(A){return A===45?(e.consume(A),E):Z(A)}function ne(A){return A===47?(e.consume(A),s="",Q):Z(A)}function Q(A){if(A===62){const H=s.toLowerCase();return Yx.includes(H)?(e.consume(A),we):Z(A)}return Jn(A)&&s.length<8?(e.consume(A),s+=String.fromCharCode(A),Q):Z(A)}function se(A){return A===93?(e.consume(A),E):Z(A)}function E(A){return A===62?(e.consume(A),we):A===45&&r===2?(e.consume(A),E):Z(A)}function we(A){return A===null||ce(A)?(e.exit("htmlFlowData"),de(A)):(e.consume(A),we)}function de(A){return e.exit("htmlFlow"),t(A)}}function uue(e,t,n){const i=this;return r;function r(s){return ce(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),o):n(s)}function o(s){return i.parser.lazy[i.now().line]?n(s):t(s)}}function lue(e,t,n){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(sf,t,n)}}const cue={name:"htmlText",tokenize:due};function due(e,t,n){const i=this;let r,o,s;return a;function a(E){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(E),l}function l(E){return E===33?(e.consume(E),u):E===47?(e.consume(E),C):E===63?(e.consume(E),S):Jn(E)?(e.consume(E),R):n(E)}function u(E){return E===45?(e.consume(E),c):E===91?(e.consume(E),o=0,m):Jn(E)?(e.consume(E),w):n(E)}function c(E){return E===45?(e.consume(E),p):n(E)}function d(E){return E===null?n(E):E===45?(e.consume(E),f):ce(E)?(s=d,ne(E)):(e.consume(E),d)}function f(E){return E===45?(e.consume(E),p):d(E)}function p(E){return E===62?Y(E):E===45?f(E):d(E)}function m(E){const we="CDATA[";return E===we.charCodeAt(o++)?(e.consume(E),o===we.length?h:m):n(E)}function h(E){return E===null?n(E):E===93?(e.consume(E),v):ce(E)?(s=h,ne(E)):(e.consume(E),h)}function v(E){return E===93?(e.consume(E),y):h(E)}function y(E){return E===62?Y(E):E===93?(e.consume(E),y):h(E)}function w(E){return E===null||E===62?Y(E):ce(E)?(s=w,ne(E)):(e.consume(E),w)}function S(E){return E===null?n(E):E===63?(e.consume(E),b):ce(E)?(s=S,ne(E)):(e.consume(E),S)}function b(E){return E===62?Y(E):S(E)}function C(E){return Jn(E)?(e.consume(E),_):n(E)}function _(E){return E===45||Xt(E)?(e.consume(E),_):k(E)}function k(E){return ce(E)?(s=k,ne(E)):Ae(E)?(e.consume(E),k):Y(E)}function R(E){return E===45||Xt(E)?(e.consume(E),R):E===47||E===62||Zt(E)?M(E):n(E)}function M(E){return E===47?(e.consume(E),Y):E===58||E===95||Jn(E)?(e.consume(E),U):ce(E)?(s=M,ne(E)):Ae(E)?(e.consume(E),M):Y(E)}function U(E){return E===45||E===46||E===58||E===95||Xt(E)?(e.consume(E),U):z(E)}function z(E){return E===61?(e.consume(E),Z):ce(E)?(s=z,ne(E)):Ae(E)?(e.consume(E),z):M(E)}function Z(E){return E===null||E===60||E===61||E===62||E===96?n(E):E===34||E===39?(e.consume(E),r=E,W):ce(E)?(s=Z,ne(E)):Ae(E)?(e.consume(E),Z):(e.consume(E),j)}function W(E){return E===r?(e.consume(E),r=void 0,L):E===null?n(E):ce(E)?(s=W,ne(E)):(e.consume(E),W)}function j(E){return E===null||E===34||E===39||E===60||E===61||E===96?n(E):E===47||E===62||Zt(E)?M(E):(e.consume(E),j)}function L(E){return E===47||E===62||Zt(E)?M(E):n(E)}function Y(E){return E===62?(e.consume(E),e.exit("htmlTextData"),e.exit("htmlText"),t):n(E)}function ne(E){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),Q}function Q(E){return Ae(E)?qe(e,se,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):se(E)}function se(E){return e.enter("htmlTextData"),s(E)}}const $y={name:"labelEnd",resolveAll:mue,resolveTo:gue,tokenize:vue},fue={tokenize:yue},pue={tokenize:bue},hue={tokenize:_ue};function mue(e){let t=-1;const n=[];for(;++t<e.length;){const i=e[t][1];if(n.push(e[t]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",t+=r}}return e.length!==n.length&&or(e,0,e.length,n),e}function gue(e,t){let n=e.length,i=0,r,o,s,a;for(;n--;)if(r=e[n][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(s){if(e[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=n,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(s=n);const l={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[s][1].end}},c={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[s-2][1].start}};return a=[["enter",l,t],["enter",u,t]],a=bn(a,e.slice(o+1,o+i+3)),a=bn(a,[["enter",c,t]]),a=bn(a,Ry(t.parser.constructs.insideSpan.null,e.slice(o+i+4,s-3),t)),a=bn(a,[["exit",c,t],e[s-2],e[s-1],["exit",u,t]]),a=bn(a,e.slice(s+1)),a=bn(a,[["exit",l,t]]),or(e,o,e.length,a),e}function vue(e,t,n){const i=this;let r=i.events.length,o,s;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return a;function a(f){return o?o._inactive?d(f):(s=i.parser.defined.includes(To(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):n(f)}function l(f){return f===40?e.attempt(fue,c,s?c:d)(f):f===91?e.attempt(pue,c,s?u:d)(f):s?c(f):d(f)}function u(f){return e.attempt(hue,c,d)(f)}function c(f){return t(f)}function d(f){return o._balanced=!0,n(f)}}function yue(e,t,n){return i;function i(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),r}function r(d){return Zt(d)?Zs(e,o)(d):o(d)}function o(d){return d===41?c(d):_j(e,s,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function s(d){return Zt(d)?Zs(e,l)(d):c(d)}function a(d){return n(d)}function l(d){return d===34||d===39||d===40?xj(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return Zt(d)?Zs(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function bue(e,t,n){const i=this;return r;function r(a){return wj.call(i,e,o,s,"reference","referenceMarker","referenceString")(a)}function o(a){return i.parser.defined.includes(To(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function s(a){return n(a)}}function _ue(e,t,n){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),t):n(o)}}const wue={name:"labelStartImage",resolveAll:$y.resolveAll,tokenize:xue};function xue(e,t,n){const i=this;return r;function r(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),o}function o(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),s):n(a)}function s(a){return a===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(a):t(a)}}const Sue={name:"labelStartLink",resolveAll:$y.resolveAll,tokenize:Eue};function Eue(e,t,n){const i=this;return r;function r(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),o}function o(s){return s===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(s):t(s)}}const Tp={name:"lineEnding",tokenize:Iue};function Iue(e,t){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),qe(e,t,"linePrefix")}}const Cl={name:"thematicBreak",tokenize:Tue};function Tue(e,t,n){let i=0,r;return o;function o(u){return e.enter("thematicBreak"),s(u)}function s(u){return r=u,a(u)}function a(u){return u===r?(e.enter("thematicBreakSequence"),l(u)):i>=3&&(u===null||ce(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===r?(e.consume(u),i++,l):(e.exit("thematicBreakSequence"),Ae(u)?qe(e,a,"whitespace")(u):a(u))}}const Ft={continuation:{tokenize:Rue},exit:Oue,name:"list",tokenize:Aue},kue={partial:!0,tokenize:Nue},Cue={partial:!0,tokenize:$ue};function Aue(e,t,n){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,s=0;return a;function a(p){const m=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Wh(p)){if(i.containerState.type||(i.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Cl,n,u)(p):u(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(p)}return n(p)}function l(p){return Wh(p)&&++s<10?(e.consume(p),l):(!i.interrupt||s<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(sf,i.interrupt?n:c,e.attempt(kue,f,d))}function c(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function d(p){return Ae(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function Rue(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check(sf,r,o);function r(a){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,qe(e,t,"listItemIndent",i.containerState.size+1)(a)}function o(a){return i.containerState.furtherBlankLines||!Ae(a)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,s(a)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(Cue,t,s)(a))}function s(a){return i.containerState._closeFlow=!0,i.interrupt=void 0,qe(e,e.attempt(Ft,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function $ue(e,t,n){const i=this;return qe(e,r,"listItemIndent",i.containerState.size+1);function r(o){const s=i.events[i.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===i.containerState.size?t(o):n(o)}}function Oue(e){e.exit(this.containerState.type)}function Nue(e,t,n){const i=this;return qe(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const s=i.events[i.events.length-1];return!Ae(o)&&s&&s[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const Xx={name:"setextUnderline",resolveTo:Pue,tokenize:Mue};function Pue(e,t){let n=e.length,i,r,o;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){i=n;break}e[n][1].type==="paragraph"&&(r=n)}else e[n][1].type==="content"&&e.splice(n,1),!o&&e[n][1].type==="definition"&&(o=n);const s={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",s,t]),e.splice(o+1,0,["exit",e[i][1],t]),e[i][1].end={...e[o][1].end}):e[i][1]=s,e.push(["exit",s,t]),e}function Mue(e,t,n){const i=this;let r;return o;function o(u){let c=i.events.length,d;for(;c--;)if(i.events[c][1].type!=="lineEnding"&&i.events[c][1].type!=="linePrefix"&&i.events[c][1].type!=="content"){d=i.events[c][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||d)?(e.enter("setextHeadingLine"),r=u,s(u)):n(u)}function s(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===r?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),Ae(u)?qe(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||ce(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const jue={tokenize:Due};function Due(e){const t=this,n=e.attempt(sf,i,e.attempt(this.parser.constructs.flowInitial,r,qe(e,e.attempt(this.parser.constructs.flow,r,e.attempt(Bae,r)),"linePrefix")));return n;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const zue={resolveAll:Ej()},Lue=Sj("string"),Uue=Sj("text");function Sj(e){return{resolveAll:Ej(e==="text"?Fue:void 0),tokenize:t};function t(n){const i=this,r=this.parser.constructs[e],o=n.attempt(r,s,a);return s;function s(c){return u(c)?o(c):a(c)}function a(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),o(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const d=r[c];let f=-1;if(d)for(;++f<d.length;){const p=d[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function Ej(e){return t;function t(n,i){let r=-1,o;for(;++r<=n.length;)o===void 0?n[r]&&n[r][1].type==="data"&&(o=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==o+2&&(n[o][1].end=n[r-1][1].end,n.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(n,i):n}}function Fue(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const i=e[n-1][1],r=t.sliceStream(i);let o=r.length,s=-1,a=0,l;for(;o--;){const u=r[o];if(typeof u=="string"){for(s=u.length;u.charCodeAt(s-1)===32;)a++,s--;if(s)break;s=-1}else if(u===-2)l=!0,a++;else if(u!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){const u={type:n===e.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?s:i.start._bufferIndex+s,_index:i.start._index+o,line:i.end.line,column:i.end.column-a,offset:i.end.offset-a},end:{...i.end}};i.end={...u.start},i.start.offset===i.end.offset?Object.assign(i,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Bue={42:Ft,43:Ft,45:Ft,48:Ft,49:Ft,50:Ft,51:Ft,52:Ft,53:Ft,54:Ft,55:Ft,56:Ft,57:Ft,62:gj},Vue={91:Gae},que={[-2]:Ip,[-1]:Ip,32:Ip},Zue={35:Qae,42:Cl,45:[Xx,Cl],60:rue,61:Xx,95:Cl,96:Kx,126:Kx},Hue={38:yj,92:vj},Gue={[-5]:Tp,[-4]:Tp,[-3]:Tp,33:wue,38:yj,42:Jh,60:[Sae,cue],91:Sue,92:[Yae,vj],93:$y,95:Jh,96:jae},Wue={null:[Jh,zue]},Jue={null:[42,95]},Kue={null:[]},Yue=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Jue,contentInitial:Vue,disable:Kue,document:Bue,flow:Zue,flowInitial:que,insideSpan:Wue,string:Hue,text:Gue},Symbol.toStringTag,{value:"Module"}));function Xue(e,t,n){let i={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},o=[];let s=[],a=[];const l={attempt:k(C),check:k(_),consume:w,enter:S,exit:b,interrupt:k(_,{interrupt:!0})},u={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&o.push(t),u;function d(z){return s=bn(s,z),v(),s[s.length-1]!==null?[]:(R(t,0),u.events=Ry(o,u.events,u),u.events)}function f(z,Z){return ele(p(z),Z)}function p(z){return Que(s,z)}function m(){const{_bufferIndex:z,_index:Z,line:W,column:j,offset:L}=i;return{_bufferIndex:z,_index:Z,line:W,column:j,offset:L}}function h(z){r[z.line]=z.column,U()}function v(){let z;for(;i._index<s.length;){const Z=s[i._index];if(typeof Z=="string")for(z=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===z&&i._bufferIndex<Z.length;)y(Z.charCodeAt(i._bufferIndex));else y(Z)}}function y(z){c=c(z)}function w(z){ce(z)?(i.line++,i.column=1,i.offset+=z===-3?2:1,U()):z!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===s[i._index].length&&(i._bufferIndex=-1,i._index++)),u.previous=z}function S(z,Z){const W=Z||{};return W.type=z,W.start=m(),u.events.push(["enter",W,u]),a.push(W),W}function b(z){const Z=a.pop();return Z.end=m(),u.events.push(["exit",Z,u]),Z}function C(z,Z){R(z,Z.from)}function _(z,Z){Z.restore()}function k(z,Z){return W;function W(j,L,Y){let ne,Q,se,E;return Array.isArray(j)?de(j):"tokenize"in j?de([j]):we(j);function we(ie){return ke;function ke(ze){const Vn=ze!==null&&ie[ze],pn=ze!==null&&ie.null,wt=[...Array.isArray(Vn)?Vn:Vn?[Vn]:[],...Array.isArray(pn)?pn:pn?[pn]:[]];return de(wt)(ze)}}function de(ie){return ne=ie,Q=0,ie.length===0?Y:A(ie[Q])}function A(ie){return ke;function ke(ze){return E=M(),se=ie,ie.partial||(u.currentConstruct=ie),ie.name&&u.parser.constructs.disable.null.includes(ie.name)?re():ie.tokenize.call(Z?Object.assign(Object.create(u),Z):u,l,H,re)(ze)}}function H(ie){return z(se,E),L}function re(ie){return E.restore(),++Q<ne.length?A(ne[Q]):Y}}}function R(z,Z){z.resolveAll&&!o.includes(z)&&o.push(z),z.resolve&&or(u.events,Z,u.events.length-Z,z.resolve(u.events.slice(Z),u)),z.resolveTo&&(u.events=z.resolveTo(u.events,u))}function M(){const z=m(),Z=u.previous,W=u.currentConstruct,j=u.events.length,L=Array.from(a);return{from:j,restore:Y};function Y(){i=z,u.previous=Z,u.currentConstruct=W,u.events.length=j,a=L,U()}}function U(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function Que(e,t){const n=t.start._index,i=t.start._bufferIndex,r=t.end._index,o=t.end._bufferIndex;let s;if(n===r)s=[e[n].slice(i,o)];else{if(s=e.slice(n,r),i>-1){const a=s[0];typeof a=="string"?s[0]=a.slice(i):s.shift()}o>0&&s.push(e[r].slice(0,o))}return s}function ele(e,t){let n=-1;const i=[];let r;for(;++n<e.length;){const o=e[n];let s;if(typeof o=="string")s=o;else switch(o){case-5:{s="\r";break}case-4:{s=`
|
|
154
|
+
`;break}case-3:{s=`\r
|
|
155
|
+
`;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&r)continue;s=" ";break}default:s=String.fromCharCode(o)}r=o===-2,i.push(s)}return i.join("")}function tle(e){const i={constructs:uae([Yue,...(e||{}).extensions||[]]),content:r(gae),defined:[],document:r(yae),flow:r(jue),lazy:{},string:r(Lue),text:r(Uue)};return i;function r(o){return s;function s(a){return Xue(i,o,a)}}}function nle(e){for(;!bj(e););return e}const Qx=/[\0\t\n\r]/g;function rle(){let e=1,t="",n=!0,i;return r;function r(o,s,a){const l=[];let u,c,d,f,p;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(s||void 0).decode(o)),d=0,t="",n&&(o.charCodeAt(0)===65279&&d++,n=void 0);d<o.length;){if(Qx.lastIndex=d,u=Qx.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){t=o.slice(d);break}if(p===10&&d===f&&i)l.push(-3),i=void 0;else switch(i&&(l.push(-5),i=void 0),d<f&&(l.push(o.slice(d,f)),e+=f-d),p){case 0:{l.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,l.push(-2);e++<c;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:i=!0,e=1}d=f+1}return a&&(i&&l.push(-5),t&&l.push(t),l.push(null)),l}}const ile=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ole(e){return e.replace(ile,sle)}function sle(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),o=r===120||r===88;return mj(n.slice(o?2:1),o?16:10)}return Ay(n)||e}const Ij={}.hasOwnProperty;function ale(e,t,n){return typeof t!="string"&&(n=t,t=void 0),ule(n)(nle(tle(n).document().write(rle()(e,t,!0))))}function ule(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Rr),autolinkProtocol:M,autolinkEmail:M,atxHeading:o(Xe),blockQuote:o(pn),characterEscape:M,characterReference:M,codeFenced:o(wt),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:o(wt,s),codeText:o(Ji,s),codeTextData:M,data:M,codeFlowValue:M,definition:o(ut),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:o(et),hardBreakEscape:o(it),hardBreakTrailing:o(it),htmlFlow:o(Te,s),htmlFlowData:M,htmlText:o(Te,s),htmlTextData:M,image:o(Gt),label:s,link:o(Rr),listItem:o(Ze),listItemValue:f,listOrdered:o(X,d),listUnordered:o(X),paragraph:o(ui),reference:A,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:o(Xe),strong:o(Cu),thematicBreak:o(Ru)},exit:{atxHeading:l(),atxHeadingSequence:C,autolink:l(),autolinkEmail:Vn,autolinkProtocol:ze,blockQuote:l(),characterEscapeValue:U,characterReferenceMarkerHexadecimal:re,characterReferenceMarkerNumeric:re,characterReferenceValue:ie,characterReference:ke,codeFenced:l(v),codeFencedFence:h,codeFencedFenceInfo:p,codeFencedFenceMeta:m,codeFlowValue:U,codeIndented:l(y),codeText:l(L),codeTextData:U,data:U,definition:l(),definitionDestinationString:b,definitionLabelString:w,definitionTitleString:S,emphasis:l(),hardBreakEscape:l(Z),hardBreakTrailing:l(Z),htmlFlow:l(W),htmlFlowData:U,htmlText:l(j),htmlTextData:U,image:l(ne),label:se,labelText:Q,lineEnding:z,link:l(Y),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:H,resourceDestinationString:E,resourceTitleString:we,resource:de,setextHeading:l(R),setextHeadingLineSequence:k,setextHeadingText:_,strong:l(),thematicBreak:l()}};Tj(t,(e||{}).mdastExtensions||[]);const n={};return i;function i(P){let V={type:"root",children:[]};const oe={stack:[V],tokenStack:[],config:t,enter:a,exit:u,buffer:s,resume:c,data:n},Se=[];let Ce=-1;for(;++Ce<P.length;)if(P[Ce][1].type==="listOrdered"||P[Ce][1].type==="listUnordered")if(P[Ce][0]==="enter")Se.push(Ce);else{const Ct=Se.pop();Ce=r(P,Ct,Ce)}for(Ce=-1;++Ce<P.length;){const Ct=t[P[Ce][0]];Ij.call(Ct,P[Ce][1].type)&&Ct[P[Ce][1].type].call(Object.assign({sliceSerialize:P[Ce][2].sliceSerialize},oe),P[Ce][1])}if(oe.tokenStack.length>0){const Ct=oe.tokenStack[oe.tokenStack.length-1];(Ct[1]||eS).call(oe,void 0,Ct[0])}for(V.position={start:Pr(P.length>0?P[0][1].start:{line:1,column:1,offset:0}),end:Pr(P.length>0?P[P.length-2][1].end:{line:1,column:1,offset:0})},Ce=-1;++Ce<t.transforms.length;)V=t.transforms[Ce](V)||V;return V}function r(P,V,oe){let Se=V-1,Ce=-1,Ct=!1,cr,hn,$r,mn;for(;++Se<=oe;){const xt=P[Se];switch(xt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{xt[0]==="enter"?Ce++:Ce--,mn=void 0;break}case"lineEndingBlank":{xt[0]==="enter"&&(cr&&!mn&&!Ce&&!$r&&($r=Se),mn=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:mn=void 0}if(!Ce&&xt[0]==="enter"&&xt[1].type==="listItemPrefix"||Ce===-1&&xt[0]==="exit"&&(xt[1].type==="listUnordered"||xt[1].type==="listOrdered")){if(cr){let Or=Se;for(hn=void 0;Or--;){const En=P[Or];if(En[1].type==="lineEnding"||En[1].type==="lineEndingBlank"){if(En[0]==="exit")continue;hn&&(P[hn][1].type="lineEndingBlank",Ct=!0),En[1].type="lineEnding",hn=Or}else if(!(En[1].type==="linePrefix"||En[1].type==="blockQuotePrefix"||En[1].type==="blockQuotePrefixWhitespace"||En[1].type==="blockQuoteMarker"||En[1].type==="listItemIndent"))break}$r&&(!hn||$r<hn)&&(cr._spread=!0),cr.end=Object.assign({},hn?P[hn][1].start:xt[1].end),P.splice(hn||Se,0,["exit",cr,xt[2]]),Se++,oe++}if(xt[1].type==="listItemPrefix"){const Or={type:"listItem",_spread:!1,start:Object.assign({},xt[1].start),end:void 0};cr=Or,P.splice(Se,0,["enter",Or,xt[2]]),Se++,oe++,$r=void 0,mn=!0}}}return P[V][1]._spread=Ct,oe}function o(P,V){return oe;function oe(Se){a.call(this,P(Se),Se),V&&V.call(this,Se)}}function s(){this.stack.push({type:"fragment",children:[]})}function a(P,V,oe){this.stack[this.stack.length-1].children.push(P),this.stack.push(P),this.tokenStack.push([V,oe||void 0]),P.position={start:Pr(V.start),end:void 0}}function l(P){return V;function V(oe){P&&P.call(this,oe),u.call(this,oe)}}function u(P,V){const oe=this.stack.pop(),Se=this.tokenStack.pop();if(Se)Se[0].type!==P.type&&(V?V.call(this,P,Se[0]):(Se[1]||eS).call(this,P,Se[0]));else throw new Error("Cannot close `"+P.type+"` ("+qs({start:P.start,end:P.end})+"): it’s not open");oe.position.end=Pr(P.end)}function c(){return sae(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(P){if(this.data.expectingFirstListItemValue){const V=this.stack[this.stack.length-2];V.start=Number.parseInt(this.sliceSerialize(P),10),this.data.expectingFirstListItemValue=void 0}}function p(){const P=this.resume(),V=this.stack[this.stack.length-1];V.lang=P}function m(){const P=this.resume(),V=this.stack[this.stack.length-1];V.meta=P}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const P=this.resume(),V=this.stack[this.stack.length-1];V.value=P.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){const P=this.resume(),V=this.stack[this.stack.length-1];V.value=P.replace(/(\r?\n|\r)$/g,"")}function w(P){const V=this.resume(),oe=this.stack[this.stack.length-1];oe.label=V,oe.identifier=To(this.sliceSerialize(P)).toLowerCase()}function S(){const P=this.resume(),V=this.stack[this.stack.length-1];V.title=P}function b(){const P=this.resume(),V=this.stack[this.stack.length-1];V.url=P}function C(P){const V=this.stack[this.stack.length-1];if(!V.depth){const oe=this.sliceSerialize(P).length;V.depth=oe}}function _(){this.data.setextHeadingSlurpLineEnding=!0}function k(P){const V=this.stack[this.stack.length-1];V.depth=this.sliceSerialize(P).codePointAt(0)===61?1:2}function R(){this.data.setextHeadingSlurpLineEnding=void 0}function M(P){const oe=this.stack[this.stack.length-1].children;let Se=oe[oe.length-1];(!Se||Se.type!=="text")&&(Se=Au(),Se.position={start:Pr(P.start),end:void 0},oe.push(Se)),this.stack.push(Se)}function U(P){const V=this.stack.pop();V.value+=this.sliceSerialize(P),V.position.end=Pr(P.end)}function z(P){const V=this.stack[this.stack.length-1];if(this.data.atHardBreak){const oe=V.children[V.children.length-1];oe.position.end=Pr(P.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(V.type)&&(M.call(this,P),U.call(this,P))}function Z(){this.data.atHardBreak=!0}function W(){const P=this.resume(),V=this.stack[this.stack.length-1];V.value=P}function j(){const P=this.resume(),V=this.stack[this.stack.length-1];V.value=P}function L(){const P=this.resume(),V=this.stack[this.stack.length-1];V.value=P}function Y(){const P=this.stack[this.stack.length-1];if(this.data.inReference){const V=this.data.referenceType||"shortcut";P.type+="Reference",P.referenceType=V,delete P.url,delete P.title}else delete P.identifier,delete P.label;this.data.referenceType=void 0}function ne(){const P=this.stack[this.stack.length-1];if(this.data.inReference){const V=this.data.referenceType||"shortcut";P.type+="Reference",P.referenceType=V,delete P.url,delete P.title}else delete P.identifier,delete P.label;this.data.referenceType=void 0}function Q(P){const V=this.sliceSerialize(P),oe=this.stack[this.stack.length-2];oe.label=ole(V),oe.identifier=To(V).toLowerCase()}function se(){const P=this.stack[this.stack.length-1],V=this.resume(),oe=this.stack[this.stack.length-1];if(this.data.inReference=!0,oe.type==="link"){const Se=P.children;oe.children=Se}else oe.alt=V}function E(){const P=this.resume(),V=this.stack[this.stack.length-1];V.url=P}function we(){const P=this.resume(),V=this.stack[this.stack.length-1];V.title=P}function de(){this.data.inReference=void 0}function A(){this.data.referenceType="collapsed"}function H(P){const V=this.resume(),oe=this.stack[this.stack.length-1];oe.label=V,oe.identifier=To(this.sliceSerialize(P)).toLowerCase(),this.data.referenceType="full"}function re(P){this.data.characterReferenceType=P.type}function ie(P){const V=this.sliceSerialize(P),oe=this.data.characterReferenceType;let Se;oe?(Se=mj(V,oe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Se=Ay(V);const Ce=this.stack[this.stack.length-1];Ce.value+=Se}function ke(P){const V=this.stack.pop();V.position.end=Pr(P.end)}function ze(P){U.call(this,P);const V=this.stack[this.stack.length-1];V.url=this.sliceSerialize(P)}function Vn(P){U.call(this,P);const V=this.stack[this.stack.length-1];V.url="mailto:"+this.sliceSerialize(P)}function pn(){return{type:"blockquote",children:[]}}function wt(){return{type:"code",lang:null,meta:null,value:""}}function Ji(){return{type:"inlineCode",value:""}}function ut(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function et(){return{type:"emphasis",children:[]}}function Xe(){return{type:"heading",depth:0,children:[]}}function it(){return{type:"break"}}function Te(){return{type:"html",value:""}}function Gt(){return{type:"image",title:null,url:"",alt:null}}function Rr(){return{type:"link",title:null,url:"",children:[]}}function X(P){return{type:"list",ordered:P.type==="listOrdered",start:null,spread:P._spread,children:[]}}function Ze(P){return{type:"listItem",spread:P._spread,checked:null,children:[]}}function ui(){return{type:"paragraph",children:[]}}function Cu(){return{type:"strong",children:[]}}function Au(){return{type:"text",value:""}}function Ru(){return{type:"thematicBreak"}}}function Pr(e){return{line:e.line,column:e.column,offset:e.offset}}function Tj(e,t){let n=-1;for(;++n<t.length;){const i=t[n];Array.isArray(i)?Tj(e,i):lle(e,i)}}function lle(e,t){let n;for(n in t)if(Ij.call(t,n))switch(n){case"canContainEols":{const i=t[n];i&&e[n].push(...i);break}case"transforms":{const i=t[n];i&&e[n].push(...i);break}case"enter":case"exit":{const i=t[n];i&&Object.assign(e[n],i);break}}}function eS(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+qs({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+qs({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+qs({start:t.start,end:t.end})+") is still open")}function cle(e){const t=this;t.parser=n;function n(i){return ale(i,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function dle(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function fle(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
156
|
+
`}]}function ple(e,t){const n=t.value?t.value+`
|
|
157
|
+
`:"",i={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function hle(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function mle(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function gle(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),r=ds(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let s,a=e.footnoteCounts.get(i);a===void 0?(a=0,e.footnoteOrder.push(i),s=e.footnoteOrder.length):s=o+1,a+=1,e.footnoteCounts.set(i,a);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function vle(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yle(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function kj(e,t){const n=t.referenceType;let i="]";if(n==="collapsed"?i+="[]":n==="full"&&(i+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+i}];const r=e.all(t),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const s=r[r.length-1];return s&&s.type==="text"?s.value+=i:r.push({type:"text",value:i}),r}function ble(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return kj(e,t);const r={src:ds(i.url||""),alt:t.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,o),e.applyData(t,o)}function _le(e,t){const n={src:ds(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,i),e.applyData(t,i)}function wle(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const i={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,i),e.applyData(t,i)}function xle(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return kj(e,t);const r={href:ds(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function Sle(e,t){const n={href:ds(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Ele(e,t,n){const i=e.all(t),r=n?Ile(n):Cj(t),o={},s=[];if(typeof t.checked=="boolean"){const c=i[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},i.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let a=-1;for(;++a<i.length;){const c=i[a];(r||a!==0||c.type!=="element"||c.tagName!=="p")&&s.push({type:"text",value:`
|
|
158
|
+
`}),c.type==="element"&&c.tagName==="p"&&!r?s.push(...c.children):s.push(c)}const l=i[i.length-1];l&&(r||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
|
|
159
|
+
`});const u={type:"element",tagName:"li",properties:o,children:s};return e.patch(t,u),e.applyData(t,u)}function Ile(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let i=-1;for(;!t&&++i<n.length;)t=Cj(n[i])}return t}function Cj(e){const t=e.spread;return t??e.children.length>1}function Tle(e,t){const n={},i=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<i.length;){const s=i[r];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function kle(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Cle(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function Ale(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Rle(e,t){const n=e.all(t),i=n.shift(),r=[];if(i){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(t.children[0],s),r.push(s)}if(n.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=Iy(t.children[1]),l=uj(t.children[t.children.length-1]);a&&l&&(s.position={start:a,end:l}),r.push(s)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function $le(e,t,n){const i=n?n.children:void 0,o=(i?i.indexOf(t):1)===0?"th":"td",s=n&&n.type==="table"?n.align:void 0,a=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<a;){const d=t.children[l],f={},p=s?s[l]:void 0;p&&(f.align=p);let m={type:"element",tagName:o,properties:f,children:[]};d&&(m.children=e.all(d),e.patch(d,m),m=e.applyData(d,m)),u.push(m)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function Ole(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const tS=9,nS=32;function Nle(e){const t=String(e),n=/\r?\n|\r/g;let i=n.exec(t),r=0;const o=[];for(;i;)o.push(rS(t.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(t);return o.push(rS(t.slice(r),r>0,!1)),o.join("")}function rS(e,t,n){let i=0,r=e.length;if(t){let o=e.codePointAt(i);for(;o===tS||o===nS;)i++,o=e.codePointAt(i)}if(n){let o=e.codePointAt(r-1);for(;o===tS||o===nS;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function Ple(e,t){const n={type:"text",value:Nle(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Mle(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const jle={blockquote:dle,break:fle,code:ple,delete:hle,emphasis:mle,footnoteReference:gle,heading:vle,html:yle,imageReference:ble,image:_le,inlineCode:wle,linkReference:xle,link:Sle,listItem:Ele,list:Tle,paragraph:kle,root:Cle,strong:Ale,table:Rle,tableCell:Ole,tableRow:$le,text:Ple,thematicBreak:Mle,toml:al,yaml:al,definition:al,footnoteDefinition:al};function al(){}const Aj=-1,af=0,Hs=1,_c=2,Oy=3,Ny=4,Py=5,My=6,Rj=7,$j=8,iS=typeof self=="object"?self:globalThis,Dle=(e,t)=>{const n=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,s]=t[r];switch(o){case af:case Aj:return n(s,r);case Hs:{const a=n([],r);for(const l of s)a.push(i(l));return a}case _c:{const a=n({},r);for(const[l,u]of s)a[i(l)]=i(u);return a}case Oy:return n(new Date(s),r);case Ny:{const{source:a,flags:l}=s;return n(new RegExp(a,l),r)}case Py:{const a=n(new Map,r);for(const[l,u]of s)a.set(i(l),i(u));return a}case My:{const a=n(new Set,r);for(const l of s)a.add(i(l));return a}case Rj:{const{name:a,message:l}=s;return n(new iS[a](l),r)}case $j:return n(BigInt(s),r);case"BigInt":return n(Object(BigInt(s)),r);case"ArrayBuffer":return n(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:a}=new Uint8Array(s);return n(new DataView(a),s)}}return n(new iS[o](s),r)};return i},oS=e=>Dle(new Map,e)(0),lo="",{toString:zle}={},{keys:Lle}=Object,Ts=e=>{const t=typeof e;if(t!=="object"||!e)return[af,t];const n=zle.call(e).slice(8,-1);switch(n){case"Array":return[Hs,lo];case"Object":return[_c,lo];case"Date":return[Oy,lo];case"RegExp":return[Ny,lo];case"Map":return[Py,lo];case"Set":return[My,lo];case"DataView":return[Hs,n]}return n.includes("Array")?[Hs,n]:n.includes("Error")?[Rj,n]:[_c,n]},ul=([e,t])=>e===af&&(t==="function"||t==="symbol"),Ule=(e,t,n,i)=>{const r=(s,a)=>{const l=i.push(s)-1;return n.set(a,l),l},o=s=>{if(n.has(s))return n.get(s);let[a,l]=Ts(s);switch(a){case af:{let c=s;switch(l){case"bigint":a=$j,c=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return r([Aj],s)}return r([a,c],s)}case Hs:{if(l){let f=s;return l==="DataView"?f=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(s)),r([l,[...f]],s)}const c=[],d=r([a,c],s);for(const f of s)c.push(o(f));return d}case _c:{if(l)switch(l){case"BigInt":return r([l,s.toString()],s);case"Boolean":case"Number":case"String":return r([l,s.valueOf()],s)}if(t&&"toJSON"in s)return o(s.toJSON());const c=[],d=r([a,c],s);for(const f of Lle(s))(e||!ul(Ts(s[f])))&&c.push([o(f),o(s[f])]);return d}case Oy:return r([a,s.toISOString()],s);case Ny:{const{source:c,flags:d}=s;return r([a,{source:c,flags:d}],s)}case Py:{const c=[],d=r([a,c],s);for(const[f,p]of s)(e||!(ul(Ts(f))||ul(Ts(p))))&&c.push([o(f),o(p)]);return d}case My:{const c=[],d=r([a,c],s);for(const f of s)(e||!ul(Ts(f)))&&c.push(o(f));return d}}const{message:u}=s;return r([a,{name:l,message:u}],s)};return o},sS=(e,{json:t,lossy:n}={})=>{const i=[];return Ule(!(t||n),!!t,new Map,i)(e),i},wc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?oS(sS(e,t)):structuredClone(e):(e,t)=>oS(sS(e,t));function Fle(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function Ble(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Vle(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Fle,i=e.options.footnoteBackLabel||Ble,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",s=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const c=e.all(u),d=String(u.identifier).toUpperCase(),f=ds(d.toLowerCase());let p=0;const m=[],h=e.footnoteCounts.get(d);for(;h!==void 0&&++p<=h;){m.length>0&&m.push({type:"text",value:" "});let w=typeof n=="string"?n:n(l,p);typeof w=="string"&&(w={type:"text",value:w}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(l,p),className:["data-footnote-backref"]},children:Array.isArray(w)?w:[w]})}const v=c[c.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const w=v.children[v.children.length-1];w&&w.type==="text"?w.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...m)}else c.push(...m);const y={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(c,!0)};e.patch(u,y),a.push(y)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...wc(s),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
160
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:`
|
|
161
|
+
`}]}}const Oj=(function(e){if(e==null)return Gle;if(typeof e=="function")return uf(e);if(typeof e=="object")return Array.isArray(e)?qle(e):Zle(e);if(typeof e=="string")return Hle(e);throw new Error("Expected function, string, or object as test")});function qle(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Oj(e[n]);return uf(i);function i(...r){let o=-1;for(;++o<t.length;)if(t[o].apply(this,r))return!0;return!1}}function Zle(e){const t=e;return uf(n);function n(i){const r=i;let o;for(o in e)if(r[o]!==t[o])return!1;return!0}}function Hle(e){return uf(t);function t(n){return n&&n.type===e}}function uf(e){return t;function t(n,i,r){return!!(Wle(n)&&e.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function Gle(){return!0}function Wle(e){return e!==null&&typeof e=="object"&&"type"in e}const Nj=[],Jle=!0,aS=!1,Kle="skip";function Yle(e,t,n,i){let r;typeof t=="function"&&typeof n!="function"?(i=n,n=t):r=t;const o=Oj(r),s=i?-1:1;a(e,void 0,[])();function a(l,u,c){const d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){const p=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(l.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Nj,m,h,v;if((!t||o(l,u,c[c.length-1]||void 0))&&(p=Xle(n(l,c)),p[0]===aS))return p;if("children"in l&&l.children){const y=l;if(y.children&&p[0]!==Kle)for(h=(i?y.children.length:-1)+s,v=c.concat(y);h>-1&&h<y.children.length;){const w=y.children[h];if(m=a(w,h,v)(),m[0]===aS)return m;h=typeof m[1]=="number"?m[1]:h+s}}return p}}}function Xle(e){return Array.isArray(e)?e:typeof e=="number"?[Jle,e]:e==null?Nj:[e]}function Pj(e,t,n,i){let r,o,s;typeof t=="function"&&typeof n!="function"?(o=void 0,s=t,r=n):(o=t,s=n,r=i),Yle(e,o,a,r);function a(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return s(l,d,c)}}const Kh={}.hasOwnProperty,Qle={};function ece(e,t){const n=t||Qle,i=new Map,r=new Map,o=new Map,s={...jle,...n.handlers},a={all:u,applyData:nce,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:s,one:l,options:n,patch:tce,wrap:ice};return Pj(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?i:r,f=String(c.identifier).toUpperCase();d.has(f)||d.set(f,c)}}),a;function l(c,d){const f=c.type,p=a.handlers[f];if(Kh.call(a.handlers,f)&&p)return p(a,c,d);if(a.options.passThrough&&a.options.passThrough.includes(f)){if("children"in c){const{children:h,...v}=c,y=wc(v);return y.children=a.all(c),y}return wc(c)}return(a.options.unknownHandler||rce)(a,c,d)}function u(c){const d=[];if("children"in c){const f=c.children;let p=-1;for(;++p<f.length;){const m=a.one(f[p],c);if(m){if(p&&f[p-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=uS(m.value)),!Array.isArray(m)&&m.type==="element")){const h=m.children[0];h&&h.type==="text"&&(h.value=uS(h.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function tce(e,t){e.position&&(t.position=zse(e))}function nce(e,t){let n=t;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(n.type==="element")n.tagName=i;else{const s="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:s}}n.type==="element"&&o&&Object.assign(n.properties,wc(o)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function rce(e,t){const n=t.data||{},i="value"in t&&!(Kh.call(n,"hProperties")||Kh.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function ice(e,t){const n=[];let i=-1;for(t&&n.push({type:"text",value:`
|
|
162
|
+
`});++i<e.length;)i&&n.push({type:"text",value:`
|
|
163
|
+
`}),n.push(e[i]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
164
|
+
`}),n}function uS(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function lS(e,t){const n=ece(e,t),i=n.one(e,void 0),r=Vle(n),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
165
|
+
`},r),o}function oce(e,t){return e&&"run"in e?async function(n,i){const r=lS(n,{file:i,...t});await e.run(r,i)}:function(n,i){return lS(n,{file:i,...e||t})}}function cS(e){if(e)throw e}var kp,dS;function sce(){if(dS)return kp;dS=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},o=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var c=e.call(u,"constructor"),d=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!d)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},s=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},a=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(i)return i(u,c).value}else return;return u[c]};return kp=function l(){var u,c,d,f,p,m,h=arguments[0],v=1,y=arguments.length,w=!1;for(typeof h=="boolean"&&(w=h,h=arguments[1]||{},v=2),(h==null||typeof h!="object"&&typeof h!="function")&&(h={});v<y;++v)if(u=arguments[v],u!=null)for(c in u)d=a(h,c),f=a(u,c),h!==f&&(w&&f&&(o(f)||(p=r(f)))?(p?(p=!1,m=d&&r(d)?d:[]):m=d&&o(d)?d:{},s(h,{name:c,newValue:l(w,m,f)})):typeof f<"u"&&s(h,{name:c,newValue:f}));return h},kp}var ace=sce();const Cp=mu(ace);function Yh(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function uce(){const e=[],t={run:n,use:i};return t;function n(...r){let o=-1;const s=r.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);a(null,...r);function a(l,...u){const c=e[++o];let d=-1;if(l){s(l);return}for(;++d<r.length;)(u[d]===null||u[d]===void 0)&&(u[d]=r[d]);r=u,c?lce(c,a)(...u):s(null,...u)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function lce(e,t){let n;return i;function i(...s){const a=e.length>s.length;let l;a&&s.push(r);try{l=e.apply(this,s)}catch(u){const c=u;if(a&&n)throw c;return r(c)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,r):l instanceof Error?r(l):o(l))}function r(s,...a){n||(n=!0,t(s,...a))}function o(s){r(null,s)}}const Gn={basename:cce,dirname:dce,extname:fce,join:pce,sep:"/"};function cce(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ku(e);let n=0,i=-1,r=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(n,i)}if(t===e)return"";let s=-1,a=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else s<0&&(o=!0,s=r+1),a>-1&&(e.codePointAt(r)===t.codePointAt(a--)?a<0&&(i=r):(a=-1,i=s));return n===i?i=s:i<0&&(i=e.length),e.slice(n,i)}function dce(e){if(ku(e),e.length===0)return".";let t=-1,n=e.length,i;for(;--n;)if(e.codePointAt(n)===47){if(i){t=n;break}}else i||(i=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function fce(e){ku(e);let t=e.length,n=-1,i=0,r=-1,o=0,s;for(;t--;){const a=e.codePointAt(t);if(a===47){if(s){i=t+1;break}continue}n<0&&(s=!0,n=t+1),a===46?r<0?r=t:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||n<0||o===0||o===1&&r===n-1&&r===i+1?"":e.slice(r,n)}function pce(...e){let t=-1,n;for(;++t<e.length;)ku(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":hce(n)}function hce(e){ku(e);const t=e.codePointAt(0)===47;let n=mce(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function mce(e,t){let n="",i=0,r=-1,o=0,s=-1,a,l;for(;++s<=e.length;){if(s<e.length)a=e.codePointAt(s);else{if(a===47)break;a=47}if(a===47){if(!(r===s-1||o===1))if(r!==s-1&&o===2){if(n.length<2||i!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",i=0):(n=n.slice(0,l),i=n.length-1-n.lastIndexOf("/")),r=s,o=0;continue}}else if(n.length>0){n="",i=0,r=s,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+e.slice(r+1,s):n=e.slice(r+1,s),i=s-r-1;r=s,o=0}else a===46&&o>-1?o++:o=-1}return n}function ku(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const gce={cwd:vce};function vce(){return"/"}function Xh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function yce(e){if(typeof e=="string")e=new URL(e);else if(!Xh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return bce(e)}function bce(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const i=t.codePointAt(n+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(t)}const Ap=["history","path","basename","stem","extname","dirname"];class Mj{constructor(t){let n;t?Xh(t)?n={path:t}:typeof t=="string"||_ce(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":gce.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Ap.length;){const o=Ap[i];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let r;for(r in n)Ap.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?Gn.basename(this.path):void 0}set basename(t){$p(t,"basename"),Rp(t,"basename"),this.path=Gn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Gn.dirname(this.path):void 0}set dirname(t){fS(this.basename,"dirname"),this.path=Gn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Gn.extname(this.path):void 0}set extname(t){if(Rp(t,"extname"),fS(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Gn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Xh(t)&&(t=yce(t)),$p(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Gn.basename(this.path,this.extname):void 0}set stem(t){$p(t,"stem"),Rp(t,"stem"),this.path=Gn.join(this.dirname||"",t+(this.extname||""))}fail(t,n,i){const r=this.message(t,n,i);throw r.fatal=!0,r}info(t,n,i){const r=this.message(t,n,i);return r.fatal=void 0,r}message(t,n,i){const r=new kt(t,n,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Rp(e,t){if(e&&e.includes(Gn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Gn.sep+"`")}function $p(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function fS(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function _ce(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const wce=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),xce={}.hasOwnProperty;class jy extends wce{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=uce()}copy(){const t=new jy;let n=-1;for(;++n<this.attachers.length;){const i=this.attachers[n];t.use(...i)}return t.data(Cp(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Pp("data",this.frozen),this.namespace[t]=n,this):xce.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Pp("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=n.call(t,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=ll(t),i=this.parser||this.Parser;return Op("parse",i),i(String(n),n)}process(t,n){const i=this;return this.freeze(),Op("process",this.parser||this.Parser),Np("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(o,s){const a=ll(t),l=i.parse(a);i.run(l,a,function(c,d,f){if(c||!d||!f)return u(c);const p=d,m=i.stringify(p,f);Ice(m)?f.value=m:f.result=m,u(c,f)});function u(c,d){c||!d?s(c):o?o(d):n(void 0,d)}}}processSync(t){let n=!1,i;return this.freeze(),Op("processSync",this.parser||this.Parser),Np("processSync",this.compiler||this.Compiler),this.process(t,r),hS("processSync","process",n),i;function r(o,s){n=!0,cS(o),i=s}}run(t,n,i){pS(t),this.freeze();const r=this.transformers;return!i&&typeof n=="function"&&(i=n,n=void 0),i?o(void 0,i):new Promise(o);function o(s,a){const l=ll(n);r.run(t,l,u);function u(c,d,f){const p=d||t;c?a(c):s?s(p):i(void 0,p,f)}}}runSync(t,n){let i=!1,r;return this.run(t,n,o),hS("runSync","run",i),r;function o(s,a){cS(s),r=a,i=!0}}stringify(t,n){this.freeze();const i=ll(n),r=this.compiler||this.Compiler;return Np("stringify",r),pS(t),r(t,i)}use(t,...n){const i=this.attachers,r=this.namespace;if(Pp("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?a(t):s(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[c,...d]=u;l(c,d)}else s(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function s(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(u.plugins),u.settings&&(r.settings=Cp(!0,r.settings,u.settings))}function a(u){let c=-1;if(u!=null)if(Array.isArray(u))for(;++c<u.length;){const d=u[c];o(d)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,c){let d=-1,f=-1;for(;++d<i.length;)if(i[d][0]===u){f=d;break}if(f===-1)i.push([u,...c]);else if(c.length>0){let[p,...m]=c;const h=i[f][1];Yh(h)&&Yh(p)&&(p=Cp(!0,h,p)),i[f]=[u,p,...m]}}}}const Sce=new jy().freeze();function Op(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Np(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Pp(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function pS(e){if(!Yh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function hS(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ll(e){return Ece(e)?e:new Mj(e)}function Ece(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Ice(e){return typeof e=="string"||Tce(e)}function Tce(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const kce="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",mS=[],gS={allowDangerousHtml:!0},Cce=/^(https?|ircs?|mailto|xmpp)$/i,Ace=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Rce(e){const t=$ce(e),n=Oce(e);return Nce(t.runSync(t.parse(n),n),e)}function $ce(e){const t=e.rehypePlugins||mS,n=e.remarkPlugins||mS,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...gS}:gS;return Sce().use(cle).use(n).use(oce,i).use(t)}function Oce(e){const t=e.children||"",n=new Mj;return typeof t=="string"&&(n.value=t),n}function Nce(e,t){const n=t.allowedElements,i=t.allowElement,r=t.components,o=t.disallowedElements,s=t.skipHtml,a=t.unwrapDisallowed,l=t.urlTransform||Pce;for(const c of Ace)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+kce+c.id,void 0);return Pj(e,u),Vse(e,{Fragment:g.Fragment,components:r,ignoreInvalidStyle:!0,jsx:g.jsx,jsxs:g.jsxs,passKeys:!0,passNode:!0});function u(c,d,f){if(c.type==="raw"&&f&&typeof d=="number")return s?f.children.splice(d,1):f.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let p;for(p in Ep)if(Object.hasOwn(Ep,p)&&Object.hasOwn(c.properties,p)){const m=c.properties[p],h=Ep[p];(h===null||h.includes(c.tagName))&&(c.properties[p]=l(String(m||""),p,c))}}if(c.type==="element"){let p=n?!n.includes(c.tagName):o?o.includes(c.tagName):!1;if(!p&&i&&typeof d=="number"&&(p=!i(c,d,f)),p&&f&&typeof d=="number")return a&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d}}}function Pce(e){const t=e.indexOf(":"),n=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return t===-1||r!==-1&&t>r||n!==-1&&t>n||i!==-1&&t>i||Cce.test(e.slice(0,t))?e:""}const Mce=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),jce=(e,t)=>{if(!e||!t)return!1;const n=i=>{const{position:r,data:o,...s}=i||{};return s};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&Mce(e.children,t.children)},Dy=(e,t)=>jce(e.node,t.node),Dce=(e={})=>Object.fromEntries(Object.entries(e??{}).map(([t,n])=>{if(!n)return[t,n];const i=n,r=({node:o,...s})=>g.jsx(i,{...s});return[t,I.memo(r,Dy)]})),zy=I.createContext(null),jj=()=>I.useContext(zy)!==null,zce=({children:e,...t})=>g.jsx(zy.Provider,{value:t,children:e}),Lce=I.memo(zce,Dy),Uce=({node:e,...t})=>g.jsx("pre",{...t}),Fce=({node:e,...t})=>g.jsx("code",{...t}),Ly=({node:e,components:{Pre:t,Code:n},code:i})=>g.jsx(t,{children:g.jsx(n,{node:e,children:i})}),Bce=()=>null,Vce=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},language:o,code:s})=>{const a=I.useMemo(()=>({Pre:t,Code:n}),[t,n]),l=o?i:Ly;return g.jsxs(g.Fragment,{children:[g.jsx(r,{node:e,language:o,code:s}),g.jsx(l,{node:e,components:a,language:o??"unknown",code:s})]})};var Mp={exports:{}};var vS;function qce(){return vS||(vS=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var o="",s=0;s<arguments.length;s++){var a=arguments[s];a&&(o=r(o,i(a)))}return o}function i(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return n.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var s="";for(var a in o)t.call(o,a)&&o[a]&&(s=r(s,a));return s}function r(o,s){return s?o?o+" "+s:o+s:o}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(Mp)),Mp.exports}var Zce=qce();const Dj=mu(Zce),yS=({className:e,...t})=>({className:n,...i})=>({className:Dj(e,n),...t,...i}),Hce=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},componentsByLanguage:o={},children:s,...a})=>{const l=I.useContext(zy),u=yS(l),c=sn(v=>g.jsx(t,{...u(v)})),d=yS(a),f=sn(v=>g.jsx(n,{...d(v)})),p=/language-(\w+)/.exec(a.className||"")?.[1]??"";if(typeof s!="string")return g.jsx(Ly,{node:e,components:{Pre:c,Code:f},code:s});const m=o[p]?.SyntaxHighlighter??i,h=o[p]?.CodeHeader??r;return g.jsx(Vce,{node:e,components:{Pre:c,Code:f,SyntaxHighlighter:m,CodeHeader:h},language:p||"unknown",code:s})},Gce=({node:e,components:t,componentsByLanguage:n,...i})=>jj()?g.jsx(Hce,{node:e,components:t,componentsByLanguage:n,...i}):g.jsx(t.Code,{...i}),Wce=I.memo(Gce,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Dy(e,t)),{useSmooth:Jce,useSmoothStatus:Kce,withSmoothContextProvider:Yce}=aO,Xce=({components:e,componentsByLanguage:t,smooth:n=!0,preprocess:i,...r})=>{const o=p1(),s=I.useMemo(()=>i?{...o,text:i(o.text)}:o,[o,i]),{text:a}=Jce(s,n),{pre:l=Uce,code:u=Fce,SyntaxHighlighter:c=Ly,CodeHeader:d=Bce}=e??{},f=I.useMemo(()=>({Pre:l,Code:u,SyntaxHighlighter:c,CodeHeader:d}),[l,u,c,d]),p=sn(h=>g.jsx(Wce,{components:f,componentsByLanguage:t,...h})),m=I.useMemo(()=>{const{pre:h,code:v,SyntaxHighlighter:y,CodeHeader:w,...S}=e??{};return{...S,pre:Lce,code:p}},[p,e]);return g.jsx(Rce,{components:m,...r,children:a})},zj=I.forwardRef(({className:e,containerProps:t,containerComponent:n="div",...i},r)=>{const o=Kce();return g.jsx(n,{"data-status":o.type,...t,className:Dj(e,t?.className),ref:r,children:g.jsx(Xce,{...i})})});zj.displayName="MarkdownTextPrimitive";const Qce=Yce(zj);function ede(e){return I.useMemo(()=>e.reduce((t,n)=>(t?.[n.language]&&!n.overrideExisting||(t={...t,[n.language]:{CodeHeader:n.Header??(()=>null),SyntaxHighlighter:n.Component??void 0}}),t),{}),[e])}const tde=()=>{const{plugins:e}=O.useElements(),t=ede(e);return g.jsx(Qce,{remarkPlugins:[rD],className:"aui-md",components:ide,componentsByLanguage:t})},Lj=I.memo(tde),nde=({language:e,code:t})=>{const i=te(({message:a})=>a).status?.type==="complete",{isCopied:r,copyToClipboard:o}=rde(),s=()=>{!t||r||o(t)};return i?g.jsxs("div",{className:"aui-code-header-root bg-muted-foreground/15 text-foreground dark:bg-muted-foreground/20 mt-4 flex items-center justify-between gap-4 rounded-t-lg px-4 py-2 text-sm font-semibold",children:[g.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),g.jsxs(Un,{tooltip:"Copy",onClick:s,children:[!r&&g.jsx(Jv,{}),r&&g.jsx(qr,{})]})]}):null},rde=({copiedDuration:e=3e3}={})=>{const[t,n]=I.useState(!1);return{isCopied:t,copyToClipboard:r=>{r&&navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},ide=Dce({h1:({className:e,...t})=>g.jsx("h1",{className:O.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>g.jsx("h2",{className:O.cn("aui-md-h2 mt-8 mb-4 scroll-m-20 text-3xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h3:({className:e,...t})=>g.jsx("h3",{className:O.cn("aui-md-h3 mt-6 mb-4 scroll-m-20 text-2xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h4:({className:e,...t})=>g.jsx("h4",{className:O.cn("aui-md-h4 mt-6 mb-4 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h5:({className:e,...t})=>g.jsx("h5",{className:O.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>g.jsx("h6",{className:O.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>g.jsx("p",{className:O.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>g.jsx("a",{className:O.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>g.jsx("blockquote",{className:O.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>g.jsx("ul",{className:O.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>g.jsx("ol",{className:O.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>g.jsx("hr",{className:O.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>g.jsx("table",{className:O.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>g.jsx("th",{className:O.cn("aui-md-th bg-muted px-4 py-2 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [[align=center]]:text-center [[align=right]]:text-right",e),...t}),td:({className:e,...t})=>g.jsx("td",{className:O.cn("aui-md-td border-b border-l px-4 py-2 text-left last:border-r [[align=center]]:text-center [[align=right]]:text-right",e),...t}),tr:({className:e,...t})=>g.jsx("tr",{className:O.cn("aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg",e),...t}),sup:({className:e,...t})=>g.jsx("sup",{className:O.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>g.jsx("pre",{className:O.cn("aui-md-pre text-foreground bg-muted overflow-x-auto rounded-t-none! rounded-b-lg border border-t-0 p-4",e),...t}),code:function({className:t,...n}){const i=jj();return g.jsx("code",{className:O.cn(!i&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...n})},CodeHeader:nde});var lf="Collapsible",[ode]=vu(lf),[sde,Uy]=ode(lf),Uj=x.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:i,defaultOpen:r,disabled:o,onOpenChange:s,...a}=e,[l,u]=Gd({prop:i,defaultProp:r??!1,onChange:s,caller:lf});return g.jsx(sde,{scope:n,disabled:o,contentId:_o(),open:l,onOpenToggle:x.useCallback(()=>u(c=>!c),[u]),children:g.jsx(dt.div,{"data-state":By(l),"data-disabled":o?"":void 0,...a,ref:t})})});Uj.displayName=lf;var Fj="CollapsibleTrigger",Bj=x.forwardRef((e,t)=>{const{__scopeCollapsible:n,...i}=e,r=Uy(Fj,n);return g.jsx(dt.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":By(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...i,ref:t,onClick:Le(e.onClick,r.onOpenToggle)})});Bj.displayName=Fj;var Fy="CollapsibleContent",Vj=x.forwardRef((e,t)=>{const{forceMount:n,...i}=e,r=Uy(Fy,e.__scopeCollapsible);return g.jsx(si,{present:n||r.open,children:({present:o})=>g.jsx(ade,{...i,ref:t,present:o})})});Vj.displayName=Fy;var ade=x.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:i,children:r,...o}=e,s=Uy(Fy,n),[a,l]=x.useState(i),u=x.useRef(null),c=mt(t,u),d=x.useRef(0),f=d.current,p=x.useRef(0),m=p.current,h=s.open||a,v=x.useRef(h),y=x.useRef(void 0);return x.useEffect(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),xn(()=>{const w=u.current;if(w){y.current=y.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();d.current=S.height,p.current=S.width,v.current||(w.style.transitionDuration=y.current.transitionDuration,w.style.animationName=y.current.animationName),l(i)}},[s.open,i]),g.jsx(dt.div,{"data-state":By(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...o,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:h&&r})});function By(e){return e?"open":"closed"}var ude=Uj;function lde({...e}){return g.jsx(ude,{"data-slot":"collapsible",...e})}function cde({...e}){return g.jsx(Bj,{"data-slot":"collapsible-trigger",...e})}function dde({...e}){return g.jsx(Vj,{"data-slot":"collapsible-content",...e})}const bS=200,qj=({className:e,children:t})=>{const n=I.useRef(null),[i,r]=I.useState(!1),o=A7(n,bS),s=I.useCallback(a=>{a||o(),r(a)},[o]);return g.jsx(lde,{ref:n,open:i,onOpenChange:s,className:O.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${bS}ms`},children:t})};qj.displayName="ReasoningRoot";const fde=({className:e})=>g.jsx("div",{className:O.cn("aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-16","bg-[linear-gradient(to_top,var(--color-background),transparent)]","fade-in-0 animate-in","group-data-[state=open]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:delay-[calc(var(--animation-duration)*0.75)]","group-data-[state=open]/collapsible-content:fill-mode-forwards","duration-(--animation-duration)","group-data-[state=open]/collapsible-content:duration-(--animation-duration)",e)}),pde=({active:e,className:t})=>g.jsxs(cde,{className:O.cn("aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground -mb-2 flex max-w-[75%] items-center gap-2 py-2 text-sm transition-colors",t,e&&"shimmer"),children:[g.jsx(F7,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),g.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[g.jsx("span",{children:"Reasoning"}),e?g.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),g.jsx(ac,{className:O.cn("aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0","transition-transform duration-(--animation-duration) ease-out","group-data-[state=closed]/trigger:-rotate-90","group-data-[state=open]/trigger:rotate-0")})]}),Zj=({className:e,children:t,"aria-busy":n})=>g.jsxs(dde,{className:O.cn("aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none","group/collapsible-content ease-out","data-[state=closed]:animate-collapsible-up","data-[state=open]:animate-collapsible-down","data-[state=closed]:fill-mode-forwards","data-[state=closed]:pointer-events-none","data-[state=open]:duration-(--animation-duration)","data-[state=closed]:duration-(--animation-duration)",e),"aria-busy":n,children:[t,g.jsx(fde,{})]});Zj.displayName="ReasoningContent";const Hj=({className:e,children:t})=>g.jsx("div",{className:O.cn("aui-reasoning-text relative z-0 space-y-4 pt-4 pl-6 leading-relaxed","transform-gpu transition-[transform,opacity]","group-data-[state=open]/collapsible-content:animate-in","group-data-[state=closed]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-in-0","group-data-[state=closed]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:slide-in-from-top-4","group-data-[state=closed]/collapsible-content:slide-out-to-top-4","group-data-[state=open]/collapsible-content:duration-(--animation-duration)","group-data-[state=closed]/collapsible-content:duration-(--animation-duration)","[&_p]:-mb-2",e),children:t});Hj.displayName="ReasoningText";const hde=()=>g.jsx(Lj,{}),mde=({children:e,startIndex:t,endIndex:n})=>{const i=te(({message:r})=>{if(r.status?.type!=="running")return!1;const o=r.parts.length-1;return o<0||r.parts[o]?.type!=="reasoning"?!1:o>=t&&o<=n});return g.jsxs(qj,{children:[g.jsx(pde,{active:i}),g.jsx(Zj,{"aria-busy":i,children:g.jsx(Hj,{children:e})})]})},Gj=I.memo(hde);Gj.displayName="Reasoning";const Wj=I.memo(mde);Wj.displayName="ReasoningGroup";function Jj({...e}){return g.jsx(x8,{"data-slot":"popover",...e})}function Kj({...e}){return g.jsx(S8,{"data-slot":"popover-trigger",...e})}function Yj({className:e,align:t="center",sideOffset:n=4,...i}){return g.jsx(E8,{"data-slot":"popover-content",align:t,sideOffset:n,className:O.cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...i})}const gde=yM("flex size-5 items-center justify-center rounded-full",{variants:{status:{pending:"border border-dashed border-muted-foreground/50",running:"text-primary",complete:"text-green-600 dark:text-green-500",error:"text-destructive",approval:"text-amber-500"}},defaultVariants:{status:"pending"}});function vde(e){switch(e){case"text/markdown":return"markdown";case"text/html":return"html";case"text/css":return"css";case"application/json":return"json";case"text/javascript":return"javascript";case"text/typescript":return"typescript";case"text/python":return"python";default:return}}function yde(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function bde(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function Xj({status:e}){return g.jsxs("div",{className:O.cn(gde({status:e})),children:[e==="pending"&&null,e==="running"&&g.jsx(uc,{className:"size-4 animate-spin"}),e==="complete"&&g.jsx(qr,{className:"size-4"}),e==="error"&&g.jsx(wu,{className:"size-4"}),e==="approval"&&g.jsx(uc,{className:"text-muted-foreground size-4 animate-spin"})]})}function _de({content:e}){const[t,n]=I.useState(!1),i=async r=>{r.stopPropagation(),await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)};return g.jsx("button",{onClick:i,className:"text-muted-foreground hover:bg-accent hover:text-foreground rounded p-1 transition-colors","aria-label":"Copy to clipboard",children:t?g.jsx(qr,{className:"size-4"}):g.jsx(Jv,{className:"size-4"})})}function Qj({text:e,language:t,className:n}){const[i,r]=I.useState(null);return I.useEffect(()=>{t&&iD.codeToHtml(e,{lang:t,theme:"github-dark-default",rootStyle:"background-color: transparent;",transformers:[{pre(o){o.properties.class="w-full py-3 px-4 max-h-[300px] overflow-y-auto whitespace-pre-wrap text-left text-sm"}}]}).then(r)},[e,t]),i?g.jsx("div",{className:O.cn("w-full bg-slate-800/90",n),dangerouslySetInnerHTML:{__html:i}}):g.jsx("pre",{className:O.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",n),children:e})}function wde({data:e}){const t=`data:image/png;base64,${e}`;return g.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
166
|
+
linear-gradient(135deg, #ccc 25%, transparent 25%),
|
|
167
|
+
linear-gradient(45deg, transparent 75%, #ccc 75%),
|
|
168
|
+
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:g.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function xde({content:e}){return g.jsx("div",{className:"w-full",children:e.content.map((t,n)=>{switch(t.type){case"text":{const i=vde(t._meta?.["getgram.ai/mime-type"]??"text/plain"),r=yde(t.text,i);return g.jsx(Qj,{text:r,language:i},n)}case"image":return g.jsx(wde,{data:t.data},n);default:return g.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},n)}})})}function _S({title:e,content:t,defaultExpanded:n=!1,highlightSyntax:i=!0,language:r="json"}){const[o,s]=I.useState(n),a=bde(t),l=a?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return g.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[g.jsxs("button",{onClick:()=>s(!o),className:"hover:bg-accent/50 flex w-full cursor-pointer items-center justify-between px-4 py-2.5 text-left transition-colors",children:[g.jsx("span",{className:"text-muted-foreground text-sm",children:e}),g.jsxs("div",{className:"flex items-center gap-1",children:[g.jsx(_de,{content:l}),g.jsx(B1,{className:O.cn("text-muted-foreground size-4 transition-transform duration-200",o&&"rotate-90")})]})]}),o&&g.jsx("div",{className:"border-border border-t",children:a?g.jsx(xde,{content:t}):i?g.jsx(Qj,{text:l,language:r}):g.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:l})})]})}function Sde({name:e,icon:t,provider:n,status:i="complete",request:r,result:o,defaultExpanded:s=!1,className:a,onApproveOnce:l,onApproveForSession:u,onDeny:c}){const d=i==="approval"&&l!==void 0&&c!==void 0,[f,p]=I.useState(s),m=r!==void 0||o!==void 0,[h,v]=I.useState("one-time"),[y,w]=I.useState(!1);I.useEffect(()=>{!d&&f&&!s&&p(!1)},[d]);const S=()=>{h==="for-session"&&u?u():l&&l()};return g.jsxs("div",{"data-slot":"tool-ui",className:O.cn("border-border bg-card overflow-hidden rounded-lg border",a),children:[n&&g.jsxs("div",{"data-slot":"tool-ui-provider",className:O.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?g.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):g.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:n.charAt(0).toUpperCase()}),g.jsx("span",{className:"text-sm font-medium",children:n})]}),g.jsxs("button",{onClick:()=>m&&p(!f),disabled:!m,className:O.cn("flex w-full items-center gap-2 px-4 py-3 text-left",m&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[g.jsx(Xj,{status:i}),g.jsx("span",{className:O.cn("flex-1 text-sm",!n&&d&&"shimmer"),children:e}),m&&g.jsx(ac,{className:O.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&m&&g.jsxs("div",{"data-slot":"tool-ui-content",children:[r!==void 0&&g.jsx(_S,{title:"Arguments",content:r,highlightSyntax:!0,language:"json"}),o!==void 0&&g.jsx(_S,{title:"Output",content:o,highlightSyntax:!0,language:"json"})]}),d&&g.jsxs("div",{"data-slot":"tool-ui-approval-actions",className:"border-border flex items-center justify-end gap-2 border-t px-4 py-3",children:[g.jsx("div",{children:g.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),g.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g.jsxs(tn,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[g.jsx(wu,{className:"mr-1 size-3"}),"Deny"]}),g.jsxs("div",{className:"flex items-center",children:[g.jsxs(tn,{variant:"default",size:"sm",onClick:S,className:"flex cursor-pointer justify-between gap-1 rounded-r-none bg-emerald-600 hover:bg-emerald-700",children:[g.jsx(qr,{className:"mr-1 size-3"}),g.jsx("span",{className:"min-w-[110px]",children:h==="one-time"?"Approve this time":"Approve always"})]}),g.jsxs(Jj,{open:y,onOpenChange:w,children:[g.jsx(Kj,{asChild:!0,children:g.jsx(tn,{variant:"default",size:"sm",className:"cursor-pointer rounded-l-none border-l border-emerald-700 bg-emerald-600 px-2 hover:bg-emerald-700",children:g.jsx(ac,{className:"size-3"})})}),g.jsxs(Yj,{align:"end",className:"w-64 p-1",sideOffset:4,children:[g.jsxs("button",{onClick:()=>{v("one-time"),w(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[g.jsx(qr,{className:O.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="one-time"&&"invisible")}),g.jsxs("div",{className:"flex flex-col gap-0.5",children:[g.jsx("span",{className:"text-sm",children:"Approve only once"}),g.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),u&&g.jsxs("button",{onClick:()=>{v("for-session"),w(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[g.jsx(qr,{className:O.cn("relative top-1 mt-0.5 size-3 shrink-0",h!=="for-session"&&"invisible")}),g.jsxs("div",{className:"flex flex-col gap-0.5",children:[g.jsx("span",{className:"text-sm",children:"Approve always"}),g.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function Ede({title:e,icon:t,status:n="complete",defaultExpanded:i=!1,children:r,className:o}){const[s,a]=I.useState(i);return g.jsxs("div",{"data-slot":"tool-ui-group",className:O.cn("border-border bg-card overflow-hidden rounded-lg border",o),children:[g.jsxs("button",{onClick:()=>a(!s),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||g.jsx(Xj,{status:n==="running"?"running":"complete"}),g.jsx("span",{className:O.cn("flex-1 text-sm font-medium",n==="running"&&"shimmer"),children:e}),g.jsx(ac,{className:O.cn("text-muted-foreground size-4 transition-transform duration-200",s&&"rotate-180")})]}),s&&g.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:r})]})}const Ide=({toolName:e,toolCallId:t,status:n,result:i,args:r})=>{const{pendingApprovals:o,whitelistTool:s,confirmPendingApproval:a,rejectPendingApproval:l}=uA(),u=o.get(t),d=te(({message:w})=>w).parts.filter(w=>w.type==="tool-call"),f=d.findIndex(w=>w.toolName===e),p=()=>{a(t)},m=()=>{s(e),a(t)},h=()=>{l(t)},v=()=>u?"approval":n.type==="incomplete"?"error":n.type==="complete"?i&&typeof i=="object"&&"isError"in i&&i.isError?"error":"complete":"running",y=()=>{if(i!==void 0)return typeof i=="object"&&i!==null&&"content"in i&&Array.isArray(i.content)||typeof i=="string",i};return g.jsx("div",{className:O.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:g.jsx(Sde,{name:e,status:v(),request:r,result:y(),onApproveOnce:u?p:void 0,onApproveForSession:u?m:void 0,onDeny:u?h:void 0,className:"rounded-none border-0"})})},Vy=()=>{const{config:e}=O.useElements(),t=e.theme??{};return I.useMemo(()=>{const{colorScheme:n="light"}=t;return{className:n==="dark"||n==="system"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":void 0}},[t])},Zr=[.23,1,.32,1];function Tde(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const kde=({children:e})=>{const t=te(({message:a})=>a).parts,n=t.filter(a=>a.type==="tool-call"),i=n.some(a=>a.status?.type==="running"),{config:r}=O.useElements(),o=r.tools?.expandToolGroupsByDefault??!1,s=I.useMemo(()=>{const a=t.filter(l=>l.type==="tool-call");return a.length===0?"No tools called":a.length===1?`Calling ${Tde(a[0].toolName)}...`:i?`Calling ${a.length} tools...`:`Executed ${a.length} tools`},[t,i]);return r.tools?.components?.[n[0]?.toolName]?e:n.length===1?g.jsx("div",{className:O.cn("my-4 w-full max-w-xl"),children:g.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):g.jsx("div",{className:"my-4 w-full max-w-xl",children:g.jsx(Ede,{title:s,status:i?"running":"complete",defaultExpanded:o,children:e})})},Cde=()=>g.jsxs("div",{className:"m-2 rounded-md border border-amber-500 bg-amber-100 px-4 py-3 text-sm text-amber-800 dark:border-amber-600 dark:bg-amber-900/30 dark:text-amber-200",children:[g.jsx("strong",{children:"Warning:"})," You are using a static session token in the client. It will expire shortly. Please"," ",g.jsx("a",{href:"https://github.com/speakeasy-api/gram/tree/main/elements#setting-up-your-backend",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-800 dark:text-amber-300 dark:hover:text-amber-200",children:"set up a session endpoint to avoid this warning."})]}),qy=({className:e})=>{const t=Vy(),n=O.useDensity(),{config:i}=O.useElements(),r=i.components??{},o=i.api&&"sessionToken"in i.api;return g.jsx(vr.LazyMotion,{features:vr.domAnimation,children:g.jsx(vr.MotionConfig,{reducedMotion:"user",children:g.jsx(A1,{className:O.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",t.className,e),children:g.jsxs($1,{className:O.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",n("p-lg")),children:[g.jsx(ma,{empty:!0,children:r.ThreadWelcome?g.jsx(r.ThreadWelcome,{}):g.jsx(Rde,{})}),o&&g.jsx(Cde,{}),g.jsx(x7,{components:{UserMessage:r.UserMessage??Lde,EditComposer:r.EditComposer??Fde,AssistantMessage:r.AssistantMessage??jde}}),g.jsx(ma,{empty:!1,children:g.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),g.jsx(Ode,{})]})})})})},Ade=()=>g.jsx(E7,{asChild:!0,children:g.jsx(Un,{tooltip:"Scroll to bottom",variant:"outline",className:"aui-thread-scroll-to-bottom dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible",children:g.jsx(D7,{})})}),Rde=()=>{const{config:e}=O.useElements(),t=O.useDensity(),{title:n,subtitle:i}=e.welcome??{},r=e.variant==="standalone";return g.jsxs("div",{className:O.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",r?"items-center justify-center":"",t("gap-lg")),children:[g.jsx("div",{className:O.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:g.jsxs("div",{className:O.cn("aui-thread-welcome-message flex flex-col",r?"items-center text-center":"size-full justify-start",t("gap-sm"),!r&&t("py-md")),children:[g.jsx(pr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:Zr},className:O.cn("aui-thread-welcome-message-motion-1 text-foreground font-semibold",t("text-title")),children:n}),g.jsx(pr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:Zr},className:O.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:i})]})}),g.jsx($de,{})]})},$de=()=>{const{config:e}=O.useElements(),t=O.useRadius(),n=O.useDensity(),i=e.welcome?.suggestions??[],r=e.variant==="standalone";return i.length===0?null:g.jsx("div",{className:O.cn("aui-thread-welcome-suggestions w-full",n("gap-md"),n("py-lg"),r?"flex flex-wrap items-center justify-center":i.length===1?"flex":"grid max-w-fit @md:grid-cols-2"),children:i.map((o,s)=>g.jsx(pr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*s,ease:Zr},className:O.cn("aui-thread-welcome-suggestion-display",!r&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:g.jsx(T7,{prompt:o.action,send:!0,asChild:!0,children:g.jsxs(tn,{variant:"ghost",className:O.cn("aui-thread-welcome-suggestion dark:hover:bg-accent/60 h-auto w-full border text-left whitespace-break-spaces",n("text-base"),r?`flex-row items-center ${n("gap-sm")} ${n("px-md")} ${n("py-sm")} ${t("full")}`:`w-full flex-1 flex-col flex-wrap items-start justify-start ${n("gap-sm")} ${n("px-lg")} ${n("py-md")} ${t("xl")}`),"aria-label":o.action,children:[g.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-foreground text-sm font-medium",children:o.title}),g.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:o.label})]})})},`suggested-action-${o.title}-${s}`))})},Ode=()=>{const{config:e}=O.useElements(),t=O.useRadius(),n=O.useDensity(),i=e.composer??{placeholder:"Send a message...",attachments:!0},r=e.components??{};return r.Composer?g.jsx(r.Composer,{}):g.jsxs("div",{className:O.cn("aui-composer-wrapper bg-background sticky bottom-0 flex w-full flex-col overflow-visible",n("gap-md"),n("py-md"),t("xl")),children:[g.jsx(Ade,{}),g.jsxs(Hv,{className:O.cn("aui-composer-root group/input-group border-input bg-background has-[textarea:focus-visible]:border-ring has-[textarea:focus-visible]:ring-ring/5 dark:bg-background relative flex w-full flex-col border px-1 pt-2 shadow-xs transition-[color,box-shadow] outline-none has-[textarea:focus-visible]:ring-1",t("xl")),children:[i.attachments&&g.jsx(pse,{}),g.jsx(Wv,{placeholder:i.placeholder,className:O.cn("aui-composer-input placeholder:text-muted-foreground mb-1 max-h-32 w-full resize-none bg-transparent px-3.5 pt-1.5 pb-3 outline-none focus-visible:ring-0",n("h-input"),n("text-base")),rows:1,autoFocus:!0,"aria-label":"Message input"}),g.jsx(Pde,{})]})]})},Nde=()=>{const{model:e,setModel:t}=O.useElements(),[n,i]=I.useState(!1),[r,o]=I.useState(!1),s=I.useRef(null),a=I.useRef(0),l=I.useRef(!1);I.useEffect(()=>{n&&!l.current&&requestAnimationFrame(()=>{const c=s.current;c&&c.scrollHeight>0&&(c.scrollTop=a.current)}),l.current=n},[n]),I.useEffect(()=>{n&&o(!1)},[n]);const u=c=>{a.current=c.currentTarget.scrollTop};return g.jsx($M,{children:g.jsxs(gy,{open:r&&!n,onOpenChange:o,children:[g.jsxs(Jj,{open:n,onOpenChange:i,children:[g.jsx(vy,{asChild:!0,children:g.jsx(Kj,{asChild:!0,children:g.jsx(tn,{variant:"ghost",size:"icon","data-state":n?"open":"closed",className:"aui-composer-model-picker data-[state=open]:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 flex w-fit items-center gap-2 rounded-full px-2.5 py-1 text-xs font-semibold","aria-label":"Model Settings",children:g.jsx(dY,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),g.jsx(Yj,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:g.jsx("div",{ref:s,className:"max-h-48 overflow-y-auto",onScroll:u,children:hv.map(c=>g.jsxs(tn,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?g.jsx("div",{children:g.jsx(qr,{className:"size-4 text-emerald-500"})}):g.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),g.jsx(yy,{side:"bottom",align:"start",children:"Model Settings"})]})})},Pde=()=>{const{config:e}=O.useElements(),t=O.useRadius(),n=e.composer??{attachments:!0};return g.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[g.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[n.attachments?g.jsx(hse,{}):g.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&g.jsx(Nde,{})]}),g.jsx(ma,{running:!1,children:g.jsx(x1,{asChild:!0,children:g.jsx(Un,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:O.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:g.jsx(L7,{className:"aui-composer-send-icon size-5"})})})}),g.jsx(ma,{running:!0,children:g.jsx(E1,{asChild:!0,children:g.jsx(tn,{type:"button",variant:"default",size:"icon",className:O.cn("aui-composer-cancel border-muted-foreground/60 hover:bg-primary/75 dark:border-muted-foreground/90 size-[34px] border",t("full")),"aria-label":"Stop generating",children:g.jsx(pY,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},Mde=()=>g.jsx(b1,{children:g.jsx(k1,{className:"aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200",children:g.jsx(C1,{className:"aui-message-error-message line-clamp-2"})})}),jde=()=>{const{config:e}=O.useElements(),t=e.tools??{},n=e.components??{};return g.jsx(qv,{asChild:!0,children:g.jsxs("div",{className:"aui-assistant-message-root animate-in fade-in slide-in-from-bottom-1 relative mx-auto w-full py-4 duration-150 ease-out last:mb-24","data-role":"assistant",children:[g.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[g.jsx(Zv,{components:{Text:n.Text??Lj,Image:n.Image??Dde,tools:{by_name:t.components,Fallback:n.ToolFallback??Ide},Reasoning:n.Reasoning??Gj,ReasoningGroup:n.ReasoningGroup??Wj,ToolGroup:n.ToolGroup??kde}}),g.jsx(Mde,{})]}),g.jsx("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:g.jsx(zde,{})})]})})},Dde=e=>g.jsx("img",{src:e.image}),zde=()=>g.jsx(Av,{hideWhenRunning:!0,autohide:"not-last",autohideFloat:"single-branch",className:"aui-assistant-action-bar-root text-muted-foreground data-floating:bg-background col-start-3 row-start-2 -ml-1 flex gap-1 data-floating:absolute data-floating:rounded-md data-floating:border data-floating:p-1 data-floating:shadow-sm",children:g.jsx(fO,{asChild:!0,children:g.jsxs(Un,{tooltip:"Copy",children:[g.jsx(oc,{copied:!0,children:g.jsx(qr,{})}),g.jsx(oc,{copied:!1,children:g.jsx(Jv,{})})]})})}),Lde=()=>{const e=O.useRadius();return g.jsx(qv,{asChild:!0,children:g.jsxs("div",{className:"aui-user-message-root animate-in fade-in slide-in-from-bottom-1 mx-auto grid w-full auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 px-2 py-4 duration-150 ease-out first:mt-3 last:mb-5 [&:where(>*)]:col-start-2","data-role":"user",children:[g.jsx(fse,{}),g.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[g.jsx("div",{className:O.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:g.jsx(Zv,{})}),g.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:g.jsx(Ude,{})})]}),g.jsx(Bde,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},Ude=()=>g.jsx(Av,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:g.jsx(AW,{asChild:!0,children:g.jsx(Un,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:g.jsx(uY,{})})})}),Fde=()=>g.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:g.jsxs(Hv,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[g.jsx(Wv,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),g.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[g.jsx(E1,{asChild:!0,children:g.jsx(tn,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),g.jsx(x1,{asChild:!0,children:g.jsx(tn,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),Bde=({className:e,...t})=>g.jsxs(_1,{hideWhenSingleBranch:!0,className:O.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[g.jsx(R8,{asChild:!0,children:g.jsx(Un,{tooltip:"Previous",children:g.jsx(Z7,{})})}),g.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[g.jsx(c1,{})," / ",g.jsx(l1,{})]}),g.jsx(C8,{asChild:!0,children:g.jsx(Un,{tooltip:"Next",children:g.jsx(B1,{})})})]});function Vde({className:e,...t}){return g.jsx("div",{"data-slot":"skeleton",className:O.cn("bg-accent animate-pulse rounded-md",e),...t})}const eD="gram-elements",Zy=({className:e})=>{const t=O.useDensity();return g.jsxs(z1,{className:O.cn("aui-root aui-thread-list-root bg-background flex flex-col items-stretch",t("gap-sm"),e,eD),children:[g.jsx("div",{className:O.cn("aui-thread-list-new-section border-b pb-2",t("py-sm"),t("px-sm")),children:g.jsx(qde,{})}),g.jsx("div",{className:O.cn("aui-thread-list-items-section flex flex-col gap-1",t("py-xs"),t("px-sm")),children:g.jsx(Zde,{})})]})},qde=()=>{const e=O.useDensity();return g.jsx(M1,{asChild:!0,children:g.jsxs(tn,{className:O.cn("aui-thread-list-new hover:bg-muted-foreground/10 data-[active=true]:bg-muted-foreground/20! flex w-full cursor-pointer items-center justify-start gap-1 rounded-lg px-2.5 py-2 text-start",e("p-sm"),e("py-xs")),variant:"ghost",children:[g.jsx(V1,{}),"New Thread"]})})},Zde=()=>te(({threads:t})=>t.isLoading)?g.jsx(Hde,{}):g.jsx(D1,{components:{ThreadListItem:Gde}}),Hde=()=>g.jsx(g.Fragment,{children:Array.from({length:5},(e,t)=>g.jsx("div",{role:"status","aria-label":"Loading threads","aria-live":"polite",className:"aui-thread-list-skeleton-wrapper flex items-center gap-2 rounded-md px-3 py-2",children:g.jsx(Vde,{className:"aui-thread-list-skeleton h-[22px] grow"})},t))}),Gde=()=>{const e=O.useRadius(),t=O.useDensity();return g.jsx(L1,{className:O.cn("aui-thread-list-item group hover:bg-muted focus-visible:bg-muted focus-visible:ring-ring data-[active=true]:bg-muted-foreground/20 flex items-center gap-2 rounded-lg transition-all focus-visible:ring-2 focus-visible:outline-none",e("md")),children:g.jsx(C7,{className:O.cn("aui-thread-list-item-trigger flex grow cursor-pointer items-center text-start",t("px-lg"),t("py-sm")),children:g.jsx(Wde,{})})})},Wde=()=>g.jsx("span",{className:"aui-thread-list-item-title text-sm",children:g.jsx(U1,{fallback:"New Chat"})}),tD=()=>{const{config:e,isExpanded:t,setIsExpanded:n}=O.useElements(),i=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:n,defaultExpanded:i}},Jde={layout:{duration:.25,ease:Zr}},Kde=({className:e})=>{const{config:t}=O.useElements(),n=Vy(),i=O.useRadius(),r=O.useDensity(),[o,s]=I.useState(t.modal?.defaultOpen??!1),{expandable:a,isExpanded:l,setIsExpanded:u}=tD(),c=t.modal?.title,d=t.modal?.icon,f=t.history?.enabled&&t.history?.showThreadList!==!1,p=t.modal?.position??"bottom-right",m=Yde(p),h=I.useMemo(()=>t.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[t.modal?.dimensions?.default]),v=I.useMemo(()=>t.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[t.modal?.dimensions?.expanded]),w=te(({thread:_})=>_).messages.some(_=>_.status?.type==="running"),S=l?v.width:h.width,b=l?v.height:h.height,C=h.maxHeight;return g.jsx(vr.LazyMotion,{features:vr.domMax,children:g.jsx(vr.MotionConfig,{reducedMotion:"user",transition:Jde,children:g.jsx("div",{className:O.cn("aui-root aui-modal-anchor fixed z-10",m,n.className,i("lg"),o&&"shadow-xl",e),children:g.jsx(vr.AnimatePresence,{mode:"wait",children:o?g.jsxs(pr.div,{layout:!0,layoutId:"chat-container",className:O.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",i("lg")),initial:!1,style:{originX:p.includes("left")?0:1,originY:p.includes("top")?0:1,width:S,height:b,maxHeight:C},children:[g.jsxs(pr.div,{className:O.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",r("h-header"),r("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:Zr},children:[g.jsx("div",{className:O.cn("flex min-w-0 items-center"),children:g.jsxs("span",{className:O.cn("text-md flex items-center gap-2 truncate font-medium",w&&"shimmer"),children:[g.jsx("span",{className:"truncate",children:c}),w&&g.jsx(uc,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),g.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[a?g.jsx("button",{type:"button",onClick:()=>u(_=>!_),className:O.cn("text-muted-foreground hover:text-foreground hover:bg-accent flex h-8 cursor-pointer items-center rounded-md px-2 text-xs transition-colors"),"aria-pressed":l,"aria-label":l?"Collapse assistant":"Expand assistant",children:l?g.jsx(nY,{strokeWidth:2,className:"size-3.5 rotate-90"}):g.jsx(X7,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,g.jsx("button",{onClick:()=>{s(!1),u(!1)},className:"text-muted-foreground hover:text-foreground hover:bg-accent -mr-1 flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors","aria-label":`Close ${c}`,children:g.jsx(wu,{className:"size-4.5"})})]})]}),g.jsxs(pr.div,{className:"aui-modal-body flex flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:Zr},children:[f&&g.jsx("div",{className:"aui-modal-thread-list w-56 shrink-0 overflow-y-auto border-r",children:g.jsx(Zy,{})}),g.jsx("div",{className:"aui-modal-thread w-full flex-1 overflow-hidden",children:g.jsx(py,{children:g.jsx(qy,{})})})]})]},"chat"):g.jsx(pr.button,{layout:!0,layoutId:"chat-container",onClick:()=>s(!0),className:O.cn("aui-modal-button bg-primary text-primary-foreground flex size-12 cursor-pointer items-center justify-center border shadow-lg transition-shadow hover:shadow-xl",i("full")),initial:!1,"aria-label":`Open ${c}`,style:{originX:1,originY:1},children:g.jsx(pr.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:Zr},className:"flex size-full items-center justify-center",children:d?d("closed"):g.jsx(eY,{className:"size-6"})})},"button")})})})})};function Yde(e){switch(e){case"bottom-left":return"left-4 bottom-4";case"top-right":return"right-4 top-4";case"top-left":return"left-4 top-4";case"bottom-right":return"right-4 bottom-4";default:O.assertNever(e)}}const Xde=({className:e})=>{const{config:t}=O.useElements(),n=Vy(),i=t.sidecar??{},{title:r,dimensions:o}=i,{isExpanded:s,setIsExpanded:a}=tD(),u=te(({thread:d})=>d).messages.some(d=>d.status?.type==="running"),c=t.history?.enabled&&t.history?.showThreadList!==!1;return g.jsx(vr.LazyMotion,{features:vr.domMax,children:g.jsxs(pr.div,{initial:!1,animate:{width:s?o?.expanded?.width??"800px":o?.default?.width??"400px",height:s?o?.expanded?.height??"100%":o?.default?.height??"100vh"},transition:{duration:.3,ease:Zr},className:O.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",n.className,e),children:[g.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[g.jsxs("span",{className:O.cn("text-md flex items-center gap-2 font-medium",u&&"shimmer"),children:[r,u&&g.jsx(uc,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]}),g.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:g.jsx(Un,{tooltip:s?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>a(d=>!d),children:s?g.jsx(iY,{className:"size-4.5"}):g.jsx(sY,{className:"size-4.5"})})})]}),g.jsxs("div",{className:"aui-sidecar-body flex h-[calc(100%-3.5rem)] overflow-hidden",children:[c&&g.jsx("div",{className:"aui-sidecar-thread-list w-56 shrink-0 overflow-y-auto border-r",children:g.jsx(Zy,{})}),g.jsx("div",{className:"aui-sidecar-content flex-1 overflow-hidden",children:g.jsx(py,{children:g.jsx(qy,{})})})]})]})})};function Qde({containerRef:e,children:t}){return g.jsx(AM.Provider,{value:e,children:t})}function jp({children:e}){const t=I.useRef(null);return g.jsx("div",{ref:t,className:eD,style:{height:"inherit",width:"inherit"},children:g.jsx(Qde,{containerRef:t,children:e})})}const efe=({className:e})=>{const{config:t}=O.useElements();switch(t.variant){case"standalone":return g.jsx(py,{children:g.jsx(jp,{children:g.jsx(qy,{})})});case"sidecar":return g.jsx(jp,{children:g.jsx(Xde,{})});default:return g.jsx(jp,{children:g.jsx(Kde,{className:e})})}};exports.ActionType=$d;exports.CENSORED_IMG_MARK=Jq;exports.CENSORED_STRING_MARK=pl;exports.Chat=efe;exports.ElementsProvider=Yie;exports.MODELS=hv;exports.NodePrivacyLevel=xe;exports.ONE_SECOND=_t;exports.PRIVACY_ATTR_NAME=dv;exports.PRIVACY_ATTR_VALUE_HIDDEN=Gq;exports.RumEventType=me;exports.ThreadList=Zy;exports.addEventListener=Ke;exports.addEventListeners=Sr;exports.addRecord=LZ;exports.addSegment=zZ;exports.addTelemetryDebug=rs;exports.addTelemetryMetrics=cu;exports.addWroteData=UZ;exports.buildTags=ev;exports.buildUrl=su;exports.canUseEventBridge=$i;exports.clearTimeout=Yt;exports.clocksNow=ct;exports.clocksOrigin=Gg;exports.createHttpRequest=rv;exports.currentDrift=gA;exports.defineFrontendTool=P7;exports.display=he;exports.elapsed=tt;exports.forEachChildNodes=Pq;exports.getEventBridge=ts;exports.getGlobalObject=fn;exports.getMutationObserverConstructor=ER;exports.getNodePrivacyLevel=fu;exports.getNodeSelfPrivacyLevel=BR;exports.getParentNode=MR;exports.getScrollX=_5;exports.getScrollY=s$;exports.getSegmentsCount=DZ;exports.getTextContent=Xq;exports.getViewportDimension=Pd;exports.hasChildNodes=Nq;exports.initViewportObservable=a$;exports.instrumentMethod=Mn;exports.instrumentSetter=_6;exports.isNodeShadowHost=lv;exports.isNodeShadowRoot=PR;exports.isPageExitReason=eR;exports.isSafari=rF;exports.jsonStringify=Qo;exports.monitor=ye;exports.monitorError=wr;exports.noop=$e;exports.objectEntries=Td;exports.reducePrivacyLevel=FR;exports.relativeToClocks=ru;exports.requestIdleCallback=dR;exports.sanitizeIfLongDataUrl=AR;exports.sendToExtension=tv;exports.setTimeout=bt;exports.shouldMaskAttribute=VR;exports.shouldMaskNode=fv;exports.supportPerformanceTimingEvent=ii;exports.throttle=ou;exports.timeStampNow=ht;exports.trackError=Kl;
|
|
169
|
+
//# sourceMappingURL=index-BVvrv2G3.cjs.map
|